@arke-institute/sdk 3.2.0 → 3.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +3 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/operations/index.cjs +40 -34
- package/dist/operations/index.cjs.map +1 -1
- package/dist/operations/index.js +40 -34
- package/dist/operations/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -488,6 +488,9 @@ var raw = __toESM(require("multiformats/codecs/raw"), 1);
|
|
|
488
488
|
var TARGET_BYTES_IN_FLIGHT = 200 * 1024 * 1024;
|
|
489
489
|
var PRESIGNED_URL_THRESHOLD = 5 * 1024 * 1024;
|
|
490
490
|
|
|
491
|
+
// src/operations/upload/single.ts
|
|
492
|
+
var PRESIGNED_THRESHOLD = 5 * 1024 * 1024;
|
|
493
|
+
|
|
491
494
|
// src/operations/folders.ts
|
|
492
495
|
var FolderOperations = class {
|
|
493
496
|
constructor(client) {
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/client/ArkeClient.ts","../src/client/config.ts","../src/client/retry.ts","../src/client/errors.ts","../src/operations/upload/cid.ts","../src/operations/upload/engine.ts","../src/operations/folders.ts","../src/operations/batch.ts","../src/operations/crypto.ts","../src/operations/cas.ts"],"sourcesContent":["/**\n * @arke-institute/sdk\n *\n * TypeScript SDK for the Arke API - auto-generated from OpenAPI spec.\n *\n * @example\n * ```typescript\n * import { ArkeClient } from '@arke-institute/sdk';\n *\n * const arke = new ArkeClient({ authToken: 'your-jwt-token' });\n *\n * // Create an entity\n * const { data, error } = await arke.api.POST('/entities', {\n * body: {\n * collection_id: '01ABC...',\n * type: 'document',\n * properties: { title: 'My Document' }\n * }\n * });\n *\n * if (error) {\n * console.error('Failed to create entity:', error);\n * } else {\n * console.log('Created entity:', data.id);\n * }\n * ```\n */\n\n// Main client\nexport {\n ArkeClient,\n createArkeClient,\n isApiKey,\n getAuthorizationHeader,\n type ArkeApiClient,\n} from './client/ArkeClient.js';\n\n// Configuration\nexport { type ArkeClientConfig, DEFAULT_CONFIG } from './client/config.js';\n\n// Errors\nexport {\n ArkeError,\n CASConflictError,\n NotFoundError,\n ValidationError,\n AuthenticationError,\n ForbiddenError,\n parseApiError,\n} from './client/errors.js';\n\n// Generated types\nexport type { paths, components, operations } from './generated/index.js';\n\n// High-level operations (TODO: implement)\nexport {\n FolderOperations,\n BatchOperations,\n CryptoOperations,\n type UploadProgress,\n type UploadDirectoryOptions,\n type UploadDirectoryResult,\n type BatchCreateOptions,\n type BatchResult,\n type KeyPair,\n type SignedPayload,\n} from './operations/index.js';\n\n// CAS retry utility\nexport {\n withCasRetry,\n calculateMaxAttempts,\n calculateCasDelay,\n isCasConflictError,\n CasRetryExhaustedError,\n DEFAULT_CAS_RETRY_CONFIG,\n type CasRetryOptions,\n type CasRetryResult,\n type CasRetryCallbacks,\n} from './operations/cas.js';\n","/**\n * Main Arke SDK Client\n *\n * Provides type-safe access to the Arke API using openapi-fetch.\n */\n\nimport createClient, { type Client } from 'openapi-fetch';\nimport type { paths, components } from '../generated/types.js';\nimport { ArkeClientConfig, DEFAULT_CONFIG } from './config.js';\nimport { createRetryFetch } from './retry.js';\n\nexport type ArkeApiClient = Client<paths>;\n\n/**\n * Check if a token is an API key (starts with 'ak_' or 'uk_')\n */\nexport function isApiKey(token: string): boolean {\n return token.startsWith('ak_') || token.startsWith('uk_');\n}\n\n/**\n * Get the appropriate Authorization header value for a token\n * - API keys (ak_*, uk_*) use: ApiKey {token}\n * - JWT tokens use: Bearer {token}\n */\nexport function getAuthorizationHeader(token: string): string {\n if (isApiKey(token)) {\n return `ApiKey ${token}`;\n }\n return `Bearer ${token}`;\n}\n\n/**\n * Type-safe client for the Arke API\n *\n * @example\n * ```typescript\n * // With JWT token\n * const arke = new ArkeClient({ authToken: 'your-jwt-token' });\n *\n * // With API key (agent or user)\n * const arke = new ArkeClient({ authToken: 'ak_your-agent-api-key' });\n * const arke = new ArkeClient({ authToken: 'uk_your-user-api-key' });\n *\n * // Create an entity\n * const { data, error } = await arke.api.POST('/entities', {\n * body: {\n * collection_id: '01ABC...',\n * type: 'document',\n * properties: { title: 'My Document' }\n * }\n * });\n *\n * // Get an entity\n * const { data } = await arke.api.GET('/entities/{id}', {\n * params: { path: { id: '01XYZ...' } }\n * });\n * ```\n */\nexport class ArkeClient {\n /**\n * The underlying openapi-fetch client with full type safety\n * Use this for all API calls: arke.api.GET, arke.api.POST, etc.\n */\n public api: ArkeApiClient;\n\n private config: ArkeClientConfig;\n\n constructor(config: ArkeClientConfig = {}) {\n this.config = {\n ...DEFAULT_CONFIG,\n ...config,\n };\n\n this.api = this.createClient();\n }\n\n private createClient(): ArkeApiClient {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...this.config.headers,\n };\n\n if (this.config.authToken) {\n headers['Authorization'] = getAuthorizationHeader(this.config.authToken);\n }\n\n if (this.config.network === 'test') {\n headers['X-Arke-Network'] = 'test';\n }\n\n // Create retry-enabled fetch if retry config is not explicitly disabled\n const customFetch =\n this.config.retry === false\n ? undefined\n : createRetryFetch(this.config.retry ?? {});\n\n return createClient<paths>({\n baseUrl: this.config.baseUrl ?? DEFAULT_CONFIG.baseUrl,\n headers,\n ...(customFetch && { fetch: customFetch }),\n });\n }\n\n /**\n * Update the authentication token\n * Recreates the underlying client with new headers\n */\n setAuthToken(token: string): void {\n this.config.authToken = token;\n this.api = this.createClient();\n }\n\n /**\n * Clear the authentication token\n */\n clearAuthToken(): void {\n this.config.authToken = undefined;\n this.api = this.createClient();\n }\n\n /**\n * Get the current configuration\n */\n getConfig(): Readonly<ArkeClientConfig> {\n return { ...this.config };\n }\n\n /**\n * Get the base URL\n */\n get baseUrl(): string {\n return this.config.baseUrl ?? DEFAULT_CONFIG.baseUrl;\n }\n\n /**\n * Check if client is authenticated\n */\n get isAuthenticated(): boolean {\n return !!this.config.authToken;\n }\n\n /**\n * Get entity content as a Blob\n *\n * This is a convenience method that handles the binary response parsing\n * that openapi-fetch doesn't handle automatically.\n *\n * @param entityId - The entity ID\n * @param key - Optional content version key (e.g., \"v1\", \"original\", \"thumbnail\"). Defaults to entity's current content key.\n *\n * @example\n * ```typescript\n * const { data, error } = await arke.getEntityContent('01ABC...');\n * // or with specific key\n * const { data, error } = await arke.getEntityContent('01ABC...', 'thumbnail');\n * if (data) {\n * const text = await data.text();\n * }\n * ```\n */\n async getEntityContent(\n entityId: string,\n key?: string\n ): Promise<{ data: Blob | undefined; error: unknown }> {\n const { data, error } = await this.api.GET('/entities/{id}/content', {\n params: { path: { id: entityId }, query: key ? { key } : {} },\n parseAs: 'blob',\n });\n return { data: data as Blob | undefined, error };\n }\n\n /**\n * Get entity content as an ArrayBuffer\n *\n * This is a convenience method that handles the binary response parsing\n * that openapi-fetch doesn't handle automatically.\n *\n * @param entityId - The entity ID\n * @param key - Content version key (e.g., \"v1\", \"original\", \"thumbnail\")\n *\n * @example\n * ```typescript\n * const { data, error } = await arke.getEntityContentAsArrayBuffer('01ABC...', 'v1');\n * if (data) {\n * const bytes = new Uint8Array(data);\n * }\n * ```\n */\n async getEntityContentAsArrayBuffer(\n entityId: string,\n key?: string\n ): Promise<{ data: ArrayBuffer | undefined; error: unknown }> {\n const { data, error } = await this.api.GET('/entities/{id}/content', {\n params: { path: { id: entityId }, query: key ? { key } : {} },\n parseAs: 'arrayBuffer',\n });\n return { data: data as ArrayBuffer | undefined, error };\n }\n\n /**\n * Get entity content as a ReadableStream\n *\n * This is a convenience method for streaming large files.\n *\n * @param entityId - The entity ID\n * @param key - Content version key (e.g., \"v1\", \"original\", \"thumbnail\")\n *\n * @example\n * ```typescript\n * const { data, error } = await arke.getEntityContentAsStream('01ABC...', 'v1');\n * if (data) {\n * const reader = data.getReader();\n * // Process chunks...\n * }\n * ```\n */\n async getEntityContentAsStream(\n entityId: string,\n key?: string\n ): Promise<{ data: ReadableStream<Uint8Array> | null | undefined; error: unknown }> {\n const { data, error } = await this.api.GET('/entities/{id}/content', {\n params: { path: { id: entityId }, query: key ? { key } : {} },\n parseAs: 'stream',\n });\n return { data: data as ReadableStream<Uint8Array> | null | undefined, error };\n }\n\n /**\n * Upload content to an entity\n *\n * This is a convenience method that handles the binary body serialization\n * that openapi-fetch doesn't handle automatically for non-JSON bodies.\n *\n * @param entityId - The entity ID\n * @param key - Content version key (e.g., \"v1\", \"original\", \"thumbnail\")\n * @param content - The content to upload\n * @param contentType - MIME type of the content\n * @param filename - Optional filename for Content-Disposition header on download\n *\n * @example\n * ```typescript\n * // Upload from a Blob\n * const blob = new Blob(['Hello, world!'], { type: 'text/plain' });\n * const { data, error } = await arke.uploadEntityContent('01ABC...', 'v1', blob, 'text/plain');\n *\n * // Upload from an ArrayBuffer\n * const buffer = new TextEncoder().encode('Hello, world!').buffer;\n * const { data, error } = await arke.uploadEntityContent('01ABC...', 'v1', buffer, 'text/plain');\n *\n * // Upload from a Uint8Array with filename\n * const bytes = new TextEncoder().encode('Hello, world!');\n * const { data, error } = await arke.uploadEntityContent('01ABC...', 'v1', bytes, 'text/plain', 'hello.txt');\n * ```\n */\n async uploadEntityContent(\n entityId: string,\n key: string,\n content: Blob | ArrayBuffer | Uint8Array,\n contentType: string,\n filename?: string\n ): Promise<{\n data: components['schemas']['UploadContentResponse'] | undefined;\n error: unknown;\n }> {\n // Convert to Blob if needed\n let body: Blob;\n if (content instanceof Blob) {\n body = content;\n } else if (content instanceof Uint8Array) {\n // Copy to a new ArrayBuffer to handle SharedArrayBuffer compatibility\n const buffer = new ArrayBuffer(content.byteLength);\n new Uint8Array(buffer).set(content);\n body = new Blob([buffer], { type: contentType });\n } else {\n // ArrayBuffer\n body = new Blob([content], { type: contentType });\n }\n\n const { data, error } = await this.api.POST('/entities/{id}/content', {\n params: { path: { id: entityId }, query: { key, filename } },\n body: body as unknown as Record<string, never>,\n bodySerializer: (b: unknown) => b as BodyInit,\n headers: { 'Content-Type': contentType },\n } as Parameters<typeof this.api.POST>[1]);\n\n return { data: data as components['schemas']['UploadContentResponse'] | undefined, error };\n }\n}\n\n/**\n * Create a new ArkeClient instance\n * Convenience function for those who prefer functional style\n */\nexport function createArkeClient(config?: ArkeClientConfig): ArkeClient {\n return new ArkeClient(config);\n}\n\n// Re-export types and errors\nexport type { ArkeClientConfig, RetryConfig } from './config.js';\nexport * from './errors.js';\n","/**\n * SDK configuration types\n */\n\nimport type { RetryConfig } from './retry.js';\n\nexport type { RetryConfig } from './retry.js';\n\nexport interface ArkeClientConfig {\n /**\n * Base URL for the Arke API\n * @default 'https://api.arke.institute'\n */\n baseUrl?: string;\n\n /**\n * Authentication token - accepts either:\n * - JWT token from Supabase auth (sent as Bearer)\n * - Agent API key with 'ak_' prefix (sent as ApiKey)\n * - User API key with 'uk_' prefix (sent as ApiKey)\n *\n * The correct Authorization header format is auto-detected from the token prefix.\n */\n authToken?: string;\n\n /**\n * Network to use ('main' or 'test')\n * Test network uses 'II' prefixed IDs and isolated data\n * @default 'main'\n */\n network?: 'main' | 'test';\n\n /**\n * Callback to refresh auth token when expired\n * Called automatically on 401 responses\n */\n onTokenRefresh?: () => Promise<string>;\n\n /**\n * Custom headers to include in all requests\n */\n headers?: Record<string, string>;\n\n /**\n * Retry configuration for transient errors\n *\n * Set to `false` to disable retries entirely.\n * If not specified, uses default retry behavior (3 retries with exponential backoff).\n *\n * CAS conflicts (409) are never retried - they are returned immediately.\n *\n * @example\n * ```typescript\n * const arke = new ArkeClient({\n * authToken: 'ak_...',\n * retry: {\n * maxRetries: 5,\n * initialDelay: 200,\n * onRetry: (attempt, error, delay) => {\n * console.log(`Retry ${attempt} after ${delay}ms`);\n * }\n * }\n * });\n * ```\n */\n retry?: RetryConfig | false;\n}\n\nexport const DEFAULT_CONFIG: Required<Pick<ArkeClientConfig, 'baseUrl' | 'network'>> = {\n baseUrl: 'https://api.arke.institute',\n network: 'main',\n};\n","/**\n * Retry logic for transient network and server errors\n */\n\n/**\n * Configuration for retry behavior\n */\nexport interface RetryConfig {\n /**\n * Maximum number of retry attempts\n * @default 3\n */\n maxRetries?: number;\n\n /**\n * Initial delay in milliseconds before first retry\n * @default 100\n */\n initialDelay?: number;\n\n /**\n * Maximum delay in milliseconds (caps exponential backoff)\n * @default 5000\n */\n maxDelay?: number;\n\n /**\n * Whether to retry on 5xx server errors\n * @default true\n */\n retryOn5xx?: boolean;\n\n /**\n * Whether to retry on network errors (connection refused, DNS, timeouts)\n * @default true\n */\n retryOnNetworkError?: boolean;\n\n /**\n * Optional callback invoked before each retry attempt\n * Useful for logging or monitoring\n */\n onRetry?: (attempt: number, error: Error, delayMs: number) => void;\n}\n\nexport const DEFAULT_RETRY_CONFIG: Required<Omit<RetryConfig, 'onRetry'>> = {\n maxRetries: 3,\n initialDelay: 100,\n maxDelay: 5000,\n retryOn5xx: true,\n retryOnNetworkError: true,\n};\n\n/**\n * HTTP status codes that should be retried\n */\nconst RETRYABLE_STATUS_CODES = new Set([\n 500, // Internal Server Error\n 502, // Bad Gateway\n 503, // Service Unavailable\n 504, // Gateway Timeout\n 520, // Cloudflare: Unknown Error\n 521, // Cloudflare: Web Server Is Down\n 522, // Cloudflare: Connection Timed Out\n 523, // Cloudflare: Origin Is Unreachable\n 524, // Cloudflare: A Timeout Occurred\n 525, // Cloudflare: SSL Handshake Failed\n 526, // Cloudflare: Invalid SSL Certificate\n 527, // Cloudflare: Railgun Error\n 530, // Cloudflare: Origin DNS Error\n]);\n\n/**\n * Status codes that should never be retried\n */\nconst NON_RETRYABLE_STATUS_CODES = new Set([\n 400, // Bad Request\n 401, // Unauthorized\n 403, // Forbidden\n 404, // Not Found\n 405, // Method Not Allowed\n 409, // Conflict (CAS errors)\n 410, // Gone\n 422, // Unprocessable Entity\n 429, // Too Many Requests (should be handled separately with rate limiting)\n]);\n\n/**\n * Check if a status code is retryable\n */\nexport function isRetryableStatus(status: number): boolean {\n if (NON_RETRYABLE_STATUS_CODES.has(status)) {\n return false;\n }\n return RETRYABLE_STATUS_CODES.has(status);\n}\n\n/**\n * Check if an error is a network error that should be retried\n */\nexport function isNetworkError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n\n // TypeError is thrown by fetch for network failures\n if (error instanceof TypeError) {\n const message = error.message.toLowerCase();\n return (\n message.includes('failed to fetch') ||\n message.includes('network') ||\n message.includes('fetch failed') ||\n message.includes('econnrefused') ||\n message.includes('econnreset') ||\n message.includes('etimedout') ||\n message.includes('enotfound') ||\n message.includes('dns') ||\n message.includes('socket')\n );\n }\n\n // Check for abort errors (timeouts)\n if (error.name === 'AbortError') {\n return true;\n }\n\n return false;\n}\n\n/**\n * Check if a response is a Cloudflare error page (HTML instead of JSON)\n */\nexport function isCloudflareErrorResponse(response: Response): boolean {\n const contentType = response.headers.get('content-type') || '';\n\n // If we expect JSON but got HTML, it's likely a Cloudflare error page\n if (contentType.includes('text/html') && !response.ok) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Calculate delay with exponential backoff and jitter\n */\nexport function calculateDelay(\n attempt: number,\n initialDelay: number,\n maxDelay: number\n): number {\n // Exponential backoff: initialDelay * 2^attempt\n const exponentialDelay = initialDelay * Math.pow(2, attempt);\n\n // Cap at maxDelay\n const cappedDelay = Math.min(exponentialDelay, maxDelay);\n\n // Add jitter (0-100% of the delay)\n const jitter = Math.random() * cappedDelay;\n\n return Math.floor(cappedDelay + jitter);\n}\n\n/**\n * Sleep for a specified number of milliseconds\n */\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Create a fetch function with retry logic\n *\n * @example\n * ```typescript\n * const retryFetch = createRetryFetch({\n * maxRetries: 3,\n * onRetry: (attempt, error, delay) => {\n * console.log(`Retry ${attempt} after ${delay}ms: ${error.message}`);\n * }\n * });\n *\n * // Use with openapi-fetch\n * const client = createClient<paths>({\n * baseUrl: 'https://api.example.com',\n * fetch: retryFetch,\n * });\n * ```\n */\nexport function createRetryFetch(config: RetryConfig = {}): typeof fetch {\n const {\n maxRetries = DEFAULT_RETRY_CONFIG.maxRetries,\n initialDelay = DEFAULT_RETRY_CONFIG.initialDelay,\n maxDelay = DEFAULT_RETRY_CONFIG.maxDelay,\n retryOn5xx = DEFAULT_RETRY_CONFIG.retryOn5xx,\n retryOnNetworkError = DEFAULT_RETRY_CONFIG.retryOnNetworkError,\n onRetry,\n } = config;\n\n return async function retryFetch(\n input: RequestInfo | URL,\n init?: RequestInit\n ): Promise<Response> {\n let lastError: Error | undefined;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n // Clone Request objects to allow retries - Request bodies can only be consumed once\n const reqInput = input instanceof Request ? input.clone() : input;\n const response = await fetch(reqInput, init);\n\n // Check for Cloudflare error pages\n if (isCloudflareErrorResponse(response) && attempt < maxRetries) {\n const error = new Error(\n `Cloudflare error (status ${response.status})`\n );\n lastError = error;\n\n const delay = calculateDelay(attempt, initialDelay, maxDelay);\n onRetry?.(attempt + 1, error, delay);\n await sleep(delay);\n continue;\n }\n\n // Check for retryable status codes\n if (retryOn5xx && isRetryableStatus(response.status) && attempt < maxRetries) {\n const error = new Error(\n `Server error (status ${response.status})`\n );\n lastError = error;\n\n const delay = calculateDelay(attempt, initialDelay, maxDelay);\n onRetry?.(attempt + 1, error, delay);\n await sleep(delay);\n continue;\n }\n\n // Success or non-retryable error\n return response;\n } catch (error) {\n // Network errors\n if (\n retryOnNetworkError &&\n isNetworkError(error) &&\n attempt < maxRetries\n ) {\n lastError = error as Error;\n\n const delay = calculateDelay(attempt, initialDelay, maxDelay);\n onRetry?.(attempt + 1, error as Error, delay);\n await sleep(delay);\n continue;\n }\n\n // Non-retryable error or exhausted retries\n throw error;\n }\n }\n\n // Exhausted all retries\n throw lastError ?? new Error('Request failed after retries');\n };\n}\n","/**\n * SDK error classes\n */\n\n/**\n * Base error class for all Arke SDK errors\n */\nexport class ArkeError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly status?: number,\n public readonly details?: unknown\n ) {\n super(message);\n this.name = 'ArkeError';\n // Maintains proper stack trace for where error was thrown\n Error.captureStackTrace?.(this, this.constructor);\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n status: this.status,\n details: this.details,\n };\n }\n}\n\n/**\n * CAS (Compare-And-Swap) conflict - entity was modified by another request\n */\nexport class CASConflictError extends ArkeError {\n constructor(\n public readonly expectedTip?: string,\n public readonly actualTip?: string\n ) {\n super(\n 'Entity was modified by another request. Refresh and retry with the current tip.',\n 'CAS_CONFLICT',\n 409,\n { expectedTip, actualTip }\n );\n this.name = 'CASConflictError';\n }\n}\n\n/**\n * Resource not found\n */\nexport class NotFoundError extends ArkeError {\n constructor(resourceType: string, id: string) {\n super(`${resourceType} not found: ${id}`, 'NOT_FOUND', 404, { resourceType, id });\n this.name = 'NotFoundError';\n }\n}\n\n/**\n * Validation error - invalid request data\n */\nexport class ValidationError extends ArkeError {\n constructor(\n message: string,\n public readonly field?: string,\n details?: unknown\n ) {\n super(message, 'VALIDATION_ERROR', 400, details ?? { field });\n this.name = 'ValidationError';\n }\n}\n\n/**\n * Authentication required or invalid\n */\nexport class AuthenticationError extends ArkeError {\n constructor(message = 'Authentication required') {\n super(message, 'AUTH_REQUIRED', 401);\n this.name = 'AuthenticationError';\n }\n}\n\n/**\n * Permission denied\n */\nexport class ForbiddenError extends ArkeError {\n constructor(action?: string, resource?: string) {\n const msg = action\n ? `Permission denied: ${action}${resource ? ` on ${resource}` : ''}`\n : 'Permission denied';\n super(msg, 'FORBIDDEN', 403, { action, resource });\n this.name = 'ForbiddenError';\n }\n}\n\n/**\n * Parse API error response into appropriate error class\n */\nexport function parseApiError(status: number, body: unknown): ArkeError {\n const errorBody = body as { error?: string; message?: string; details?: unknown } | null;\n const message = errorBody?.error ?? errorBody?.message ?? 'Unknown error';\n\n switch (status) {\n case 400:\n return new ValidationError(message, undefined, errorBody?.details);\n\n case 401:\n return new AuthenticationError(message);\n\n case 403:\n return new ForbiddenError(message);\n\n case 404:\n return new NotFoundError('Resource', 'unknown');\n\n case 409: {\n // Parse CAS conflict details if available\n const details = errorBody?.details as { expected?: string; actual?: string } | undefined;\n return new CASConflictError(details?.expected, details?.actual);\n }\n\n default:\n return new ArkeError(message, 'API_ERROR', status, errorBody?.details);\n }\n}\n","/**\n * CID Computation Utility\n *\n * Computes IPFS CIDv1 (base32) for file content.\n * Uses raw codec (0x55) and SHA-256 hash.\n *\n * Note: This module is not used internally by the upload engine (the server\n * computes CIDs from uploaded content). It is exported for convenience in case\n * you want to verify entity CIDs, detect duplicates before upload, or perform\n * other content-addressed operations.\n */\n\nimport { CID } from 'multiformats/cid';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport * as raw from 'multiformats/codecs/raw';\n\n/**\n * Compute CIDv1 for binary content.\n * Returns base32 encoded string (bafk... prefix for raw codec).\n *\n * @param data - Binary content as ArrayBuffer, Uint8Array, or Blob\n * @returns CIDv1 string in base32 encoding\n *\n * @example\n * ```typescript\n * const cid = await computeCid(new TextEncoder().encode('hello world'));\n * // Returns: \"bafkreifzjut3te2nhyekklss27nh3k72ysco7y32koao5eei66wof36n5e\"\n * ```\n */\nexport async function computeCid(data: ArrayBuffer | Uint8Array | Blob): Promise<string> {\n // Convert to Uint8Array\n let bytes: Uint8Array;\n\n if (data instanceof Blob) {\n const buffer = await data.arrayBuffer();\n bytes = new Uint8Array(buffer);\n } else if (data instanceof ArrayBuffer) {\n bytes = new Uint8Array(data);\n } else {\n bytes = data;\n }\n\n // Compute SHA-256 hash\n const hash = await sha256.digest(bytes);\n\n // Create CIDv1 with raw codec\n const cid = CID.create(1, raw.code, hash);\n\n // Return base32 encoded string\n return cid.toString();\n}\n\n/**\n * Verify a CID matches the content.\n *\n * @param data - Binary content\n * @param expectedCid - CID to verify against\n * @returns true if CID matches\n */\nexport async function verifyCid(\n data: ArrayBuffer | Uint8Array | Blob,\n expectedCid: string\n): Promise<boolean> {\n const computed = await computeCid(data);\n return computed === expectedCid;\n}\n","/**\n * Upload Engine\n *\n * Core upload implementation optimized for fast tree visibility:\n * 1. Create folders by depth (with unidirectional 'in' → parent)\n * 2. Create file entities (metadata only, high parallelism)\n * 3. Backlink parents with 'contains' relationships\n * → Tree is now browsable! Users can explore structure immediately.\n * 4. Upload file content via POST /files/{id}/content (byte-based pool, ~200MB in flight)\n * - Direct upload to API endpoint\n * - API streams to R2, computes CID, updates entity atomically\n *\n * Byte-based pool (for uploads):\n * - Maintains ~200MB of data in flight at all times\n * - When a file completes, next file starts immediately (no gaps)\n * - Small files: Many upload in parallel\n * - Large files: Fewer upload in parallel (bandwidth-limited)\n * - Single file > 200MB: Uploads alone when pool is empty\n *\n * This minimizes time-to-browse by:\n * - Creating all entities before uploading content\n * - Using unidirectional 'in' relationship on entity creation\n * - Adding all 'contains' relationships in a single PUT per parent\n */\n\nimport type { ArkeClient } from '../../client/ArkeClient.js';\nimport { getAuthorizationHeader } from '../../client/ArkeClient.js';\nimport type { components } from '../../generated/types.js';\nimport { computeCid } from './cid.js';\nimport type {\n UploadTree,\n UploadOptions,\n UploadResult,\n UploadProgress,\n CreatedFolder,\n CreatedFile,\n CreatedEntity,\n UploadFolder,\n} from './types.js';\n\ntype CreateCollectionRequest = components['schemas']['CreateCollectionRequest'];\ntype CreateEntityRequest = components['schemas']['CreateEntityRequest'];\ntype UpdateEntityRequest = components['schemas']['UpdateEntityRequest'];\ntype UpdateCollectionRequest = components['schemas']['UpdateCollectionRequest'];\n\n// Phase constants\nconst PHASE_COUNT = 3; // creating, backlinking, uploading (excluding complete/error)\nconst PHASE_INDEX: Record<string, number> = {\n creating: 0,\n backlinking: 1,\n uploading: 2,\n complete: 3,\n error: -1,\n};\n\n// Batch creation constants\nconst BATCH_SIZE = 100; // Entities per batch request\nconst BATCH_CONCURRENCY = 25; // Concurrent batch requests\nconst BACKLINK_CONCURRENCY = 100; // Concurrent backlink PUTs\nconst MAX_UPLOAD_CONCURRENCY = 500; // Max concurrent upload requests\n\n// =============================================================================\n// Concurrency Utilities\n// =============================================================================\n\n/**\n * Simple concurrency limiter for parallel operations.\n */\nasync function parallelLimit<T, R>(\n items: T[],\n concurrency: number,\n fn: (item: T, index: number) => Promise<R>\n): Promise<R[]> {\n const results: R[] = [];\n let index = 0;\n\n async function worker(): Promise<void> {\n while (index < items.length) {\n const currentIndex = index++;\n const item = items[currentIndex]!;\n results[currentIndex] = await fn(item, currentIndex);\n }\n }\n\n const workers = Array.from({ length: Math.min(concurrency, items.length) }, () => worker());\n await Promise.all(workers);\n\n return results;\n}\n\n/**\n * Split array into chunks of specified size.\n */\nfunction chunk<T>(array: T[], size: number): T[][] {\n const chunks: T[][] = [];\n for (let i = 0; i < array.length; i += size) {\n chunks.push(array.slice(i, i + size));\n }\n return chunks;\n}\n\n// =============================================================================\n// Byte-Based Pool\n// =============================================================================\n\n/** Target bytes in flight (~200MB) */\nconst TARGET_BYTES_IN_FLIGHT = 200 * 1024 * 1024;\n\n/** Threshold for using presigned URLs (5MB) - larger files bypass API worker */\nconst PRESIGNED_URL_THRESHOLD = 5 * 1024 * 1024;\n\n/**\n * Pool that maintains a target number of bytes in flight AND limits concurrent requests.\n *\n * When a file completes, its bytes are released and the next\n * waiting file can start immediately. This keeps the pipeline full.\n *\n * - Small files: Many run in parallel (up to ~200MB worth or maxConcurrent)\n * - Large files: Fewer run in parallel\n * - Single file > 200MB: Runs alone (allowed when pool is empty)\n */\nclass BytePool {\n private bytesInFlight = 0;\n private activeCount = 0;\n private waitQueue: Array<() => void> = [];\n\n constructor(\n private targetBytes: number = TARGET_BYTES_IN_FLIGHT,\n private maxConcurrent: number = MAX_UPLOAD_CONCURRENCY\n ) {}\n\n async run<T>(size: number, fn: () => Promise<T>): Promise<T> {\n // Wait until we have room for BOTH bytes AND request count\n // Exception: if pool is empty, always allow (handles files > targetBytes)\n while (\n (this.bytesInFlight > 0 && this.bytesInFlight + size > this.targetBytes) ||\n this.activeCount >= this.maxConcurrent\n ) {\n await new Promise<void>((resolve) => this.waitQueue.push(resolve));\n }\n\n this.bytesInFlight += size;\n this.activeCount++;\n try {\n return await fn();\n } finally {\n this.bytesInFlight -= size;\n this.activeCount--;\n // Wake ALL waiting tasks so they can re-evaluate the condition.\n // wake-one is incorrect here: if a large file finishes, multiple\n // smaller files may now fit but only the first waiter would check.\n const queue = this.waitQueue.splice(0);\n for (const resolve of queue) resolve();\n }\n }\n}\n\n// =============================================================================\n// Helper Functions\n// =============================================================================\n\n/**\n * Parse folder path to get parent path.\n * e.g., \"docs/images/photos\" -> \"docs/images\"\n */\nfunction getParentPath(relativePath: string): string | null {\n const lastSlash = relativePath.lastIndexOf('/');\n if (lastSlash === -1) return null;\n return relativePath.slice(0, lastSlash);\n}\n\n/**\n * Group folders by depth level.\n */\nfunction groupFoldersByDepth(folders: UploadFolder[]): Map<number, UploadFolder[]> {\n const byDepth = new Map<number, UploadFolder[]>();\n\n for (const folder of folders) {\n const depth = folder.relativePath.split('/').length - 1;\n if (!byDepth.has(depth)) byDepth.set(depth, []);\n byDepth.get(depth)!.push(folder);\n }\n\n return byDepth;\n}\n\n// =============================================================================\n// Main Upload Function\n// =============================================================================\n\n/**\n * Main upload function.\n * Orchestrates the entire upload process with optimized relationship strategy.\n */\nexport async function uploadTree(\n client: ArkeClient,\n tree: UploadTree,\n options: UploadOptions\n): Promise<UploadResult> {\n const { target, onProgress, concurrency = 10, continueOnError = false, maxBytesInFlight, note } = options;\n\n const errors: Array<{ path: string; error: string }> = [];\n const createdFolders: CreatedFolder[] = [];\n const createdFiles: CreatedFile[] = [];\n\n // Maps for tracking (include label for peer_label in relationships)\n const foldersByPath = new Map<string, { id: string; cid: string; label: string }>();\n\n // Calculate totals\n const totalEntities = tree.files.length + tree.folders.length;\n const totalBytes = tree.files.reduce((sum, f) => sum + f.size, 0);\n let completedEntities = 0;\n let bytesUploaded = 0;\n\n // Helper to report progress\n const reportProgress = (progress: Partial<UploadProgress>) => {\n if (onProgress) {\n const phase = progress.phase || 'creating';\n const phaseIndex = PHASE_INDEX[phase] ?? -1;\n\n // Calculate phase percent based on current phase\n let phasePercent = 0;\n if (phase === 'creating') {\n // Creating phase: progress is based on entities created\n const done = progress.completedEntities ?? completedEntities;\n phasePercent = totalEntities > 0 ? Math.round((done / totalEntities) * 100) : 100;\n } else if (phase === 'backlinking') {\n // Backlinking phase: progress is based on parents updated\n const done = progress.completedParents ?? 0;\n const total = progress.totalParents ?? 0;\n phasePercent = total > 0 ? Math.round((done / total) * 100) : 100;\n } else if (phase === 'uploading') {\n // Uploading phase: progress is based on bytes uploaded\n const done = progress.bytesUploaded ?? bytesUploaded;\n phasePercent = totalBytes > 0 ? Math.round((done / totalBytes) * 100) : 100;\n } else if (phase === 'complete') {\n phasePercent = 100;\n }\n\n onProgress({\n phase,\n phaseIndex,\n phaseCount: PHASE_COUNT,\n phasePercent,\n totalEntities,\n completedEntities,\n totalParents: 0,\n completedParents: 0,\n totalBytes,\n bytesUploaded,\n ...progress,\n } as UploadProgress);\n }\n };\n\n try {\n // ─────────────────────────────────────────────────────────────────────────\n // SETUP: Resolve or create collection\n // ─────────────────────────────────────────────────────────────────────────\n let collectionId: string;\n let collectionCid: string;\n let collectionLabel: string;\n let collectionCreated = false;\n\n if (target.createCollection) {\n const collectionBody: CreateCollectionRequest = {\n label: target.createCollection.label,\n description: target.createCollection.description,\n roles: target.createCollection.roles,\n note,\n };\n\n const { data, error } = await client.api.POST('/collections', {\n body: collectionBody,\n });\n\n if (error || !data) {\n throw new Error(`Failed to create collection: ${JSON.stringify(error)}`);\n }\n\n collectionId = data.id;\n collectionCid = data.cid;\n collectionLabel = target.createCollection.label;\n collectionCreated = true;\n } else if (target.collectionId) {\n collectionId = target.collectionId;\n\n const { data, error } = await client.api.GET('/collections/{id}', {\n params: { path: { id: collectionId } },\n });\n\n if (error || !data) {\n throw new Error(`Failed to fetch collection: ${JSON.stringify(error)}`);\n }\n\n collectionCid = data.cid;\n collectionLabel = (data.properties?.label as string) ?? collectionId;\n } else {\n throw new Error('Must provide either collectionId or createCollection in target');\n }\n\n // Determine the parent for root-level items\n const rootParentId = target.parentId ?? collectionId;\n let rootParentLabel = collectionLabel;\n let rootParentType: 'collection' | 'folder' = 'collection';\n\n // If a specific parent folder is provided, fetch its label\n if (target.parentId && target.parentId !== collectionId) {\n const { data: parentData, error: parentError } = await client.api.GET('/entities/{id}', {\n params: { path: { id: target.parentId } },\n });\n if (parentError || !parentData) {\n throw new Error(`Failed to fetch parent folder: ${JSON.stringify(parentError)}`);\n }\n rootParentLabel = (parentData.properties?.label as string) ?? target.parentId;\n rootParentType = 'folder';\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // PHASE 1: Create entities (folders by depth, then files)\n // ─────────────────────────────────────────────────────────────────────────\n reportProgress({ phase: 'creating', completedEntities: 0 });\n\n // Group folders by depth\n const foldersByDepth = groupFoldersByDepth(tree.folders);\n const sortedDepths = [...foldersByDepth.keys()].sort((a, b) => a - b);\n\n // Create folders depth by depth (parents before children) using batch endpoint\n for (const depth of sortedDepths) {\n const foldersAtDepth = foldersByDepth.get(depth)!;\n\n // Build batch items for all folders at this depth\n const batchItems = foldersAtDepth.map((folder) => {\n const parentPath = getParentPath(folder.relativePath);\n const parentInfo = parentPath ? foldersByPath.get(parentPath)! : null;\n const parentId = parentInfo ? parentInfo.id : rootParentId;\n const parentType = parentInfo ? 'folder' : rootParentType;\n const parentLabel = parentInfo ? parentInfo.label : rootParentLabel;\n\n return {\n folder, // Track for result processing\n entity: {\n type: 'folder',\n properties: { label: folder.name },\n note,\n relationships: [{ predicate: 'in', peer: parentId, peer_type: parentType, peer_label: parentLabel }],\n },\n };\n });\n\n // Chunk into batches of BATCH_SIZE and create in parallel\n const batches = chunk(batchItems, BATCH_SIZE);\n\n await parallelLimit(batches, BATCH_CONCURRENCY, async (batch) => {\n const { data, error } = await client.api.POST('/entities/batch', {\n params: { query: { validate_relationships: 'false' } },\n body: {\n default_collection: collectionId,\n entities: batch.map((item) => item.entity),\n },\n });\n\n if (error || !data) {\n throw new Error(`Batch folder creation failed: ${JSON.stringify(error)}`);\n }\n\n // Process results - map back to folders by index\n for (const result of data.results) {\n const batchItem = batch[result.index];\n if (!batchItem) continue;\n const folder = batchItem.folder;\n\n if (result.success) {\n // Track folder (include label for peer_label in child relationships)\n foldersByPath.set(folder.relativePath, {\n id: result.id,\n cid: result.cid,\n label: folder.name,\n });\n createdFolders.push({\n name: folder.name,\n relativePath: folder.relativePath,\n id: result.id,\n entityCid: result.cid,\n });\n completedEntities++;\n } else {\n // BatchCreateFailure\n const errorMsg = result.error;\n if (continueOnError) {\n errors.push({ path: folder.relativePath, error: `Folder creation failed: ${errorMsg}` });\n completedEntities++;\n } else {\n throw new Error(`Failed to create folder ${folder.relativePath}: ${errorMsg}`);\n }\n }\n }\n\n reportProgress({ phase: 'creating', completedEntities });\n });\n }\n\n // Create file entities (metadata only, no content upload yet) using batch endpoint\n // Build batch items for all files\n const fileBatchItems = tree.files.map((file) => {\n const parentPath = getParentPath(file.relativePath);\n const parentInfo = parentPath ? foldersByPath.get(parentPath)! : null;\n const parentId = parentInfo ? parentInfo.id : rootParentId;\n const parentType = parentInfo ? 'folder' : rootParentType;\n const parentLabel = parentInfo ? parentInfo.label : rootParentLabel;\n\n return {\n file, // Track for result processing\n entity: {\n type: 'file',\n properties: {\n label: file.name,\n filename: file.name,\n content_type: file.mimeType,\n size: file.size,\n },\n note,\n relationships: [{ predicate: 'in', peer: parentId, peer_type: parentType, peer_label: parentLabel }],\n },\n };\n });\n\n // Chunk into batches of BATCH_SIZE and create in parallel\n const fileBatches = chunk(fileBatchItems, BATCH_SIZE);\n\n await parallelLimit(fileBatches, BATCH_CONCURRENCY, async (batch) => {\n const { data, error } = await client.api.POST('/entities/batch', {\n params: { query: { validate_relationships: 'false' } },\n body: {\n default_collection: collectionId,\n entities: batch.map((item) => item.entity),\n },\n });\n\n if (error || !data) {\n throw new Error(`Batch file creation failed: ${JSON.stringify(error)}`);\n }\n\n // Process results - map back to files by index\n for (const result of data.results) {\n const batchItem = batch[result.index];\n if (!batchItem) continue;\n const file = batchItem.file;\n\n if (result.success) {\n // Track file for later upload\n createdFiles.push({\n ...file,\n id: result.id,\n entityCid: result.cid,\n });\n completedEntities++;\n } else {\n // BatchCreateFailure\n const errorMsg = result.error;\n if (continueOnError) {\n errors.push({ path: file.relativePath, error: errorMsg });\n completedEntities++;\n } else {\n throw new Error(`Failed to create file ${file.relativePath}: ${errorMsg}`);\n }\n }\n }\n\n reportProgress({ phase: 'creating', completedEntities });\n });\n\n // ─────────────────────────────────────────────────────────────────────────\n // PHASE 2: Backlink - Update each parent with 'contains' relationships\n // Uses cached CIDs to avoid GETs, with retry on 409 conflict\n // ─────────────────────────────────────────────────────────────────────────\n\n // Build parent -> children map (include label for peer_label)\n const childrenByParent = new Map<string, Array<{ id: string; type: 'file' | 'folder'; label: string }>>();\n\n // Add folders as children of their parents\n for (const folder of createdFolders) {\n const parentPath = getParentPath(folder.relativePath);\n const parentId = parentPath ? foldersByPath.get(parentPath)!.id : rootParentId;\n\n if (!childrenByParent.has(parentId)) childrenByParent.set(parentId, []);\n childrenByParent.get(parentId)!.push({ id: folder.id, type: 'folder', label: folder.name });\n }\n\n // Add files as children of their parents\n for (const file of createdFiles) {\n const parentPath = getParentPath(file.relativePath);\n const parentId = parentPath ? foldersByPath.get(parentPath)!.id : rootParentId;\n\n if (!childrenByParent.has(parentId)) childrenByParent.set(parentId, []);\n childrenByParent.get(parentId)!.push({ id: file.id, type: 'file', label: file.name });\n }\n\n const totalParents = childrenByParent.size;\n let completedParents = 0;\n\n reportProgress({ phase: 'backlinking', totalParents, completedParents: 0 });\n\n // Update all parents in parallel - each parent gets one PUT with all its children\n // Use cached CIDs from creation phase, only fetch fresh on 409 conflict\n const parentEntries = [...childrenByParent.entries()];\n\n await parallelLimit(parentEntries, BACKLINK_CONCURRENCY, async ([parentId, children]) => {\n try {\n const isCollection = parentId === collectionId;\n\n // Build relationships_add array with all children (include peer_label for display)\n const relationshipsAdd = children.map((child) => ({\n predicate: 'contains' as const,\n peer: child.id,\n peer_type: child.type,\n peer_label: child.label,\n }));\n\n // Get cached CID - no GET required for entities we created\n let expectTip: string;\n if (isCollection) {\n expectTip = collectionCid; // From setup phase\n } else {\n // Check if it's a folder we created (have cached CID)\n const folderInfo = [...foldersByPath.values()].find((f) => f.id === parentId);\n if (folderInfo) {\n expectTip = folderInfo.cid;\n } else {\n // Root parent provided by user - need to fetch tip\n const { data: tipData, error: tipError } = await client.api.GET('/entities/{id}/tip', {\n params: { path: { id: parentId } },\n });\n if (tipError || !tipData) {\n throw new Error(`Failed to get tip: ${JSON.stringify(tipError)}`);\n }\n expectTip = tipData.cid;\n }\n }\n\n // Attempt PUT with cached CID, retry once on 409 conflict\n // Skip relationship validation - we just created these entities\n const attemptPut = async (tip: string, isRetry: boolean): Promise<void> => {\n if (isCollection) {\n const { error, response } = await client.api.PUT('/collections/{id}', {\n params: { path: { id: parentId }, query: { validate_relationships: 'false' } },\n body: {\n expect_tip: tip,\n relationships_add: relationshipsAdd,\n note: note ? `${note} (backlink${isRetry ? ' retry' : ''})` : `Upload backlink${isRetry ? ' retry' : ''}`,\n },\n });\n\n if (error) {\n // Check for CAS conflict (409) - retry with fresh tip\n if (response?.status === 409 && !isRetry) {\n const { data: freshData } = await client.api.GET('/collections/{id}', {\n params: { path: { id: parentId } },\n });\n if (!freshData) throw new Error('Failed to get fresh collection tip');\n return attemptPut(freshData.cid, true);\n }\n throw new Error(JSON.stringify(error));\n }\n } else {\n const { error, response } = await client.api.PUT('/entities/{id}', {\n params: { path: { id: parentId }, query: { validate_relationships: 'false' } },\n body: {\n expect_tip: tip,\n relationships_add: relationshipsAdd,\n note: note ? `${note} (backlink${isRetry ? ' retry' : ''})` : `Upload backlink${isRetry ? ' retry' : ''}`,\n },\n });\n\n if (error) {\n // Check for CAS conflict (409) - retry with fresh tip via fast /tip endpoint\n if (response?.status === 409 && !isRetry) {\n const { data: freshTip, error: tipError } = await client.api.GET('/entities/{id}/tip', {\n params: { path: { id: parentId } },\n });\n if (tipError || !freshTip) throw new Error(`Failed to get fresh tip: ${JSON.stringify(tipError)}`);\n return attemptPut(freshTip.cid, true);\n }\n throw new Error(JSON.stringify(error));\n }\n }\n };\n\n await attemptPut(expectTip, false);\n\n completedParents++;\n reportProgress({\n phase: 'backlinking',\n totalParents,\n completedParents,\n currentItem: `parent:${parentId}`,\n });\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n if (continueOnError) {\n errors.push({ path: `parent:${parentId}`, error: `Backlink failed: ${errorMsg}` });\n completedParents++;\n } else {\n throw new Error(`Failed to backlink parent ${parentId}: ${errorMsg}`);\n }\n }\n });\n\n // ─────────────────────────────────────────────────────────────────────────\n // PHASE 3: Upload file content\n // Tree is now browsable! Users can explore while content uploads.\n //\n // Two paths based on file size:\n // - Small files (<5MB): Direct upload through API (simple, CID computed server-side)\n // - Large files (>=5MB): Presigned URL to R2 (fast, CID computed client-side)\n // ─────────────────────────────────────────────────────────────────────────\n reportProgress({ phase: 'uploading', bytesUploaded: 0 });\n\n // Use byte-based pool to maintain target bytes in flight\n const pool = new BytePool(maxBytesInFlight);\n\n await Promise.all(\n createdFiles.map(async (file) => {\n await pool.run(file.size, async () => {\n try {\n // Get file data\n const fileData = await file.getData();\n\n let body: Blob;\n if (fileData instanceof Blob) {\n body = fileData;\n } else if (fileData instanceof Uint8Array) {\n const arrayBuffer = new ArrayBuffer(fileData.byteLength);\n new Uint8Array(arrayBuffer).set(fileData);\n body = new Blob([arrayBuffer], { type: file.mimeType });\n } else {\n body = new Blob([fileData], { type: file.mimeType });\n }\n\n if (file.size >= PRESIGNED_URL_THRESHOLD) {\n // ─────────────────────────────────────────────────────────────\n // LARGE FILE: Presigned URL flow (bypasses API worker)\n // ─────────────────────────────────────────────────────────────\n\n // 1. Compute CID client-side\n const fileCid = await computeCid(fileData);\n\n // 2. Get presigned URL from API\n const { data: urlData, error: urlError } = await client.api.POST(\n '/entities/{id}/content/upload-url',\n {\n params: { path: { id: file.id } },\n body: {\n content_type: file.mimeType,\n size: file.size,\n key: 'v1',\n },\n }\n );\n\n if (urlError || !urlData) {\n throw new Error(`Failed to get presigned URL: ${JSON.stringify(urlError)}`);\n }\n\n // 3. PUT directly to R2 (fast!)\n const r2Response = await fetch(urlData.upload_url, {\n method: 'PUT',\n headers: { 'Content-Type': file.mimeType },\n body: body,\n });\n\n if (!r2Response.ok) {\n const errorText = await r2Response.text();\n throw new Error(`R2 upload failed: ${r2Response.status} ${errorText}`);\n }\n\n // 4. Complete upload by updating entity metadata\n const { error: completeError } = await client.api.POST(\n '/entities/{id}/content/complete',\n {\n params: { path: { id: file.id } },\n body: {\n key: 'v1',\n cid: fileCid,\n size: file.size,\n content_type: file.mimeType,\n filename: file.name,\n expect_tip: file.entityCid,\n },\n }\n );\n\n if (completeError) {\n throw new Error(`Failed to complete upload: ${JSON.stringify(completeError)}`);\n }\n } else {\n // ─────────────────────────────────────────────────────────────\n // SMALL FILE: Direct upload through API\n // ─────────────────────────────────────────────────────────────\n\n const { error: uploadError } = await client.api.POST('/entities/{id}/content', {\n params: { path: { id: file.id }, query: { key: 'v1', filename: file.name } },\n body: body as unknown as Record<string, never>,\n bodySerializer: (b: unknown) => b as BodyInit,\n headers: { 'Content-Type': file.mimeType },\n } as Parameters<typeof client.api.POST>[1]);\n\n if (uploadError) {\n throw new Error(`Upload failed: ${JSON.stringify(uploadError)}`);\n }\n }\n\n bytesUploaded += file.size;\n reportProgress({\n phase: 'uploading',\n bytesUploaded,\n currentItem: file.relativePath,\n });\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n if (continueOnError) {\n errors.push({ path: file.relativePath, error: `Upload failed: ${errorMsg}` });\n } else {\n throw new Error(`Failed to upload ${file.relativePath}: ${errorMsg}`);\n }\n }\n });\n })\n );\n\n // ─────────────────────────────────────────────────────────────────────────\n // Complete!\n // ─────────────────────────────────────────────────────────────────────────\n reportProgress({ phase: 'complete', totalParents, completedParents, bytesUploaded });\n\n const resultFolders: CreatedEntity[] = createdFolders.map((f) => ({\n id: f.id,\n cid: f.entityCid,\n type: 'folder' as const,\n relativePath: f.relativePath,\n }));\n\n const resultFiles: CreatedEntity[] = createdFiles.map((f) => ({\n id: f.id,\n cid: f.entityCid,\n type: 'file' as const,\n relativePath: f.relativePath,\n }));\n\n return {\n success: errors.length === 0,\n collection: {\n id: collectionId,\n cid: collectionCid,\n created: collectionCreated,\n },\n folders: resultFolders,\n files: resultFiles,\n errors,\n };\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n\n reportProgress({\n phase: 'error',\n error: errorMsg,\n });\n\n return {\n success: false,\n collection: {\n id: target.collectionId ?? '',\n cid: '',\n created: false,\n },\n folders: createdFolders.map((f) => ({\n id: f.id,\n cid: f.entityCid,\n type: 'folder' as const,\n relativePath: f.relativePath,\n })),\n files: createdFiles.map((f) => ({\n id: f.id,\n cid: f.entityCid,\n type: 'file' as const,\n relativePath: f.relativePath,\n })),\n errors: [...errors, { path: '', error: errorMsg }],\n };\n }\n}\n","/**\n * Folder Operations (Legacy)\n *\n * @deprecated Use the new upload module instead:\n * ```typescript\n * import { uploadTree, buildUploadTree } from '@arke-institute/sdk/operations';\n *\n * const tree = buildUploadTree([\n * { path: 'docs/readme.md', data: readmeBuffer },\n * { path: 'images/logo.png', data: logoBlob },\n * ]);\n * const result = await uploadTree(client, tree, {\n * target: { collectionId: '...' },\n * });\n * ```\n */\n\nimport type { ArkeClient } from '../client/ArkeClient.js';\n\n/**\n * @deprecated Use UploadProgress from upload module\n */\nexport interface UploadProgress {\n phase: 'scanning' | 'creating-folders' | 'uploading-files' | 'linking' | 'complete';\n totalFiles: number;\n completedFiles: number;\n totalFolders: number;\n completedFolders: number;\n currentFile?: string;\n}\n\n/**\n * @deprecated Use UploadOptions from upload module\n */\nexport interface UploadDirectoryOptions {\n /** Collection to upload into */\n collectionId: string;\n /** Parent folder ID (optional - creates at root if not provided) */\n parentFolderId?: string;\n /** Progress callback */\n onProgress?: (progress: UploadProgress) => void;\n /** Max concurrent uploads */\n concurrency?: number;\n}\n\n/**\n * @deprecated Use UploadResult from upload module\n */\nexport interface UploadDirectoryResult {\n /** Root folder entity */\n rootFolder: unknown;\n /** All created folder entities */\n folders: unknown[];\n /** All created file entities */\n files: unknown[];\n}\n\n/**\n * Folder operations helper\n *\n * @deprecated Use uploadTree and buildUploadTree functions instead:\n * ```typescript\n * import { uploadTree, buildUploadTree } from '@arke-institute/sdk/operations';\n *\n * const tree = buildUploadTree([\n * { path: 'docs/readme.md', data: readmeBuffer },\n * ]);\n * const result = await uploadTree(client, tree, {\n * target: { collectionId: '...' },\n * });\n * ```\n */\nexport class FolderOperations {\n constructor(private client: ArkeClient) {\n void client; // Suppress unused warning\n }\n\n /**\n * Upload a local directory to Arke\n *\n * @deprecated This method has been removed. Use uploadTree and buildUploadTree instead.\n */\n async uploadDirectory(\n _localPath: string,\n _options: UploadDirectoryOptions\n ): Promise<UploadDirectoryResult> {\n throw new Error(\n 'FolderOperations.uploadDirectory has been removed. ' +\n 'Use uploadTree() with buildUploadTree() instead. ' +\n 'See: https://github.com/arke-institute/arke-sdk#upload-module'\n );\n }\n}\n","/**\n * Batch Operations\n *\n * High-level operations for bulk entity and relationship management.\n *\n * TODO: Implement batch operations\n * - createEntities: Create multiple entities in parallel\n * - updateEntities: Update multiple entities in parallel\n * - createRelationships: Create multiple relationships in parallel\n */\n\nimport type { ArkeClient } from '../client/ArkeClient.js';\n\nexport interface BatchCreateOptions {\n /** Max concurrent operations */\n concurrency?: number;\n /** Continue on individual failures */\n continueOnError?: boolean;\n /** Progress callback */\n onProgress?: (completed: number, total: number) => void;\n}\n\nexport interface BatchResult<T> {\n /** Successfully completed operations */\n succeeded: T[];\n /** Failed operations with errors */\n failed: Array<{ input: unknown; error: Error }>;\n}\n\n/**\n * Batch operations helper\n *\n * @example\n * ```typescript\n * const batch = new BatchOperations(arkeClient);\n * const result = await batch.createEntities([\n * { type: 'document', properties: { title: 'Doc 1' } },\n * { type: 'document', properties: { title: 'Doc 2' } },\n * ], { concurrency: 5 });\n * ```\n */\nexport class BatchOperations {\n constructor(private client: ArkeClient) {}\n\n /**\n * Create multiple entities in parallel\n *\n * TODO: Implement this method\n */\n async createEntities(\n _entities: Array<{\n collectionId: string;\n type: string;\n properties?: Record<string, unknown>;\n }>,\n _options?: BatchCreateOptions\n ): Promise<BatchResult<unknown>> {\n throw new Error('BatchOperations.createEntities is not yet implemented');\n }\n\n /**\n * Create multiple relationships in parallel\n *\n * TODO: Implement this method\n */\n async createRelationships(\n _relationships: Array<{\n sourceId: string;\n targetId: string;\n predicate: string;\n bidirectional?: boolean;\n properties?: Record<string, unknown>;\n }>,\n _options?: BatchCreateOptions\n ): Promise<BatchResult<unknown>> {\n throw new Error('BatchOperations.createRelationships is not yet implemented');\n }\n}\n","/**\n * Crypto Operations\n *\n * Cryptographic utilities for agents and content addressing.\n *\n * TODO: Implement crypto operations\n * - generateKeyPair: Generate Ed25519 key pair for agent authentication\n * - signPayload: Sign a payload with agent private key\n * - computeCID: Compute IPFS CID for content\n */\n\n/**\n * Ed25519 key pair for agent authentication\n */\nexport interface KeyPair {\n /** Public key in base64 */\n publicKey: string;\n /** Private key in base64 (keep secret!) */\n privateKey: string;\n}\n\n/**\n * Signed payload with signature\n */\nexport interface SignedPayload {\n /** Original payload */\n payload: string;\n /** Ed25519 signature in base64 */\n signature: string;\n /** Timestamp of signature */\n timestamp: number;\n}\n\n/**\n * Crypto operations helper\n *\n * @example\n * ```typescript\n * // Generate key pair for a new agent\n * const { publicKey, privateKey } = await CryptoOperations.generateKeyPair();\n *\n * // Sign a payload\n * const signed = await CryptoOperations.signPayload(privateKey, payload);\n * ```\n */\nexport class CryptoOperations {\n /**\n * Generate an Ed25519 key pair for agent authentication\n *\n * TODO: Implement using Node.js crypto or Web Crypto API\n */\n static async generateKeyPair(): Promise<KeyPair> {\n throw new Error('CryptoOperations.generateKeyPair is not yet implemented');\n }\n\n /**\n * Sign a payload with an Ed25519 private key\n *\n * TODO: Implement signature generation\n */\n static async signPayload(_privateKey: string, _payload: string): Promise<SignedPayload> {\n throw new Error('CryptoOperations.signPayload is not yet implemented');\n }\n\n /**\n * Verify an Ed25519 signature\n *\n * TODO: Implement signature verification\n */\n static async verifySignature(\n _publicKey: string,\n _payload: string,\n _signature: string\n ): Promise<boolean> {\n throw new Error('CryptoOperations.verifySignature is not yet implemented');\n }\n\n /**\n * Compute IPFS CID for content\n *\n * TODO: Implement using multiformats library\n */\n static async computeCID(_content: Uint8Array): Promise<string> {\n throw new Error('CryptoOperations.computeCID is not yet implemented');\n }\n}\n","/**\n * CAS (Compare-And-Swap) retry utility for concurrent updates\n *\n * Use this for additive operations where your update doesn't depend on\n * current state - you just need the tip for CAS validation.\n */\n\nimport { CASConflictError } from '../client/errors.js';\n\n/**\n * Configuration for CAS retry behavior\n */\nexport interface CasRetryOptions {\n /**\n * Expected number of concurrent writers - affects retry timing.\n * Higher concurrency = more initial spread and more retry headroom.\n * @default 10\n */\n concurrency?: number;\n\n /**\n * Override: maximum retry attempts.\n * If not specified, calculated from concurrency.\n */\n maxAttempts?: number;\n\n /**\n * Base delay between retries in ms.\n * Actual delay grows exponentially with jitter.\n * @default 50\n */\n baseDelayMs?: number;\n\n /**\n * Maximum delay between retries in ms (caps exponential growth).\n * @default 10000\n */\n maxDelayMs?: number;\n\n /**\n * Add initial random delay before first attempt to spread concurrent requests.\n * Delay range: 0 to (concurrency * 100)ms. E.g., 500 concurrent = 0-50s spread.\n * This dramatically reduces collisions by staggering first attempts.\n * @default true\n */\n spreadInitial?: boolean;\n\n /**\n * Called before each retry attempt.\n * Useful for logging or monitoring.\n */\n onRetry?: (attempt: number, error: CASConflictError, delayMs: number) => void;\n}\n\n/**\n * Result of a successful CAS retry operation\n */\nexport interface CasRetryResult<T> {\n /** The successful response data */\n data: T;\n /** Number of attempts made (1 = succeeded first try) */\n attempts: number;\n}\n\n/**\n * Callbacks for CAS retry operation\n */\nexport interface CasRetryCallbacks<T> {\n /** Get the current tip/CID - called before each attempt */\n getTip: () => Promise<string>;\n /** Perform the update with given tip - return {data, error} like openapi-fetch */\n update: (tip: string) => Promise<{ data?: T; error?: unknown }>;\n}\n\n/**\n * Default configuration values\n */\nexport const DEFAULT_CAS_RETRY_CONFIG = {\n concurrency: 10,\n baseDelayMs: 50,\n maxDelayMs: 10000, // 10 seconds - allows more spread at high concurrency\n} as const;\n\n/**\n * Calculate max attempts from concurrency level.\n * Formula: max(5, ceil(log2(concurrency) * 4) + floor(concurrency / 100))\n *\n * The logarithmic component handles the base scaling, while the linear\n * component adds extra headroom at very high concurrency levels.\n *\n * Examples:\n * - concurrency 10 → 14 attempts\n * - concurrency 100 → 28 attempts\n * - concurrency 500 → 41 attempts\n * - concurrency 1000 → 50 attempts\n */\nexport function calculateMaxAttempts(concurrency: number): number {\n const logComponent = Math.ceil(Math.log2(Math.max(2, concurrency)) * 4);\n const linearComponent = Math.floor(concurrency / 100);\n return Math.max(5, logComponent + linearComponent);\n}\n\n/**\n * Calculate delay with exponential backoff and heavy jitter.\n * Jitter is 0-100% of the base delay to spread concurrent retries.\n *\n * Formula: min(baseDelay * 1.5^attempt + random(0, baseDelay * 1.5^attempt), maxDelay)\n */\nexport function calculateCasDelay(\n attempt: number,\n baseDelayMs: number,\n maxDelayMs: number\n): number {\n // Exponential backoff: baseDelay * 1.5^attempt\n const exponentialDelay = baseDelayMs * Math.pow(1.5, attempt);\n\n // Cap at maxDelay before adding jitter\n const cappedDelay = Math.min(exponentialDelay, maxDelayMs);\n\n // Heavy jitter: 0-100% of the delay (critical for spreading concurrent retries)\n const jitter = Math.random() * cappedDelay;\n\n return Math.floor(cappedDelay + jitter);\n}\n\n/**\n * Check if an error is a CAS conflict.\n * Handles multiple error shapes:\n * - openapi-fetch: { status: 409, ... }\n * - API error body: { error: \"CAS failure: ...\" }\n */\nexport function isCasConflictError(error: unknown): boolean {\n if (error === null || error === undefined) {\n return false;\n }\n\n if (typeof error !== 'object') {\n return false;\n }\n\n // Check for status 409 (openapi-fetch error shape)\n if ('status' in error && (error as { status: unknown }).status === 409) {\n return true;\n }\n\n // Check for error message pattern (API returns CAS failures this way)\n if ('error' in error) {\n const errorMsg = (error as { error: unknown }).error;\n if (typeof errorMsg === 'string' && errorMsg.startsWith('CAS failure:')) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Sleep for a specified duration\n */\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Error thrown when CAS retries are exhausted\n */\nexport class CasRetryExhaustedError extends Error {\n constructor(\n public readonly attempts: number,\n public readonly lastError: CASConflictError\n ) {\n super(\n `CAS update failed after ${attempts} attempts. ` +\n `Expected tip: ${lastError.expectedTip}, actual: ${lastError.actualTip}`\n );\n this.name = 'CasRetryExhaustedError';\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\n\n/**\n * Wrap a CAS update operation with automatic retry on conflicts.\n *\n * Use this for additive operations where your update doesn't depend on\n * current state - you just need the tip for CAS validation.\n *\n * @example\n * ```typescript\n * const { data, attempts } = await withCasRetry({\n * getTip: async () => {\n * const { data } = await client.api.GET('/entities/{id}/tip', {\n * params: { path: { id: entityId } }\n * });\n * return data!.cid;\n * },\n * update: async (tip) => {\n * return client.api.PUT('/entities/{id}', {\n * params: { path: { id: entityId } },\n * body: {\n * expect_tip: tip,\n * relationships_add: [{ predicate: 'contains', peer: childId }]\n * }\n * });\n * }\n * }, { concurrency: 100 });\n * ```\n *\n * @param callbacks.getTip - Function to fetch the current tip/CID\n * @param callbacks.update - Function to perform the update with the tip\n * @param options - Retry configuration\n * @returns The successful result with attempt count\n * @throws {CasRetryExhaustedError} When all retries are exhausted\n * @throws {Error} For non-CAS errors (not retried)\n */\nexport async function withCasRetry<T>(\n callbacks: CasRetryCallbacks<T>,\n options?: CasRetryOptions\n): Promise<CasRetryResult<T>> {\n const {\n concurrency = DEFAULT_CAS_RETRY_CONFIG.concurrency,\n maxAttempts: maxAttemptsOverride,\n baseDelayMs = DEFAULT_CAS_RETRY_CONFIG.baseDelayMs,\n maxDelayMs = DEFAULT_CAS_RETRY_CONFIG.maxDelayMs,\n spreadInitial = true,\n onRetry,\n } = options ?? {};\n\n const maxAttempts = maxAttemptsOverride ?? calculateMaxAttempts(concurrency);\n\n // Initial spread: random delay before first attempt to reduce initial collisions\n // Range: 0 to (concurrency * 100)ms - e.g., 500 concurrent = 0-50s spread\n // This spreads first attempts over time, dramatically reducing collisions\n if (spreadInitial && concurrency > 1) {\n const initialSpread = Math.floor(Math.random() * concurrency * 100);\n await sleep(initialSpread);\n }\n\n let lastCasError: CASConflictError | undefined;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n // Get fresh tip before each attempt\n const tip = await callbacks.getTip();\n\n // Attempt the update\n const { data, error } = await callbacks.update(tip);\n\n // Success!\n if (!error && data !== undefined) {\n return { data, attempts: attempt };\n }\n\n // Check if it's a CAS conflict\n if (isCasConflictError(error)) {\n // Parse the error details from various formats\n let expectedTip: string | undefined;\n let actualTip: string | undefined;\n\n const errorObj = error as Record<string, unknown>;\n\n // Format 1: { details: { expected, actual } }\n if (errorObj.details && typeof errorObj.details === 'object') {\n const details = errorObj.details as { expected?: string; actual?: string };\n expectedTip = details.expected;\n actualTip = details.actual;\n }\n\n // Format 2: { error: \"CAS failure: expected tip X, got Y\" }\n if (!expectedTip && typeof errorObj.error === 'string') {\n const match = errorObj.error.match(/expected tip (\\S+), got (\\S+)/);\n if (match) {\n expectedTip = match[1];\n actualTip = match[2];\n }\n }\n\n lastCasError = new CASConflictError(expectedTip, actualTip);\n\n // If we have more attempts, wait and retry\n if (attempt < maxAttempts) {\n const delay = calculateCasDelay(attempt - 1, baseDelayMs, maxDelayMs);\n onRetry?.(attempt, lastCasError, delay);\n await sleep(delay);\n continue;\n }\n } else {\n // Non-CAS error - throw immediately, don't retry\n throw new Error(\n `Update failed with non-CAS error: ${JSON.stringify(error)}`\n );\n }\n }\n\n // Exhausted all attempts\n throw new CasRetryExhaust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C,UAAM,gBAAgB,KAAK,MAAM,KAAK,OAAO,IAAI,cAAc,GAAG;AAClE,UAAMA,OAAM,aAAa;AAAA,EAC3B;AAEA,MAAI;AAEJ,WAAS,UAAU,GAAG,WAAW,aAAa,WAAW;AAEvD,UAAM,MAAM,MAAM,UAAU,OAAO;AAGnC,UAAM,EAAE,MAAM,MAAM,IAAI,MAAM,UAAU,OAAO,GAAG;AAGlD,QAAI,CAAC,SAAS,SAAS,QAAW;AAChC,aAAO,EAAE,MAAM,UAAU,QAAQ;AAAA,IACnC;AAGA,QAAI,mBAAmB,KAAK,GAAG;AAE7B,UAAI;AACJ,UAAI;AAEJ,YAAM,WAAW;AAGjB,UAAI,SAAS,WAAW,OAAO,SAAS,YAAY,UAAU;AAC5D,cAAM,UAAU,SAAS;AACzB,sBAAc,QAAQ;AACtB,oBAAY,QAAQ;AAAA,MACtB;AAGA,UAAI,CAAC,eAAe,OAAO,SAAS,UAAU,UAAU;AACtD,cAAM,QAAQ,SAAS,MAAM,MAAM,+BAA+B;AAClE,YAAI,OAAO;AACT,wBAAc,MAAM,CAAC;AACrB,sBAAY,MAAM,CAAC;AAAA,QACrB;AAAA,MACF;AAEA,qBAAe,IAAI,iBAAiB,aAAa,SAAS;AAG1D,UAAI,UAAU,aAAa;AACzB,cAAM,QAAQ,kBAAkB,UAAU,GAAG,aAAa,UAAU;AACpE,kBAAU,SAAS,cAAc,KAAK;AACtC,cAAMA,OAAM,KAAK;AACjB;AAAA,MACF;AAAA,IACF,OAAO;AAEL,YAAM,IAAI;AAAA,QACR,qCAAqC,KAAK,UAAU,KAAK,CAAC;AAAA,MAC5D;AAAA,IACF;AAAA,EACF;AAGA,QAAM,IAAI;AAAA,IACR;AAAA,IACA,gBAAgB,IAAI,iBAAiB;AAAA,EACvC;AACF;","names":["code","createClient","sleep"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/client/ArkeClient.ts","../src/client/config.ts","../src/client/retry.ts","../src/client/errors.ts","../src/operations/upload/cid.ts","../src/operations/upload/engine.ts","../src/operations/upload/single.ts","../src/operations/folders.ts","../src/operations/batch.ts","../src/operations/crypto.ts","../src/operations/cas.ts"],"sourcesContent":["/**\n * @arke-institute/sdk\n *\n * TypeScript SDK for the Arke API - auto-generated from OpenAPI spec.\n *\n * @example\n * ```typescript\n * import { ArkeClient } from '@arke-institute/sdk';\n *\n * const arke = new ArkeClient({ authToken: 'your-jwt-token' });\n *\n * // Create an entity\n * const { data, error } = await arke.api.POST('/entities', {\n * body: {\n * collection_id: '01ABC...',\n * type: 'document',\n * properties: { title: 'My Document' }\n * }\n * });\n *\n * if (error) {\n * console.error('Failed to create entity:', error);\n * } else {\n * console.log('Created entity:', data.id);\n * }\n * ```\n */\n\n// Main client\nexport {\n ArkeClient,\n createArkeClient,\n isApiKey,\n getAuthorizationHeader,\n type ArkeApiClient,\n} from './client/ArkeClient.js';\n\n// Configuration\nexport { type ArkeClientConfig, DEFAULT_CONFIG } from './client/config.js';\n\n// Errors\nexport {\n ArkeError,\n CASConflictError,\n NotFoundError,\n ValidationError,\n AuthenticationError,\n ForbiddenError,\n parseApiError,\n} from './client/errors.js';\n\n// Generated types\nexport type { paths, components, operations } from './generated/index.js';\n\n// High-level operations (TODO: implement)\nexport {\n FolderOperations,\n BatchOperations,\n CryptoOperations,\n type UploadProgress,\n type UploadDirectoryOptions,\n type UploadDirectoryResult,\n type BatchCreateOptions,\n type BatchResult,\n type KeyPair,\n type SignedPayload,\n} from './operations/index.js';\n\n// CAS retry utility\nexport {\n withCasRetry,\n calculateMaxAttempts,\n calculateCasDelay,\n isCasConflictError,\n CasRetryExhaustedError,\n DEFAULT_CAS_RETRY_CONFIG,\n type CasRetryOptions,\n type CasRetryResult,\n type CasRetryCallbacks,\n} from './operations/cas.js';\n","/**\n * Main Arke SDK Client\n *\n * Provides type-safe access to the Arke API using openapi-fetch.\n */\n\nimport createClient, { type Client } from 'openapi-fetch';\nimport type { paths, components } from '../generated/types.js';\nimport { ArkeClientConfig, DEFAULT_CONFIG } from './config.js';\nimport { createRetryFetch } from './retry.js';\n\nexport type ArkeApiClient = Client<paths>;\n\n/**\n * Check if a token is an API key (starts with 'ak_' or 'uk_')\n */\nexport function isApiKey(token: string): boolean {\n return token.startsWith('ak_') || token.startsWith('uk_');\n}\n\n/**\n * Get the appropriate Authorization header value for a token\n * - API keys (ak_*, uk_*) use: ApiKey {token}\n * - JWT tokens use: Bearer {token}\n */\nexport function getAuthorizationHeader(token: string): string {\n if (isApiKey(token)) {\n return `ApiKey ${token}`;\n }\n return `Bearer ${token}`;\n}\n\n/**\n * Type-safe client for the Arke API\n *\n * @example\n * ```typescript\n * // With JWT token\n * const arke = new ArkeClient({ authToken: 'your-jwt-token' });\n *\n * // With API key (agent or user)\n * const arke = new ArkeClient({ authToken: 'ak_your-agent-api-key' });\n * const arke = new ArkeClient({ authToken: 'uk_your-user-api-key' });\n *\n * // Create an entity\n * const { data, error } = await arke.api.POST('/entities', {\n * body: {\n * collection_id: '01ABC...',\n * type: 'document',\n * properties: { title: 'My Document' }\n * }\n * });\n *\n * // Get an entity\n * const { data } = await arke.api.GET('/entities/{id}', {\n * params: { path: { id: '01XYZ...' } }\n * });\n * ```\n */\nexport class ArkeClient {\n /**\n * The underlying openapi-fetch client with full type safety\n * Use this for all API calls: arke.api.GET, arke.api.POST, etc.\n */\n public api: ArkeApiClient;\n\n private config: ArkeClientConfig;\n\n constructor(config: ArkeClientConfig = {}) {\n this.config = {\n ...DEFAULT_CONFIG,\n ...config,\n };\n\n this.api = this.createClient();\n }\n\n private createClient(): ArkeApiClient {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...this.config.headers,\n };\n\n if (this.config.authToken) {\n headers['Authorization'] = getAuthorizationHeader(this.config.authToken);\n }\n\n if (this.config.network === 'test') {\n headers['X-Arke-Network'] = 'test';\n }\n\n // Create retry-enabled fetch if retry config is not explicitly disabled\n const customFetch =\n this.config.retry === false\n ? undefined\n : createRetryFetch(this.config.retry ?? {});\n\n return createClient<paths>({\n baseUrl: this.config.baseUrl ?? DEFAULT_CONFIG.baseUrl,\n headers,\n ...(customFetch && { fetch: customFetch }),\n });\n }\n\n /**\n * Update the authentication token\n * Recreates the underlying client with new headers\n */\n setAuthToken(token: string): void {\n this.config.authToken = token;\n this.api = this.createClient();\n }\n\n /**\n * Clear the authentication token\n */\n clearAuthToken(): void {\n this.config.authToken = undefined;\n this.api = this.createClient();\n }\n\n /**\n * Get the current configuration\n */\n getConfig(): Readonly<ArkeClientConfig> {\n return { ...this.config };\n }\n\n /**\n * Get the base URL\n */\n get baseUrl(): string {\n return this.config.baseUrl ?? DEFAULT_CONFIG.baseUrl;\n }\n\n /**\n * Check if client is authenticated\n */\n get isAuthenticated(): boolean {\n return !!this.config.authToken;\n }\n\n /**\n * Get entity content as a Blob\n *\n * This is a convenience method that handles the binary response parsing\n * that openapi-fetch doesn't handle automatically.\n *\n * @param entityId - The entity ID\n * @param key - Optional content version key (e.g., \"v1\", \"original\", \"thumbnail\"). Defaults to entity's current content key.\n *\n * @example\n * ```typescript\n * const { data, error } = await arke.getEntityContent('01ABC...');\n * // or with specific key\n * const { data, error } = await arke.getEntityContent('01ABC...', 'thumbnail');\n * if (data) {\n * const text = await data.text();\n * }\n * ```\n */\n async getEntityContent(\n entityId: string,\n key?: string\n ): Promise<{ data: Blob | undefined; error: unknown }> {\n const { data, error } = await this.api.GET('/entities/{id}/content', {\n params: { path: { id: entityId }, query: key ? { key } : {} },\n parseAs: 'blob',\n });\n return { data: data as Blob | undefined, error };\n }\n\n /**\n * Get entity content as an ArrayBuffer\n *\n * This is a convenience method that handles the binary response parsing\n * that openapi-fetch doesn't handle automatically.\n *\n * @param entityId - The entity ID\n * @param key - Content version key (e.g., \"v1\", \"original\", \"thumbnail\")\n *\n * @example\n * ```typescript\n * const { data, error } = await arke.getEntityContentAsArrayBuffer('01ABC...', 'v1');\n * if (data) {\n * const bytes = new Uint8Array(data);\n * }\n * ```\n */\n async getEntityContentAsArrayBuffer(\n entityId: string,\n key?: string\n ): Promise<{ data: ArrayBuffer | undefined; error: unknown }> {\n const { data, error } = await this.api.GET('/entities/{id}/content', {\n params: { path: { id: entityId }, query: key ? { key } : {} },\n parseAs: 'arrayBuffer',\n });\n return { data: data as ArrayBuffer | undefined, error };\n }\n\n /**\n * Get entity content as a ReadableStream\n *\n * This is a convenience method for streaming large files.\n *\n * @param entityId - The entity ID\n * @param key - Content version key (e.g., \"v1\", \"original\", \"thumbnail\")\n *\n * @example\n * ```typescript\n * const { data, error } = await arke.getEntityContentAsStream('01ABC...', 'v1');\n * if (data) {\n * const reader = data.getReader();\n * // Process chunks...\n * }\n * ```\n */\n async getEntityContentAsStream(\n entityId: string,\n key?: string\n ): Promise<{ data: ReadableStream<Uint8Array> | null | undefined; error: unknown }> {\n const { data, error } = await this.api.GET('/entities/{id}/content', {\n params: { path: { id: entityId }, query: key ? { key } : {} },\n parseAs: 'stream',\n });\n return { data: data as ReadableStream<Uint8Array> | null | undefined, error };\n }\n\n /**\n * Upload content to an entity\n *\n * This is a convenience method that handles the binary body serialization\n * that openapi-fetch doesn't handle automatically for non-JSON bodies.\n *\n * @param entityId - The entity ID\n * @param key - Content version key (e.g., \"v1\", \"original\", \"thumbnail\")\n * @param content - The content to upload\n * @param contentType - MIME type of the content\n * @param filename - Optional filename for Content-Disposition header on download\n *\n * @example\n * ```typescript\n * // Upload from a Blob\n * const blob = new Blob(['Hello, world!'], { type: 'text/plain' });\n * const { data, error } = await arke.uploadEntityContent('01ABC...', 'v1', blob, 'text/plain');\n *\n * // Upload from an ArrayBuffer\n * const buffer = new TextEncoder().encode('Hello, world!').buffer;\n * const { data, error } = await arke.uploadEntityContent('01ABC...', 'v1', buffer, 'text/plain');\n *\n * // Upload from a Uint8Array with filename\n * const bytes = new TextEncoder().encode('Hello, world!');\n * const { data, error } = await arke.uploadEntityContent('01ABC...', 'v1', bytes, 'text/plain', 'hello.txt');\n * ```\n */\n async uploadEntityContent(\n entityId: string,\n key: string,\n content: Blob | ArrayBuffer | Uint8Array,\n contentType: string,\n filename?: string\n ): Promise<{\n data: components['schemas']['UploadContentResponse'] | undefined;\n error: unknown;\n }> {\n // Convert to Blob if needed\n let body: Blob;\n if (content instanceof Blob) {\n body = content;\n } else if (content instanceof Uint8Array) {\n // Copy to a new ArrayBuffer to handle SharedArrayBuffer compatibility\n const buffer = new ArrayBuffer(content.byteLength);\n new Uint8Array(buffer).set(content);\n body = new Blob([buffer], { type: contentType });\n } else {\n // ArrayBuffer\n body = new Blob([content], { type: contentType });\n }\n\n const { data, error } = await this.api.POST('/entities/{id}/content', {\n params: { path: { id: entityId }, query: { key, filename } },\n body: body as unknown as Record<string, never>,\n bodySerializer: (b: unknown) => b as BodyInit,\n headers: { 'Content-Type': contentType },\n } as Parameters<typeof this.api.POST>[1]);\n\n return { data: data as components['schemas']['UploadContentResponse'] | undefined, error };\n }\n}\n\n/**\n * Create a new ArkeClient instance\n * Convenience function for those who prefer functional style\n */\nexport function createArkeClient(config?: ArkeClientConfig): ArkeClient {\n return new ArkeClient(config);\n}\n\n// Re-export types and errors\nexport type { ArkeClientConfig, RetryConfig } from './config.js';\nexport * from './errors.js';\n","/**\n * SDK configuration types\n */\n\nimport type { RetryConfig } from './retry.js';\n\nexport type { RetryConfig } from './retry.js';\n\nexport interface ArkeClientConfig {\n /**\n * Base URL for the Arke API\n * @default 'https://api.arke.institute'\n */\n baseUrl?: string;\n\n /**\n * Authentication token - accepts either:\n * - JWT token from Supabase auth (sent as Bearer)\n * - Agent API key with 'ak_' prefix (sent as ApiKey)\n * - User API key with 'uk_' prefix (sent as ApiKey)\n *\n * The correct Authorization header format is auto-detected from the token prefix.\n */\n authToken?: string;\n\n /**\n * Network to use ('main' or 'test')\n * Test network uses 'II' prefixed IDs and isolated data\n * @default 'main'\n */\n network?: 'main' | 'test';\n\n /**\n * Callback to refresh auth token when expired\n * Called automatically on 401 responses\n */\n onTokenRefresh?: () => Promise<string>;\n\n /**\n * Custom headers to include in all requests\n */\n headers?: Record<string, string>;\n\n /**\n * Retry configuration for transient errors\n *\n * Set to `false` to disable retries entirely.\n * If not specified, uses default retry behavior (3 retries with exponential backoff).\n *\n * CAS conflicts (409) are never retried - they are returned immediately.\n *\n * @example\n * ```typescript\n * const arke = new ArkeClient({\n * authToken: 'ak_...',\n * retry: {\n * maxRetries: 5,\n * initialDelay: 200,\n * onRetry: (attempt, error, delay) => {\n * console.log(`Retry ${attempt} after ${delay}ms`);\n * }\n * }\n * });\n * ```\n */\n retry?: RetryConfig | false;\n}\n\nexport const DEFAULT_CONFIG: Required<Pick<ArkeClientConfig, 'baseUrl' | 'network'>> = {\n baseUrl: 'https://api.arke.institute',\n network: 'main',\n};\n","/**\n * Retry logic for transient network and server errors\n */\n\n/**\n * Configuration for retry behavior\n */\nexport interface RetryConfig {\n /**\n * Maximum number of retry attempts\n * @default 3\n */\n maxRetries?: number;\n\n /**\n * Initial delay in milliseconds before first retry\n * @default 100\n */\n initialDelay?: number;\n\n /**\n * Maximum delay in milliseconds (caps exponential backoff)\n * @default 5000\n */\n maxDelay?: number;\n\n /**\n * Whether to retry on 5xx server errors\n * @default true\n */\n retryOn5xx?: boolean;\n\n /**\n * Whether to retry on network errors (connection refused, DNS, timeouts)\n * @default true\n */\n retryOnNetworkError?: boolean;\n\n /**\n * Optional callback invoked before each retry attempt\n * Useful for logging or monitoring\n */\n onRetry?: (attempt: number, error: Error, delayMs: number) => void;\n}\n\nexport const DEFAULT_RETRY_CONFIG: Required<Omit<RetryConfig, 'onRetry'>> = {\n maxRetries: 3,\n initialDelay: 100,\n maxDelay: 5000,\n retryOn5xx: true,\n retryOnNetworkError: true,\n};\n\n/**\n * HTTP status codes that should be retried\n */\nconst RETRYABLE_STATUS_CODES = new Set([\n 500, // Internal Server Error\n 502, // Bad Gateway\n 503, // Service Unavailable\n 504, // Gateway Timeout\n 520, // Cloudflare: Unknown Error\n 521, // Cloudflare: Web Server Is Down\n 522, // Cloudflare: Connection Timed Out\n 523, // Cloudflare: Origin Is Unreachable\n 524, // Cloudflare: A Timeout Occurred\n 525, // Cloudflare: SSL Handshake Failed\n 526, // Cloudflare: Invalid SSL Certificate\n 527, // Cloudflare: Railgun Error\n 530, // Cloudflare: Origin DNS Error\n]);\n\n/**\n * Status codes that should never be retried\n */\nconst NON_RETRYABLE_STATUS_CODES = new Set([\n 400, // Bad Request\n 401, // Unauthorized\n 403, // Forbidden\n 404, // Not Found\n 405, // Method Not Allowed\n 409, // Conflict (CAS errors)\n 410, // Gone\n 422, // Unprocessable Entity\n 429, // Too Many Requests (should be handled separately with rate limiting)\n]);\n\n/**\n * Check if a status code is retryable\n */\nexport function isRetryableStatus(status: number): boolean {\n if (NON_RETRYABLE_STATUS_CODES.has(status)) {\n return false;\n }\n return RETRYABLE_STATUS_CODES.has(status);\n}\n\n/**\n * Check if an error is a network error that should be retried\n */\nexport function isNetworkError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n\n // TypeError is thrown by fetch for network failures\n if (error instanceof TypeError) {\n const message = error.message.toLowerCase();\n return (\n message.includes('failed to fetch') ||\n message.includes('network') ||\n message.includes('fetch failed') ||\n message.includes('econnrefused') ||\n message.includes('econnreset') ||\n message.includes('etimedout') ||\n message.includes('enotfound') ||\n message.includes('dns') ||\n message.includes('socket')\n );\n }\n\n // Check for abort errors (timeouts)\n if (error.name === 'AbortError') {\n return true;\n }\n\n return false;\n}\n\n/**\n * Check if a response is a Cloudflare error page (HTML instead of JSON)\n */\nexport function isCloudflareErrorResponse(response: Response): boolean {\n const contentType = response.headers.get('content-type') || '';\n\n // If we expect JSON but got HTML, it's likely a Cloudflare error page\n if (contentType.includes('text/html') && !response.ok) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Calculate delay with exponential backoff and jitter\n */\nexport function calculateDelay(\n attempt: number,\n initialDelay: number,\n maxDelay: number\n): number {\n // Exponential backoff: initialDelay * 2^attempt\n const exponentialDelay = initialDelay * Math.pow(2, attempt);\n\n // Cap at maxDelay\n const cappedDelay = Math.min(exponentialDelay, maxDelay);\n\n // Add jitter (0-100% of the delay)\n const jitter = Math.random() * cappedDelay;\n\n return Math.floor(cappedDelay + jitter);\n}\n\n/**\n * Sleep for a specified number of milliseconds\n */\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Create a fetch function with retry logic\n *\n * @example\n * ```typescript\n * const retryFetch = createRetryFetch({\n * maxRetries: 3,\n * onRetry: (attempt, error, delay) => {\n * console.log(`Retry ${attempt} after ${delay}ms: ${error.message}`);\n * }\n * });\n *\n * // Use with openapi-fetch\n * const client = createClient<paths>({\n * baseUrl: 'https://api.example.com',\n * fetch: retryFetch,\n * });\n * ```\n */\nexport function createRetryFetch(config: RetryConfig = {}): typeof fetch {\n const {\n maxRetries = DEFAULT_RETRY_CONFIG.maxRetries,\n initialDelay = DEFAULT_RETRY_CONFIG.initialDelay,\n maxDelay = DEFAULT_RETRY_CONFIG.maxDelay,\n retryOn5xx = DEFAULT_RETRY_CONFIG.retryOn5xx,\n retryOnNetworkError = DEFAULT_RETRY_CONFIG.retryOnNetworkError,\n onRetry,\n } = config;\n\n return async function retryFetch(\n input: RequestInfo | URL,\n init?: RequestInit\n ): Promise<Response> {\n let lastError: Error | undefined;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n // Clone Request objects to allow retries - Request bodies can only be consumed once\n const reqInput = input instanceof Request ? input.clone() : input;\n const response = await fetch(reqInput, init);\n\n // Check for Cloudflare error pages\n if (isCloudflareErrorResponse(response) && attempt < maxRetries) {\n const error = new Error(\n `Cloudflare error (status ${response.status})`\n );\n lastError = error;\n\n const delay = calculateDelay(attempt, initialDelay, maxDelay);\n onRetry?.(attempt + 1, error, delay);\n await sleep(delay);\n continue;\n }\n\n // Check for retryable status codes\n if (retryOn5xx && isRetryableStatus(response.status) && attempt < maxRetries) {\n const error = new Error(\n `Server error (status ${response.status})`\n );\n lastError = error;\n\n const delay = calculateDelay(attempt, initialDelay, maxDelay);\n onRetry?.(attempt + 1, error, delay);\n await sleep(delay);\n continue;\n }\n\n // Success or non-retryable error\n return response;\n } catch (error) {\n // Network errors\n if (\n retryOnNetworkError &&\n isNetworkError(error) &&\n attempt < maxRetries\n ) {\n lastError = error as Error;\n\n const delay = calculateDelay(attempt, initialDelay, maxDelay);\n onRetry?.(attempt + 1, error as Error, delay);\n await sleep(delay);\n continue;\n }\n\n // Non-retryable error or exhausted retries\n throw error;\n }\n }\n\n // Exhausted all retries\n throw lastError ?? new Error('Request failed after retries');\n };\n}\n","/**\n * SDK error classes\n */\n\n/**\n * Base error class for all Arke SDK errors\n */\nexport class ArkeError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly status?: number,\n public readonly details?: unknown\n ) {\n super(message);\n this.name = 'ArkeError';\n // Maintains proper stack trace for where error was thrown\n Error.captureStackTrace?.(this, this.constructor);\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n status: this.status,\n details: this.details,\n };\n }\n}\n\n/**\n * CAS (Compare-And-Swap) conflict - entity was modified by another request\n */\nexport class CASConflictError extends ArkeError {\n constructor(\n public readonly expectedTip?: string,\n public readonly actualTip?: string\n ) {\n super(\n 'Entity was modified by another request. Refresh and retry with the current tip.',\n 'CAS_CONFLICT',\n 409,\n { expectedTip, actualTip }\n );\n this.name = 'CASConflictError';\n }\n}\n\n/**\n * Resource not found\n */\nexport class NotFoundError extends ArkeError {\n constructor(resourceType: string, id: string) {\n super(`${resourceType} not found: ${id}`, 'NOT_FOUND', 404, { resourceType, id });\n this.name = 'NotFoundError';\n }\n}\n\n/**\n * Validation error - invalid request data\n */\nexport class ValidationError extends ArkeError {\n constructor(\n message: string,\n public readonly field?: string,\n details?: unknown\n ) {\n super(message, 'VALIDATION_ERROR', 400, details ?? { field });\n this.name = 'ValidationError';\n }\n}\n\n/**\n * Authentication required or invalid\n */\nexport class AuthenticationError extends ArkeError {\n constructor(message = 'Authentication required') {\n super(message, 'AUTH_REQUIRED', 401);\n this.name = 'AuthenticationError';\n }\n}\n\n/**\n * Permission denied\n */\nexport class ForbiddenError extends ArkeError {\n constructor(action?: string, resource?: string) {\n const msg = action\n ? `Permission denied: ${action}${resource ? ` on ${resource}` : ''}`\n : 'Permission denied';\n super(msg, 'FORBIDDEN', 403, { action, resource });\n this.name = 'ForbiddenError';\n }\n}\n\n/**\n * Parse API error response into appropriate error class\n */\nexport function parseApiError(status: number, body: unknown): ArkeError {\n const errorBody = body as { error?: string; message?: string; details?: unknown } | null;\n const message = errorBody?.error ?? errorBody?.message ?? 'Unknown error';\n\n switch (status) {\n case 400:\n return new ValidationError(message, undefined, errorBody?.details);\n\n case 401:\n return new AuthenticationError(message);\n\n case 403:\n return new ForbiddenError(message);\n\n case 404:\n return new NotFoundError('Resource', 'unknown');\n\n case 409: {\n // Parse CAS conflict details if available\n const details = errorBody?.details as { expected?: string; actual?: string } | undefined;\n return new CASConflictError(details?.expected, details?.actual);\n }\n\n default:\n return new ArkeError(message, 'API_ERROR', status, errorBody?.details);\n }\n}\n","/**\n * CID Computation Utility\n *\n * Computes IPFS CIDv1 (base32) for file content.\n * Uses raw codec (0x55) and SHA-256 hash.\n *\n * Note: This module is not used internally by the upload engine (the server\n * computes CIDs from uploaded content). It is exported for convenience in case\n * you want to verify entity CIDs, detect duplicates before upload, or perform\n * other content-addressed operations.\n */\n\nimport { CID } from 'multiformats/cid';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport * as raw from 'multiformats/codecs/raw';\n\n/**\n * Compute CIDv1 for binary content.\n * Returns base32 encoded string (bafk... prefix for raw codec).\n *\n * @param data - Binary content as ArrayBuffer, Uint8Array, or Blob\n * @returns CIDv1 string in base32 encoding\n *\n * @example\n * ```typescript\n * const cid = await computeCid(new TextEncoder().encode('hello world'));\n * // Returns: \"bafkreifzjut3te2nhyekklss27nh3k72ysco7y32koao5eei66wof36n5e\"\n * ```\n */\nexport async function computeCid(data: ArrayBuffer | Uint8Array | Blob): Promise<string> {\n // Convert to Uint8Array\n let bytes: Uint8Array;\n\n if (data instanceof Blob) {\n const buffer = await data.arrayBuffer();\n bytes = new Uint8Array(buffer);\n } else if (data instanceof ArrayBuffer) {\n bytes = new Uint8Array(data);\n } else {\n bytes = data;\n }\n\n // Compute SHA-256 hash\n const hash = await sha256.digest(bytes);\n\n // Create CIDv1 with raw codec\n const cid = CID.create(1, raw.code, hash);\n\n // Return base32 encoded string\n return cid.toString();\n}\n\n/**\n * Verify a CID matches the content.\n *\n * @param data - Binary content\n * @param expectedCid - CID to verify against\n * @returns true if CID matches\n */\nexport async function verifyCid(\n data: ArrayBuffer | Uint8Array | Blob,\n expectedCid: string\n): Promise<boolean> {\n const computed = await computeCid(data);\n return computed === expectedCid;\n}\n","/**\n * Upload Engine\n *\n * Core upload implementation optimized for fast tree visibility:\n * 1. Create folders by depth (with unidirectional 'in' → parent)\n * 2. Create file entities (metadata only, high parallelism)\n * 3. Backlink parents with 'contains' relationships\n * → Tree is now browsable! Users can explore structure immediately.\n * 4. Upload file content via POST /files/{id}/content (byte-based pool, ~200MB in flight)\n * - Direct upload to API endpoint\n * - API streams to R2, computes CID, updates entity atomically\n *\n * Byte-based pool (for uploads):\n * - Maintains ~200MB of data in flight at all times\n * - When a file completes, next file starts immediately (no gaps)\n * - Small files: Many upload in parallel\n * - Large files: Fewer upload in parallel (bandwidth-limited)\n * - Single file > 200MB: Uploads alone when pool is empty\n *\n * This minimizes time-to-browse by:\n * - Creating all entities before uploading content\n * - Using unidirectional 'in' relationship on entity creation\n * - Adding all 'contains' relationships in a single PUT per parent\n */\n\nimport type { ArkeClient } from '../../client/ArkeClient.js';\nimport { getAuthorizationHeader } from '../../client/ArkeClient.js';\nimport type { components } from '../../generated/types.js';\nimport { computeCid } from './cid.js';\nimport type {\n UploadTree,\n UploadOptions,\n UploadResult,\n UploadProgress,\n CreatedFolder,\n CreatedFile,\n CreatedEntity,\n UploadFolder,\n} from './types.js';\n\ntype CreateCollectionRequest = components['schemas']['CreateCollectionRequest'];\ntype CreateEntityRequest = components['schemas']['CreateEntityRequest'];\ntype UpdateEntityRequest = components['schemas']['UpdateEntityRequest'];\ntype UpdateCollectionRequest = components['schemas']['UpdateCollectionRequest'];\n\n// Phase constants\nconst PHASE_COUNT = 3; // creating, backlinking, uploading (excluding complete/error)\nconst PHASE_INDEX: Record<string, number> = {\n creating: 0,\n backlinking: 1,\n uploading: 2,\n complete: 3,\n error: -1,\n};\n\n// Batch creation constants\nconst BATCH_SIZE = 100; // Entities per batch request\nconst BATCH_CONCURRENCY = 25; // Concurrent batch requests\nconst BACKLINK_CONCURRENCY = 100; // Concurrent backlink PUTs\nconst MAX_UPLOAD_CONCURRENCY = 500; // Max concurrent upload requests\n\n// =============================================================================\n// Concurrency Utilities\n// =============================================================================\n\n/**\n * Simple concurrency limiter for parallel operations.\n */\nasync function parallelLimit<T, R>(\n items: T[],\n concurrency: number,\n fn: (item: T, index: number) => Promise<R>\n): Promise<R[]> {\n const results: R[] = [];\n let index = 0;\n\n async function worker(): Promise<void> {\n while (index < items.length) {\n const currentIndex = index++;\n const item = items[currentIndex]!;\n results[currentIndex] = await fn(item, currentIndex);\n }\n }\n\n const workers = Array.from({ length: Math.min(concurrency, items.length) }, () => worker());\n await Promise.all(workers);\n\n return results;\n}\n\n/**\n * Split array into chunks of specified size.\n */\nfunction chunk<T>(array: T[], size: number): T[][] {\n const chunks: T[][] = [];\n for (let i = 0; i < array.length; i += size) {\n chunks.push(array.slice(i, i + size));\n }\n return chunks;\n}\n\n// =============================================================================\n// Byte-Based Pool\n// =============================================================================\n\n/** Target bytes in flight (~200MB) */\nconst TARGET_BYTES_IN_FLIGHT = 200 * 1024 * 1024;\n\n/** Threshold for using presigned URLs (5MB) - larger files bypass API worker */\nconst PRESIGNED_URL_THRESHOLD = 5 * 1024 * 1024;\n\n/**\n * Pool that maintains a target number of bytes in flight AND limits concurrent requests.\n *\n * When a file completes, its bytes are released and the next\n * waiting file can start immediately. This keeps the pipeline full.\n *\n * - Small files: Many run in parallel (up to ~200MB worth or maxConcurrent)\n * - Large files: Fewer run in parallel\n * - Single file > 200MB: Runs alone (allowed when pool is empty)\n */\nclass BytePool {\n private bytesInFlight = 0;\n private activeCount = 0;\n private waitQueue: Array<() => void> = [];\n\n constructor(\n private targetBytes: number = TARGET_BYTES_IN_FLIGHT,\n private maxConcurrent: number = MAX_UPLOAD_CONCURRENCY\n ) {}\n\n async run<T>(size: number, fn: () => Promise<T>): Promise<T> {\n // Wait until we have room for BOTH bytes AND request count\n // Exception: if pool is empty, always allow (handles files > targetBytes)\n while (\n (this.bytesInFlight > 0 && this.bytesInFlight + size > this.targetBytes) ||\n this.activeCount >= this.maxConcurrent\n ) {\n await new Promise<void>((resolve) => this.waitQueue.push(resolve));\n }\n\n this.bytesInFlight += size;\n this.activeCount++;\n try {\n return await fn();\n } finally {\n this.bytesInFlight -= size;\n this.activeCount--;\n // Wake ALL waiting tasks so they can re-evaluate the condition.\n // wake-one is incorrect here: if a large file finishes, multiple\n // smaller files may now fit but only the first waiter would check.\n const queue = this.waitQueue.splice(0);\n for (const resolve of queue) resolve();\n }\n }\n}\n\n// =============================================================================\n// Helper Functions\n// =============================================================================\n\n/**\n * Parse folder path to get parent path.\n * e.g., \"docs/images/photos\" -> \"docs/images\"\n */\nfunction getParentPath(relativePath: string): string | null {\n const lastSlash = relativePath.lastIndexOf('/');\n if (lastSlash === -1) return null;\n return relativePath.slice(0, lastSlash);\n}\n\n/**\n * Group folders by depth level.\n */\nfunction groupFoldersByDepth(folders: UploadFolder[]): Map<number, UploadFolder[]> {\n const byDepth = new Map<number, UploadFolder[]>();\n\n for (const folder of folders) {\n const depth = folder.relativePath.split('/').length - 1;\n if (!byDepth.has(depth)) byDepth.set(depth, []);\n byDepth.get(depth)!.push(folder);\n }\n\n return byDepth;\n}\n\n// =============================================================================\n// Main Upload Function\n// =============================================================================\n\n/**\n * Main upload function.\n * Orchestrates the entire upload process with optimized relationship strategy.\n */\nexport async function uploadTree(\n client: ArkeClient,\n tree: UploadTree,\n options: UploadOptions\n): Promise<UploadResult> {\n const { target, onProgress, concurrency = 10, continueOnError = false, maxBytesInFlight, note } = options;\n\n const errors: Array<{ path: string; error: string }> = [];\n const createdFolders: CreatedFolder[] = [];\n const createdFiles: CreatedFile[] = [];\n\n // Maps for tracking (include label for peer_label in relationships)\n const foldersByPath = new Map<string, { id: string; cid: string; label: string }>();\n\n // Calculate totals\n const totalEntities = tree.files.length + tree.folders.length;\n const totalBytes = tree.files.reduce((sum, f) => sum + f.size, 0);\n let completedEntities = 0;\n let bytesUploaded = 0;\n\n // Helper to report progress\n const reportProgress = (progress: Partial<UploadProgress>) => {\n if (onProgress) {\n const phase = progress.phase || 'creating';\n const phaseIndex = PHASE_INDEX[phase] ?? -1;\n\n // Calculate phase percent based on current phase\n let phasePercent = 0;\n if (phase === 'creating') {\n // Creating phase: progress is based on entities created\n const done = progress.completedEntities ?? completedEntities;\n phasePercent = totalEntities > 0 ? Math.round((done / totalEntities) * 100) : 100;\n } else if (phase === 'backlinking') {\n // Backlinking phase: progress is based on parents updated\n const done = progress.completedParents ?? 0;\n const total = progress.totalParents ?? 0;\n phasePercent = total > 0 ? Math.round((done / total) * 100) : 100;\n } else if (phase === 'uploading') {\n // Uploading phase: progress is based on bytes uploaded\n const done = progress.bytesUploaded ?? bytesUploaded;\n phasePercent = totalBytes > 0 ? Math.round((done / totalBytes) * 100) : 100;\n } else if (phase === 'complete') {\n phasePercent = 100;\n }\n\n onProgress({\n phase,\n phaseIndex,\n phaseCount: PHASE_COUNT,\n phasePercent,\n totalEntities,\n completedEntities,\n totalParents: 0,\n completedParents: 0,\n totalBytes,\n bytesUploaded,\n ...progress,\n } as UploadProgress);\n }\n };\n\n try {\n // ─────────────────────────────────────────────────────────────────────────\n // SETUP: Resolve or create collection\n // ─────────────────────────────────────────────────────────────────────────\n let collectionId: string;\n let collectionCid: string;\n let collectionLabel: string;\n let collectionCreated = false;\n\n if (target.createCollection) {\n const collectionBody: CreateCollectionRequest = {\n label: target.createCollection.label,\n description: target.createCollection.description,\n roles: target.createCollection.roles,\n note,\n };\n\n const { data, error } = await client.api.POST('/collections', {\n body: collectionBody,\n });\n\n if (error || !data) {\n throw new Error(`Failed to create collection: ${JSON.stringify(error)}`);\n }\n\n collectionId = data.id;\n collectionCid = data.cid;\n collectionLabel = target.createCollection.label;\n collectionCreated = true;\n } else if (target.collectionId) {\n collectionId = target.collectionId;\n\n const { data, error } = await client.api.GET('/collections/{id}', {\n params: { path: { id: collectionId } },\n });\n\n if (error || !data) {\n throw new Error(`Failed to fetch collection: ${JSON.stringify(error)}`);\n }\n\n collectionCid = data.cid;\n collectionLabel = (data.properties?.label as string) ?? collectionId;\n } else {\n throw new Error('Must provide either collectionId or createCollection in target');\n }\n\n // Determine the parent for root-level items\n const rootParentId = target.parentId ?? collectionId;\n let rootParentLabel = collectionLabel;\n let rootParentType: 'collection' | 'folder' = 'collection';\n\n // If a specific parent folder is provided, fetch its label\n if (target.parentId && target.parentId !== collectionId) {\n const { data: parentData, error: parentError } = await client.api.GET('/entities/{id}', {\n params: { path: { id: target.parentId } },\n });\n if (parentError || !parentData) {\n throw new Error(`Failed to fetch parent folder: ${JSON.stringify(parentError)}`);\n }\n rootParentLabel = (parentData.properties?.label as string) ?? target.parentId;\n rootParentType = 'folder';\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // PHASE 1: Create entities (folders by depth, then files)\n // ─────────────────────────────────────────────────────────────────────────\n reportProgress({ phase: 'creating', completedEntities: 0 });\n\n // Group folders by depth\n const foldersByDepth = groupFoldersByDepth(tree.folders);\n const sortedDepths = [...foldersByDepth.keys()].sort((a, b) => a - b);\n\n // Create folders depth by depth (parents before children) using batch endpoint\n for (const depth of sortedDepths) {\n const foldersAtDepth = foldersByDepth.get(depth)!;\n\n // Build batch items for all folders at this depth\n const batchItems = foldersAtDepth.map((folder) => {\n const parentPath = getParentPath(folder.relativePath);\n const parentInfo = parentPath ? foldersByPath.get(parentPath)! : null;\n const parentId = parentInfo ? parentInfo.id : rootParentId;\n const parentType = parentInfo ? 'folder' : rootParentType;\n const parentLabel = parentInfo ? parentInfo.label : rootParentLabel;\n\n return {\n folder, // Track for result processing\n entity: {\n type: 'folder',\n properties: { label: folder.name },\n note,\n relationships: [{ predicate: 'in', peer: parentId, peer_type: parentType, peer_label: parentLabel }],\n },\n };\n });\n\n // Chunk into batches of BATCH_SIZE and create in parallel\n const batches = chunk(batchItems, BATCH_SIZE);\n\n await parallelLimit(batches, BATCH_CONCURRENCY, async (batch) => {\n const { data, error } = await client.api.POST('/entities/batch', {\n params: { query: { validate_relationships: 'false' } },\n body: {\n default_collection: collectionId,\n entities: batch.map((item) => item.entity),\n },\n });\n\n if (error || !data) {\n throw new Error(`Batch folder creation failed: ${JSON.stringify(error)}`);\n }\n\n // Process results - map back to folders by index\n for (const result of data.results) {\n const batchItem = batch[result.index];\n if (!batchItem) continue;\n const folder = batchItem.folder;\n\n if (result.success) {\n // Track folder (include label for peer_label in child relationships)\n foldersByPath.set(folder.relativePath, {\n id: result.id,\n cid: result.cid,\n label: folder.name,\n });\n createdFolders.push({\n name: folder.name,\n relativePath: folder.relativePath,\n id: result.id,\n entityCid: result.cid,\n });\n completedEntities++;\n } else {\n // BatchCreateFailure\n const errorMsg = result.error;\n if (continueOnError) {\n errors.push({ path: folder.relativePath, error: `Folder creation failed: ${errorMsg}` });\n completedEntities++;\n } else {\n throw new Error(`Failed to create folder ${folder.relativePath}: ${errorMsg}`);\n }\n }\n }\n\n reportProgress({ phase: 'creating', completedEntities });\n });\n }\n\n // Create file entities (metadata only, no content upload yet) using batch endpoint\n // Build batch items for all files\n const fileBatchItems = tree.files.map((file) => {\n const parentPath = getParentPath(file.relativePath);\n const parentInfo = parentPath ? foldersByPath.get(parentPath)! : null;\n const parentId = parentInfo ? parentInfo.id : rootParentId;\n const parentType = parentInfo ? 'folder' : rootParentType;\n const parentLabel = parentInfo ? parentInfo.label : rootParentLabel;\n\n return {\n file, // Track for result processing\n entity: {\n type: 'file',\n properties: {\n label: file.name,\n filename: file.name,\n content_type: file.mimeType,\n size: file.size,\n },\n note,\n relationships: [{ predicate: 'in', peer: parentId, peer_type: parentType, peer_label: parentLabel }],\n },\n };\n });\n\n // Chunk into batches of BATCH_SIZE and create in parallel\n const fileBatches = chunk(fileBatchItems, BATCH_SIZE);\n\n await parallelLimit(fileBatches, BATCH_CONCURRENCY, async (batch) => {\n const { data, error } = await client.api.POST('/entities/batch', {\n params: { query: { validate_relationships: 'false' } },\n body: {\n default_collection: collectionId,\n entities: batch.map((item) => item.entity),\n },\n });\n\n if (error || !data) {\n throw new Error(`Batch file creation failed: ${JSON.stringify(error)}`);\n }\n\n // Process results - map back to files by index\n for (const result of data.results) {\n const batchItem = batch[result.index];\n if (!batchItem) continue;\n const file = batchItem.file;\n\n if (result.success) {\n // Track file for later upload\n createdFiles.push({\n ...file,\n id: result.id,\n entityCid: result.cid,\n });\n completedEntities++;\n } else {\n // BatchCreateFailure\n const errorMsg = result.error;\n if (continueOnError) {\n errors.push({ path: file.relativePath, error: errorMsg });\n completedEntities++;\n } else {\n throw new Error(`Failed to create file ${file.relativePath}: ${errorMsg}`);\n }\n }\n }\n\n reportProgress({ phase: 'creating', completedEntities });\n });\n\n // ─────────────────────────────────────────────────────────────────────────\n // PHASE 2: Backlink - Update each parent with 'contains' relationships\n // Uses cached CIDs to avoid GETs, with retry on 409 conflict\n // ─────────────────────────────────────────────────────────────────────────\n\n // Build parent -> children map (include label for peer_label)\n const childrenByParent = new Map<string, Array<{ id: string; type: 'file' | 'folder'; label: string }>>();\n\n // Add folders as children of their parents\n for (const folder of createdFolders) {\n const parentPath = getParentPath(folder.relativePath);\n const parentId = parentPath ? foldersByPath.get(parentPath)!.id : rootParentId;\n\n if (!childrenByParent.has(parentId)) childrenByParent.set(parentId, []);\n childrenByParent.get(parentId)!.push({ id: folder.id, type: 'folder', label: folder.name });\n }\n\n // Add files as children of their parents\n for (const file of createdFiles) {\n const parentPath = getParentPath(file.relativePath);\n const parentId = parentPath ? foldersByPath.get(parentPath)!.id : rootParentId;\n\n if (!childrenByParent.has(parentId)) childrenByParent.set(parentId, []);\n childrenByParent.get(parentId)!.push({ id: file.id, type: 'file', label: file.name });\n }\n\n const totalParents = childrenByParent.size;\n let completedParents = 0;\n\n reportProgress({ phase: 'backlinking', totalParents, completedParents: 0 });\n\n // Update all parents in parallel - each parent gets one PUT with all its children\n // Use cached CIDs from creation phase, only fetch fresh on 409 conflict\n const parentEntries = [...childrenByParent.entries()];\n\n await parallelLimit(parentEntries, BACKLINK_CONCURRENCY, async ([parentId, children]) => {\n try {\n const isCollection = parentId === collectionId;\n\n // Build relationships_add array with all children (include peer_label for display)\n const relationshipsAdd = children.map((child) => ({\n predicate: 'contains' as const,\n peer: child.id,\n peer_type: child.type,\n peer_label: child.label,\n }));\n\n // Get cached CID - no GET required for entities we created\n let expectTip: string;\n if (isCollection) {\n expectTip = collectionCid; // From setup phase\n } else {\n // Check if it's a folder we created (have cached CID)\n const folderInfo = [...foldersByPath.values()].find((f) => f.id === parentId);\n if (folderInfo) {\n expectTip = folderInfo.cid;\n } else {\n // Root parent provided by user - need to fetch tip\n const { data: tipData, error: tipError } = await client.api.GET('/entities/{id}/tip', {\n params: { path: { id: parentId } },\n });\n if (tipError || !tipData) {\n throw new Error(`Failed to get tip: ${JSON.stringify(tipError)}`);\n }\n expectTip = tipData.cid;\n }\n }\n\n // Attempt PUT with cached CID, retry once on 409 conflict\n // Skip relationship validation - we just created these entities\n const attemptPut = async (tip: string, isRetry: boolean): Promise<void> => {\n if (isCollection) {\n const { error, response } = await client.api.PUT('/collections/{id}', {\n params: { path: { id: parentId }, query: { validate_relationships: 'false' } },\n body: {\n expect_tip: tip,\n relationships_add: relationshipsAdd,\n note: note ? `${note} (backlink${isRetry ? ' retry' : ''})` : `Upload backlink${isRetry ? ' retry' : ''}`,\n },\n });\n\n if (error) {\n // Check for CAS conflict (409) - retry with fresh tip\n if (response?.status === 409 && !isRetry) {\n const { data: freshData } = await client.api.GET('/collections/{id}', {\n params: { path: { id: parentId } },\n });\n if (!freshData) throw new Error('Failed to get fresh collection tip');\n return attemptPut(freshData.cid, true);\n }\n throw new Error(JSON.stringify(error));\n }\n } else {\n const { error, response } = await client.api.PUT('/entities/{id}', {\n params: { path: { id: parentId }, query: { validate_relationships: 'false' } },\n body: {\n expect_tip: tip,\n relationships_add: relationshipsAdd,\n note: note ? `${note} (backlink${isRetry ? ' retry' : ''})` : `Upload backlink${isRetry ? ' retry' : ''}`,\n },\n });\n\n if (error) {\n // Check for CAS conflict (409) - retry with fresh tip via fast /tip endpoint\n if (response?.status === 409 && !isRetry) {\n const { data: freshTip, error: tipError } = await client.api.GET('/entities/{id}/tip', {\n params: { path: { id: parentId } },\n });\n if (tipError || !freshTip) throw new Error(`Failed to get fresh tip: ${JSON.stringify(tipError)}`);\n return attemptPut(freshTip.cid, true);\n }\n throw new Error(JSON.stringify(error));\n }\n }\n };\n\n await attemptPut(expectTip, false);\n\n completedParents++;\n reportProgress({\n phase: 'backlinking',\n totalParents,\n completedParents,\n currentItem: `parent:${parentId}`,\n });\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n if (continueOnError) {\n errors.push({ path: `parent:${parentId}`, error: `Backlink failed: ${errorMsg}` });\n completedParents++;\n } else {\n throw new Error(`Failed to backlink parent ${parentId}: ${errorMsg}`);\n }\n }\n });\n\n // ─────────────────────────────────────────────────────────────────────────\n // PHASE 3: Upload file content\n // Tree is now browsable! Users can explore while content uploads.\n //\n // Two paths based on file size:\n // - Small files (<5MB): Direct upload through API (simple, CID computed server-side)\n // - Large files (>=5MB): Presigned URL to R2 (fast, CID computed client-side)\n // ─────────────────────────────────────────────────────────────────────────\n reportProgress({ phase: 'uploading', bytesUploaded: 0 });\n\n // Use byte-based pool to maintain target bytes in flight\n const pool = new BytePool(maxBytesInFlight);\n\n await Promise.all(\n createdFiles.map(async (file) => {\n await pool.run(file.size, async () => {\n try {\n // Get file data\n const fileData = await file.getData();\n\n let body: Blob;\n if (fileData instanceof Blob) {\n body = fileData;\n } else if (fileData instanceof Uint8Array) {\n const arrayBuffer = new ArrayBuffer(fileData.byteLength);\n new Uint8Array(arrayBuffer).set(fileData);\n body = new Blob([arrayBuffer], { type: file.mimeType });\n } else {\n body = new Blob([fileData], { type: file.mimeType });\n }\n\n if (file.size >= PRESIGNED_URL_THRESHOLD) {\n // ─────────────────────────────────────────────────────────────\n // LARGE FILE: Presigned URL flow (bypasses API worker)\n // ─────────────────────────────────────────────────────────────\n\n // 1. Compute CID client-side\n const fileCid = await computeCid(fileData);\n\n // 2. Get presigned URL from API\n const { data: urlData, error: urlError } = await client.api.POST(\n '/entities/{id}/content/upload-url',\n {\n params: { path: { id: file.id } },\n body: {\n content_type: file.mimeType,\n size: file.size,\n key: 'v1',\n },\n }\n );\n\n if (urlError || !urlData) {\n throw new Error(`Failed to get presigned URL: ${JSON.stringify(urlError)}`);\n }\n\n // 3. PUT directly to R2 (fast!)\n const r2Response = await fetch(urlData.upload_url, {\n method: 'PUT',\n headers: { 'Content-Type': file.mimeType },\n body: body,\n });\n\n if (!r2Response.ok) {\n const errorText = await r2Response.text();\n throw new Error(`R2 upload failed: ${r2Response.status} ${errorText}`);\n }\n\n // 4. Complete upload by updating entity metadata\n const { error: completeError } = await client.api.POST(\n '/entities/{id}/content/complete',\n {\n params: { path: { id: file.id } },\n body: {\n key: 'v1',\n cid: fileCid,\n size: file.size,\n content_type: file.mimeType,\n filename: file.name,\n expect_tip: file.entityCid,\n },\n }\n );\n\n if (completeError) {\n throw new Error(`Failed to complete upload: ${JSON.stringify(completeError)}`);\n }\n } else {\n // ─────────────────────────────────────────────────────────────\n // SMALL FILE: Direct upload through API\n // ─────────────────────────────────────────────────────────────\n\n const { error: uploadError } = await client.api.POST('/entities/{id}/content', {\n params: { path: { id: file.id }, query: { key: 'v1', filename: file.name } },\n body: body as unknown as Record<string, never>,\n bodySerializer: (b: unknown) => b as BodyInit,\n headers: { 'Content-Type': file.mimeType },\n } as Parameters<typeof client.api.POST>[1]);\n\n if (uploadError) {\n throw new Error(`Upload failed: ${JSON.stringify(uploadError)}`);\n }\n }\n\n bytesUploaded += file.size;\n reportProgress({\n phase: 'uploading',\n bytesUploaded,\n currentItem: file.relativePath,\n });\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n if (continueOnError) {\n errors.push({ path: file.relativePath, error: `Upload failed: ${errorMsg}` });\n } else {\n throw new Error(`Failed to upload ${file.relativePath}: ${errorMsg}`);\n }\n }\n });\n })\n );\n\n // ─────────────────────────────────────────────────────────────────────────\n // Complete!\n // ─────────────────────────────────────────────────────────────────────────\n reportProgress({ phase: 'complete', totalParents, completedParents, bytesUploaded });\n\n const resultFolders: CreatedEntity[] = createdFolders.map((f) => ({\n id: f.id,\n cid: f.entityCid,\n type: 'folder' as const,\n relativePath: f.relativePath,\n }));\n\n const resultFiles: CreatedEntity[] = createdFiles.map((f) => ({\n id: f.id,\n cid: f.entityCid,\n type: 'file' as const,\n relativePath: f.relativePath,\n }));\n\n return {\n success: errors.length === 0,\n collection: {\n id: collectionId,\n cid: collectionCid,\n created: collectionCreated,\n },\n folders: resultFolders,\n files: resultFiles,\n errors,\n };\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n\n reportProgress({\n phase: 'error',\n error: errorMsg,\n });\n\n return {\n success: false,\n collection: {\n id: target.collectionId ?? '',\n cid: '',\n created: false,\n },\n folders: createdFolders.map((f) => ({\n id: f.id,\n cid: f.entityCid,\n type: 'folder' as const,\n relativePath: f.relativePath,\n })),\n files: createdFiles.map((f) => ({\n id: f.id,\n cid: f.entityCid,\n type: 'file' as const,\n relativePath: f.relativePath,\n })),\n errors: [...errors, { path: '', error: errorMsg }],\n };\n }\n}\n","/**\n * Single File Upload Helper\n *\n * Simplified upload for a single file to an existing entity.\n * Automatically handles direct vs presigned upload based on file size.\n */\n\nimport { ArkeClient, getAuthorizationHeader } from '../../client/ArkeClient.js';\nimport { computeCid } from './cid.js';\nimport { getMimeType } from './scanners.js';\n\n/**\n * Build auth headers for raw fetch requests.\n */\nfunction buildAuthHeaders(client: ArkeClient): Record<string, string> {\n const config = client.getConfig();\n const headers: Record<string, string> = {};\n\n if (config.authToken) {\n headers['Authorization'] = getAuthorizationHeader(config.authToken);\n }\n\n if (config.network === 'test') {\n headers['X-Arke-Network'] = 'test';\n }\n\n return headers;\n}\n\n/** Threshold for using presigned URLs (5MB) */\nconst PRESIGNED_THRESHOLD = 5 * 1024 * 1024;\n\n/**\n * Options for uploading to an entity.\n */\nexport interface UploadToEntityOptions {\n /**\n * Version key for the content (default: \"v1\").\n * Use different keys for multiple versions: \"original\", \"thumbnail\", etc.\n */\n key?: string;\n\n /**\n * MIME type of the content.\n * Auto-detected from filename if not provided.\n */\n contentType?: string;\n\n /**\n * Original filename (for Content-Disposition on download).\n * Uses the file's name if a File object is provided.\n */\n filename?: string;\n\n /**\n * Progress callback for large files (presigned uploads only).\n * Called with bytes uploaded and total bytes.\n */\n onProgress?: (uploaded: number, total: number) => void;\n\n /**\n * Force presigned upload even for small files.\n * Useful for testing or when you want client-side CID computation.\n */\n forcePresigned?: boolean;\n}\n\n/**\n * Result of uploading to an entity.\n */\nexport interface UploadToEntityResult {\n /** Entity ID */\n id: string;\n\n /** New entity CID after upload */\n cid: string;\n\n /** Previous entity CID */\n prevCid: string;\n\n /** Content metadata */\n content: {\n key: string;\n cid: string;\n size: number;\n contentType: string;\n filename?: string;\n };\n\n /** Whether presigned upload was used */\n usedPresigned: boolean;\n}\n\n/**\n * Upload a file to an existing entity.\n *\n * Automatically chooses the optimal upload method:\n * - **Direct upload** (< 5MB): Streams through API, server computes CID\n * - **Presigned upload** (>= 5MB): Direct to R2, client computes CID\n *\n * @example\n * ```typescript\n * // Browser: From drag-drop or file input\n * const file = event.dataTransfer.files[0];\n * const result = await uploadToEntity(client, entityId, file);\n *\n * // Browser: From Blob\n * const blob = new Blob([data], { type: 'application/json' });\n * const result = await uploadToEntity(client, entityId, blob, {\n * filename: 'data.json',\n * });\n *\n * // Node.js: From Buffer\n * const buffer = await fs.readFile('document.pdf');\n * const result = await uploadToEntity(client, entityId, buffer, {\n * filename: 'document.pdf',\n * contentType: 'application/pdf',\n * });\n * ```\n */\nexport async function uploadToEntity(\n client: ArkeClient,\n entityId: string,\n data: File | Blob | ArrayBuffer | Uint8Array,\n options: UploadToEntityOptions = {}\n): Promise<UploadToEntityResult> {\n const {\n key = 'v1',\n forcePresigned = false,\n onProgress,\n } = options;\n\n // Determine file properties\n let size: number;\n let filename: string | undefined = options.filename;\n let contentType: string | undefined = options.contentType;\n\n if (data instanceof File) {\n size = data.size;\n filename = filename ?? data.name;\n contentType = contentType ?? (data.type || getMimeType(data.name));\n } else if (data instanceof Blob) {\n size = data.size;\n contentType = contentType ?? (data.type || 'application/octet-stream');\n } else if (data instanceof ArrayBuffer) {\n size = data.byteLength;\n contentType = contentType ?? 'application/octet-stream';\n } else {\n // Uint8Array\n size = data.length;\n contentType = contentType ?? 'application/octet-stream';\n }\n\n // Auto-detect content type from filename if still not set\n if (contentType === 'application/octet-stream' && filename) {\n contentType = getMimeType(filename);\n }\n\n // Decide upload method\n const usePresigned = forcePresigned || size >= PRESIGNED_THRESHOLD;\n\n if (usePresigned) {\n return uploadPresigned(client, entityId, data, {\n key,\n size,\n filename,\n contentType,\n onProgress,\n });\n } else {\n return uploadDirect(client, entityId, data, {\n key,\n size,\n filename,\n contentType,\n });\n }\n}\n\n/**\n * Direct upload - streams through API worker.\n * Best for small files (< 5MB).\n */\nasync function uploadDirect(\n client: ArkeClient,\n entityId: string,\n data: File | Blob | ArrayBuffer | Uint8Array,\n params: {\n key: string;\n size: number;\n filename?: string;\n contentType: string;\n }\n): Promise<UploadToEntityResult> {\n // Convert to Blob for fetch body\n let body: Blob;\n if (data instanceof Blob) {\n body = data;\n } else if (data instanceof ArrayBuffer) {\n body = new Blob([data], { type: params.contentType });\n } else {\n // Uint8Array - copy to regular ArrayBuffer to handle SharedArrayBuffer\n const buffer = new ArrayBuffer(data.byteLength);\n new Uint8Array(buffer).set(data);\n body = new Blob([buffer], { type: params.contentType });\n }\n\n // Use raw fetch for binary upload (openapi-fetch doesn't handle raw binary well)\n const url = new URL(`/entities/${entityId}/content`, client.baseUrl);\n url.searchParams.set('key', params.key);\n if (params.filename) {\n url.searchParams.set('filename', params.filename);\n }\n\n const response = await fetch(url.toString(), {\n method: 'POST',\n headers: {\n 'Content-Type': params.contentType,\n 'Content-Length': params.size.toString(),\n ...buildAuthHeaders(client),\n },\n body,\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({ error: response.statusText }));\n throw new Error(`Upload failed: ${error.error || response.statusText}`);\n }\n\n const result = await response.json();\n\n return {\n id: result.id,\n cid: result.cid,\n prevCid: result.prev_cid,\n content: {\n key: params.key,\n cid: result.content.cid,\n size: result.content.size,\n contentType: result.content.content_type,\n filename: result.content.filename,\n },\n usedPresigned: false,\n };\n}\n\n/**\n * Presigned upload - direct to R2 storage.\n * Best for large files (>= 5MB).\n */\nasync function uploadPresigned(\n client: ArkeClient,\n entityId: string,\n data: File | Blob | ArrayBuffer | Uint8Array,\n params: {\n key: string;\n size: number;\n filename?: string;\n contentType: string;\n onProgress?: (uploaded: number, total: number) => void;\n }\n): Promise<UploadToEntityResult> {\n // Step 1: Get current entity tip for CAS\n const { data: entity, error: getError } = await client.api.GET('/entities/{id}/tip', {\n params: { path: { id: entityId } },\n });\n\n if (getError || !entity) {\n throw new Error(`Failed to get entity: ${JSON.stringify(getError)}`);\n }\n\n const expectTip = entity.cid;\n\n // Step 2: Get presigned URL\n const { data: presigned, error: urlError } = await client.api.POST(\n '/entities/{id}/content/upload-url',\n {\n params: { path: { id: entityId } },\n body: {\n key: params.key,\n content_type: params.contentType,\n size: params.size,\n filename: params.filename,\n },\n }\n );\n\n if (urlError || !presigned) {\n throw new Error(`Failed to get upload URL: ${JSON.stringify(urlError)}`);\n }\n\n // Step 3: Compute CID (required for presigned flow)\n let bytes: ArrayBuffer;\n if (data instanceof Blob) {\n bytes = await data.arrayBuffer();\n } else if (data instanceof ArrayBuffer) {\n bytes = data;\n } else {\n // Uint8Array - copy to regular ArrayBuffer to handle SharedArrayBuffer\n const buffer = new ArrayBuffer(data.byteLength);\n new Uint8Array(buffer).set(data);\n bytes = buffer;\n }\n\n const contentCid = await computeCid(new Uint8Array(bytes));\n\n // Step 4: Upload to presigned URL\n if (params.onProgress && typeof XMLHttpRequest !== 'undefined') {\n // Browser with progress tracking\n await uploadWithProgress(presigned.upload_url, bytes, params.contentType, params.onProgress);\n } else {\n // Simple fetch upload (Node.js or browser without progress)\n const uploadResponse = await fetch(presigned.upload_url, {\n method: 'PUT',\n headers: {\n 'Content-Type': params.contentType,\n },\n body: bytes,\n });\n\n if (!uploadResponse.ok) {\n throw new Error(`Upload to R2 failed: ${uploadResponse.statusText}`);\n }\n }\n\n // Step 5: Complete upload\n const { data: complete, error: completeError } = await client.api.POST(\n '/entities/{id}/content/complete',\n {\n params: { path: { id: entityId } },\n body: {\n key: params.key,\n cid: contentCid,\n size: params.size,\n content_type: params.contentType,\n filename: params.filename,\n expect_tip: expectTip,\n },\n }\n );\n\n if (completeError || !complete) {\n throw new Error(`Failed to complete upload: ${JSON.stringify(completeError)}`);\n }\n\n return {\n id: complete.id,\n cid: complete.cid,\n prevCid: complete.prev_cid,\n content: {\n key: params.key,\n cid: complete.content.cid,\n size: complete.content.size,\n contentType: complete.content.content_type,\n filename: complete.content.filename,\n },\n usedPresigned: true,\n };\n}\n\n/**\n * Upload with progress tracking using XMLHttpRequest.\n * Only available in browser environments.\n */\nfunction uploadWithProgress(\n url: string,\n data: ArrayBuffer,\n contentType: string,\n onProgress: (uploaded: number, total: number) => void\n): Promise<void> {\n return new Promise((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n xhr.open('PUT', url, true);\n xhr.setRequestHeader('Content-Type', contentType);\n\n xhr.upload.onprogress = (event) => {\n if (event.lengthComputable) {\n onProgress(event.loaded, event.total);\n }\n };\n\n xhr.onload = () => {\n if (xhr.status >= 200 && xhr.status < 300) {\n resolve();\n } else {\n reject(new Error(`Upload failed: ${xhr.statusText}`));\n }\n };\n\n xhr.onerror = () => reject(new Error('Upload failed: network error'));\n xhr.onabort = () => reject(new Error('Upload aborted'));\n\n xhr.send(data);\n });\n}\n","/**\n * Folder Operations (Legacy)\n *\n * @deprecated Use the new upload module instead:\n * ```typescript\n * import { uploadTree, buildUploadTree } from '@arke-institute/sdk/operations';\n *\n * const tree = buildUploadTree([\n * { path: 'docs/readme.md', data: readmeBuffer },\n * { path: 'images/logo.png', data: logoBlob },\n * ]);\n * const result = await uploadTree(client, tree, {\n * target: { collectionId: '...' },\n * });\n * ```\n */\n\nimport type { ArkeClient } from '../client/ArkeClient.js';\n\n/**\n * @deprecated Use UploadProgress from upload module\n */\nexport interface UploadProgress {\n phase: 'scanning' | 'creating-folders' | 'uploading-files' | 'linking' | 'complete';\n totalFiles: number;\n completedFiles: number;\n totalFolders: number;\n completedFolders: number;\n currentFile?: string;\n}\n\n/**\n * @deprecated Use UploadOptions from upload module\n */\nexport interface UploadDirectoryOptions {\n /** Collection to upload into */\n collectionId: string;\n /** Parent folder ID (optional - creates at root if not provided) */\n parentFolderId?: string;\n /** Progress callback */\n onProgress?: (progress: UploadProgress) => void;\n /** Max concurrent uploads */\n concurrency?: number;\n}\n\n/**\n * @deprecated Use UploadResult from upload module\n */\nexport interface UploadDirectoryResult {\n /** Root folder entity */\n rootFolder: unknown;\n /** All created folder entities */\n folders: unknown[];\n /** All created file entities */\n files: unknown[];\n}\n\n/**\n * Folder operations helper\n *\n * @deprecated Use uploadTree and buildUploadTree functions instead:\n * ```typescript\n * import { uploadTree, buildUploadTree } from '@arke-institute/sdk/operations';\n *\n * const tree = buildUploadTree([\n * { path: 'docs/readme.md', data: readmeBuffer },\n * ]);\n * const result = await uploadTree(client, tree, {\n * target: { collectionId: '...' },\n * });\n * ```\n */\nexport class FolderOperations {\n constructor(private client: ArkeClient) {\n void client; // Suppress unused warning\n }\n\n /**\n * Upload a local directory to Arke\n *\n * @deprecated This method has been removed. Use uploadTree and buildUploadTree instead.\n */\n async uploadDirectory(\n _localPath: string,\n _options: UploadDirectoryOptions\n ): Promise<UploadDirectoryResult> {\n throw new Error(\n 'FolderOperations.uploadDirectory has been removed. ' +\n 'Use uploadTree() with buildUploadTree() instead. ' +\n 'See: https://github.com/arke-institute/arke-sdk#upload-module'\n );\n }\n}\n","/**\n * Batch Operations\n *\n * High-level operations for bulk entity and relationship management.\n *\n * TODO: Implement batch operations\n * - createEntities: Create multiple entities in parallel\n * - updateEntities: Update multiple entities in parallel\n * - createRelationships: Create multiple relationships in parallel\n */\n\nimport type { ArkeClient } from '../client/ArkeClient.js';\n\nexport interface BatchCreateOptions {\n /** Max concurrent operations */\n concurrency?: number;\n /** Continue on individual failures */\n continueOnError?: boolean;\n /** Progress callback */\n onProgress?: (completed: number, total: number) => void;\n}\n\nexport interface BatchResult<T> {\n /** Successfully completed operations */\n succeeded: T[];\n /** Failed operations with errors */\n failed: Array<{ input: unknown; error: Error }>;\n}\n\n/**\n * Batch operations helper\n *\n * @example\n * ```typescript\n * const batch = new BatchOperations(arkeClient);\n * const result = await batch.createEntities([\n * { type: 'document', properties: { title: 'Doc 1' } },\n * { type: 'document', properties: { title: 'Doc 2' } },\n * ], { concurrency: 5 });\n * ```\n */\nexport class BatchOperations {\n constructor(private client: ArkeClient) {}\n\n /**\n * Create multiple entities in parallel\n *\n * TODO: Implement this method\n */\n async createEntities(\n _entities: Array<{\n collectionId: string;\n type: string;\n properties?: Record<string, unknown>;\n }>,\n _options?: BatchCreateOptions\n ): Promise<BatchResult<unknown>> {\n throw new Error('BatchOperations.createEntities is not yet implemented');\n }\n\n /**\n * Create multiple relationships in parallel\n *\n * TODO: Implement this method\n */\n async createRelationships(\n _relationships: Array<{\n sourceId: string;\n targetId: string;\n predicate: string;\n bidirectional?: boolean;\n properties?: Record<string, unknown>;\n }>,\n _options?: BatchCreateOptions\n ): Promise<BatchResult<unknown>> {\n throw new Error('BatchOperations.createRelationships is not yet implemented');\n }\n}\n","/**\n * Crypto Operations\n *\n * Cryptographic utilities for agents and content addressing.\n *\n * TODO: Implement crypto operations\n * - generateKeyPair: Generate Ed25519 key pair for agent authentication\n * - signPayload: Sign a payload with agent private key\n * - computeCID: Compute IPFS CID for content\n */\n\n/**\n * Ed25519 key pair for agent authentication\n */\nexport interface KeyPair {\n /** Public key in base64 */\n publicKey: string;\n /** Private key in base64 (keep secret!) */\n privateKey: string;\n}\n\n/**\n * Signed payload with signature\n */\nexport interface SignedPayload {\n /** Original payload */\n payload: string;\n /** Ed25519 signature in base64 */\n signature: string;\n /** Timestamp of signature */\n timestamp: number;\n}\n\n/**\n * Crypto operations helper\n *\n * @example\n * ```typescript\n * // Generate key pair for a new agent\n * const { publicKey, privateKey } = await CryptoOperations.generateKeyPair();\n *\n * // Sign a payload\n * const signed = await CryptoOperations.signPayload(privateKey, payload);\n * ```\n */\nexport class CryptoOperations {\n /**\n * Generate an Ed25519 key pair for agent authentication\n *\n * TODO: Implement using Node.js crypto or Web Crypto API\n */\n static async generateKeyPair(): Promise<KeyPair> {\n throw new Error('CryptoOperations.generateKeyPair is not yet implemented');\n }\n\n /**\n * Sign a payload with an Ed25519 private key\n *\n * TODO: Implement signature generation\n */\n static async signPayload(_privateKey: string, _payload: string): Promise<SignedPayload> {\n throw new Error('CryptoOperations.signPayload is not yet implemented');\n }\n\n /**\n * Verify an Ed25519 signature\n *\n * TODO: Implement signature verification\n */\n static async verifySignature(\n _publicKey: string,\n _payload: string,\n _signature: string\n ): Promise<boolean> {\n throw new Error('CryptoOperations.verifySignature is not yet implemented');\n }\n\n /**\n * Compute IPFS CID for content\n *\n * TODO: Implement using multiformats library\n */\n static async computeCID(_content: Uint8Array): Promise<string> {\n throw new Error('CryptoOperations.computeCID is not yet implemented');\n }\n}\n","/**\n * CAS (Compare-And-Swap) retry utility for concurrent updates\n *\n * Use this for additive operations where your update doesn't depend on\n * current state - you just need the tip for CAS validation.\n */\n\nimport { CASConflictError } from '../client/errors.js';\n\n/**\n * Configuration for CAS retry behavior\n */\nexport interface CasRetryOptions {\n /**\n * Expected number of concurrent writers - affects retry timing.\n * Higher concurrency = more initial spread and more retry headroom.\n * @default 10\n */\n concurrency?: number;\n\n /**\n * Override: maximum retry attempts.\n * If not specified, calculated from concurrency.\n */\n maxAttempts?: number;\n\n /**\n * Base delay between retries in ms.\n * Actual delay grows exponentially with jitter.\n * @default 50\n */\n baseDelayMs?: number;\n\n /**\n * Maximum delay between retries in ms (caps exponential growth).\n * @default 10000\n */\n maxDelayMs?: number;\n\n /**\n * Add initial random delay before first attempt to spread concurrent requests.\n * Delay range: 0 to (concurrency * 100)ms. E.g., 500 concurrent = 0-50s spread.\n * This dramatically reduces collisions by staggering first attempts.\n * @default true\n */\n spreadInitial?: boolean;\n\n /**\n * Called before each retry attempt.\n * Useful for logging or monitoring.\n */\n onRetry?: (attempt: number, error: CASConflictError, delayMs: number) => void;\n}\n\n/**\n * Result of a successful CAS retry operation\n */\nexport interface CasRetryResult<T> {\n /** The successful response data */\n data: T;\n /** Number of attempts made (1 = succeeded first try) */\n attempts: number;\n}\n\n/**\n * Callbacks for CAS retry operation\n */\nexport interface CasRetryCallbacks<T> {\n /** Get the current tip/CID - called before each attempt */\n getTip: () => Promise<string>;\n /** Perform the update with given tip - return {data, error} like openapi-fetch */\n update: (tip: string) => Promise<{ data?: T; error?: unknown }>;\n}\n\n/**\n * Default configuration values\n */\nexport const DEFAULT_CAS_RETRY_CONFIG = {\n concurrency: 10,\n baseDelayMs: 50,\n maxDelayMs: 10000, // 10 seconds - allows more spread at high concurrency\n} as const;\n\n/**\n * Calculate max attempts from concurrency level.\n * Formula: max(5, ceil(log2(concurrency) * 4) + floor(concurrency / 100))\n *\n * The logarithmic component handles the base scaling, while the linear\n * component adds extra headroom at very high concurrency levels.\n *\n * Examples:\n * - concurrency 10 → 14 attempts\n * - concurrency 100 → 28 attempts\n * - concurrency 500 → 41 attempts\n * - concurrency 1000 → 50 attempts\n */\nexport function calculateMaxAttempts(concurrency: number): number {\n const logComponent = Math.ceil(Math.log2(Math.max(2, concurrency)) * 4);\n const linearComponent = Math.floor(concurrency / 100);\n return Math.max(5, logComponent + linearComponent);\n}\n\n/**\n * Calculate delay with exponential backoff and heavy jitter.\n * Jitter is 0-100% of the base delay to spread concurrent retries.\n *\n * Formula: min(baseDelay * 1.5^attempt + random(0, baseDelay * 1.5^attempt), maxDelay)\n */\nexport function calculateCasDelay(\n attempt: number,\n baseDelayMs: number,\n maxDelayMs: number\n): number {\n // Exponential backoff: baseDelay * 1.5^attempt\n const exponentialDelay = baseDelayMs * Math.pow(1.5, attempt);\n\n // Cap at maxDelay before adding jitter\n const cappedDelay = Math.min(exponentialDelay, maxDelayMs);\n\n // Heavy jitter: 0-100% of the delay (critical for spreading concurrent retries)\n const jitter = Math.random() * cappedDelay;\n\n return Math.floor(cappedDelay + jitter);\n}\n\n/**\n * Check if an error is a CAS conflict.\n * Handles multiple error shapes:\n * - openapi-fetch: { status: 409, ... }\n * - API error body: { error: \"CAS failure: ...\" }\n */\nexport function isCasConflictError(error: unknown): boolean {\n if (error === null || error === undefined) {\n return false;\n }\n\n if (typeof error !== 'object') {\n return false;\n }\n\n // Check for status 409 (openapi-fetch error shape)\n if ('status' in error && (error as { status: unknown }).status === 409) {\n return true;\n }\n\n // Check for error message pattern (API returns CAS failures this way)\n if ('error' in error) {\n const errorMsg = (error as { error: unknown }).error;\n if (typeof errorMsg === 'string' && errorMsg.startsWith('CAS failure:')) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Sleep for a specified duration\n */\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Error thrown when CAS retries are exhausted\n */\nexport class CasRetryExhaustedError extends Error {\n constructor(\n public readonly attempts: number,\n public readonly lastError: CASConflictError\n ) {\n super(\n `CAS update failed after ${attempts} attempts. ` +\n `Expected tip: ${lastError.expectedTip}, actual: ${lastError.actualTip}`\n );\n this.name = 'CasRetryExhaustedError';\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\n\n/**\n * Wrap a CAS update operation with automatic retry on conflicts.\n *\n * Use this for additive operations where your update doesn't depend on\n * current state - you just need the tip for CAS validation.\n *\n * @example\n * ```typescript\n * const { data, attempts } = await withCasRetry({\n * getTip: async () => {\n * const { data } = await client.api.GET('/entities/{id}/tip', {\n * params: { path: { id: entityId } }\n * });\n * return data!.cid;\n * },\n * update: async (tip) => {\n * return client.api.PUT('/entities/{id}', {\n * params: { path: { id: entityId } },\n * body: {\n * expect_tip: tip,\n * relationships_add: [{ predicate: 'contains', peer: childId }]\n * }\n * });\n * }\n * }, { concurrency: 100 });\n * ```\n *\n * @param callbacks.getTip - Function to fetch the current tip/CID\n * @param callbacks.update - Function to perform the update with the tip\n * @param options - Retry configuration\n * @returns The successful result with attempt count\n * @throws {CasRetryExhaustedError} When all retries are exhausted\n * @throws {Error} For non-CAS errors (not retried)\n */\nexport async function withCasRetry<T>(\n callbacks: CasRetryCallbacks<T>,\n options?: CasRetryOptions\n): Promise<CasRetryResult<T>> {\n const {\n concurrency = DEFAULT_CAS_RETRY_CONFIG.concurrency,\n maxAttempts: maxAttemptsOverride,\n baseDelayMs = DEFAULT_CAS_RETRY_CONFIG.baseDelayMs,\n maxDelayMs = DEFAULT_CAS_RETRY_CONFIG.maxDelayMs,\n spreadInitial = true,\n onRetry,\n } = options ?? {};\n\n const maxAttempts = maxAttemptsOverride ?? calculateMaxAttempts(concurrency);\n\n // Initial spread: random delay before first attempt to reduce initial collisions\n // Range: 0 to (concurrency * 100)ms - e.g., 500 concurrent = 0-50s spread\n // This spreads first attempts over time, dramatically reducing collisions\n if (spreadInitial && concurrency > 1) {\n const initialSpread = Math.floor(Math.random() * concurrency * 100);\n await sleep(initialSpread);\n }\n\n let lastCasError: CASConflictError | undefined;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n // Get fresh tip before each attempt\n const tip = await callbacks.getTip();\n\n // Attempt the update\n const { data, error } = await callbacks.update(tip);\n\n // Success!\n if (!error && data !== undefined) {\n return { data, attempts: attempt };\n }\n\n // Check if it's a CAS conflict\n if (isCasConflictError(error)) {\n // Parse the error details from various formats\n let expectedTip: string | undefined;\n let actualTip: string | undefined;\n\n const errorObj = error as Record<string, unknown>;\n\n // Format 1: { details: { expected, actual } }\n if (errorObj.details && typeof errorObj.details === 'object') {\n const details = errorObj.details as { expected?: string; actual?: string };\n expectedTip = details.expected;\n actualTip = details.actual;\n }\n\n // Format 2: { error: \"CAS failure: expected tip X, got Y\" }\n if (!expectedTip && typeof errorObj.error === 'string') {\n const match = errorObj.error.match(/expected tip (\\S+), got (\\S+)/);\n if (match) {\n expectedTip = match[1];\n actualTip = match[2];\n }\n }\n\n lastCasError = new CASConflictError(expectedTip, actualTip);\n\n // If we have more attempts, wait and retry\n if (attempt < maxAttempts) {\n const delay = calculateCasDelay(attempt - 1, baseDelayMs, maxDelayMs);\n onRetry?.(attempt, lastCasError, delay);\n await sleep(delay);\n continue;\n }\n } else {\n // Non-CAS error - throw immediately, don't retry\n throw new Error(\n `Update failed with non-CAS error: ${JSON.stringify(error)}`\n );\n }\n }\n\n // Exhausted all attempts\n throw new CasRetryExhaustedError(\n maxAttempts,\n lastCasError ?? new CASConflictError()\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACMA,2BAA0C;;;AC8DnC,IAAM,iBAA0E;AAAA,EACrF,SAAS;AAAA,EACT,SAAS;AACX;;;AC1BO,IAAM,uBAA+D;AAAA,EAC1E,YAAY;AAAA,EACZ,cAAc;AAAA,EACd,UAAU;AAAA,EACV,YAAY;AAAA,EACZ,qBAAqB;AACvB;AAKA,IAAM,yBAAyB,oB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AAS,WAAW,OAAO,SAAS,YAAY,UAAU;AAC5D,cAAM,UAAU,SAAS;AACzB,sBAAc,QAAQ;AACtB,oBAAY,QAAQ;AAAA,MACtB;AAGA,UAAI,CAAC,eAAe,OAAO,SAAS,UAAU,UAAU;AACtD,cAAM,QAAQ,SAAS,MAAM,MAAM,+BAA+B;AAClE,YAAI,OAAO;AACT,wBAAc,MAAM,CAAC;AACrB,sBAAY,MAAM,CAAC;AAAA,QACrB;AAAA,MACF;AAEA,qBAAe,IAAI,iBAAiB,aAAa,SAAS;AAG1D,UAAI,UAAU,aAAa;AACzB,cAAM,QAAQ,kBAAkB,UAAU,GAAG,aAAa,UAAU;AACpE,kBAAU,SAAS,cAAc,KAAK;AACtC,cAAMA,OAAM,KAAK;AACjB;AAAA,MACF;AAAA,IACF,OAAO;AAEL,YAAM,IAAI;AAAA,QACR,qCAAqC,KAAK,UAAU,KAAK,CAAC;AAAA,MAC5D;AAAA,IACF;AAAA,EACF;AAGA,QAAM,IAAI;AAAA,IACR;AAAA,IACA,gBAAgB,IAAI,iBAAiB;AAAA,EACvC;AACF;","names":["code","createClient","sleep"]}
|
package/dist/index.js
CHANGED
|
@@ -432,6 +432,9 @@ import * as raw from "multiformats/codecs/raw";
|
|
|
432
432
|
var TARGET_BYTES_IN_FLIGHT = 200 * 1024 * 1024;
|
|
433
433
|
var PRESIGNED_URL_THRESHOLD = 5 * 1024 * 1024;
|
|
434
434
|
|
|
435
|
+
// src/operations/upload/single.ts
|
|
436
|
+
var PRESIGNED_THRESHOLD = 5 * 1024 * 1024;
|
|
437
|
+
|
|
435
438
|
// src/operations/folders.ts
|
|
436
439
|
var FolderOperations = class {
|
|
437
440
|
constructor(client) {
|