@scalemule/sdk 0.0.16 → 0.0.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -881,6 +881,21 @@ interface UploadCompleteResponse {
881
881
  already_completed: boolean;
882
882
  scan_queued: boolean;
883
883
  }
884
+ interface UploadFailureReport {
885
+ fileId: string;
886
+ completionToken: string;
887
+ step: string;
888
+ errorCode: string;
889
+ errorMessage?: string;
890
+ httpStatus?: number;
891
+ attempt?: number;
892
+ diagnostics?: Record<string, unknown>;
893
+ }
894
+ interface UploadFailureReportResponse {
895
+ file_id: string;
896
+ recorded: boolean;
897
+ upload_status: string;
898
+ }
884
899
  interface MultipartStartResponse {
885
900
  upload_session_id: string;
886
901
  file_id: string;
@@ -947,6 +962,7 @@ declare class StorageService extends ServiceModule {
947
962
  getUploadUrl(filename: string, contentType: string, options?: {
948
963
  isPublic?: boolean;
949
964
  expiresIn?: number;
965
+ sizeBytes?: number;
950
966
  metadata?: Record<string, unknown>;
951
967
  }, requestOptions?: RequestOptions): Promise<ApiResponse<PresignedUploadResponse>>;
952
968
  /**
@@ -957,6 +973,11 @@ declare class StorageService extends ServiceModule {
957
973
  sizeBytes?: number;
958
974
  checksum?: string;
959
975
  }, requestOptions?: RequestOptions): Promise<ApiResponse<UploadCompleteResponse>>;
976
+ /**
977
+ * Persist a structured client-side upload failure against a file record.
978
+ * Best used by split-upload clients that call getUploadUrl() manually.
979
+ */
980
+ reportUploadFailure(params: UploadFailureReport, requestOptions?: RequestOptions): Promise<ApiResponse<UploadFailureReportResponse>>;
960
981
  /** Start a multipart upload session. */
961
982
  startMultipartUpload(params: {
962
983
  filename: string;
@@ -1050,6 +1071,7 @@ declare class StorageService extends ServiceModule {
1050
1071
  private defaultChunkSize;
1051
1072
  private defaultConcurrency;
1052
1073
  private maybeCompress;
1074
+ private reportUploadFailureBestEffort;
1053
1075
  private getOrCreateTelemetry;
1054
1076
  /** Build RequestOptions with X-Upload-Session-Id header for cross-boundary correlation */
1055
1077
  private withSessionHeader;
@@ -1252,6 +1274,73 @@ declare function getPartRange(partNumber: number, chunkSize: number, totalSize:
1252
1274
  size: number;
1253
1275
  };
1254
1276
 
1277
+ /**
1278
+ * Standalone S3 upload utilities for browser environments.
1279
+ *
1280
+ * These functions handle the client-side portion of presigned URL uploads:
1281
+ * - Single PUT for small files (with retry + stall detection)
1282
+ * - Multipart chunked upload for large files (parallel parts, per-chunk retry, ETag collection)
1283
+ *
1284
+ * Used by any app that gets presigned URLs from the server and needs to upload to S3.
1285
+ * The server-side proxy routes are app-specific; these utilities are app-agnostic.
1286
+ */
1287
+ interface S3UploadProgress {
1288
+ loaded: number;
1289
+ total: number;
1290
+ percentage: number;
1291
+ }
1292
+ interface S3SingleUploadOptions {
1293
+ onProgress?: (progress: S3UploadProgress) => void;
1294
+ signal?: AbortSignal;
1295
+ /** Max retries per attempt (default: 3) */
1296
+ maxRetries?: number;
1297
+ /** Stall timeout in ms — abort if no progress for this long (default: 45000) */
1298
+ stallTimeoutMs?: number;
1299
+ }
1300
+ interface S3SingleUploadResult {
1301
+ success: boolean;
1302
+ error?: string;
1303
+ }
1304
+ interface MultipartPartUrl {
1305
+ partNumber: number;
1306
+ url: string;
1307
+ }
1308
+ interface MultipartConfig {
1309
+ partSizeBytes: number;
1310
+ totalParts: number;
1311
+ partUrls: MultipartPartUrl[];
1312
+ /** Fetch fresh URLs when needed (e.g., on 403 expiry). App provides this via its proxy route. */
1313
+ fetchMoreUrls?: (partNumbers: number[]) => Promise<MultipartPartUrl[] | null>;
1314
+ }
1315
+ interface S3MultipartOptions {
1316
+ onProgress?: (progress: S3UploadProgress) => void;
1317
+ signal?: AbortSignal;
1318
+ /** Max concurrent part uploads (default: 3) */
1319
+ concurrency?: number;
1320
+ /** Max retries per part (default: 3) */
1321
+ maxRetries?: number;
1322
+ }
1323
+ interface PartResult {
1324
+ partNumber: number;
1325
+ etag: string;
1326
+ }
1327
+ interface S3MultipartResult {
1328
+ success: boolean;
1329
+ parts?: PartResult[];
1330
+ error?: string;
1331
+ }
1332
+ /**
1333
+ * Upload a file to S3 via a single presigned PUT.
1334
+ * Includes retry on 5xx/network errors and stall detection.
1335
+ */
1336
+ declare function uploadSingleToS3(url: string, file: File | Blob, options?: S3SingleUploadOptions): Promise<S3SingleUploadResult>;
1337
+ /**
1338
+ * Upload a file to S3 using multipart chunked upload.
1339
+ * Splits the file into chunks, uploads in parallel with per-chunk retry,
1340
+ * collects ETags for completion.
1341
+ */
1342
+ declare function uploadMultipartToS3(file: File | Blob, config: MultipartConfig, options?: S3MultipartOptions): Promise<S3MultipartResult>;
1343
+
1255
1344
  /**
1256
1345
  * Realtime Service Module
1257
1346
  *
@@ -5152,4 +5241,4 @@ declare class ScaleMule {
5152
5241
  getClient(): ScaleMuleClient;
5153
5242
  }
5154
5243
 
5155
- export { type AccountBalance, AccountsService, type ActiveUsers, type ActivityItem, AgentAuthService, AgentModelsService, type AgentProfile, AgentProjectsService, type AgentResponse, type AgentSecurityPolicy, AgentSessionsService, type AgentSigningKey, type AgentToken, type AgentToolEntitlement, AgentToolsService, type Workspace as AgentWorkspace, AgentsService, type AggregateOptions, type AggregateResult, type AnalyticsEvent, AnalyticsService, type ApiError, type ApiKey, type ApiResponse, type Appeal, type Application, type Attachment, type Attendee, type AuditLog, type AuthRegisterAgentRequest, type AuthRegisterAgentResponse, AuthService, type AuthSession, type AuthUser, type BackupCodes, BillingService, type CacheEntry, CacheService, type CalendarEvent, type CatalogEntry, CatalogService, type ChatMessage, type ChatReaction, ChatService, type ClaimResult, type Client, type ClientContext, type Collection, type Comment, CommunicationService, type CompletedPart, ComplianceService, type CompressionConfig, type ConnectedAccount, type ConnectedAccountSubscription, type ConnectedSetupIntentResponse, type ConnectedSubscriptionListParams, type ConnectionStatus, type ContentFlag, type Conversation, type CostReportDay, type CreateFlagRequest, type CreateRuleRequest, type CreateSegmentRequest, type CreateSessionResponse, type CreateVariantRequest, type Credential, type CredentialScope, type Customer, type DataAccessPolicy, type DataExport, DataService, type DataSource, type DeadLetterJob, type DeviceInfo, type Document, type ErrorCode, ErrorCodes, type EventAggregation, EventsService, type FileInfo, type FlagAuditEntry, type FlagCheck, type FlagCondition, FlagContentService, type FlagDefinition, type FlagDetail, type FlagEnvironment, type FlagEvaluation, type FlagSegment, type FlagVariant, FlagsService, type FollowStatus, type FunctionExecution, type FunctionMetrics, FunctionsService, type Funnel, type FunnelConversion, type GdprRequest, type GrantInfo, type GraphEdge, type GraphNode, GraphService, IdentityService, type IdentityType, type IncomingRequestLike, type Invoice, type JobExecution, type JobStats, type Leaderboard, type LeaderboardEntry, LeaderboardService, type Like, type Listing, ListingsService, type LogEntry, type LogInput, type LogQueryParams, type LogQueryResponse, type LogRecord, LoggerService, type LoginActivitySummary, type LoginDeviceInfo, type LoginHistoryEntry, type LoginRiskInfo, type MessageCallback, type MessageStatus, type MetricDataPoint, type MfaStatus, type Model, type ModelEntitlement, type ModelPricing, type ModelProvider, type UsageSummary as ModelUsageSummary, type MultipartCompleteResponse, type MultipartPartUrlsResponse, type MultipartStartResponse, type NetworkClass, type OAuthProvider, type OAuthUrl, OrchestratorService, PHOTO_BREAKPOINTS, type PaginatedResponse, type PaginationMetadata, type PaginationParams, type PartUrl, type Participant, type Payment, type PaymentListParams, type PaymentMethod, type PaymentStatusResponse, type Payout, type PayoutSchedule, type PermissionCheck, type PermissionMatrix, PermissionsService, type PhotoInfo, PhotoService, type Pipeline, type PipelineVersion, type Policy, type PresenceCallback, type PresenceEvent, type PresignedUploadResponse, type Price, type Product, type Project, type ProjectDocument, type ProjectGrant, type ProjectMember, type PushToken, type QueryFilter, type QueryOptions, type QuerySort, type QueueJob, QueueService, type ReadStatus, RealtimeService, type RedeemResult, type Refund, type RegisterAgentRequest, type RegisterAgentResponse, type RequestOptions, type ResumeSession, type Role, type RuntimeTemplate, type RuntimeTemplateVersion, ScaleMule, ScaleMuleClient, type ScaleMuleConfig, type SchedulerJob, SchedulerService, type SearchResult, SearchService, type SecurityLayers, type ServerlessFunction, type ServiceHealth, ServiceModule, type Session, type SessionArtifact, type SessionInfo, type SessionLog, type Severity, type ShortestPathResult, type SignedUrlResponse, type SocialPost, SocialService, type SocialUser, type SsoConfig, type StatusCallback, type StorageAdapter, StorageService, type StrategyResult, type SubmitResult, type Subscription, type TargetingRule, type Task, type TaskAttempt, type TaskTransition, type Team, type TeamInvitation, type TeamMember, TeamsService, type TelemetryPayload, type Tool, type ToolCapability, type ToolIntegration, type TopEvent, type TotpSetup, type Transaction, type TransactionListParams, type TransactionSummary, type TransactionSummaryParams, type Transfer, type TransformOptions, type TransformResult, type TraversalResult, type UpdateFlagRequest, type UpdateRuleRequest, type UpdateSegmentRequest, type UpdateVariantRequest, type UploadCompleteResponse, type UploadEngineConfig, type UploadOptions, type UploadPlan, UploadResumeStore, type UploadStrategy, UploadTelemetry, type UploadTelemetryConfig, type UploadTelemetryEvent, type UpsertEnvironmentRequest, type UsageRecord, type UsageSummary$1 as UsageSummary, type UserRank, type VideoInfo, VideoService, type VideoUploadOptions, type Webhook, WebhooksService, type Workflow, type WorkflowExecution, type Workspace$1 as Workspace, type WorkspaceInvitation, type WorkspaceMember, WorkspacesService, buildClientContextHeaders, calculateTotalParts, canPerform, createUploadPlan, ScaleMule as default, detectNetworkClass, extractClientContext, generateUploadSessionId, getMeasuredBandwidthMbps, getPartRange, hasMinRoleLevel, resolveStrategy, validateIP };
5244
+ export { type AccountBalance, AccountsService, type ActiveUsers, type ActivityItem, AgentAuthService, AgentModelsService, type AgentProfile, AgentProjectsService, type AgentResponse, type AgentSecurityPolicy, AgentSessionsService, type AgentSigningKey, type AgentToken, type AgentToolEntitlement, AgentToolsService, type Workspace as AgentWorkspace, AgentsService, type AggregateOptions, type AggregateResult, type AnalyticsEvent, AnalyticsService, type ApiError, type ApiKey, type ApiResponse, type Appeal, type Application, type Attachment, type Attendee, type AuditLog, type AuthRegisterAgentRequest, type AuthRegisterAgentResponse, AuthService, type AuthSession, type AuthUser, type BackupCodes, BillingService, type CacheEntry, CacheService, type CalendarEvent, type CatalogEntry, CatalogService, type ChatMessage, type ChatReaction, ChatService, type ClaimResult, type Client, type ClientContext, type Collection, type Comment, CommunicationService, type CompletedPart, ComplianceService, type CompressionConfig, type ConnectedAccount, type ConnectedAccountSubscription, type ConnectedSetupIntentResponse, type ConnectedSubscriptionListParams, type ConnectionStatus, type ContentFlag, type Conversation, type CostReportDay, type CreateFlagRequest, type CreateRuleRequest, type CreateSegmentRequest, type CreateSessionResponse, type CreateVariantRequest, type Credential, type CredentialScope, type Customer, type DataAccessPolicy, type DataExport, DataService, type DataSource, type DeadLetterJob, type DeviceInfo, type Document, type ErrorCode, ErrorCodes, type EventAggregation, EventsService, type FileInfo, type FlagAuditEntry, type FlagCheck, type FlagCondition, FlagContentService, type FlagDefinition, type FlagDetail, type FlagEnvironment, type FlagEvaluation, type FlagSegment, type FlagVariant, FlagsService, type FollowStatus, type FunctionExecution, type FunctionMetrics, FunctionsService, type Funnel, type FunnelConversion, type GdprRequest, type GrantInfo, type GraphEdge, type GraphNode, GraphService, IdentityService, type IdentityType, type IncomingRequestLike, type Invoice, type JobExecution, type JobStats, type Leaderboard, type LeaderboardEntry, LeaderboardService, type Like, type Listing, ListingsService, type LogEntry, type LogInput, type LogQueryParams, type LogQueryResponse, type LogRecord, LoggerService, type LoginActivitySummary, type LoginDeviceInfo, type LoginHistoryEntry, type LoginRiskInfo, type MessageCallback, type MessageStatus, type MetricDataPoint, type MfaStatus, type Model, type ModelEntitlement, type ModelPricing, type ModelProvider, type UsageSummary as ModelUsageSummary, type MultipartCompleteResponse, type MultipartConfig, type MultipartPartUrl, type MultipartPartUrlsResponse, type MultipartStartResponse, type NetworkClass, type OAuthProvider, type OAuthUrl, OrchestratorService, PHOTO_BREAKPOINTS, type PaginatedResponse, type PaginationMetadata, type PaginationParams, type PartResult, type PartUrl, type Participant, type Payment, type PaymentListParams, type PaymentMethod, type PaymentStatusResponse, type Payout, type PayoutSchedule, type PermissionCheck, type PermissionMatrix, PermissionsService, type PhotoInfo, PhotoService, type Pipeline, type PipelineVersion, type Policy, type PresenceCallback, type PresenceEvent, type PresignedUploadResponse, type Price, type Product, type Project, type ProjectDocument, type ProjectGrant, type ProjectMember, type PushToken, type QueryFilter, type QueryOptions, type QuerySort, type QueueJob, QueueService, type ReadStatus, RealtimeService, type RedeemResult, type Refund, type RegisterAgentRequest, type RegisterAgentResponse, type RequestOptions, type ResumeSession, type Role, type RuntimeTemplate, type RuntimeTemplateVersion, type S3MultipartOptions, type S3MultipartResult, type S3SingleUploadOptions, type S3SingleUploadResult, type S3UploadProgress, ScaleMule, ScaleMuleClient, type ScaleMuleConfig, type SchedulerJob, SchedulerService, type SearchResult, SearchService, type SecurityLayers, type ServerlessFunction, type ServiceHealth, ServiceModule, type Session, type SessionArtifact, type SessionInfo, type SessionLog, type Severity, type ShortestPathResult, type SignedUrlResponse, type SocialPost, SocialService, type SocialUser, type SsoConfig, type StatusCallback, type StorageAdapter, StorageService, type StrategyResult, type SubmitResult, type Subscription, type TargetingRule, type Task, type TaskAttempt, type TaskTransition, type Team, type TeamInvitation, type TeamMember, TeamsService, type TelemetryPayload, type Tool, type ToolCapability, type ToolIntegration, type TopEvent, type TotpSetup, type Transaction, type TransactionListParams, type TransactionSummary, type TransactionSummaryParams, type Transfer, type TransformOptions, type TransformResult, type TraversalResult, type UpdateFlagRequest, type UpdateRuleRequest, type UpdateSegmentRequest, type UpdateVariantRequest, type UploadCompleteResponse, type UploadEngineConfig, type UploadFailureReport, type UploadFailureReportResponse, type UploadOptions, type UploadPlan, UploadResumeStore, type UploadStrategy, UploadTelemetry, type UploadTelemetryConfig, type UploadTelemetryEvent, type UpsertEnvironmentRequest, type UsageRecord, type UsageSummary$1 as UsageSummary, type UserRank, type VideoInfo, VideoService, type VideoUploadOptions, type Webhook, WebhooksService, type Workflow, type WorkflowExecution, type Workspace$1 as Workspace, type WorkspaceInvitation, type WorkspaceMember, WorkspacesService, buildClientContextHeaders, calculateTotalParts, canPerform, createUploadPlan, ScaleMule as default, detectNetworkClass, extractClientContext, generateUploadSessionId, getMeasuredBandwidthMbps, getPartRange, hasMinRoleLevel, resolveStrategy, uploadMultipartToS3, uploadSingleToS3, validateIP };
package/dist/index.d.ts CHANGED
@@ -881,6 +881,21 @@ interface UploadCompleteResponse {
881
881
  already_completed: boolean;
882
882
  scan_queued: boolean;
883
883
  }
884
+ interface UploadFailureReport {
885
+ fileId: string;
886
+ completionToken: string;
887
+ step: string;
888
+ errorCode: string;
889
+ errorMessage?: string;
890
+ httpStatus?: number;
891
+ attempt?: number;
892
+ diagnostics?: Record<string, unknown>;
893
+ }
894
+ interface UploadFailureReportResponse {
895
+ file_id: string;
896
+ recorded: boolean;
897
+ upload_status: string;
898
+ }
884
899
  interface MultipartStartResponse {
885
900
  upload_session_id: string;
886
901
  file_id: string;
@@ -947,6 +962,7 @@ declare class StorageService extends ServiceModule {
947
962
  getUploadUrl(filename: string, contentType: string, options?: {
948
963
  isPublic?: boolean;
949
964
  expiresIn?: number;
965
+ sizeBytes?: number;
950
966
  metadata?: Record<string, unknown>;
951
967
  }, requestOptions?: RequestOptions): Promise<ApiResponse<PresignedUploadResponse>>;
952
968
  /**
@@ -957,6 +973,11 @@ declare class StorageService extends ServiceModule {
957
973
  sizeBytes?: number;
958
974
  checksum?: string;
959
975
  }, requestOptions?: RequestOptions): Promise<ApiResponse<UploadCompleteResponse>>;
976
+ /**
977
+ * Persist a structured client-side upload failure against a file record.
978
+ * Best used by split-upload clients that call getUploadUrl() manually.
979
+ */
980
+ reportUploadFailure(params: UploadFailureReport, requestOptions?: RequestOptions): Promise<ApiResponse<UploadFailureReportResponse>>;
960
981
  /** Start a multipart upload session. */
961
982
  startMultipartUpload(params: {
962
983
  filename: string;
@@ -1050,6 +1071,7 @@ declare class StorageService extends ServiceModule {
1050
1071
  private defaultChunkSize;
1051
1072
  private defaultConcurrency;
1052
1073
  private maybeCompress;
1074
+ private reportUploadFailureBestEffort;
1053
1075
  private getOrCreateTelemetry;
1054
1076
  /** Build RequestOptions with X-Upload-Session-Id header for cross-boundary correlation */
1055
1077
  private withSessionHeader;
@@ -1252,6 +1274,73 @@ declare function getPartRange(partNumber: number, chunkSize: number, totalSize:
1252
1274
  size: number;
1253
1275
  };
1254
1276
 
1277
+ /**
1278
+ * Standalone S3 upload utilities for browser environments.
1279
+ *
1280
+ * These functions handle the client-side portion of presigned URL uploads:
1281
+ * - Single PUT for small files (with retry + stall detection)
1282
+ * - Multipart chunked upload for large files (parallel parts, per-chunk retry, ETag collection)
1283
+ *
1284
+ * Used by any app that gets presigned URLs from the server and needs to upload to S3.
1285
+ * The server-side proxy routes are app-specific; these utilities are app-agnostic.
1286
+ */
1287
+ interface S3UploadProgress {
1288
+ loaded: number;
1289
+ total: number;
1290
+ percentage: number;
1291
+ }
1292
+ interface S3SingleUploadOptions {
1293
+ onProgress?: (progress: S3UploadProgress) => void;
1294
+ signal?: AbortSignal;
1295
+ /** Max retries per attempt (default: 3) */
1296
+ maxRetries?: number;
1297
+ /** Stall timeout in ms — abort if no progress for this long (default: 45000) */
1298
+ stallTimeoutMs?: number;
1299
+ }
1300
+ interface S3SingleUploadResult {
1301
+ success: boolean;
1302
+ error?: string;
1303
+ }
1304
+ interface MultipartPartUrl {
1305
+ partNumber: number;
1306
+ url: string;
1307
+ }
1308
+ interface MultipartConfig {
1309
+ partSizeBytes: number;
1310
+ totalParts: number;
1311
+ partUrls: MultipartPartUrl[];
1312
+ /** Fetch fresh URLs when needed (e.g., on 403 expiry). App provides this via its proxy route. */
1313
+ fetchMoreUrls?: (partNumbers: number[]) => Promise<MultipartPartUrl[] | null>;
1314
+ }
1315
+ interface S3MultipartOptions {
1316
+ onProgress?: (progress: S3UploadProgress) => void;
1317
+ signal?: AbortSignal;
1318
+ /** Max concurrent part uploads (default: 3) */
1319
+ concurrency?: number;
1320
+ /** Max retries per part (default: 3) */
1321
+ maxRetries?: number;
1322
+ }
1323
+ interface PartResult {
1324
+ partNumber: number;
1325
+ etag: string;
1326
+ }
1327
+ interface S3MultipartResult {
1328
+ success: boolean;
1329
+ parts?: PartResult[];
1330
+ error?: string;
1331
+ }
1332
+ /**
1333
+ * Upload a file to S3 via a single presigned PUT.
1334
+ * Includes retry on 5xx/network errors and stall detection.
1335
+ */
1336
+ declare function uploadSingleToS3(url: string, file: File | Blob, options?: S3SingleUploadOptions): Promise<S3SingleUploadResult>;
1337
+ /**
1338
+ * Upload a file to S3 using multipart chunked upload.
1339
+ * Splits the file into chunks, uploads in parallel with per-chunk retry,
1340
+ * collects ETags for completion.
1341
+ */
1342
+ declare function uploadMultipartToS3(file: File | Blob, config: MultipartConfig, options?: S3MultipartOptions): Promise<S3MultipartResult>;
1343
+
1255
1344
  /**
1256
1345
  * Realtime Service Module
1257
1346
  *
@@ -5152,4 +5241,4 @@ declare class ScaleMule {
5152
5241
  getClient(): ScaleMuleClient;
5153
5242
  }
5154
5243
 
5155
- export { type AccountBalance, AccountsService, type ActiveUsers, type ActivityItem, AgentAuthService, AgentModelsService, type AgentProfile, AgentProjectsService, type AgentResponse, type AgentSecurityPolicy, AgentSessionsService, type AgentSigningKey, type AgentToken, type AgentToolEntitlement, AgentToolsService, type Workspace as AgentWorkspace, AgentsService, type AggregateOptions, type AggregateResult, type AnalyticsEvent, AnalyticsService, type ApiError, type ApiKey, type ApiResponse, type Appeal, type Application, type Attachment, type Attendee, type AuditLog, type AuthRegisterAgentRequest, type AuthRegisterAgentResponse, AuthService, type AuthSession, type AuthUser, type BackupCodes, BillingService, type CacheEntry, CacheService, type CalendarEvent, type CatalogEntry, CatalogService, type ChatMessage, type ChatReaction, ChatService, type ClaimResult, type Client, type ClientContext, type Collection, type Comment, CommunicationService, type CompletedPart, ComplianceService, type CompressionConfig, type ConnectedAccount, type ConnectedAccountSubscription, type ConnectedSetupIntentResponse, type ConnectedSubscriptionListParams, type ConnectionStatus, type ContentFlag, type Conversation, type CostReportDay, type CreateFlagRequest, type CreateRuleRequest, type CreateSegmentRequest, type CreateSessionResponse, type CreateVariantRequest, type Credential, type CredentialScope, type Customer, type DataAccessPolicy, type DataExport, DataService, type DataSource, type DeadLetterJob, type DeviceInfo, type Document, type ErrorCode, ErrorCodes, type EventAggregation, EventsService, type FileInfo, type FlagAuditEntry, type FlagCheck, type FlagCondition, FlagContentService, type FlagDefinition, type FlagDetail, type FlagEnvironment, type FlagEvaluation, type FlagSegment, type FlagVariant, FlagsService, type FollowStatus, type FunctionExecution, type FunctionMetrics, FunctionsService, type Funnel, type FunnelConversion, type GdprRequest, type GrantInfo, type GraphEdge, type GraphNode, GraphService, IdentityService, type IdentityType, type IncomingRequestLike, type Invoice, type JobExecution, type JobStats, type Leaderboard, type LeaderboardEntry, LeaderboardService, type Like, type Listing, ListingsService, type LogEntry, type LogInput, type LogQueryParams, type LogQueryResponse, type LogRecord, LoggerService, type LoginActivitySummary, type LoginDeviceInfo, type LoginHistoryEntry, type LoginRiskInfo, type MessageCallback, type MessageStatus, type MetricDataPoint, type MfaStatus, type Model, type ModelEntitlement, type ModelPricing, type ModelProvider, type UsageSummary as ModelUsageSummary, type MultipartCompleteResponse, type MultipartPartUrlsResponse, type MultipartStartResponse, type NetworkClass, type OAuthProvider, type OAuthUrl, OrchestratorService, PHOTO_BREAKPOINTS, type PaginatedResponse, type PaginationMetadata, type PaginationParams, type PartUrl, type Participant, type Payment, type PaymentListParams, type PaymentMethod, type PaymentStatusResponse, type Payout, type PayoutSchedule, type PermissionCheck, type PermissionMatrix, PermissionsService, type PhotoInfo, PhotoService, type Pipeline, type PipelineVersion, type Policy, type PresenceCallback, type PresenceEvent, type PresignedUploadResponse, type Price, type Product, type Project, type ProjectDocument, type ProjectGrant, type ProjectMember, type PushToken, type QueryFilter, type QueryOptions, type QuerySort, type QueueJob, QueueService, type ReadStatus, RealtimeService, type RedeemResult, type Refund, type RegisterAgentRequest, type RegisterAgentResponse, type RequestOptions, type ResumeSession, type Role, type RuntimeTemplate, type RuntimeTemplateVersion, ScaleMule, ScaleMuleClient, type ScaleMuleConfig, type SchedulerJob, SchedulerService, type SearchResult, SearchService, type SecurityLayers, type ServerlessFunction, type ServiceHealth, ServiceModule, type Session, type SessionArtifact, type SessionInfo, type SessionLog, type Severity, type ShortestPathResult, type SignedUrlResponse, type SocialPost, SocialService, type SocialUser, type SsoConfig, type StatusCallback, type StorageAdapter, StorageService, type StrategyResult, type SubmitResult, type Subscription, type TargetingRule, type Task, type TaskAttempt, type TaskTransition, type Team, type TeamInvitation, type TeamMember, TeamsService, type TelemetryPayload, type Tool, type ToolCapability, type ToolIntegration, type TopEvent, type TotpSetup, type Transaction, type TransactionListParams, type TransactionSummary, type TransactionSummaryParams, type Transfer, type TransformOptions, type TransformResult, type TraversalResult, type UpdateFlagRequest, type UpdateRuleRequest, type UpdateSegmentRequest, type UpdateVariantRequest, type UploadCompleteResponse, type UploadEngineConfig, type UploadOptions, type UploadPlan, UploadResumeStore, type UploadStrategy, UploadTelemetry, type UploadTelemetryConfig, type UploadTelemetryEvent, type UpsertEnvironmentRequest, type UsageRecord, type UsageSummary$1 as UsageSummary, type UserRank, type VideoInfo, VideoService, type VideoUploadOptions, type Webhook, WebhooksService, type Workflow, type WorkflowExecution, type Workspace$1 as Workspace, type WorkspaceInvitation, type WorkspaceMember, WorkspacesService, buildClientContextHeaders, calculateTotalParts, canPerform, createUploadPlan, ScaleMule as default, detectNetworkClass, extractClientContext, generateUploadSessionId, getMeasuredBandwidthMbps, getPartRange, hasMinRoleLevel, resolveStrategy, validateIP };
5244
+ export { type AccountBalance, AccountsService, type ActiveUsers, type ActivityItem, AgentAuthService, AgentModelsService, type AgentProfile, AgentProjectsService, type AgentResponse, type AgentSecurityPolicy, AgentSessionsService, type AgentSigningKey, type AgentToken, type AgentToolEntitlement, AgentToolsService, type Workspace as AgentWorkspace, AgentsService, type AggregateOptions, type AggregateResult, type AnalyticsEvent, AnalyticsService, type ApiError, type ApiKey, type ApiResponse, type Appeal, type Application, type Attachment, type Attendee, type AuditLog, type AuthRegisterAgentRequest, type AuthRegisterAgentResponse, AuthService, type AuthSession, type AuthUser, type BackupCodes, BillingService, type CacheEntry, CacheService, type CalendarEvent, type CatalogEntry, CatalogService, type ChatMessage, type ChatReaction, ChatService, type ClaimResult, type Client, type ClientContext, type Collection, type Comment, CommunicationService, type CompletedPart, ComplianceService, type CompressionConfig, type ConnectedAccount, type ConnectedAccountSubscription, type ConnectedSetupIntentResponse, type ConnectedSubscriptionListParams, type ConnectionStatus, type ContentFlag, type Conversation, type CostReportDay, type CreateFlagRequest, type CreateRuleRequest, type CreateSegmentRequest, type CreateSessionResponse, type CreateVariantRequest, type Credential, type CredentialScope, type Customer, type DataAccessPolicy, type DataExport, DataService, type DataSource, type DeadLetterJob, type DeviceInfo, type Document, type ErrorCode, ErrorCodes, type EventAggregation, EventsService, type FileInfo, type FlagAuditEntry, type FlagCheck, type FlagCondition, FlagContentService, type FlagDefinition, type FlagDetail, type FlagEnvironment, type FlagEvaluation, type FlagSegment, type FlagVariant, FlagsService, type FollowStatus, type FunctionExecution, type FunctionMetrics, FunctionsService, type Funnel, type FunnelConversion, type GdprRequest, type GrantInfo, type GraphEdge, type GraphNode, GraphService, IdentityService, type IdentityType, type IncomingRequestLike, type Invoice, type JobExecution, type JobStats, type Leaderboard, type LeaderboardEntry, LeaderboardService, type Like, type Listing, ListingsService, type LogEntry, type LogInput, type LogQueryParams, type LogQueryResponse, type LogRecord, LoggerService, type LoginActivitySummary, type LoginDeviceInfo, type LoginHistoryEntry, type LoginRiskInfo, type MessageCallback, type MessageStatus, type MetricDataPoint, type MfaStatus, type Model, type ModelEntitlement, type ModelPricing, type ModelProvider, type UsageSummary as ModelUsageSummary, type MultipartCompleteResponse, type MultipartConfig, type MultipartPartUrl, type MultipartPartUrlsResponse, type MultipartStartResponse, type NetworkClass, type OAuthProvider, type OAuthUrl, OrchestratorService, PHOTO_BREAKPOINTS, type PaginatedResponse, type PaginationMetadata, type PaginationParams, type PartResult, type PartUrl, type Participant, type Payment, type PaymentListParams, type PaymentMethod, type PaymentStatusResponse, type Payout, type PayoutSchedule, type PermissionCheck, type PermissionMatrix, PermissionsService, type PhotoInfo, PhotoService, type Pipeline, type PipelineVersion, type Policy, type PresenceCallback, type PresenceEvent, type PresignedUploadResponse, type Price, type Product, type Project, type ProjectDocument, type ProjectGrant, type ProjectMember, type PushToken, type QueryFilter, type QueryOptions, type QuerySort, type QueueJob, QueueService, type ReadStatus, RealtimeService, type RedeemResult, type Refund, type RegisterAgentRequest, type RegisterAgentResponse, type RequestOptions, type ResumeSession, type Role, type RuntimeTemplate, type RuntimeTemplateVersion, type S3MultipartOptions, type S3MultipartResult, type S3SingleUploadOptions, type S3SingleUploadResult, type S3UploadProgress, ScaleMule, ScaleMuleClient, type ScaleMuleConfig, type SchedulerJob, SchedulerService, type SearchResult, SearchService, type SecurityLayers, type ServerlessFunction, type ServiceHealth, ServiceModule, type Session, type SessionArtifact, type SessionInfo, type SessionLog, type Severity, type ShortestPathResult, type SignedUrlResponse, type SocialPost, SocialService, type SocialUser, type SsoConfig, type StatusCallback, type StorageAdapter, StorageService, type StrategyResult, type SubmitResult, type Subscription, type TargetingRule, type Task, type TaskAttempt, type TaskTransition, type Team, type TeamInvitation, type TeamMember, TeamsService, type TelemetryPayload, type Tool, type ToolCapability, type ToolIntegration, type TopEvent, type TotpSetup, type Transaction, type TransactionListParams, type TransactionSummary, type TransactionSummaryParams, type Transfer, type TransformOptions, type TransformResult, type TraversalResult, type UpdateFlagRequest, type UpdateRuleRequest, type UpdateSegmentRequest, type UpdateVariantRequest, type UploadCompleteResponse, type UploadEngineConfig, type UploadFailureReport, type UploadFailureReportResponse, type UploadOptions, type UploadPlan, UploadResumeStore, type UploadStrategy, UploadTelemetry, type UploadTelemetryConfig, type UploadTelemetryEvent, type UpsertEnvironmentRequest, type UsageRecord, type UsageSummary$1 as UsageSummary, type UserRank, type VideoInfo, VideoService, type VideoUploadOptions, type Webhook, WebhooksService, type Workflow, type WorkflowExecution, type Workspace$1 as Workspace, type WorkspaceInvitation, type WorkspaceMember, WorkspacesService, buildClientContextHeaders, calculateTotalParts, canPerform, createUploadPlan, ScaleMule as default, detectNetworkClass, extractClientContext, generateUploadSessionId, getMeasuredBandwidthMbps, getPartRange, hasMinRoleLevel, resolveStrategy, uploadMultipartToS3, uploadSingleToS3, validateIP };
package/dist/index.js CHANGED
@@ -359,6 +359,8 @@ __export(index_exports, {
359
359
  normalizeAndValidatePhone: () => import_phone.normalizeAndValidatePhone,
360
360
  normalizePhoneNumber: () => import_phone.normalizePhoneNumber,
361
361
  resolveStrategy: () => resolveStrategy,
362
+ uploadMultipartToS3: () => uploadMultipartToS3,
363
+ uploadSingleToS3: () => uploadSingleToS3,
362
364
  validateIP: () => validateIP
363
365
  });
364
366
  module.exports = __toCommonJS(index_exports);
@@ -1848,6 +1850,22 @@ var StorageService = class extends ServiceModule {
1848
1850
  file_id,
1849
1851
  reason: uploadResult.error.code
1850
1852
  });
1853
+ await this.reportUploadFailureBestEffort(
1854
+ {
1855
+ fileId: file_id,
1856
+ completionToken: completion_token,
1857
+ step: "s3_put",
1858
+ errorCode: uploadResult.error.code,
1859
+ errorMessage: uploadResult.error.message,
1860
+ httpStatus: uploadResult.error.status || void 0,
1861
+ attempt: asNumber2(uploadResult.error.details?.attempt),
1862
+ diagnostics: {
1863
+ ...getUploadEnvironmentDiagnostics(),
1864
+ ...uploadResult.error.details || {}
1865
+ }
1866
+ },
1867
+ requestOpts
1868
+ );
1851
1869
  return { data: null, error: uploadResult.error };
1852
1870
  }
1853
1871
  const completeResult = await this.post(
@@ -1865,6 +1883,21 @@ var StorageService = class extends ServiceModule {
1865
1883
  file_id,
1866
1884
  duration_ms: Date.now() - directStart
1867
1885
  });
1886
+ await this.reportUploadFailureBestEffort(
1887
+ {
1888
+ fileId: file_id,
1889
+ completionToken: completion_token,
1890
+ step: "complete",
1891
+ errorCode: completeResult.error.code,
1892
+ errorMessage: completeResult.error.message,
1893
+ httpStatus: completeResult.error.status || void 0,
1894
+ diagnostics: {
1895
+ ...getUploadEnvironmentDiagnostics(),
1896
+ duration_ms: Date.now() - directStart
1897
+ }
1898
+ },
1899
+ requestOpts
1900
+ );
1868
1901
  } else {
1869
1902
  telemetry?.emit(sessionId, "upload.completed", {
1870
1903
  file_id,
@@ -2027,6 +2060,17 @@ var StorageService = class extends ServiceModule {
2027
2060
  if (options?.signal?.aborted) {
2028
2061
  await this.abortMultipart(upload_session_id, completionToken, requestOpts);
2029
2062
  telemetry?.emit(sessionId, "upload.aborted", { file_id });
2063
+ await this.reportUploadFailureBestEffort(
2064
+ {
2065
+ fileId: file_id,
2066
+ completionToken,
2067
+ step: "multipart_abort",
2068
+ errorCode: "aborted",
2069
+ errorMessage: "Upload aborted",
2070
+ diagnostics: getUploadEnvironmentDiagnostics()
2071
+ },
2072
+ requestOpts
2073
+ );
2030
2074
  return { data: null, error: { code: "aborted", message: "Upload aborted", status: 0 } };
2031
2075
  }
2032
2076
  const remainingUrlCount = pendingParts.slice(partIndex).filter((p) => availableUrls.has(p)).length;
@@ -2128,6 +2172,20 @@ var StorageService = class extends ServiceModule {
2128
2172
  const errorMsg = result.error || "Part upload returned no ETag";
2129
2173
  await this.abortMultipart(upload_session_id, completionToken, requestOpts);
2130
2174
  telemetry?.emit(sessionId, "upload.multipart.aborted", { file_id, error: errorMsg });
2175
+ await this.reportUploadFailureBestEffort(
2176
+ {
2177
+ fileId: file_id,
2178
+ completionToken,
2179
+ step: "multipart_part",
2180
+ errorCode: "upload_error",
2181
+ errorMessage: errorMsg,
2182
+ diagnostics: {
2183
+ ...getUploadEnvironmentDiagnostics(),
2184
+ part_number: result.partNum
2185
+ }
2186
+ },
2187
+ requestOpts
2188
+ );
2131
2189
  return {
2132
2190
  data: null,
2133
2191
  error: { code: "upload_error", message: `Part ${result.partNum} failed: ${errorMsg}`, status: 0 }
@@ -2167,6 +2225,21 @@ var StorageService = class extends ServiceModule {
2167
2225
  error: completeResult.error.message,
2168
2226
  duration_ms: Date.now() - multipartStart
2169
2227
  });
2228
+ await this.reportUploadFailureBestEffort(
2229
+ {
2230
+ fileId: file_id,
2231
+ completionToken,
2232
+ step: "multipart_complete",
2233
+ errorCode: completeResult.error.code,
2234
+ errorMessage: completeResult.error.message,
2235
+ httpStatus: completeResult.error.status || void 0,
2236
+ diagnostics: {
2237
+ ...getUploadEnvironmentDiagnostics(),
2238
+ duration_ms: Date.now() - multipartStart
2239
+ }
2240
+ },
2241
+ requestOpts
2242
+ );
2170
2243
  return { data: null, error: completeResult.error };
2171
2244
  }
2172
2245
  telemetry?.emit(sessionId, "upload.multipart.completed", {
@@ -2227,6 +2300,7 @@ var StorageService = class extends ServiceModule {
2227
2300
  content_type: contentType,
2228
2301
  is_public: options?.isPublic ?? true,
2229
2302
  expires_in: options?.expiresIn ?? 3600,
2303
+ size_bytes: options?.sizeBytes,
2230
2304
  metadata: options?.metadata
2231
2305
  },
2232
2306
  requestOptions
@@ -2248,6 +2322,26 @@ var StorageService = class extends ServiceModule {
2248
2322
  requestOptions
2249
2323
  );
2250
2324
  }
2325
+ /**
2326
+ * Persist a structured client-side upload failure against a file record.
2327
+ * Best used by split-upload clients that call getUploadUrl() manually.
2328
+ */
2329
+ async reportUploadFailure(params, requestOptions) {
2330
+ return this.post(
2331
+ "/signed-url/report-failure",
2332
+ {
2333
+ file_id: params.fileId,
2334
+ completion_token: params.completionToken,
2335
+ step: params.step,
2336
+ error_code: params.errorCode,
2337
+ error_message: params.errorMessage,
2338
+ http_status: params.httpStatus,
2339
+ attempt: params.attempt,
2340
+ diagnostics: params.diagnostics
2341
+ },
2342
+ requestOptions
2343
+ );
2344
+ }
2251
2345
  // --------------------------------------------------------------------------
2252
2346
  // Multipart Public API (for advanced/server-side usage)
2253
2347
  // --------------------------------------------------------------------------
@@ -2373,6 +2467,13 @@ var StorageService = class extends ServiceModule {
2373
2467
  telemetry?.emit(sessionId || "", "upload.retried", { attempt });
2374
2468
  }
2375
2469
  const result = await this.uploadToPresignedUrl(url, file, onProgress, signal);
2470
+ if (result.error) {
2471
+ result.error.details = {
2472
+ ...result.error.details || {},
2473
+ attempt: attempt + 1,
2474
+ max_attempts: RETRY_DELAYS.length
2475
+ };
2476
+ }
2376
2477
  if (!result.error) return result;
2377
2478
  if (result.error.code === "aborted") return result;
2378
2479
  if (result.error.status && NON_RETRYABLE_STATUS_CODES.has(result.error.status)) {
@@ -2424,7 +2525,12 @@ var StorageService = class extends ServiceModule {
2424
2525
  error: {
2425
2526
  code: "upload_error",
2426
2527
  message: `S3 upload failed: ${response.status} ${response.statusText}`,
2427
- status: response.status
2528
+ status: response.status,
2529
+ details: {
2530
+ transport: "fetch",
2531
+ total_bytes: file.size,
2532
+ online: getOnlineStatus()
2533
+ }
2428
2534
  }
2429
2535
  };
2430
2536
  }
@@ -2442,7 +2548,12 @@ var StorageService = class extends ServiceModule {
2442
2548
  error: {
2443
2549
  code: isStall ? "upload_stalled" : "upload_error",
2444
2550
  message: isStall ? `Upload stalled (no progress for ${stallTimeout / 1e3}s)` : err instanceof Error ? err.message : "S3 upload failed",
2445
- status: 0
2551
+ status: 0,
2552
+ details: {
2553
+ transport: "fetch",
2554
+ total_bytes: file.size,
2555
+ online: getOnlineStatus()
2556
+ }
2446
2557
  }
2447
2558
  };
2448
2559
  }
@@ -2452,6 +2563,8 @@ var StorageService = class extends ServiceModule {
2452
2563
  const xhr = new XMLHttpRequest();
2453
2564
  const stallTimeout = getStallTimeout();
2454
2565
  let stallTimer = null;
2566
+ let lastLoaded = 0;
2567
+ let totalBytes = file.size;
2455
2568
  const resetStallTimer = () => {
2456
2569
  if (stallTimer !== null) clearTimeout(stallTimer);
2457
2570
  stallTimer = setTimeout(() => {
@@ -2461,7 +2574,14 @@ var StorageService = class extends ServiceModule {
2461
2574
  error: {
2462
2575
  code: "upload_stalled",
2463
2576
  message: `Upload stalled (no progress for ${stallTimeout / 1e3}s)`,
2464
- status: 0
2577
+ status: 0,
2578
+ details: {
2579
+ transport: "xhr",
2580
+ bytes_sent: lastLoaded,
2581
+ total_bytes: totalBytes,
2582
+ progress_percent: totalBytes > 0 ? Math.round(lastLoaded / totalBytes * 100) : void 0,
2583
+ online: getOnlineStatus()
2584
+ }
2465
2585
  }
2466
2586
  });
2467
2587
  }, stallTimeout);
@@ -2488,6 +2608,8 @@ var StorageService = class extends ServiceModule {
2488
2608
  }
2489
2609
  xhr.upload.addEventListener("progress", (event) => {
2490
2610
  resetStallTimer();
2611
+ lastLoaded = event.loaded;
2612
+ totalBytes = event.total || totalBytes;
2491
2613
  if (event.lengthComputable && onProgress) {
2492
2614
  onProgress(Math.round(event.loaded / event.total * 100));
2493
2615
  }
@@ -2503,7 +2625,14 @@ var StorageService = class extends ServiceModule {
2503
2625
  error: {
2504
2626
  code: "upload_error",
2505
2627
  message: `S3 upload failed: ${xhr.status}`,
2506
- status: xhr.status
2628
+ status: xhr.status,
2629
+ details: {
2630
+ transport: "xhr",
2631
+ bytes_sent: lastLoaded,
2632
+ total_bytes: totalBytes,
2633
+ progress_percent: totalBytes > 0 ? Math.round(lastLoaded / totalBytes * 100) : void 0,
2634
+ online: getOnlineStatus()
2635
+ }
2507
2636
  }
2508
2637
  });
2509
2638
  }
@@ -2512,7 +2641,18 @@ var StorageService = class extends ServiceModule {
2512
2641
  clearStallTimer();
2513
2642
  resolve({
2514
2643
  data: null,
2515
- error: { code: "upload_error", message: "S3 upload failed", status: 0 }
2644
+ error: {
2645
+ code: "upload_error",
2646
+ message: "S3 upload failed",
2647
+ status: 0,
2648
+ details: {
2649
+ transport: "xhr",
2650
+ bytes_sent: lastLoaded,
2651
+ total_bytes: totalBytes,
2652
+ progress_percent: totalBytes > 0 ? Math.round(lastLoaded / totalBytes * 100) : void 0,
2653
+ online: getOnlineStatus()
2654
+ }
2655
+ }
2516
2656
  });
2517
2657
  });
2518
2658
  xhr.addEventListener("abort", () => {
@@ -2621,6 +2761,12 @@ var StorageService = class extends ServiceModule {
2621
2761
  return null;
2622
2762
  }
2623
2763
  }
2764
+ async reportUploadFailureBestEffort(params, requestOptions) {
2765
+ try {
2766
+ await this.reportUploadFailure(params, requestOptions);
2767
+ } catch {
2768
+ }
2769
+ }
2624
2770
  getOrCreateTelemetry() {
2625
2771
  if (!this.telemetry) {
2626
2772
  this.telemetry = new UploadTelemetry(this.client);
@@ -2660,6 +2806,38 @@ function getNetworkEffectiveType2() {
2660
2806
  }
2661
2807
  return "4g";
2662
2808
  }
2809
+ function getOnlineStatus() {
2810
+ if (typeof navigator === "undefined") return void 0;
2811
+ return navigator.onLine;
2812
+ }
2813
+ function getUploadEnvironmentDiagnostics() {
2814
+ const diagnostics = {
2815
+ network_type: getNetworkEffectiveType2(),
2816
+ online: getOnlineStatus()
2817
+ };
2818
+ if (typeof navigator !== "undefined") {
2819
+ const nav = navigator;
2820
+ if (typeof nav.hardwareConcurrency === "number") {
2821
+ diagnostics.hardware_concurrency = nav.hardwareConcurrency;
2822
+ }
2823
+ if (typeof nav.deviceMemory === "number") {
2824
+ diagnostics.device_memory_gb = nav.deviceMemory;
2825
+ }
2826
+ if (nav.connection?.downlink != null) {
2827
+ diagnostics.downlink_mbps = nav.connection.downlink;
2828
+ }
2829
+ if (nav.connection?.rtt != null) {
2830
+ diagnostics.rtt_ms = nav.connection.rtt;
2831
+ }
2832
+ }
2833
+ if (typeof document !== "undefined") {
2834
+ diagnostics.visibility_state = document.visibilityState;
2835
+ }
2836
+ return diagnostics;
2837
+ }
2838
+ function asNumber2(value) {
2839
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
2840
+ }
2663
2841
 
2664
2842
  // src/index.ts
2665
2843
  init_upload_resume();
@@ -2758,6 +2936,199 @@ function getPartRange(partNumber, chunkSize, totalSize) {
2758
2936
  return { start, end, size: end - start };
2759
2937
  }
2760
2938
 
2939
+ // src/services/upload-to-s3.ts
2940
+ var DEFAULT_RETRY_DELAYS = [0, 1e3, 3e3];
2941
+ var DEFAULT_STALL_TIMEOUT_MS3 = 45e3;
2942
+ var DEFAULT_CONCURRENCY = 3;
2943
+ async function uploadSingleToS3(url, file, options) {
2944
+ const maxRetries = options?.maxRetries ?? 3;
2945
+ const retryDelays = DEFAULT_RETRY_DELAYS.slice(0, maxRetries);
2946
+ const stallTimeout = options?.stallTimeoutMs ?? DEFAULT_STALL_TIMEOUT_MS3;
2947
+ for (let attempt = 0; attempt < retryDelays.length; attempt++) {
2948
+ if (attempt > 0) {
2949
+ await sleep3(retryDelays[attempt] || 1e3);
2950
+ }
2951
+ if (options?.signal?.aborted) {
2952
+ return { success: false, error: "Upload aborted" };
2953
+ }
2954
+ const result = await doSinglePut(url, file, options?.onProgress, options?.signal, stallTimeout);
2955
+ if (result === "success") return { success: true };
2956
+ if (result === "abort") return { success: false, error: "Upload aborted" };
2957
+ if (result === "stall") return { success: false, error: "Upload stalled \u2014 no progress" };
2958
+ }
2959
+ return { success: false, error: "Upload failed after retries" };
2960
+ }
2961
+ function doSinglePut(url, file, onProgress, signal, stallTimeoutMs) {
2962
+ return new Promise((resolve) => {
2963
+ const xhr = new XMLHttpRequest();
2964
+ let stallTimer = null;
2965
+ const resetStallTimer = () => {
2966
+ if (stallTimer) clearTimeout(stallTimer);
2967
+ if (stallTimeoutMs) {
2968
+ stallTimer = setTimeout(() => {
2969
+ xhr.abort();
2970
+ resolve("stall");
2971
+ }, stallTimeoutMs);
2972
+ }
2973
+ };
2974
+ xhr.upload.addEventListener("progress", (e) => {
2975
+ resetStallTimer();
2976
+ if (e.lengthComputable && onProgress) {
2977
+ onProgress({
2978
+ loaded: e.loaded,
2979
+ total: e.total,
2980
+ percentage: Math.round(e.loaded / e.total * 100)
2981
+ });
2982
+ }
2983
+ });
2984
+ xhr.addEventListener("load", () => {
2985
+ if (stallTimer) clearTimeout(stallTimer);
2986
+ if (xhr.status >= 200 && xhr.status < 300) {
2987
+ resolve("success");
2988
+ } else if (xhr.status >= 500) {
2989
+ resolve("retry");
2990
+ } else {
2991
+ resolve("retry");
2992
+ }
2993
+ });
2994
+ xhr.addEventListener("error", () => {
2995
+ if (stallTimer) clearTimeout(stallTimer);
2996
+ resolve("retry");
2997
+ });
2998
+ xhr.addEventListener("abort", () => {
2999
+ if (stallTimer) clearTimeout(stallTimer);
3000
+ });
3001
+ if (signal) {
3002
+ signal.addEventListener(
3003
+ "abort",
3004
+ () => {
3005
+ xhr.abort();
3006
+ if (stallTimer) clearTimeout(stallTimer);
3007
+ resolve("abort");
3008
+ },
3009
+ { once: true }
3010
+ );
3011
+ }
3012
+ xhr.open("PUT", url);
3013
+ xhr.setRequestHeader("Content-Type", file.type || "application/octet-stream");
3014
+ resetStallTimer();
3015
+ xhr.send(file);
3016
+ });
3017
+ }
3018
+ async function uploadMultipartToS3(file, config, options) {
3019
+ const { partSizeBytes, totalParts, partUrls: initialPartUrls, fetchMoreUrls } = config;
3020
+ const concurrency = options?.concurrency ?? DEFAULT_CONCURRENCY;
3021
+ const maxRetries = options?.maxRetries ?? 3;
3022
+ const completedParts = [];
3023
+ const availableUrls = /* @__PURE__ */ new Map();
3024
+ for (const pu of initialPartUrls) {
3025
+ availableUrls.set(pu.partNumber, pu.url);
3026
+ }
3027
+ let totalUploaded = 0;
3028
+ for (let i = 0; i < totalParts; i += concurrency) {
3029
+ if (options?.signal?.aborted) {
3030
+ return { success: false, error: "Upload aborted" };
3031
+ }
3032
+ const batchPartNumbers = [];
3033
+ for (let j = i; j < Math.min(i + concurrency, totalParts); j++) {
3034
+ batchPartNumbers.push(j + 1);
3035
+ }
3036
+ const missingUrls = batchPartNumbers.filter((p) => !availableUrls.has(p));
3037
+ if (missingUrls.length > 0 && fetchMoreUrls) {
3038
+ const fetched = await fetchMoreUrls(missingUrls);
3039
+ if (fetched) {
3040
+ for (const pu of fetched) availableUrls.set(pu.partNumber, pu.url);
3041
+ }
3042
+ }
3043
+ const results = await Promise.all(
3044
+ batchPartNumbers.map(async (partNum) => {
3045
+ const url = availableUrls.get(partNum);
3046
+ if (!url) return { partNum, error: "No URL available" };
3047
+ const start = (partNum - 1) * partSizeBytes;
3048
+ const end = Math.min(start + partSizeBytes, file.size);
3049
+ const blob = file.slice(start, end);
3050
+ let result = await uploadPartWithRetry(url, blob, partNum, maxRetries, options?.signal);
3051
+ if (!result && fetchMoreUrls) {
3052
+ const freshUrls = await fetchMoreUrls([partNum]);
3053
+ if (freshUrls?.[0]) {
3054
+ availableUrls.set(partNum, freshUrls[0].url);
3055
+ result = await uploadPartWithRetry(freshUrls[0].url, blob, partNum, maxRetries, options?.signal);
3056
+ }
3057
+ }
3058
+ if (result) {
3059
+ totalUploaded += end - start;
3060
+ options?.onProgress?.({
3061
+ loaded: totalUploaded,
3062
+ total: file.size,
3063
+ percentage: Math.round(totalUploaded / file.size * 100)
3064
+ });
3065
+ return { partNum, etag: result.etag };
3066
+ }
3067
+ return { partNum, error: "Part upload failed after retries" };
3068
+ })
3069
+ );
3070
+ for (const result of results) {
3071
+ if ("error" in result) {
3072
+ return { success: false, error: `Part ${result.partNum}: ${result.error}` };
3073
+ }
3074
+ completedParts.push({ partNumber: result.partNum, etag: result.etag });
3075
+ }
3076
+ }
3077
+ return {
3078
+ success: true,
3079
+ parts: completedParts.sort((a, b) => a.partNumber - b.partNumber)
3080
+ };
3081
+ }
3082
+ async function uploadPartWithRetry(url, blob, _partNumber, maxRetries, signal) {
3083
+ const retryDelays = DEFAULT_RETRY_DELAYS.slice(0, maxRetries);
3084
+ for (let attempt = 0; attempt < retryDelays.length; attempt++) {
3085
+ if (attempt > 0) await sleep3(retryDelays[attempt] || 1e3);
3086
+ if (signal?.aborted) return null;
3087
+ const result = await doPartPut(url, blob, signal);
3088
+ if (result === "abort") return null;
3089
+ if (typeof result === "object") return result;
3090
+ }
3091
+ return null;
3092
+ }
3093
+ function doPartPut(url, blob, signal) {
3094
+ return new Promise((resolve) => {
3095
+ const xhr = new XMLHttpRequest();
3096
+ xhr.addEventListener("load", () => {
3097
+ if (xhr.status >= 200 && xhr.status < 300) {
3098
+ const etag = xhr.getResponseHeader("etag");
3099
+ if (etag) {
3100
+ resolve({ etag });
3101
+ } else {
3102
+ resolve("retry");
3103
+ }
3104
+ } else if (xhr.status === 403) {
3105
+ resolve("retry");
3106
+ } else if (xhr.status >= 500) {
3107
+ resolve("retry");
3108
+ } else {
3109
+ resolve("retry");
3110
+ }
3111
+ });
3112
+ xhr.addEventListener("error", () => resolve("retry"));
3113
+ xhr.addEventListener("abort", () => resolve("abort"));
3114
+ if (signal) {
3115
+ signal.addEventListener(
3116
+ "abort",
3117
+ () => {
3118
+ xhr.abort();
3119
+ resolve("abort");
3120
+ },
3121
+ { once: true }
3122
+ );
3123
+ }
3124
+ xhr.open("PUT", url);
3125
+ xhr.send(blob);
3126
+ });
3127
+ }
3128
+ function sleep3(ms) {
3129
+ return new Promise((r) => setTimeout(r, ms));
3130
+ }
3131
+
2761
3132
  // src/services/realtime.ts
2762
3133
  var DEFAULT_RECONNECT_BASE_MS = 1e3;
2763
3134
  var MAX_RECONNECT_MS = 3e4;
@@ -4419,8 +4790,8 @@ var SearchService = class extends ServiceModule {
4419
4790
  async query(queryStr, queryOptions, requestOptions) {
4420
4791
  return this.post("", { query: queryStr, ...queryOptions }, requestOptions);
4421
4792
  }
4422
- async index(indexName, document, options) {
4423
- return this.post("/documents", { index: indexName, ...document }, options);
4793
+ async index(indexName, document2, options) {
4794
+ return this.post("/documents", { index: indexName, ...document2 }, options);
4424
4795
  }
4425
4796
  async removeDocument(indexName, docId, options) {
4426
4797
  return this.del(`/documents/${indexName}/${docId}`, options);
@@ -5449,5 +5820,7 @@ var index_default = ScaleMule;
5449
5820
  normalizeAndValidatePhone,
5450
5821
  normalizePhoneNumber,
5451
5822
  resolveStrategy,
5823
+ uploadMultipartToS3,
5824
+ uploadSingleToS3,
5452
5825
  validateIP
5453
5826
  });
package/dist/index.mjs CHANGED
@@ -1497,6 +1497,22 @@ var StorageService = class extends ServiceModule {
1497
1497
  file_id,
1498
1498
  reason: uploadResult.error.code
1499
1499
  });
1500
+ await this.reportUploadFailureBestEffort(
1501
+ {
1502
+ fileId: file_id,
1503
+ completionToken: completion_token,
1504
+ step: "s3_put",
1505
+ errorCode: uploadResult.error.code,
1506
+ errorMessage: uploadResult.error.message,
1507
+ httpStatus: uploadResult.error.status || void 0,
1508
+ attempt: asNumber2(uploadResult.error.details?.attempt),
1509
+ diagnostics: {
1510
+ ...getUploadEnvironmentDiagnostics(),
1511
+ ...uploadResult.error.details || {}
1512
+ }
1513
+ },
1514
+ requestOpts
1515
+ );
1500
1516
  return { data: null, error: uploadResult.error };
1501
1517
  }
1502
1518
  const completeResult = await this.post(
@@ -1514,6 +1530,21 @@ var StorageService = class extends ServiceModule {
1514
1530
  file_id,
1515
1531
  duration_ms: Date.now() - directStart
1516
1532
  });
1533
+ await this.reportUploadFailureBestEffort(
1534
+ {
1535
+ fileId: file_id,
1536
+ completionToken: completion_token,
1537
+ step: "complete",
1538
+ errorCode: completeResult.error.code,
1539
+ errorMessage: completeResult.error.message,
1540
+ httpStatus: completeResult.error.status || void 0,
1541
+ diagnostics: {
1542
+ ...getUploadEnvironmentDiagnostics(),
1543
+ duration_ms: Date.now() - directStart
1544
+ }
1545
+ },
1546
+ requestOpts
1547
+ );
1517
1548
  } else {
1518
1549
  telemetry?.emit(sessionId, "upload.completed", {
1519
1550
  file_id,
@@ -1676,6 +1707,17 @@ var StorageService = class extends ServiceModule {
1676
1707
  if (options?.signal?.aborted) {
1677
1708
  await this.abortMultipart(upload_session_id, completionToken, requestOpts);
1678
1709
  telemetry?.emit(sessionId, "upload.aborted", { file_id });
1710
+ await this.reportUploadFailureBestEffort(
1711
+ {
1712
+ fileId: file_id,
1713
+ completionToken,
1714
+ step: "multipart_abort",
1715
+ errorCode: "aborted",
1716
+ errorMessage: "Upload aborted",
1717
+ diagnostics: getUploadEnvironmentDiagnostics()
1718
+ },
1719
+ requestOpts
1720
+ );
1679
1721
  return { data: null, error: { code: "aborted", message: "Upload aborted", status: 0 } };
1680
1722
  }
1681
1723
  const remainingUrlCount = pendingParts.slice(partIndex).filter((p) => availableUrls.has(p)).length;
@@ -1777,6 +1819,20 @@ var StorageService = class extends ServiceModule {
1777
1819
  const errorMsg = result.error || "Part upload returned no ETag";
1778
1820
  await this.abortMultipart(upload_session_id, completionToken, requestOpts);
1779
1821
  telemetry?.emit(sessionId, "upload.multipart.aborted", { file_id, error: errorMsg });
1822
+ await this.reportUploadFailureBestEffort(
1823
+ {
1824
+ fileId: file_id,
1825
+ completionToken,
1826
+ step: "multipart_part",
1827
+ errorCode: "upload_error",
1828
+ errorMessage: errorMsg,
1829
+ diagnostics: {
1830
+ ...getUploadEnvironmentDiagnostics(),
1831
+ part_number: result.partNum
1832
+ }
1833
+ },
1834
+ requestOpts
1835
+ );
1780
1836
  return {
1781
1837
  data: null,
1782
1838
  error: { code: "upload_error", message: `Part ${result.partNum} failed: ${errorMsg}`, status: 0 }
@@ -1816,6 +1872,21 @@ var StorageService = class extends ServiceModule {
1816
1872
  error: completeResult.error.message,
1817
1873
  duration_ms: Date.now() - multipartStart
1818
1874
  });
1875
+ await this.reportUploadFailureBestEffort(
1876
+ {
1877
+ fileId: file_id,
1878
+ completionToken,
1879
+ step: "multipart_complete",
1880
+ errorCode: completeResult.error.code,
1881
+ errorMessage: completeResult.error.message,
1882
+ httpStatus: completeResult.error.status || void 0,
1883
+ diagnostics: {
1884
+ ...getUploadEnvironmentDiagnostics(),
1885
+ duration_ms: Date.now() - multipartStart
1886
+ }
1887
+ },
1888
+ requestOpts
1889
+ );
1819
1890
  return { data: null, error: completeResult.error };
1820
1891
  }
1821
1892
  telemetry?.emit(sessionId, "upload.multipart.completed", {
@@ -1876,6 +1947,7 @@ var StorageService = class extends ServiceModule {
1876
1947
  content_type: contentType,
1877
1948
  is_public: options?.isPublic ?? true,
1878
1949
  expires_in: options?.expiresIn ?? 3600,
1950
+ size_bytes: options?.sizeBytes,
1879
1951
  metadata: options?.metadata
1880
1952
  },
1881
1953
  requestOptions
@@ -1897,6 +1969,26 @@ var StorageService = class extends ServiceModule {
1897
1969
  requestOptions
1898
1970
  );
1899
1971
  }
1972
+ /**
1973
+ * Persist a structured client-side upload failure against a file record.
1974
+ * Best used by split-upload clients that call getUploadUrl() manually.
1975
+ */
1976
+ async reportUploadFailure(params, requestOptions) {
1977
+ return this.post(
1978
+ "/signed-url/report-failure",
1979
+ {
1980
+ file_id: params.fileId,
1981
+ completion_token: params.completionToken,
1982
+ step: params.step,
1983
+ error_code: params.errorCode,
1984
+ error_message: params.errorMessage,
1985
+ http_status: params.httpStatus,
1986
+ attempt: params.attempt,
1987
+ diagnostics: params.diagnostics
1988
+ },
1989
+ requestOptions
1990
+ );
1991
+ }
1900
1992
  // --------------------------------------------------------------------------
1901
1993
  // Multipart Public API (for advanced/server-side usage)
1902
1994
  // --------------------------------------------------------------------------
@@ -2022,6 +2114,13 @@ var StorageService = class extends ServiceModule {
2022
2114
  telemetry?.emit(sessionId || "", "upload.retried", { attempt });
2023
2115
  }
2024
2116
  const result = await this.uploadToPresignedUrl(url, file, onProgress, signal);
2117
+ if (result.error) {
2118
+ result.error.details = {
2119
+ ...result.error.details || {},
2120
+ attempt: attempt + 1,
2121
+ max_attempts: RETRY_DELAYS.length
2122
+ };
2123
+ }
2025
2124
  if (!result.error) return result;
2026
2125
  if (result.error.code === "aborted") return result;
2027
2126
  if (result.error.status && NON_RETRYABLE_STATUS_CODES.has(result.error.status)) {
@@ -2073,7 +2172,12 @@ var StorageService = class extends ServiceModule {
2073
2172
  error: {
2074
2173
  code: "upload_error",
2075
2174
  message: `S3 upload failed: ${response.status} ${response.statusText}`,
2076
- status: response.status
2175
+ status: response.status,
2176
+ details: {
2177
+ transport: "fetch",
2178
+ total_bytes: file.size,
2179
+ online: getOnlineStatus()
2180
+ }
2077
2181
  }
2078
2182
  };
2079
2183
  }
@@ -2091,7 +2195,12 @@ var StorageService = class extends ServiceModule {
2091
2195
  error: {
2092
2196
  code: isStall ? "upload_stalled" : "upload_error",
2093
2197
  message: isStall ? `Upload stalled (no progress for ${stallTimeout / 1e3}s)` : err instanceof Error ? err.message : "S3 upload failed",
2094
- status: 0
2198
+ status: 0,
2199
+ details: {
2200
+ transport: "fetch",
2201
+ total_bytes: file.size,
2202
+ online: getOnlineStatus()
2203
+ }
2095
2204
  }
2096
2205
  };
2097
2206
  }
@@ -2101,6 +2210,8 @@ var StorageService = class extends ServiceModule {
2101
2210
  const xhr = new XMLHttpRequest();
2102
2211
  const stallTimeout = getStallTimeout();
2103
2212
  let stallTimer = null;
2213
+ let lastLoaded = 0;
2214
+ let totalBytes = file.size;
2104
2215
  const resetStallTimer = () => {
2105
2216
  if (stallTimer !== null) clearTimeout(stallTimer);
2106
2217
  stallTimer = setTimeout(() => {
@@ -2110,7 +2221,14 @@ var StorageService = class extends ServiceModule {
2110
2221
  error: {
2111
2222
  code: "upload_stalled",
2112
2223
  message: `Upload stalled (no progress for ${stallTimeout / 1e3}s)`,
2113
- status: 0
2224
+ status: 0,
2225
+ details: {
2226
+ transport: "xhr",
2227
+ bytes_sent: lastLoaded,
2228
+ total_bytes: totalBytes,
2229
+ progress_percent: totalBytes > 0 ? Math.round(lastLoaded / totalBytes * 100) : void 0,
2230
+ online: getOnlineStatus()
2231
+ }
2114
2232
  }
2115
2233
  });
2116
2234
  }, stallTimeout);
@@ -2137,6 +2255,8 @@ var StorageService = class extends ServiceModule {
2137
2255
  }
2138
2256
  xhr.upload.addEventListener("progress", (event) => {
2139
2257
  resetStallTimer();
2258
+ lastLoaded = event.loaded;
2259
+ totalBytes = event.total || totalBytes;
2140
2260
  if (event.lengthComputable && onProgress) {
2141
2261
  onProgress(Math.round(event.loaded / event.total * 100));
2142
2262
  }
@@ -2152,7 +2272,14 @@ var StorageService = class extends ServiceModule {
2152
2272
  error: {
2153
2273
  code: "upload_error",
2154
2274
  message: `S3 upload failed: ${xhr.status}`,
2155
- status: xhr.status
2275
+ status: xhr.status,
2276
+ details: {
2277
+ transport: "xhr",
2278
+ bytes_sent: lastLoaded,
2279
+ total_bytes: totalBytes,
2280
+ progress_percent: totalBytes > 0 ? Math.round(lastLoaded / totalBytes * 100) : void 0,
2281
+ online: getOnlineStatus()
2282
+ }
2156
2283
  }
2157
2284
  });
2158
2285
  }
@@ -2161,7 +2288,18 @@ var StorageService = class extends ServiceModule {
2161
2288
  clearStallTimer();
2162
2289
  resolve({
2163
2290
  data: null,
2164
- error: { code: "upload_error", message: "S3 upload failed", status: 0 }
2291
+ error: {
2292
+ code: "upload_error",
2293
+ message: "S3 upload failed",
2294
+ status: 0,
2295
+ details: {
2296
+ transport: "xhr",
2297
+ bytes_sent: lastLoaded,
2298
+ total_bytes: totalBytes,
2299
+ progress_percent: totalBytes > 0 ? Math.round(lastLoaded / totalBytes * 100) : void 0,
2300
+ online: getOnlineStatus()
2301
+ }
2302
+ }
2165
2303
  });
2166
2304
  });
2167
2305
  xhr.addEventListener("abort", () => {
@@ -2270,6 +2408,12 @@ var StorageService = class extends ServiceModule {
2270
2408
  return null;
2271
2409
  }
2272
2410
  }
2411
+ async reportUploadFailureBestEffort(params, requestOptions) {
2412
+ try {
2413
+ await this.reportUploadFailure(params, requestOptions);
2414
+ } catch {
2415
+ }
2416
+ }
2273
2417
  getOrCreateTelemetry() {
2274
2418
  if (!this.telemetry) {
2275
2419
  this.telemetry = new UploadTelemetry(this.client);
@@ -2309,6 +2453,38 @@ function getNetworkEffectiveType() {
2309
2453
  }
2310
2454
  return "4g";
2311
2455
  }
2456
+ function getOnlineStatus() {
2457
+ if (typeof navigator === "undefined") return void 0;
2458
+ return navigator.onLine;
2459
+ }
2460
+ function getUploadEnvironmentDiagnostics() {
2461
+ const diagnostics = {
2462
+ network_type: getNetworkEffectiveType(),
2463
+ online: getOnlineStatus()
2464
+ };
2465
+ if (typeof navigator !== "undefined") {
2466
+ const nav = navigator;
2467
+ if (typeof nav.hardwareConcurrency === "number") {
2468
+ diagnostics.hardware_concurrency = nav.hardwareConcurrency;
2469
+ }
2470
+ if (typeof nav.deviceMemory === "number") {
2471
+ diagnostics.device_memory_gb = nav.deviceMemory;
2472
+ }
2473
+ if (nav.connection?.downlink != null) {
2474
+ diagnostics.downlink_mbps = nav.connection.downlink;
2475
+ }
2476
+ if (nav.connection?.rtt != null) {
2477
+ diagnostics.rtt_ms = nav.connection.rtt;
2478
+ }
2479
+ }
2480
+ if (typeof document !== "undefined") {
2481
+ diagnostics.visibility_state = document.visibilityState;
2482
+ }
2483
+ return diagnostics;
2484
+ }
2485
+ function asNumber2(value) {
2486
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
2487
+ }
2312
2488
 
2313
2489
  // src/services/upload-strategy.ts
2314
2490
  var MULTIPART_THRESHOLD2 = 8 * 1024 * 1024;
@@ -2404,6 +2580,199 @@ function getPartRange(partNumber, chunkSize, totalSize) {
2404
2580
  return { start, end, size: end - start };
2405
2581
  }
2406
2582
 
2583
+ // src/services/upload-to-s3.ts
2584
+ var DEFAULT_RETRY_DELAYS = [0, 1e3, 3e3];
2585
+ var DEFAULT_STALL_TIMEOUT_MS3 = 45e3;
2586
+ var DEFAULT_CONCURRENCY = 3;
2587
+ async function uploadSingleToS3(url, file, options) {
2588
+ const maxRetries = options?.maxRetries ?? 3;
2589
+ const retryDelays = DEFAULT_RETRY_DELAYS.slice(0, maxRetries);
2590
+ const stallTimeout = options?.stallTimeoutMs ?? DEFAULT_STALL_TIMEOUT_MS3;
2591
+ for (let attempt = 0; attempt < retryDelays.length; attempt++) {
2592
+ if (attempt > 0) {
2593
+ await sleep3(retryDelays[attempt] || 1e3);
2594
+ }
2595
+ if (options?.signal?.aborted) {
2596
+ return { success: false, error: "Upload aborted" };
2597
+ }
2598
+ const result = await doSinglePut(url, file, options?.onProgress, options?.signal, stallTimeout);
2599
+ if (result === "success") return { success: true };
2600
+ if (result === "abort") return { success: false, error: "Upload aborted" };
2601
+ if (result === "stall") return { success: false, error: "Upload stalled \u2014 no progress" };
2602
+ }
2603
+ return { success: false, error: "Upload failed after retries" };
2604
+ }
2605
+ function doSinglePut(url, file, onProgress, signal, stallTimeoutMs) {
2606
+ return new Promise((resolve) => {
2607
+ const xhr = new XMLHttpRequest();
2608
+ let stallTimer = null;
2609
+ const resetStallTimer = () => {
2610
+ if (stallTimer) clearTimeout(stallTimer);
2611
+ if (stallTimeoutMs) {
2612
+ stallTimer = setTimeout(() => {
2613
+ xhr.abort();
2614
+ resolve("stall");
2615
+ }, stallTimeoutMs);
2616
+ }
2617
+ };
2618
+ xhr.upload.addEventListener("progress", (e) => {
2619
+ resetStallTimer();
2620
+ if (e.lengthComputable && onProgress) {
2621
+ onProgress({
2622
+ loaded: e.loaded,
2623
+ total: e.total,
2624
+ percentage: Math.round(e.loaded / e.total * 100)
2625
+ });
2626
+ }
2627
+ });
2628
+ xhr.addEventListener("load", () => {
2629
+ if (stallTimer) clearTimeout(stallTimer);
2630
+ if (xhr.status >= 200 && xhr.status < 300) {
2631
+ resolve("success");
2632
+ } else if (xhr.status >= 500) {
2633
+ resolve("retry");
2634
+ } else {
2635
+ resolve("retry");
2636
+ }
2637
+ });
2638
+ xhr.addEventListener("error", () => {
2639
+ if (stallTimer) clearTimeout(stallTimer);
2640
+ resolve("retry");
2641
+ });
2642
+ xhr.addEventListener("abort", () => {
2643
+ if (stallTimer) clearTimeout(stallTimer);
2644
+ });
2645
+ if (signal) {
2646
+ signal.addEventListener(
2647
+ "abort",
2648
+ () => {
2649
+ xhr.abort();
2650
+ if (stallTimer) clearTimeout(stallTimer);
2651
+ resolve("abort");
2652
+ },
2653
+ { once: true }
2654
+ );
2655
+ }
2656
+ xhr.open("PUT", url);
2657
+ xhr.setRequestHeader("Content-Type", file.type || "application/octet-stream");
2658
+ resetStallTimer();
2659
+ xhr.send(file);
2660
+ });
2661
+ }
2662
+ async function uploadMultipartToS3(file, config, options) {
2663
+ const { partSizeBytes, totalParts, partUrls: initialPartUrls, fetchMoreUrls } = config;
2664
+ const concurrency = options?.concurrency ?? DEFAULT_CONCURRENCY;
2665
+ const maxRetries = options?.maxRetries ?? 3;
2666
+ const completedParts = [];
2667
+ const availableUrls = /* @__PURE__ */ new Map();
2668
+ for (const pu of initialPartUrls) {
2669
+ availableUrls.set(pu.partNumber, pu.url);
2670
+ }
2671
+ let totalUploaded = 0;
2672
+ for (let i = 0; i < totalParts; i += concurrency) {
2673
+ if (options?.signal?.aborted) {
2674
+ return { success: false, error: "Upload aborted" };
2675
+ }
2676
+ const batchPartNumbers = [];
2677
+ for (let j = i; j < Math.min(i + concurrency, totalParts); j++) {
2678
+ batchPartNumbers.push(j + 1);
2679
+ }
2680
+ const missingUrls = batchPartNumbers.filter((p) => !availableUrls.has(p));
2681
+ if (missingUrls.length > 0 && fetchMoreUrls) {
2682
+ const fetched = await fetchMoreUrls(missingUrls);
2683
+ if (fetched) {
2684
+ for (const pu of fetched) availableUrls.set(pu.partNumber, pu.url);
2685
+ }
2686
+ }
2687
+ const results = await Promise.all(
2688
+ batchPartNumbers.map(async (partNum) => {
2689
+ const url = availableUrls.get(partNum);
2690
+ if (!url) return { partNum, error: "No URL available" };
2691
+ const start = (partNum - 1) * partSizeBytes;
2692
+ const end = Math.min(start + partSizeBytes, file.size);
2693
+ const blob = file.slice(start, end);
2694
+ let result = await uploadPartWithRetry(url, blob, partNum, maxRetries, options?.signal);
2695
+ if (!result && fetchMoreUrls) {
2696
+ const freshUrls = await fetchMoreUrls([partNum]);
2697
+ if (freshUrls?.[0]) {
2698
+ availableUrls.set(partNum, freshUrls[0].url);
2699
+ result = await uploadPartWithRetry(freshUrls[0].url, blob, partNum, maxRetries, options?.signal);
2700
+ }
2701
+ }
2702
+ if (result) {
2703
+ totalUploaded += end - start;
2704
+ options?.onProgress?.({
2705
+ loaded: totalUploaded,
2706
+ total: file.size,
2707
+ percentage: Math.round(totalUploaded / file.size * 100)
2708
+ });
2709
+ return { partNum, etag: result.etag };
2710
+ }
2711
+ return { partNum, error: "Part upload failed after retries" };
2712
+ })
2713
+ );
2714
+ for (const result of results) {
2715
+ if ("error" in result) {
2716
+ return { success: false, error: `Part ${result.partNum}: ${result.error}` };
2717
+ }
2718
+ completedParts.push({ partNumber: result.partNum, etag: result.etag });
2719
+ }
2720
+ }
2721
+ return {
2722
+ success: true,
2723
+ parts: completedParts.sort((a, b) => a.partNumber - b.partNumber)
2724
+ };
2725
+ }
2726
+ async function uploadPartWithRetry(url, blob, _partNumber, maxRetries, signal) {
2727
+ const retryDelays = DEFAULT_RETRY_DELAYS.slice(0, maxRetries);
2728
+ for (let attempt = 0; attempt < retryDelays.length; attempt++) {
2729
+ if (attempt > 0) await sleep3(retryDelays[attempt] || 1e3);
2730
+ if (signal?.aborted) return null;
2731
+ const result = await doPartPut(url, blob, signal);
2732
+ if (result === "abort") return null;
2733
+ if (typeof result === "object") return result;
2734
+ }
2735
+ return null;
2736
+ }
2737
+ function doPartPut(url, blob, signal) {
2738
+ return new Promise((resolve) => {
2739
+ const xhr = new XMLHttpRequest();
2740
+ xhr.addEventListener("load", () => {
2741
+ if (xhr.status >= 200 && xhr.status < 300) {
2742
+ const etag = xhr.getResponseHeader("etag");
2743
+ if (etag) {
2744
+ resolve({ etag });
2745
+ } else {
2746
+ resolve("retry");
2747
+ }
2748
+ } else if (xhr.status === 403) {
2749
+ resolve("retry");
2750
+ } else if (xhr.status >= 500) {
2751
+ resolve("retry");
2752
+ } else {
2753
+ resolve("retry");
2754
+ }
2755
+ });
2756
+ xhr.addEventListener("error", () => resolve("retry"));
2757
+ xhr.addEventListener("abort", () => resolve("abort"));
2758
+ if (signal) {
2759
+ signal.addEventListener(
2760
+ "abort",
2761
+ () => {
2762
+ xhr.abort();
2763
+ resolve("abort");
2764
+ },
2765
+ { once: true }
2766
+ );
2767
+ }
2768
+ xhr.open("PUT", url);
2769
+ xhr.send(blob);
2770
+ });
2771
+ }
2772
+ function sleep3(ms) {
2773
+ return new Promise((r) => setTimeout(r, ms));
2774
+ }
2775
+
2407
2776
  // src/services/realtime.ts
2408
2777
  var DEFAULT_RECONNECT_BASE_MS = 1e3;
2409
2778
  var MAX_RECONNECT_MS = 3e4;
@@ -4065,8 +4434,8 @@ var SearchService = class extends ServiceModule {
4065
4434
  async query(queryStr, queryOptions, requestOptions) {
4066
4435
  return this.post("", { query: queryStr, ...queryOptions }, requestOptions);
4067
4436
  }
4068
- async index(indexName, document, options) {
4069
- return this.post("/documents", { index: indexName, ...document }, options);
4437
+ async index(indexName, document2, options) {
4438
+ return this.post("/documents", { index: indexName, ...document2 }, options);
4070
4439
  }
4071
4440
  async removeDocument(indexName, docId, options) {
4072
4441
  return this.del(`/documents/${indexName}/${docId}`, options);
@@ -5095,5 +5464,7 @@ export {
5095
5464
  normalizeAndValidatePhone,
5096
5465
  normalizePhoneNumber,
5097
5466
  resolveStrategy,
5467
+ uploadMultipartToS3,
5468
+ uploadSingleToS3,
5098
5469
  validateIP
5099
5470
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scalemule/sdk",
3
- "version": "0.0.16",
3
+ "version": "0.0.18",
4
4
  "description": "Official TypeScript/JavaScript SDK for ScaleMule Backend-as-a-Service",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",