@scalemule/sdk 0.0.20 → 0.0.22

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
@@ -125,6 +125,20 @@ interface ScaleMuleConfig {
125
125
  enableRateLimitQueue?: boolean;
126
126
  /** Enable offline queue — queues requests when offline, syncs on reconnect */
127
127
  enableOfflineQueue?: boolean;
128
+ /** Enable multi-account session pool (Google Account Chooser style). Default: false */
129
+ enableMultiSession?: boolean;
130
+ }
131
+ /**
132
+ * A session entry in the multi-account session pool.
133
+ */
134
+ interface SessionPoolEntry {
135
+ token: string;
136
+ userId: string;
137
+ email: string;
138
+ fullName?: string;
139
+ avatarUrl?: string;
140
+ expiresAt?: string;
141
+ addedAt: string;
128
142
  }
129
143
  /**
130
144
  * Per-request options that override client defaults.
@@ -234,21 +248,6 @@ declare function extractClientContext(request: IncomingRequestLike): ClientConte
234
248
  */
235
249
  declare function buildClientContextHeaders(context: ClientContext | undefined): Record<string, string>;
236
250
 
237
- /**
238
- * ScaleMule Core HTTP Client
239
- *
240
- * Fetch-based client with:
241
- * - { data, error } response contract
242
- * - Exponential backoff with jitter on retries
243
- * - x-idempotency-key on POST retries (prevents duplicate side effects)
244
- * - Rate limit queue (auto-queues on 429)
245
- * - Offline queue with persistence
246
- * - AbortController / AbortSignal support
247
- * - Works in browser, Node.js 18+, and edge runtimes
248
- *
249
- * Promoted from sdks/scalemule-nextjs and adapted for the base SDK.
250
- */
251
-
252
251
  declare class ScaleMuleClient {
253
252
  private apiKey;
254
253
  private baseUrl;
@@ -262,6 +261,9 @@ declare class ScaleMuleClient {
262
261
  private rateLimitQueue;
263
262
  private offlineQueue;
264
263
  private workspaceId;
264
+ private anonymousId;
265
+ private multiSessionEnabled;
266
+ private sessionPool;
265
267
  constructor(config: ScaleMuleConfig);
266
268
  initialize(): Promise<void>;
267
269
  setSession(token: string, userId: string): Promise<void>;
@@ -271,6 +273,22 @@ declare class ScaleMuleClient {
271
273
  getSessionToken(): string | null;
272
274
  getUserId(): string | null;
273
275
  isAuthenticated(): boolean;
276
+ getAnonymousId(): string | null;
277
+ isMultiSessionEnabled(): boolean;
278
+ /** Get all accounts in the session pool */
279
+ getSessionPool(): SessionPoolEntry[];
280
+ /** Get the active account entry, or null */
281
+ getActiveAccount(): SessionPoolEntry | null;
282
+ /** Add an account to the session pool and set it as active */
283
+ addAccount(entry: SessionPoolEntry): Promise<void>;
284
+ /** Switch to a different account in the pool. Returns false if not found. */
285
+ switchAccount(userId: string): Promise<boolean>;
286
+ /** Remove a specific account from the pool */
287
+ removeAccount(userId: string): Promise<void>;
288
+ /** Clear all accounts from the pool */
289
+ clearAllAccounts(): Promise<void>;
290
+ /** Persist session pool to storage */
291
+ private persistSessionPool;
274
292
  getBaseUrl(): string;
275
293
  getApiKey(): string;
276
294
  isOnline(): boolean;
@@ -607,6 +625,7 @@ declare class AuthService extends ServiceModule {
607
625
  email: string;
608
626
  password: string;
609
627
  remember_me?: boolean;
628
+ device_fingerprint?: Record<string, unknown>;
610
629
  }, options?: RequestOptions): Promise<ApiResponse<AuthSession>>;
611
630
  logout(options?: RequestOptions): Promise<ApiResponse<{
612
631
  logged_out: boolean;
@@ -4095,6 +4114,16 @@ declare class IdentityService extends ServiceModule {
4095
4114
  revokeApiKey(id: string, options?: RequestOptions): Promise<ApiResponse<{
4096
4115
  revoked: boolean;
4097
4116
  }>>;
4117
+ /**
4118
+ * Explicitly link an anonymous_id to the current authenticated user.
4119
+ * Called automatically on init when both a session and anonymous_id exist
4120
+ * (transitional path for users who registered before identity linking existed).
4121
+ */
4122
+ identify(anonymousId: string, deviceFingerprintHash?: string, options?: RequestOptions): Promise<ApiResponse<{
4123
+ linked: boolean;
4124
+ anonymous_id: string;
4125
+ message: string;
4126
+ }>>;
4098
4127
  }
4099
4128
 
4100
4129
  /**
@@ -5133,17 +5162,6 @@ declare class AgentSessionsService extends ServiceModule {
5133
5162
  listArtifacts(sessionId: string, options?: RequestOptions): Promise<ApiResponse<SessionArtifact[]>>;
5134
5163
  }
5135
5164
 
5136
- /**
5137
- * ScaleMule SDK for TypeScript/JavaScript
5138
- *
5139
- * Official SDK for ScaleMule Backend-as-a-Service (v2)
5140
- *
5141
- * All methods return { data, error } — never throws on API errors.
5142
- * List methods return { data[], metadata, error } with standardized pagination.
5143
- *
5144
- * @packageDocumentation
5145
- */
5146
-
5147
5165
  /**
5148
5166
  * Main entry point for the ScaleMule SDK.
5149
5167
  *
@@ -5238,6 +5256,18 @@ declare class ScaleMule {
5238
5256
  getUserId(): string | null;
5239
5257
  /** Whether a session token is set. */
5240
5258
  isAuthenticated(): boolean;
5259
+ /** The anonymous visitor ID used for identity linking. */
5260
+ getAnonymousId(): string | null;
5261
+ /** Get all accounts in the session pool (requires enableMultiSession) */
5262
+ getSessionPool(): SessionPoolEntry[];
5263
+ /** Get the active account, or null */
5264
+ getActiveAccount(): SessionPoolEntry | null;
5265
+ /** Switch to a different account in the pool. Returns false if not found. */
5266
+ switchAccount(userId: string): Promise<boolean>;
5267
+ /** Remove a specific account from the pool */
5268
+ removeAccount(userId: string): Promise<void>;
5269
+ /** Clear all accounts from the pool */
5270
+ clearAllAccounts(): Promise<void>;
5241
5271
  /** The base URL being used for API requests. */
5242
5272
  getBaseUrl(): string;
5243
5273
  /** Set the active workspace context. All subsequent requests include this as x-sm-workspace-id. */
@@ -5248,4 +5278,4 @@ declare class ScaleMule {
5248
5278
  getClient(): ScaleMuleClient;
5249
5279
  }
5250
5280
 
5251
- 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 };
5281
+ 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 SessionPoolEntry, 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
@@ -125,6 +125,20 @@ interface ScaleMuleConfig {
125
125
  enableRateLimitQueue?: boolean;
126
126
  /** Enable offline queue — queues requests when offline, syncs on reconnect */
127
127
  enableOfflineQueue?: boolean;
128
+ /** Enable multi-account session pool (Google Account Chooser style). Default: false */
129
+ enableMultiSession?: boolean;
130
+ }
131
+ /**
132
+ * A session entry in the multi-account session pool.
133
+ */
134
+ interface SessionPoolEntry {
135
+ token: string;
136
+ userId: string;
137
+ email: string;
138
+ fullName?: string;
139
+ avatarUrl?: string;
140
+ expiresAt?: string;
141
+ addedAt: string;
128
142
  }
129
143
  /**
130
144
  * Per-request options that override client defaults.
@@ -234,21 +248,6 @@ declare function extractClientContext(request: IncomingRequestLike): ClientConte
234
248
  */
235
249
  declare function buildClientContextHeaders(context: ClientContext | undefined): Record<string, string>;
236
250
 
237
- /**
238
- * ScaleMule Core HTTP Client
239
- *
240
- * Fetch-based client with:
241
- * - { data, error } response contract
242
- * - Exponential backoff with jitter on retries
243
- * - x-idempotency-key on POST retries (prevents duplicate side effects)
244
- * - Rate limit queue (auto-queues on 429)
245
- * - Offline queue with persistence
246
- * - AbortController / AbortSignal support
247
- * - Works in browser, Node.js 18+, and edge runtimes
248
- *
249
- * Promoted from sdks/scalemule-nextjs and adapted for the base SDK.
250
- */
251
-
252
251
  declare class ScaleMuleClient {
253
252
  private apiKey;
254
253
  private baseUrl;
@@ -262,6 +261,9 @@ declare class ScaleMuleClient {
262
261
  private rateLimitQueue;
263
262
  private offlineQueue;
264
263
  private workspaceId;
264
+ private anonymousId;
265
+ private multiSessionEnabled;
266
+ private sessionPool;
265
267
  constructor(config: ScaleMuleConfig);
266
268
  initialize(): Promise<void>;
267
269
  setSession(token: string, userId: string): Promise<void>;
@@ -271,6 +273,22 @@ declare class ScaleMuleClient {
271
273
  getSessionToken(): string | null;
272
274
  getUserId(): string | null;
273
275
  isAuthenticated(): boolean;
276
+ getAnonymousId(): string | null;
277
+ isMultiSessionEnabled(): boolean;
278
+ /** Get all accounts in the session pool */
279
+ getSessionPool(): SessionPoolEntry[];
280
+ /** Get the active account entry, or null */
281
+ getActiveAccount(): SessionPoolEntry | null;
282
+ /** Add an account to the session pool and set it as active */
283
+ addAccount(entry: SessionPoolEntry): Promise<void>;
284
+ /** Switch to a different account in the pool. Returns false if not found. */
285
+ switchAccount(userId: string): Promise<boolean>;
286
+ /** Remove a specific account from the pool */
287
+ removeAccount(userId: string): Promise<void>;
288
+ /** Clear all accounts from the pool */
289
+ clearAllAccounts(): Promise<void>;
290
+ /** Persist session pool to storage */
291
+ private persistSessionPool;
274
292
  getBaseUrl(): string;
275
293
  getApiKey(): string;
276
294
  isOnline(): boolean;
@@ -607,6 +625,7 @@ declare class AuthService extends ServiceModule {
607
625
  email: string;
608
626
  password: string;
609
627
  remember_me?: boolean;
628
+ device_fingerprint?: Record<string, unknown>;
610
629
  }, options?: RequestOptions): Promise<ApiResponse<AuthSession>>;
611
630
  logout(options?: RequestOptions): Promise<ApiResponse<{
612
631
  logged_out: boolean;
@@ -4095,6 +4114,16 @@ declare class IdentityService extends ServiceModule {
4095
4114
  revokeApiKey(id: string, options?: RequestOptions): Promise<ApiResponse<{
4096
4115
  revoked: boolean;
4097
4116
  }>>;
4117
+ /**
4118
+ * Explicitly link an anonymous_id to the current authenticated user.
4119
+ * Called automatically on init when both a session and anonymous_id exist
4120
+ * (transitional path for users who registered before identity linking existed).
4121
+ */
4122
+ identify(anonymousId: string, deviceFingerprintHash?: string, options?: RequestOptions): Promise<ApiResponse<{
4123
+ linked: boolean;
4124
+ anonymous_id: string;
4125
+ message: string;
4126
+ }>>;
4098
4127
  }
4099
4128
 
4100
4129
  /**
@@ -5133,17 +5162,6 @@ declare class AgentSessionsService extends ServiceModule {
5133
5162
  listArtifacts(sessionId: string, options?: RequestOptions): Promise<ApiResponse<SessionArtifact[]>>;
5134
5163
  }
5135
5164
 
5136
- /**
5137
- * ScaleMule SDK for TypeScript/JavaScript
5138
- *
5139
- * Official SDK for ScaleMule Backend-as-a-Service (v2)
5140
- *
5141
- * All methods return { data, error } — never throws on API errors.
5142
- * List methods return { data[], metadata, error } with standardized pagination.
5143
- *
5144
- * @packageDocumentation
5145
- */
5146
-
5147
5165
  /**
5148
5166
  * Main entry point for the ScaleMule SDK.
5149
5167
  *
@@ -5238,6 +5256,18 @@ declare class ScaleMule {
5238
5256
  getUserId(): string | null;
5239
5257
  /** Whether a session token is set. */
5240
5258
  isAuthenticated(): boolean;
5259
+ /** The anonymous visitor ID used for identity linking. */
5260
+ getAnonymousId(): string | null;
5261
+ /** Get all accounts in the session pool (requires enableMultiSession) */
5262
+ getSessionPool(): SessionPoolEntry[];
5263
+ /** Get the active account, or null */
5264
+ getActiveAccount(): SessionPoolEntry | null;
5265
+ /** Switch to a different account in the pool. Returns false if not found. */
5266
+ switchAccount(userId: string): Promise<boolean>;
5267
+ /** Remove a specific account from the pool */
5268
+ removeAccount(userId: string): Promise<void>;
5269
+ /** Clear all accounts from the pool */
5270
+ clearAllAccounts(): Promise<void>;
5241
5271
  /** The base URL being used for API requests. */
5242
5272
  getBaseUrl(): string;
5243
5273
  /** Set the active workspace context. All subsequent requests include this as x-sm-workspace-id. */
@@ -5248,4 +5278,4 @@ declare class ScaleMule {
5248
5278
  getClient(): ScaleMuleClient;
5249
5279
  }
5250
5280
 
5251
- 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 };
5281
+ 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 SessionPoolEntry, 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
@@ -467,6 +467,9 @@ var SESSION_STORAGE_KEY = "scalemule_session";
467
467
  var USER_ID_STORAGE_KEY = "scalemule_user_id";
468
468
  var OFFLINE_QUEUE_KEY = "scalemule_offline_queue";
469
469
  var WORKSPACE_STORAGE_KEY = "scalemule_workspace_id";
470
+ var ANONYMOUS_ID_STORAGE_KEY = "scalemule_anonymous_id";
471
+ var SESSION_POOL_KEY = "scalemule_session_pool";
472
+ var ACTIVE_ACCOUNT_KEY = "scalemule_active_account";
470
473
  var GATEWAY_URLS = {
471
474
  dev: "https://api-dev.scalemule.com",
472
475
  prod: "https://api.scalemule.com"
@@ -659,6 +662,8 @@ var ScaleMuleClient = class {
659
662
  this.rateLimitQueue = null;
660
663
  this.offlineQueue = null;
661
664
  this.workspaceId = null;
665
+ this.anonymousId = null;
666
+ this.sessionPool = /* @__PURE__ */ new Map();
662
667
  this.apiKey = config.apiKey;
663
668
  this.baseUrl = config.baseUrl || GATEWAY_URLS[config.environment || "prod"];
664
669
  this.debug = config.debug || false;
@@ -673,6 +678,7 @@ var ScaleMuleClient = class {
673
678
  this.offlineQueue = new OfflineQueue(this.storage);
674
679
  this.offlineQueue.setOnlineCallback(() => this.syncOfflineQueue());
675
680
  }
681
+ this.multiSessionEnabled = config.enableMultiSession || false;
676
682
  }
677
683
  // --------------------------------------------------------------------------
678
684
  // Session Management
@@ -684,7 +690,46 @@ var ScaleMuleClient = class {
684
690
  if (userId) this.userId = userId;
685
691
  const wsId = await this.storage.getItem(WORKSPACE_STORAGE_KEY);
686
692
  if (wsId) this.workspaceId = wsId;
687
- if (this.debug) console.log("[ScaleMule] Initialized, session:", !!token);
693
+ let anonId = await this.storage.getItem(ANONYMOUS_ID_STORAGE_KEY);
694
+ if (!anonId) {
695
+ anonId = crypto.randomUUID();
696
+ await this.storage.setItem(ANONYMOUS_ID_STORAGE_KEY, anonId);
697
+ }
698
+ this.anonymousId = anonId;
699
+ if (this.multiSessionEnabled) {
700
+ const poolJson = await this.storage.getItem(SESSION_POOL_KEY);
701
+ if (poolJson) {
702
+ try {
703
+ const entries = JSON.parse(poolJson);
704
+ this.sessionPool = new Map(Object.entries(entries));
705
+ } catch {
706
+ }
707
+ }
708
+ if (token && userId && !this.sessionPool.has(userId)) {
709
+ this.sessionPool.set(userId, {
710
+ token,
711
+ userId,
712
+ email: "",
713
+ addedAt: (/* @__PURE__ */ new Date()).toISOString()
714
+ });
715
+ await this.persistSessionPool();
716
+ }
717
+ const activeId = await this.storage.getItem(ACTIVE_ACCOUNT_KEY);
718
+ if (activeId && this.sessionPool.has(activeId)) {
719
+ const entry = this.sessionPool.get(activeId);
720
+ this.sessionToken = entry.token;
721
+ this.userId = activeId;
722
+ }
723
+ }
724
+ if (this.debug)
725
+ console.log(
726
+ "[ScaleMule] Initialized, session:",
727
+ !!this.sessionToken,
728
+ "anonymousId:",
729
+ anonId,
730
+ "poolSize:",
731
+ this.sessionPool.size
732
+ );
688
733
  }
689
734
  async setSession(token, userId) {
690
735
  this.sessionToken = token;
@@ -693,12 +738,27 @@ var ScaleMuleClient = class {
693
738
  await this.storage.setItem(USER_ID_STORAGE_KEY, userId);
694
739
  }
695
740
  async clearSession() {
741
+ if (this.multiSessionEnabled && this.userId) {
742
+ this.sessionPool.delete(this.userId);
743
+ await this.persistSessionPool();
744
+ const next = this.sessionPool.entries().next().value;
745
+ if (next) {
746
+ const [nextUserId, nextEntry] = next;
747
+ this.sessionToken = nextEntry.token;
748
+ this.userId = nextUserId;
749
+ await this.storage.setItem(SESSION_STORAGE_KEY, nextEntry.token);
750
+ await this.storage.setItem(USER_ID_STORAGE_KEY, nextUserId);
751
+ await this.storage.setItem(ACTIVE_ACCOUNT_KEY, nextUserId);
752
+ return;
753
+ }
754
+ }
696
755
  this.sessionToken = null;
697
756
  this.userId = null;
698
757
  this.workspaceId = null;
699
758
  await this.storage.removeItem(SESSION_STORAGE_KEY);
700
759
  await this.storage.removeItem(USER_ID_STORAGE_KEY);
701
760
  await this.storage.removeItem(WORKSPACE_STORAGE_KEY);
761
+ await this.storage.removeItem(ACTIVE_ACCOUNT_KEY);
702
762
  }
703
763
  setAccessToken(token) {
704
764
  this.sessionToken = token;
@@ -715,6 +775,80 @@ var ScaleMuleClient = class {
715
775
  isAuthenticated() {
716
776
  return this.sessionToken !== null;
717
777
  }
778
+ getAnonymousId() {
779
+ return this.anonymousId;
780
+ }
781
+ isMultiSessionEnabled() {
782
+ return this.multiSessionEnabled;
783
+ }
784
+ // --------------------------------------------------------------------------
785
+ // Multi-Account Session Pool (Phase 2)
786
+ // --------------------------------------------------------------------------
787
+ /** Get all accounts in the session pool */
788
+ getSessionPool() {
789
+ return Array.from(this.sessionPool.values());
790
+ }
791
+ /** Get the active account entry, or null */
792
+ getActiveAccount() {
793
+ if (!this.userId) return null;
794
+ return this.sessionPool.get(this.userId) || null;
795
+ }
796
+ /** Add an account to the session pool and set it as active */
797
+ async addAccount(entry) {
798
+ this.sessionPool.set(entry.userId, entry);
799
+ this.sessionToken = entry.token;
800
+ this.userId = entry.userId;
801
+ await this.storage.setItem(SESSION_STORAGE_KEY, entry.token);
802
+ await this.storage.setItem(USER_ID_STORAGE_KEY, entry.userId);
803
+ await this.storage.setItem(ACTIVE_ACCOUNT_KEY, entry.userId);
804
+ await this.persistSessionPool();
805
+ }
806
+ /** Switch to a different account in the pool. Returns false if not found. */
807
+ async switchAccount(userId) {
808
+ const entry = this.sessionPool.get(userId);
809
+ if (!entry) return false;
810
+ this.sessionToken = entry.token;
811
+ this.userId = userId;
812
+ this.workspaceId = null;
813
+ await this.storage.setItem(SESSION_STORAGE_KEY, entry.token);
814
+ await this.storage.setItem(USER_ID_STORAGE_KEY, userId);
815
+ await this.storage.setItem(ACTIVE_ACCOUNT_KEY, userId);
816
+ await this.storage.removeItem(WORKSPACE_STORAGE_KEY);
817
+ return true;
818
+ }
819
+ /** Remove a specific account from the pool */
820
+ async removeAccount(userId) {
821
+ this.sessionPool.delete(userId);
822
+ await this.persistSessionPool();
823
+ if (this.userId === userId) {
824
+ const next = this.sessionPool.entries().next().value;
825
+ if (next) {
826
+ await this.switchAccount(next[0]);
827
+ } else {
828
+ await this.clearSession();
829
+ }
830
+ }
831
+ }
832
+ /** Clear all accounts from the pool */
833
+ async clearAllAccounts() {
834
+ this.sessionPool.clear();
835
+ await this.storage.removeItem(SESSION_POOL_KEY);
836
+ await this.storage.removeItem(ACTIVE_ACCOUNT_KEY);
837
+ this.sessionToken = null;
838
+ this.userId = null;
839
+ this.workspaceId = null;
840
+ await this.storage.removeItem(SESSION_STORAGE_KEY);
841
+ await this.storage.removeItem(USER_ID_STORAGE_KEY);
842
+ await this.storage.removeItem(WORKSPACE_STORAGE_KEY);
843
+ }
844
+ /** Persist session pool to storage */
845
+ async persistSessionPool() {
846
+ const obj = {};
847
+ for (const [k, v] of this.sessionPool) {
848
+ obj[k] = v;
849
+ }
850
+ await this.storage.setItem(SESSION_POOL_KEY, JSON.stringify(obj));
851
+ }
718
852
  getBaseUrl() {
719
853
  return this.baseUrl;
720
854
  }
@@ -764,6 +898,9 @@ var ScaleMuleClient = class {
764
898
  if (this.workspaceId) {
765
899
  headers["x-sm-workspace-id"] = this.workspaceId;
766
900
  }
901
+ if (!this.sessionToken && this.anonymousId) {
902
+ headers["x-anonymous-id"] = this.anonymousId;
903
+ }
767
904
  let bodyStr;
768
905
  if (init.body !== void 0 && init.body !== null) {
769
906
  bodyStr = typeof init.body === "string" ? init.body : JSON.stringify(init.body);
@@ -1210,6 +1347,21 @@ function asString(parent, key) {
1210
1347
  var import_phone = require("@scalemule/ui/phone");
1211
1348
 
1212
1349
  // src/services/auth.ts
1350
+ function collectDeviceFingerprint() {
1351
+ if (typeof window === "undefined" || typeof navigator === "undefined") return void 0;
1352
+ try {
1353
+ return {
1354
+ screen: `${screen.width}x${screen.height}x${screen.colorDepth}`,
1355
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
1356
+ language: navigator.language,
1357
+ platform: navigator.platform,
1358
+ cookie_enabled: navigator.cookieEnabled,
1359
+ do_not_track: navigator.doNotTrack
1360
+ };
1361
+ } catch {
1362
+ return void 0;
1363
+ }
1364
+ }
1213
1365
  var AuthMfaApi = class extends ServiceModule {
1214
1366
  constructor() {
1215
1367
  super(...arguments);
@@ -1308,12 +1460,42 @@ var AuthService = class extends ServiceModule {
1308
1460
  async register(data, options) {
1309
1461
  const payload = {
1310
1462
  ...data,
1311
- phone: this.sanitizePhoneField(data.phone)
1463
+ phone: this.sanitizePhoneField(data.phone),
1464
+ anonymous_id: this.client.getAnonymousId()
1312
1465
  };
1313
- return this.post("/register", payload, options);
1466
+ const result = await this.post("/register", payload, options);
1467
+ if (result.data && this.client.isMultiSessionEnabled()) {
1468
+ await this.client.addAccount({
1469
+ token: result.data.session_token,
1470
+ userId: result.data.user.id,
1471
+ email: result.data.user.email,
1472
+ fullName: result.data.user.full_name,
1473
+ avatarUrl: result.data.user.avatar_url,
1474
+ expiresAt: result.data.expires_at,
1475
+ addedAt: (/* @__PURE__ */ new Date()).toISOString()
1476
+ });
1477
+ }
1478
+ return result;
1314
1479
  }
1315
1480
  async login(data, options) {
1316
- return this.post("/login", data, options);
1481
+ const payload = {
1482
+ ...data,
1483
+ anonymous_id: this.client.getAnonymousId(),
1484
+ device_fingerprint: data.device_fingerprint || collectDeviceFingerprint()
1485
+ };
1486
+ const result = await this.post("/login", payload, options);
1487
+ if (result.data && this.client.isMultiSessionEnabled()) {
1488
+ await this.client.addAccount({
1489
+ token: result.data.session_token,
1490
+ userId: result.data.user.id,
1491
+ email: result.data.user.email,
1492
+ fullName: result.data.user.full_name,
1493
+ avatarUrl: result.data.user.avatar_url,
1494
+ expiresAt: result.data.expires_at,
1495
+ addedAt: (/* @__PURE__ */ new Date()).toISOString()
1496
+ });
1497
+ }
1498
+ return result;
1317
1499
  }
1318
1500
  async logout(options) {
1319
1501
  return this.post("/logout", void 0, options);
@@ -2844,7 +3026,7 @@ init_upload_resume();
2844
3026
 
2845
3027
  // src/services/upload-strategy.ts
2846
3028
  var MULTIPART_THRESHOLD2 = 8 * 1024 * 1024;
2847
- var MULTIPART_THRESHOLD_SLOW2 = 4 * 1024 * 1024;
3029
+ var MULTIPART_THRESHOLD_SLOW2 = 1 * 1024 * 1024;
2848
3030
  var DEFAULT_STALL_TIMEOUT_MS2 = 45e3;
2849
3031
  var SLOW_STALL_TIMEOUT_MS = 9e4;
2850
3032
  var CHUNK_SIZES = {
@@ -2954,7 +3136,6 @@ async function uploadSingleToS3(url, file, options) {
2954
3136
  const result = await doSinglePut(url, file, options?.onProgress, options?.signal, stallTimeout);
2955
3137
  if (result === "success") return { success: true };
2956
3138
  if (result === "abort") return { success: false, error: "Upload aborted" };
2957
- if (result === "stall") return { success: false, error: "Upload stalled \u2014 no progress" };
2958
3139
  }
2959
3140
  return { success: false, error: "Upload failed after retries" };
2960
3141
  }
@@ -4074,7 +4255,11 @@ var AnalyticsService = class extends ServiceModule {
4074
4255
  // Event Tracking (v2 — JetStream buffered)
4075
4256
  // --------------------------------------------------------------------------
4076
4257
  async track(event, properties, userId, options) {
4077
- return this.post("/v2/events", { event_name: event, properties, user_id: userId }, options);
4258
+ const payload = { event_name: event, properties, user_id: userId };
4259
+ if (!userId && !this.client.isAuthenticated()) {
4260
+ payload.anonymous_id = this.client.getAnonymousId();
4261
+ }
4262
+ return this.post("/v2/events", payload, options);
4078
4263
  }
4079
4264
  async trackBatch(events, options) {
4080
4265
  const mapped = events.map(({ event, ...rest }) => ({ event_name: event, ...rest }));
@@ -5198,6 +5383,18 @@ var IdentityService = class extends ServiceModule {
5198
5383
  async revokeApiKey(id, options) {
5199
5384
  return this.del(`/api-keys/${id}`, options);
5200
5385
  }
5386
+ /**
5387
+ * Explicitly link an anonymous_id to the current authenticated user.
5388
+ * Called automatically on init when both a session and anonymous_id exist
5389
+ * (transitional path for users who registered before identity linking existed).
5390
+ */
5391
+ async identify(anonymousId, deviceFingerprintHash, options) {
5392
+ return this.post(
5393
+ "/identify",
5394
+ { anonymous_id: anonymousId, device_fingerprint_hash: deviceFingerprintHash },
5395
+ options
5396
+ );
5397
+ }
5201
5398
  };
5202
5399
 
5203
5400
  // src/services/catalog.ts
@@ -5754,7 +5951,12 @@ var ScaleMule = class {
5754
5951
  * Call this once after construction, before making authenticated requests.
5755
5952
  */
5756
5953
  async initialize() {
5757
- return this._client.initialize();
5954
+ await this._client.initialize();
5955
+ const anonymousId = this._client.getAnonymousId();
5956
+ if (this._client.isAuthenticated() && anonymousId) {
5957
+ this.identity.identify(anonymousId).catch(() => {
5958
+ });
5959
+ }
5758
5960
  }
5759
5961
  /**
5760
5962
  * Set authentication session (token + userId).
@@ -5787,6 +5989,33 @@ var ScaleMule = class {
5787
5989
  isAuthenticated() {
5788
5990
  return this._client.isAuthenticated();
5789
5991
  }
5992
+ /** The anonymous visitor ID used for identity linking. */
5993
+ getAnonymousId() {
5994
+ return this._client.getAnonymousId();
5995
+ }
5996
+ // --------------------------------------------------------------------------
5997
+ // Multi-Account Session Pool (Phase 2)
5998
+ // --------------------------------------------------------------------------
5999
+ /** Get all accounts in the session pool (requires enableMultiSession) */
6000
+ getSessionPool() {
6001
+ return this._client.getSessionPool();
6002
+ }
6003
+ /** Get the active account, or null */
6004
+ getActiveAccount() {
6005
+ return this._client.getActiveAccount();
6006
+ }
6007
+ /** Switch to a different account in the pool. Returns false if not found. */
6008
+ async switchAccount(userId) {
6009
+ return this._client.switchAccount(userId);
6010
+ }
6011
+ /** Remove a specific account from the pool */
6012
+ async removeAccount(userId) {
6013
+ return this._client.removeAccount(userId);
6014
+ }
6015
+ /** Clear all accounts from the pool */
6016
+ async clearAllAccounts() {
6017
+ return this._client.clearAllAccounts();
6018
+ }
5790
6019
  /** The base URL being used for API requests. */
5791
6020
  getBaseUrl() {
5792
6021
  return this._client.getBaseUrl();
package/dist/index.mjs CHANGED
@@ -104,6 +104,9 @@ var SESSION_STORAGE_KEY = "scalemule_session";
104
104
  var USER_ID_STORAGE_KEY = "scalemule_user_id";
105
105
  var OFFLINE_QUEUE_KEY = "scalemule_offline_queue";
106
106
  var WORKSPACE_STORAGE_KEY = "scalemule_workspace_id";
107
+ var ANONYMOUS_ID_STORAGE_KEY = "scalemule_anonymous_id";
108
+ var SESSION_POOL_KEY = "scalemule_session_pool";
109
+ var ACTIVE_ACCOUNT_KEY = "scalemule_active_account";
107
110
  var GATEWAY_URLS = {
108
111
  dev: "https://api-dev.scalemule.com",
109
112
  prod: "https://api.scalemule.com"
@@ -296,6 +299,8 @@ var ScaleMuleClient = class {
296
299
  this.rateLimitQueue = null;
297
300
  this.offlineQueue = null;
298
301
  this.workspaceId = null;
302
+ this.anonymousId = null;
303
+ this.sessionPool = /* @__PURE__ */ new Map();
299
304
  this.apiKey = config.apiKey;
300
305
  this.baseUrl = config.baseUrl || GATEWAY_URLS[config.environment || "prod"];
301
306
  this.debug = config.debug || false;
@@ -310,6 +315,7 @@ var ScaleMuleClient = class {
310
315
  this.offlineQueue = new OfflineQueue(this.storage);
311
316
  this.offlineQueue.setOnlineCallback(() => this.syncOfflineQueue());
312
317
  }
318
+ this.multiSessionEnabled = config.enableMultiSession || false;
313
319
  }
314
320
  // --------------------------------------------------------------------------
315
321
  // Session Management
@@ -321,7 +327,46 @@ var ScaleMuleClient = class {
321
327
  if (userId) this.userId = userId;
322
328
  const wsId = await this.storage.getItem(WORKSPACE_STORAGE_KEY);
323
329
  if (wsId) this.workspaceId = wsId;
324
- if (this.debug) console.log("[ScaleMule] Initialized, session:", !!token);
330
+ let anonId = await this.storage.getItem(ANONYMOUS_ID_STORAGE_KEY);
331
+ if (!anonId) {
332
+ anonId = crypto.randomUUID();
333
+ await this.storage.setItem(ANONYMOUS_ID_STORAGE_KEY, anonId);
334
+ }
335
+ this.anonymousId = anonId;
336
+ if (this.multiSessionEnabled) {
337
+ const poolJson = await this.storage.getItem(SESSION_POOL_KEY);
338
+ if (poolJson) {
339
+ try {
340
+ const entries = JSON.parse(poolJson);
341
+ this.sessionPool = new Map(Object.entries(entries));
342
+ } catch {
343
+ }
344
+ }
345
+ if (token && userId && !this.sessionPool.has(userId)) {
346
+ this.sessionPool.set(userId, {
347
+ token,
348
+ userId,
349
+ email: "",
350
+ addedAt: (/* @__PURE__ */ new Date()).toISOString()
351
+ });
352
+ await this.persistSessionPool();
353
+ }
354
+ const activeId = await this.storage.getItem(ACTIVE_ACCOUNT_KEY);
355
+ if (activeId && this.sessionPool.has(activeId)) {
356
+ const entry = this.sessionPool.get(activeId);
357
+ this.sessionToken = entry.token;
358
+ this.userId = activeId;
359
+ }
360
+ }
361
+ if (this.debug)
362
+ console.log(
363
+ "[ScaleMule] Initialized, session:",
364
+ !!this.sessionToken,
365
+ "anonymousId:",
366
+ anonId,
367
+ "poolSize:",
368
+ this.sessionPool.size
369
+ );
325
370
  }
326
371
  async setSession(token, userId) {
327
372
  this.sessionToken = token;
@@ -330,12 +375,27 @@ var ScaleMuleClient = class {
330
375
  await this.storage.setItem(USER_ID_STORAGE_KEY, userId);
331
376
  }
332
377
  async clearSession() {
378
+ if (this.multiSessionEnabled && this.userId) {
379
+ this.sessionPool.delete(this.userId);
380
+ await this.persistSessionPool();
381
+ const next = this.sessionPool.entries().next().value;
382
+ if (next) {
383
+ const [nextUserId, nextEntry] = next;
384
+ this.sessionToken = nextEntry.token;
385
+ this.userId = nextUserId;
386
+ await this.storage.setItem(SESSION_STORAGE_KEY, nextEntry.token);
387
+ await this.storage.setItem(USER_ID_STORAGE_KEY, nextUserId);
388
+ await this.storage.setItem(ACTIVE_ACCOUNT_KEY, nextUserId);
389
+ return;
390
+ }
391
+ }
333
392
  this.sessionToken = null;
334
393
  this.userId = null;
335
394
  this.workspaceId = null;
336
395
  await this.storage.removeItem(SESSION_STORAGE_KEY);
337
396
  await this.storage.removeItem(USER_ID_STORAGE_KEY);
338
397
  await this.storage.removeItem(WORKSPACE_STORAGE_KEY);
398
+ await this.storage.removeItem(ACTIVE_ACCOUNT_KEY);
339
399
  }
340
400
  setAccessToken(token) {
341
401
  this.sessionToken = token;
@@ -352,6 +412,80 @@ var ScaleMuleClient = class {
352
412
  isAuthenticated() {
353
413
  return this.sessionToken !== null;
354
414
  }
415
+ getAnonymousId() {
416
+ return this.anonymousId;
417
+ }
418
+ isMultiSessionEnabled() {
419
+ return this.multiSessionEnabled;
420
+ }
421
+ // --------------------------------------------------------------------------
422
+ // Multi-Account Session Pool (Phase 2)
423
+ // --------------------------------------------------------------------------
424
+ /** Get all accounts in the session pool */
425
+ getSessionPool() {
426
+ return Array.from(this.sessionPool.values());
427
+ }
428
+ /** Get the active account entry, or null */
429
+ getActiveAccount() {
430
+ if (!this.userId) return null;
431
+ return this.sessionPool.get(this.userId) || null;
432
+ }
433
+ /** Add an account to the session pool and set it as active */
434
+ async addAccount(entry) {
435
+ this.sessionPool.set(entry.userId, entry);
436
+ this.sessionToken = entry.token;
437
+ this.userId = entry.userId;
438
+ await this.storage.setItem(SESSION_STORAGE_KEY, entry.token);
439
+ await this.storage.setItem(USER_ID_STORAGE_KEY, entry.userId);
440
+ await this.storage.setItem(ACTIVE_ACCOUNT_KEY, entry.userId);
441
+ await this.persistSessionPool();
442
+ }
443
+ /** Switch to a different account in the pool. Returns false if not found. */
444
+ async switchAccount(userId) {
445
+ const entry = this.sessionPool.get(userId);
446
+ if (!entry) return false;
447
+ this.sessionToken = entry.token;
448
+ this.userId = userId;
449
+ this.workspaceId = null;
450
+ await this.storage.setItem(SESSION_STORAGE_KEY, entry.token);
451
+ await this.storage.setItem(USER_ID_STORAGE_KEY, userId);
452
+ await this.storage.setItem(ACTIVE_ACCOUNT_KEY, userId);
453
+ await this.storage.removeItem(WORKSPACE_STORAGE_KEY);
454
+ return true;
455
+ }
456
+ /** Remove a specific account from the pool */
457
+ async removeAccount(userId) {
458
+ this.sessionPool.delete(userId);
459
+ await this.persistSessionPool();
460
+ if (this.userId === userId) {
461
+ const next = this.sessionPool.entries().next().value;
462
+ if (next) {
463
+ await this.switchAccount(next[0]);
464
+ } else {
465
+ await this.clearSession();
466
+ }
467
+ }
468
+ }
469
+ /** Clear all accounts from the pool */
470
+ async clearAllAccounts() {
471
+ this.sessionPool.clear();
472
+ await this.storage.removeItem(SESSION_POOL_KEY);
473
+ await this.storage.removeItem(ACTIVE_ACCOUNT_KEY);
474
+ this.sessionToken = null;
475
+ this.userId = null;
476
+ this.workspaceId = null;
477
+ await this.storage.removeItem(SESSION_STORAGE_KEY);
478
+ await this.storage.removeItem(USER_ID_STORAGE_KEY);
479
+ await this.storage.removeItem(WORKSPACE_STORAGE_KEY);
480
+ }
481
+ /** Persist session pool to storage */
482
+ async persistSessionPool() {
483
+ const obj = {};
484
+ for (const [k, v] of this.sessionPool) {
485
+ obj[k] = v;
486
+ }
487
+ await this.storage.setItem(SESSION_POOL_KEY, JSON.stringify(obj));
488
+ }
355
489
  getBaseUrl() {
356
490
  return this.baseUrl;
357
491
  }
@@ -401,6 +535,9 @@ var ScaleMuleClient = class {
401
535
  if (this.workspaceId) {
402
536
  headers["x-sm-workspace-id"] = this.workspaceId;
403
537
  }
538
+ if (!this.sessionToken && this.anonymousId) {
539
+ headers["x-anonymous-id"] = this.anonymousId;
540
+ }
404
541
  let bodyStr;
405
542
  if (init.body !== void 0 && init.body !== null) {
406
543
  bodyStr = typeof init.body === "string" ? init.body : JSON.stringify(init.body);
@@ -857,6 +994,21 @@ import {
857
994
  } from "@scalemule/ui/phone";
858
995
 
859
996
  // src/services/auth.ts
997
+ function collectDeviceFingerprint() {
998
+ if (typeof window === "undefined" || typeof navigator === "undefined") return void 0;
999
+ try {
1000
+ return {
1001
+ screen: `${screen.width}x${screen.height}x${screen.colorDepth}`,
1002
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
1003
+ language: navigator.language,
1004
+ platform: navigator.platform,
1005
+ cookie_enabled: navigator.cookieEnabled,
1006
+ do_not_track: navigator.doNotTrack
1007
+ };
1008
+ } catch {
1009
+ return void 0;
1010
+ }
1011
+ }
860
1012
  var AuthMfaApi = class extends ServiceModule {
861
1013
  constructor() {
862
1014
  super(...arguments);
@@ -955,12 +1107,42 @@ var AuthService = class extends ServiceModule {
955
1107
  async register(data, options) {
956
1108
  const payload = {
957
1109
  ...data,
958
- phone: this.sanitizePhoneField(data.phone)
1110
+ phone: this.sanitizePhoneField(data.phone),
1111
+ anonymous_id: this.client.getAnonymousId()
959
1112
  };
960
- return this.post("/register", payload, options);
1113
+ const result = await this.post("/register", payload, options);
1114
+ if (result.data && this.client.isMultiSessionEnabled()) {
1115
+ await this.client.addAccount({
1116
+ token: result.data.session_token,
1117
+ userId: result.data.user.id,
1118
+ email: result.data.user.email,
1119
+ fullName: result.data.user.full_name,
1120
+ avatarUrl: result.data.user.avatar_url,
1121
+ expiresAt: result.data.expires_at,
1122
+ addedAt: (/* @__PURE__ */ new Date()).toISOString()
1123
+ });
1124
+ }
1125
+ return result;
961
1126
  }
962
1127
  async login(data, options) {
963
- return this.post("/login", data, options);
1128
+ const payload = {
1129
+ ...data,
1130
+ anonymous_id: this.client.getAnonymousId(),
1131
+ device_fingerprint: data.device_fingerprint || collectDeviceFingerprint()
1132
+ };
1133
+ const result = await this.post("/login", payload, options);
1134
+ if (result.data && this.client.isMultiSessionEnabled()) {
1135
+ await this.client.addAccount({
1136
+ token: result.data.session_token,
1137
+ userId: result.data.user.id,
1138
+ email: result.data.user.email,
1139
+ fullName: result.data.user.full_name,
1140
+ avatarUrl: result.data.user.avatar_url,
1141
+ expiresAt: result.data.expires_at,
1142
+ addedAt: (/* @__PURE__ */ new Date()).toISOString()
1143
+ });
1144
+ }
1145
+ return result;
964
1146
  }
965
1147
  async logout(options) {
966
1148
  return this.post("/logout", void 0, options);
@@ -2488,7 +2670,7 @@ function asNumber2(value) {
2488
2670
 
2489
2671
  // src/services/upload-strategy.ts
2490
2672
  var MULTIPART_THRESHOLD2 = 8 * 1024 * 1024;
2491
- var MULTIPART_THRESHOLD_SLOW2 = 4 * 1024 * 1024;
2673
+ var MULTIPART_THRESHOLD_SLOW2 = 1 * 1024 * 1024;
2492
2674
  var DEFAULT_STALL_TIMEOUT_MS2 = 45e3;
2493
2675
  var SLOW_STALL_TIMEOUT_MS = 9e4;
2494
2676
  var CHUNK_SIZES = {
@@ -2598,7 +2780,6 @@ async function uploadSingleToS3(url, file, options) {
2598
2780
  const result = await doSinglePut(url, file, options?.onProgress, options?.signal, stallTimeout);
2599
2781
  if (result === "success") return { success: true };
2600
2782
  if (result === "abort") return { success: false, error: "Upload aborted" };
2601
- if (result === "stall") return { success: false, error: "Upload stalled \u2014 no progress" };
2602
2783
  }
2603
2784
  return { success: false, error: "Upload failed after retries" };
2604
2785
  }
@@ -3718,7 +3899,11 @@ var AnalyticsService = class extends ServiceModule {
3718
3899
  // Event Tracking (v2 — JetStream buffered)
3719
3900
  // --------------------------------------------------------------------------
3720
3901
  async track(event, properties, userId, options) {
3721
- return this.post("/v2/events", { event_name: event, properties, user_id: userId }, options);
3902
+ const payload = { event_name: event, properties, user_id: userId };
3903
+ if (!userId && !this.client.isAuthenticated()) {
3904
+ payload.anonymous_id = this.client.getAnonymousId();
3905
+ }
3906
+ return this.post("/v2/events", payload, options);
3722
3907
  }
3723
3908
  async trackBatch(events, options) {
3724
3909
  const mapped = events.map(({ event, ...rest }) => ({ event_name: event, ...rest }));
@@ -4842,6 +5027,18 @@ var IdentityService = class extends ServiceModule {
4842
5027
  async revokeApiKey(id, options) {
4843
5028
  return this.del(`/api-keys/${id}`, options);
4844
5029
  }
5030
+ /**
5031
+ * Explicitly link an anonymous_id to the current authenticated user.
5032
+ * Called automatically on init when both a session and anonymous_id exist
5033
+ * (transitional path for users who registered before identity linking existed).
5034
+ */
5035
+ async identify(anonymousId, deviceFingerprintHash, options) {
5036
+ return this.post(
5037
+ "/identify",
5038
+ { anonymous_id: anonymousId, device_fingerprint_hash: deviceFingerprintHash },
5039
+ options
5040
+ );
5041
+ }
4845
5042
  };
4846
5043
 
4847
5044
  // src/services/catalog.ts
@@ -5398,7 +5595,12 @@ var ScaleMule = class {
5398
5595
  * Call this once after construction, before making authenticated requests.
5399
5596
  */
5400
5597
  async initialize() {
5401
- return this._client.initialize();
5598
+ await this._client.initialize();
5599
+ const anonymousId = this._client.getAnonymousId();
5600
+ if (this._client.isAuthenticated() && anonymousId) {
5601
+ this.identity.identify(anonymousId).catch(() => {
5602
+ });
5603
+ }
5402
5604
  }
5403
5605
  /**
5404
5606
  * Set authentication session (token + userId).
@@ -5431,6 +5633,33 @@ var ScaleMule = class {
5431
5633
  isAuthenticated() {
5432
5634
  return this._client.isAuthenticated();
5433
5635
  }
5636
+ /** The anonymous visitor ID used for identity linking. */
5637
+ getAnonymousId() {
5638
+ return this._client.getAnonymousId();
5639
+ }
5640
+ // --------------------------------------------------------------------------
5641
+ // Multi-Account Session Pool (Phase 2)
5642
+ // --------------------------------------------------------------------------
5643
+ /** Get all accounts in the session pool (requires enableMultiSession) */
5644
+ getSessionPool() {
5645
+ return this._client.getSessionPool();
5646
+ }
5647
+ /** Get the active account, or null */
5648
+ getActiveAccount() {
5649
+ return this._client.getActiveAccount();
5650
+ }
5651
+ /** Switch to a different account in the pool. Returns false if not found. */
5652
+ async switchAccount(userId) {
5653
+ return this._client.switchAccount(userId);
5654
+ }
5655
+ /** Remove a specific account from the pool */
5656
+ async removeAccount(userId) {
5657
+ return this._client.removeAccount(userId);
5658
+ }
5659
+ /** Clear all accounts from the pool */
5660
+ async clearAllAccounts() {
5661
+ return this._client.clearAllAccounts();
5662
+ }
5434
5663
  /** The base URL being used for API requests. */
5435
5664
  getBaseUrl() {
5436
5665
  return this._client.getBaseUrl();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scalemule/sdk",
3
- "version": "0.0.20",
3
+ "version": "0.0.22",
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",