@scalemule/sdk 0.0.76 → 0.0.78

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.
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Experiments (A/B tests) on top of scalemule-flags variants.
3
+ *
4
+ * Convention shared by every ScaleMule client and the analytics service:
5
+ * - An experiment is a flag with two or more weighted variants. Evaluating it with a stable
6
+ * identifier (`session_id` or `user_id`) yields the visitor's `variant_key`.
7
+ * - Every analytics event sent while a visitor is in an experiment carries
8
+ * `properties.experiments = { "<flag_key>": "<variant_key>" }`.
9
+ * - `experiment_exposed` is tracked once per visitor and flag when the variant is first shown.
10
+ * - The analytics service reports per-variant results from those properties
11
+ * (`GET /v1/analytics/admin/experiments/{flag_key}`), so any tracked event can be the goal.
12
+ */
13
+ declare const EXPERIMENTS_PROPERTY = "experiments";
14
+ declare const EXPERIMENT_EXPOSED_EVENT = "experiment_exposed";
15
+ declare const MAX_EXPERIMENTS_PER_EVENT = 10;
16
+ /** Active assignments for one visitor: flag key → variant key. */
17
+ type ExperimentAssignments = Record<string, string>;
18
+ interface ExperimentAssignment<T = unknown> {
19
+ flag_key: string;
20
+ /** The variant the visitor is in, or null when the flag is off, missing or has no variants. */
21
+ variant: string | null;
22
+ /** The raw flag evaluation this assignment came from, when one was made. */
23
+ evaluation?: ExperimentEvaluationLike<T> | null;
24
+ }
25
+ /** The subset of a flag evaluation the experiment helpers read. */
26
+ interface ExperimentEvaluationLike<T = unknown> {
27
+ flag_key?: string;
28
+ value?: T;
29
+ reason?: string;
30
+ variant_key?: string | null;
31
+ }
32
+ declare function isExperimentKey(value: unknown): value is string;
33
+ declare function isVariantKey(value: unknown): value is string;
34
+ /**
35
+ * The variant a flag evaluation puts the visitor in.
36
+ * Weighted variants report `variant_key`; a rule or default that serves a string value counts as
37
+ * that variant (so a rule can pin everyone to "modern" and the report still groups them).
38
+ */
39
+ declare function experimentVariant(evaluation: ExperimentEvaluationLike | null | undefined): string | null;
40
+ /** Keeps only well-formed `{ flag_key: variant_key }` pairs, at most MAX_EXPERIMENTS_PER_EVENT. */
41
+ declare function normalizeExperiments(input: unknown): ExperimentAssignments;
42
+ /** Merges the visitor's assignments into event properties under `experiments`. Empty assignments add nothing. */
43
+ declare function withExperiments(properties: Record<string, unknown> | undefined, experiments: ExperimentAssignments | undefined): Record<string, unknown> | undefined;
44
+ /** The `experiment_exposed` event for one assignment. */
45
+ declare function exposureEvent(flagKey: string, variant: string): {
46
+ event_name: string;
47
+ event_category: string;
48
+ properties: Record<string, unknown>;
49
+ };
50
+ /** Key under which a client remembers that an exposure was already sent this session. */
51
+ declare function exposureStorageKey(flagKey: string): string;
52
+
53
+ export { type ExperimentAssignment as E, MAX_EXPERIMENTS_PER_EVENT as M, EXPERIMENTS_PROPERTY as a, EXPERIMENT_EXPOSED_EVENT as b, type ExperimentAssignments as c, type ExperimentEvaluationLike as d, experimentVariant as e, exposureEvent as f, exposureStorageKey as g, isVariantKey as h, isExperimentKey as i, normalizeExperiments as n, withExperiments as w };
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Experiments (A/B tests) on top of scalemule-flags variants.
3
+ *
4
+ * Convention shared by every ScaleMule client and the analytics service:
5
+ * - An experiment is a flag with two or more weighted variants. Evaluating it with a stable
6
+ * identifier (`session_id` or `user_id`) yields the visitor's `variant_key`.
7
+ * - Every analytics event sent while a visitor is in an experiment carries
8
+ * `properties.experiments = { "<flag_key>": "<variant_key>" }`.
9
+ * - `experiment_exposed` is tracked once per visitor and flag when the variant is first shown.
10
+ * - The analytics service reports per-variant results from those properties
11
+ * (`GET /v1/analytics/admin/experiments/{flag_key}`), so any tracked event can be the goal.
12
+ */
13
+ declare const EXPERIMENTS_PROPERTY = "experiments";
14
+ declare const EXPERIMENT_EXPOSED_EVENT = "experiment_exposed";
15
+ declare const MAX_EXPERIMENTS_PER_EVENT = 10;
16
+ /** Active assignments for one visitor: flag key → variant key. */
17
+ type ExperimentAssignments = Record<string, string>;
18
+ interface ExperimentAssignment<T = unknown> {
19
+ flag_key: string;
20
+ /** The variant the visitor is in, or null when the flag is off, missing or has no variants. */
21
+ variant: string | null;
22
+ /** The raw flag evaluation this assignment came from, when one was made. */
23
+ evaluation?: ExperimentEvaluationLike<T> | null;
24
+ }
25
+ /** The subset of a flag evaluation the experiment helpers read. */
26
+ interface ExperimentEvaluationLike<T = unknown> {
27
+ flag_key?: string;
28
+ value?: T;
29
+ reason?: string;
30
+ variant_key?: string | null;
31
+ }
32
+ declare function isExperimentKey(value: unknown): value is string;
33
+ declare function isVariantKey(value: unknown): value is string;
34
+ /**
35
+ * The variant a flag evaluation puts the visitor in.
36
+ * Weighted variants report `variant_key`; a rule or default that serves a string value counts as
37
+ * that variant (so a rule can pin everyone to "modern" and the report still groups them).
38
+ */
39
+ declare function experimentVariant(evaluation: ExperimentEvaluationLike | null | undefined): string | null;
40
+ /** Keeps only well-formed `{ flag_key: variant_key }` pairs, at most MAX_EXPERIMENTS_PER_EVENT. */
41
+ declare function normalizeExperiments(input: unknown): ExperimentAssignments;
42
+ /** Merges the visitor's assignments into event properties under `experiments`. Empty assignments add nothing. */
43
+ declare function withExperiments(properties: Record<string, unknown> | undefined, experiments: ExperimentAssignments | undefined): Record<string, unknown> | undefined;
44
+ /** The `experiment_exposed` event for one assignment. */
45
+ declare function exposureEvent(flagKey: string, variant: string): {
46
+ event_name: string;
47
+ event_category: string;
48
+ properties: Record<string, unknown>;
49
+ };
50
+ /** Key under which a client remembers that an exposure was already sent this session. */
51
+ declare function exposureStorageKey(flagKey: string): string;
52
+
53
+ export { type ExperimentAssignment as E, MAX_EXPERIMENTS_PER_EVENT as M, EXPERIMENTS_PROPERTY as a, EXPERIMENT_EXPOSED_EVENT as b, type ExperimentAssignments as c, type ExperimentEvaluationLike as d, experimentVariant as e, exposureEvent as f, exposureStorageKey as g, isVariantKey as h, isExperimentKey as i, normalizeExperiments as n, withExperiments as w };
@@ -1,3 +1,5 @@
1
+ import { E as ExperimentAssignment } from '../experiments-RH_CTd1R.mjs';
2
+
1
3
  /** Wire format types matching the Rust FlagConfigWire from /v1/flags/config */
2
4
  interface FlagConfigWire {
3
5
  version: number;
@@ -96,6 +98,8 @@ declare class FlagClient {
96
98
  private doInit;
97
99
  private buildIndexes;
98
100
  evaluate(flagKey: string, context: EvaluationContext): FlagEvaluation;
101
+ /** Local-evaluation counterpart of `FlagsService.experiment`: the visitor's variant for a flag with weighted variants. */
102
+ experiment(flagKey: string, context: EvaluationContext): ExperimentAssignment;
99
103
  evaluateBatch(flagKeys: string[], context: EvaluationContext): Record<string, FlagEvaluation>;
100
104
  shutdown(): Promise<void>;
101
105
  private connectStream;
@@ -1,3 +1,5 @@
1
+ import { E as ExperimentAssignment } from '../experiments-RH_CTd1R.js';
2
+
1
3
  /** Wire format types matching the Rust FlagConfigWire from /v1/flags/config */
2
4
  interface FlagConfigWire {
3
5
  version: number;
@@ -96,6 +98,8 @@ declare class FlagClient {
96
98
  private doInit;
97
99
  private buildIndexes;
98
100
  evaluate(flagKey: string, context: EvaluationContext): FlagEvaluation;
101
+ /** Local-evaluation counterpart of `FlagsService.experiment`: the visitor's variant for a flag with weighted variants. */
102
+ experiment(flagKey: string, context: EvaluationContext): ExperimentAssignment;
99
103
  evaluateBatch(flagKeys: string[], context: EvaluationContext): Record<string, FlagEvaluation>;
100
104
  shutdown(): Promise<void>;
101
105
  private connectStream;
@@ -279,6 +279,18 @@ function result(flag, environment, value, reason) {
279
279
  };
280
280
  }
281
281
 
282
+ // src/experiments.ts
283
+ var VARIANT_PATTERN = /^[a-z0-9][a-z0-9_.:-]{0,63}$/;
284
+ function isVariantKey(value) {
285
+ return typeof value === "string" && VARIANT_PATTERN.test(value);
286
+ }
287
+ function experimentVariant(evaluation) {
288
+ if (!evaluation) return null;
289
+ if (isVariantKey(evaluation.variant_key)) return evaluation.variant_key;
290
+ if (isVariantKey(evaluation.value)) return evaluation.value;
291
+ return null;
292
+ }
293
+
282
294
  // src/flags/client.ts
283
295
  var FlagClient = class {
284
296
  constructor(options) {
@@ -353,6 +365,11 @@ var FlagClient = class {
353
365
  this.recordTelemetry(result2);
354
366
  return result2;
355
367
  }
368
+ /** Local-evaluation counterpart of `FlagsService.experiment`: the visitor's variant for a flag with weighted variants. */
369
+ experiment(flagKey, context) {
370
+ const evaluation = this.evaluate(flagKey, context);
371
+ return { flag_key: flagKey, variant: experimentVariant(evaluation), evaluation };
372
+ }
356
373
  evaluateBatch(flagKeys, context) {
357
374
  if (!this.config) throw new Error("FlagClient not initialized \u2014 call init() first");
358
375
  const results = {};
@@ -250,6 +250,18 @@ function result(flag, environment, value, reason) {
250
250
  };
251
251
  }
252
252
 
253
+ // src/experiments.ts
254
+ var VARIANT_PATTERN = /^[a-z0-9][a-z0-9_.:-]{0,63}$/;
255
+ function isVariantKey(value) {
256
+ return typeof value === "string" && VARIANT_PATTERN.test(value);
257
+ }
258
+ function experimentVariant(evaluation) {
259
+ if (!evaluation) return null;
260
+ if (isVariantKey(evaluation.variant_key)) return evaluation.variant_key;
261
+ if (isVariantKey(evaluation.value)) return evaluation.value;
262
+ return null;
263
+ }
264
+
253
265
  // src/flags/client.ts
254
266
  var FlagClient = class {
255
267
  constructor(options) {
@@ -324,6 +336,11 @@ var FlagClient = class {
324
336
  this.recordTelemetry(result2);
325
337
  return result2;
326
338
  }
339
+ /** Local-evaluation counterpart of `FlagsService.experiment`: the visitor's variant for a flag with weighted variants. */
340
+ experiment(flagKey, context) {
341
+ const evaluation = this.evaluate(flagKey, context);
342
+ return { flag_key: flagKey, variant: experimentVariant(evaluation), evaluation };
343
+ }
327
344
  evaluateBatch(flagKeys, context) {
328
345
  if (!this.config) throw new Error("FlagClient not initialized \u2014 call init() first");
329
346
  const results = {};
package/dist/index.d.mts CHANGED
@@ -1,4 +1,6 @@
1
1
  export { PHONE_COUNTRIES, PhoneCountry, PhoneNormalizationResult, composePhoneNumber, countryFlag, detectCountryFromE164, findPhoneCountryByCode, findPhoneCountryByDialCode, isValidE164Phone, normalizeAndValidatePhone, normalizePhoneNumber } from '@scalemule/ui/phone';
2
+ import { E as ExperimentAssignment } from './experiments-RH_CTd1R.mjs';
3
+ export { a as EXPERIMENTS_PROPERTY, b as EXPERIMENT_EXPOSED_EVENT, c as ExperimentAssignments, d as ExperimentEvaluationLike, M as MAX_EXPERIMENTS_PER_EVENT, e as experimentVariant, f as exposureEvent, g as exposureStorageKey, i as isExperimentKey, h as isVariantKey, n as normalizeExperiments, w as withExperiments } from './experiments-RH_CTd1R.mjs';
2
4
 
3
5
  /**
4
6
  * ScaleMule SDK Types
@@ -3689,6 +3691,13 @@ declare class AnalyticsService extends ServiceModule {
3689
3691
  track(event: string, properties?: Record<string, unknown>, userId?: string, options?: RequestOptions): Promise<ApiResponse<{
3690
3692
  tracked: boolean;
3691
3693
  }>>;
3694
+ /**
3695
+ * Track that a visitor saw an experiment variant. Send it once per visitor and flag; the event
3696
+ * carries `properties.experiments` so the experiment report attributes it.
3697
+ */
3698
+ trackExposure(flagKey: string, variant: string, userId?: string, options?: RequestOptions): Promise<ApiResponse<{
3699
+ tracked: boolean;
3700
+ }>>;
3692
3701
  trackBatch(events: Array<{
3693
3702
  event: string;
3694
3703
  properties?: Record<string, unknown>;
@@ -3877,6 +3886,12 @@ interface UpsertEnvironmentRequest {
3877
3886
  declare class FlagsService extends ServiceModule {
3878
3887
  protected basePath: string;
3879
3888
  evaluate<T = unknown>(flagKey: string, context?: Record<string, unknown>, environment?: string, options?: RequestOptions): Promise<ApiResponse<FlagEvaluation<T>>>;
3889
+ /**
3890
+ * Assign a visitor to an experiment: a flag with weighted variants, evaluated with a stable
3891
+ * identifier (`session_id` or `user_id`) so the assignment is sticky. Attach the result to
3892
+ * analytics events with `withExperiments` and track one exposure with `analytics.trackExposure`.
3893
+ */
3894
+ experiment<T = unknown>(flagKey: string, context?: Record<string, unknown>, environment?: string, options?: RequestOptions): Promise<ApiResponse<ExperimentAssignment<T>>>;
3880
3895
  evaluateBatch(flagKeys: string[], context?: Record<string, unknown>, environment?: string, options?: RequestOptions): Promise<ApiResponse<Record<string, FlagEvaluation>>>;
3881
3896
  evaluateAll(context?: Record<string, unknown>, environment?: string, options?: RequestOptions): Promise<ApiResponse<Record<string, FlagEvaluation>>>;
3882
3897
  list(params?: {
@@ -8399,6 +8414,7 @@ declare class AgentSessionsService extends ServiceModule {
8399
8414
  listArtifacts(sessionId: string, options?: RequestOptions): Promise<ApiResponse<SessionArtifact[]>>;
8400
8415
  }
8401
8416
 
8417
+ /** Browser capture shared by applications. Capture starts only on a user gesture. */
8402
8418
  declare function prepareCommunityMapAttachment(file: File): Promise<File>;
8403
8419
  interface MediaCaptureSession {
8404
8420
  stream: MediaStream;
@@ -8558,4 +8574,4 @@ declare class ScaleMule {
8558
8574
  getClient(): ScaleMuleClient;
8559
8575
  }
8560
8576
 
8561
- export { type AcceptQuoteInput, type AccountBalance, type AccountSwitcherPrivacy, 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 AppointmentDepositValue, type Attachment, type Attendee, type AudioRegisterResult, AudioService, type AudioUploadViaStorageResult, type AuditLog, type AuthRegisterAgentRequest, type AuthRegisterAgentResponse, AuthService, type AuthSession, type AuthUser, type BackupCodes, BillingService, type BookingCompletionResult, BookingsService, type CacheEntry, CacheService, type CalendarEvent, type CallParticipant, type CallSession, type CatalogEntry, CatalogService, type ChatMessage, type ChatReaction, ChatService, type ClaimResult, type Client, type ClientContext, type Collection, type Comment, CommunicationService, type CommunityMapArea, type CommunityMapCanonicalArea, type CommunityMapCollection, type CommunityMapCollectionConfig, type CommunityMapComment, type CommunityMapCommentInput, type CommunityMapCommentPage, type CommunityMapConsent, type CommunityMapEditorialCollection, type CommunityMapEditorialComment, type CommunityMapEditorialFeature, type CommunityMapEditorialMedia, type CommunityMapFeature, type CommunityMapFeatureDraft, type CommunityMapFeatureQuery, type CommunityMapFeatureStatus, type CommunityMapGeometry, type CommunityMapMedia, type CommunityMapOwnSubmission, type CommunityMapOwnSubmissionPage, type CommunityMapPage, type CommunityMapPosition, type CommunityMapPrecision, type CommunityMapPrivateReport, type CommunityMapPrivateSubmission, type CommunityMapProposal, type CommunityMapPublicContent, type CommunityMapQueueQuery, type CommunityMapReactionDefinition, type CommunityMapReceipt, type CommunityMapReportInput, type CommunityMapReportReason, type CommunityMapRevision, type CommunityMapSource, type CommunityMapSubmissionInput, type CommunityMapSubmissionPolicy, type CommunityMapSubmissionStatus, type CommunityMapSubmissionUpdate, type CommunityMapView, type CommunityMapVote, CommunityMapsEditorialService, CommunityMapsGeographyService, CommunityMapsService, type CommunityValueOutcome, type CompletedPart, ComplianceService, type CompressionConfig, ConferenceService, type ConferenceSettings, type ConnectedAccount, type ConnectedAccountSubscription, type ConnectedSetupIntentResponse, type ConnectedSubscriptionListParams, type ConnectionStatus, type ContentFlag, type ContentPolicy, type Conversation, type CostReportDay, type CreateProjectInput as CreateCreatorProjectInput, type CreateFlagRequest, type CreateLeadInput, type CreatePollInput, type CreateQuoteInput, type CreateRuleRequest, type CreateSegmentRequest, type CreateSessionResponse, type CreateVariantRequest, type GenerationJob as CreatorJob, CreatorMakerService, type GenerationOutput as CreatorOutput, type CreatorProject, type CreatorUsage, type Credential, type CredentialScope, type Customer, type CustomerStats, type DataAccessPolicy, type DataExport, DataService, type DataSource, type DeadLetterJob, type DecisionBatchItem, type DecisionBatchResult, type DecisionEvaluateOptions, type DecisionOutcome, type DecisionProposedAction, type DecisionReceipt, type DecisionResult, type DecisionTraceLevel, type DecisionVersions, DecisionsService, type DeviceInfo, type DirectoryUser, type DirectoryUserDetail, type DirectoryUsersListResponse, type Document, type ErrorCode, ErrorCodes, type EventAggregation, EventsService, type FileInfo, type FileStatus, 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 GenerateInput, type GrantInfo, type GraphEdge, type GraphNode, GraphService, IdentityService, type IdentityType, type IncomingRequestLike, type IntelligenceAction, type IntelligenceCache, type IntelligenceChangePage, type IntelligenceClaim, type IntelligenceEvent, type IntelligenceKind, type IntelligenceRecordPage, type IntelligenceRelease, type IntelligenceReleaseReceipt, type IntelligenceSection, type IntelligenceSource, type IntelligenceStatus, type IntelligenceVerification, type Invoice, type JobExecution, type JobStats, type JoinCallResponse, type KnownAccount, type KnownAccountDisplay, LEGACY_ANONYMOUS_ID_KEYS, type Lead, type Leaderboard, type LeaderboardEntry, LeaderboardService, LeadsService, type Like, type ListNotificationsParams, type Listing, ListingsService, type LocalBriefing, type LocalIntelligencePreferences, type LocalIntelligenceRecord, LocalIntelligenceService, type LogEntry, type LogInput, type LogQueryParams, type LogQueryResponse, type LogRecord, LoggerService, type LoginActivitySummary, type LoginDeviceInfo, type LoginHistoryEntry, type LoginRiskInfo, MEDIA_PRESETS, type MediaAsset, type MediaCaptureSession, type MediaKind, type MediaManifest, type MediaManifestOptions, type MediaPolicy, type MediaPreset, type MediaPresetSpec, MediaService, type MediaUploadEvent, type MediaUploadOptions, type MediaUploadPhase, type MediaUploadResult, type MessageCallback, type MessagePin, 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 Notification, type NotificationListResponse, NotificationsService, 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 PinnedMessagesResponse, type Pipeline, type PipelineVersion, type Policy, type Poll, type PollBallot, type PollChoice, type PollChoiceInput, type PollListOptions, type PollMedia, type PollMediaKind, type PollStatus, PollsService, type PresenceCallback, type PresenceEvent, type PresignedUploadResponse, type Price, type Product, type Project, type ProjectDocument, type ProjectGrant, type ProjectMember, type PushApiFetcher, type PushPreferences, type PushSettings, type PushSubscriptionInfo, type PushToken, type PushTokenAssociationResult, type PushTopic, type QueryFilter, type QueryOptions, type QuerySort, type QueueJob, QueueService, type Quote, type QuoteDeposit, type QuoteState, type ReadStatus, RealtimeService, type ReceiptVerification, type RedeemResult, type ReferralAnalytics, type ReferralCampaign, type ReferralProfile, type ReferralStats, ReferralsService, type Refund, type RegisterAgentRequest, type RegisterAgentResponse, type RegisterPushTokenData, type RequestOptions, type ResolvedReferral, type ResumeSession, type Role, type RuntimeTemplate, type RuntimeTemplateVersion, type S3MultipartOptions, type S3MultipartResult, type S3SingleUploadOptions, type S3SingleUploadResult, type S3UploadProgress, STORAGE_KEYS, ScaleMule, ScaleMuleClient, type ScaleMuleConfig, type SchedulerJob, SchedulerService, type SearchResult, SearchService, type SearchUsersParams, type SecurityLayers, type ServerlessFunction, type ServiceHealth, ServiceModule, type Session, type SessionArtifact, type SessionInfo, type SessionLog, type SessionPoolEntry, type Severity, type ShareLink, type ShortestPathResult, type SignedUrlResponse, type SocialContentProjection, type SocialContentProjectionInput, type SocialDiscoveryCreatorInput, type SocialPolicyAction, type SocialPolicyBatchDecisionItem, type SocialPolicyBatchDecisionRequest, type SocialPolicyBatchDecisionResponse, type SocialPolicyBatchDecisionTarget, type SocialPolicyBlockRequest, type SocialPolicyContactRequest, type SocialPolicyContactRequestListItem, type SocialPolicyContactRequestQuery, type SocialPolicyContactRequestRequest, type SocialPolicyContext, type SocialPolicyDecision, type SocialPolicyDecisionLimits, type SocialPolicyDecisionRequest, type SocialPolicyDecisionResponse, type SocialPolicyIdentity, type SocialPolicyIdentityType, type SocialPolicyMuteRequest, type SocialPolicyPolicyPack, type SocialPolicyRelationship, type SocialPolicyRelationshipQuery, type SocialPolicyRelationshipRequest, type SocialPolicyReportRequest, SocialPolicyService, type SocialPolicySettings, type SocialPolicyUnblockRequest, type SocialPolicyUpdateSettingsRequest, type SocialPost, SocialService, type SocialUser, type SsoConfig, type StatusCallback, type StorageAdapter, StorageService, type StorageSettings, type StrategyResult, type StylePreset, 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 TtsAccessMode, type TtsAudioInfo, type TtsJobStatus, type TtsListVoicesParams, TtsService, type TtsSpeechMetadata, type TtsSpeechProfile, type TtsSynthesizeParams, type TtsSynthesizeQueuedResult, type TtsSynthesizeReadyResult, type TtsSynthesizeResult, type TtsVoice, type TtsVoicesResponse, type UnreadCountResponse, type UpdateFlagRequest, type UpdatePollInput, 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 VoteState, WEB_PUSH_SERVICE_WORKER, WebPushManager, type WebPushManagerOptions, type WebPushSubscriptionData, type Webhook, WebhooksService, type WebrtcStats, type Workflow, type WorkflowExecution, type Workspace$1 as Workspace, type WorkspaceInvitation, type WorkspaceMember, WorkspacesService, applyIntelligenceChanges, buildClientContextHeaders, calculateTotalParts, canPerform, createUploadPlan, ScaleMule as default, detectNetworkClass, ensureAnonymousId, extractClientContext, generateAnonymousId, generateUploadSessionId, getMeasuredBandwidthMbps, getPartRange, hasMinRoleLevel, pollSharePercent, pollVoterKey, prepareCommunityMapAttachment, readAnonymousId, resolveStrategy, startMediaCapture, uploadMultipartToS3, uploadSingleToS3, validateIP };
8577
+ export { type AcceptQuoteInput, type AccountBalance, type AccountSwitcherPrivacy, 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 AppointmentDepositValue, type Attachment, type Attendee, type AudioRegisterResult, AudioService, type AudioUploadViaStorageResult, type AuditLog, type AuthRegisterAgentRequest, type AuthRegisterAgentResponse, AuthService, type AuthSession, type AuthUser, type BackupCodes, BillingService, type BookingCompletionResult, BookingsService, type CacheEntry, CacheService, type CalendarEvent, type CallParticipant, type CallSession, type CatalogEntry, CatalogService, type ChatMessage, type ChatReaction, ChatService, type ClaimResult, type Client, type ClientContext, type Collection, type Comment, CommunicationService, type CommunityMapArea, type CommunityMapCanonicalArea, type CommunityMapCollection, type CommunityMapCollectionConfig, type CommunityMapComment, type CommunityMapCommentInput, type CommunityMapCommentPage, type CommunityMapConsent, type CommunityMapEditorialCollection, type CommunityMapEditorialComment, type CommunityMapEditorialFeature, type CommunityMapEditorialMedia, type CommunityMapFeature, type CommunityMapFeatureDraft, type CommunityMapFeatureQuery, type CommunityMapFeatureStatus, type CommunityMapGeometry, type CommunityMapMedia, type CommunityMapOwnSubmission, type CommunityMapOwnSubmissionPage, type CommunityMapPage, type CommunityMapPosition, type CommunityMapPrecision, type CommunityMapPrivateReport, type CommunityMapPrivateSubmission, type CommunityMapProposal, type CommunityMapPublicContent, type CommunityMapQueueQuery, type CommunityMapReactionDefinition, type CommunityMapReceipt, type CommunityMapReportInput, type CommunityMapReportReason, type CommunityMapRevision, type CommunityMapSource, type CommunityMapSubmissionInput, type CommunityMapSubmissionPolicy, type CommunityMapSubmissionStatus, type CommunityMapSubmissionUpdate, type CommunityMapView, type CommunityMapVote, CommunityMapsEditorialService, CommunityMapsGeographyService, CommunityMapsService, type CommunityValueOutcome, type CompletedPart, ComplianceService, type CompressionConfig, ConferenceService, type ConferenceSettings, type ConnectedAccount, type ConnectedAccountSubscription, type ConnectedSetupIntentResponse, type ConnectedSubscriptionListParams, type ConnectionStatus, type ContentFlag, type ContentPolicy, type Conversation, type CostReportDay, type CreateProjectInput as CreateCreatorProjectInput, type CreateFlagRequest, type CreateLeadInput, type CreatePollInput, type CreateQuoteInput, type CreateRuleRequest, type CreateSegmentRequest, type CreateSessionResponse, type CreateVariantRequest, type GenerationJob as CreatorJob, CreatorMakerService, type GenerationOutput as CreatorOutput, type CreatorProject, type CreatorUsage, type Credential, type CredentialScope, type Customer, type CustomerStats, type DataAccessPolicy, type DataExport, DataService, type DataSource, type DeadLetterJob, type DecisionBatchItem, type DecisionBatchResult, type DecisionEvaluateOptions, type DecisionOutcome, type DecisionProposedAction, type DecisionReceipt, type DecisionResult, type DecisionTraceLevel, type DecisionVersions, DecisionsService, type DeviceInfo, type DirectoryUser, type DirectoryUserDetail, type DirectoryUsersListResponse, type Document, type ErrorCode, ErrorCodes, type EventAggregation, EventsService, ExperimentAssignment, type FileInfo, type FileStatus, 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 GenerateInput, type GrantInfo, type GraphEdge, type GraphNode, GraphService, IdentityService, type IdentityType, type IncomingRequestLike, type IntelligenceAction, type IntelligenceCache, type IntelligenceChangePage, type IntelligenceClaim, type IntelligenceEvent, type IntelligenceKind, type IntelligenceRecordPage, type IntelligenceRelease, type IntelligenceReleaseReceipt, type IntelligenceSection, type IntelligenceSource, type IntelligenceStatus, type IntelligenceVerification, type Invoice, type JobExecution, type JobStats, type JoinCallResponse, type KnownAccount, type KnownAccountDisplay, LEGACY_ANONYMOUS_ID_KEYS, type Lead, type Leaderboard, type LeaderboardEntry, LeaderboardService, LeadsService, type Like, type ListNotificationsParams, type Listing, ListingsService, type LocalBriefing, type LocalIntelligencePreferences, type LocalIntelligenceRecord, LocalIntelligenceService, type LogEntry, type LogInput, type LogQueryParams, type LogQueryResponse, type LogRecord, LoggerService, type LoginActivitySummary, type LoginDeviceInfo, type LoginHistoryEntry, type LoginRiskInfo, MEDIA_PRESETS, type MediaAsset, type MediaCaptureSession, type MediaKind, type MediaManifest, type MediaManifestOptions, type MediaPolicy, type MediaPreset, type MediaPresetSpec, MediaService, type MediaUploadEvent, type MediaUploadOptions, type MediaUploadPhase, type MediaUploadResult, type MessageCallback, type MessagePin, 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 Notification, type NotificationListResponse, NotificationsService, 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 PinnedMessagesResponse, type Pipeline, type PipelineVersion, type Policy, type Poll, type PollBallot, type PollChoice, type PollChoiceInput, type PollListOptions, type PollMedia, type PollMediaKind, type PollStatus, PollsService, type PresenceCallback, type PresenceEvent, type PresignedUploadResponse, type Price, type Product, type Project, type ProjectDocument, type ProjectGrant, type ProjectMember, type PushApiFetcher, type PushPreferences, type PushSettings, type PushSubscriptionInfo, type PushToken, type PushTokenAssociationResult, type PushTopic, type QueryFilter, type QueryOptions, type QuerySort, type QueueJob, QueueService, type Quote, type QuoteDeposit, type QuoteState, type ReadStatus, RealtimeService, type ReceiptVerification, type RedeemResult, type ReferralAnalytics, type ReferralCampaign, type ReferralProfile, type ReferralStats, ReferralsService, type Refund, type RegisterAgentRequest, type RegisterAgentResponse, type RegisterPushTokenData, type RequestOptions, type ResolvedReferral, type ResumeSession, type Role, type RuntimeTemplate, type RuntimeTemplateVersion, type S3MultipartOptions, type S3MultipartResult, type S3SingleUploadOptions, type S3SingleUploadResult, type S3UploadProgress, STORAGE_KEYS, ScaleMule, ScaleMuleClient, type ScaleMuleConfig, type SchedulerJob, SchedulerService, type SearchResult, SearchService, type SearchUsersParams, type SecurityLayers, type ServerlessFunction, type ServiceHealth, ServiceModule, type Session, type SessionArtifact, type SessionInfo, type SessionLog, type SessionPoolEntry, type Severity, type ShareLink, type ShortestPathResult, type SignedUrlResponse, type SocialContentProjection, type SocialContentProjectionInput, type SocialDiscoveryCreatorInput, type SocialPolicyAction, type SocialPolicyBatchDecisionItem, type SocialPolicyBatchDecisionRequest, type SocialPolicyBatchDecisionResponse, type SocialPolicyBatchDecisionTarget, type SocialPolicyBlockRequest, type SocialPolicyContactRequest, type SocialPolicyContactRequestListItem, type SocialPolicyContactRequestQuery, type SocialPolicyContactRequestRequest, type SocialPolicyContext, type SocialPolicyDecision, type SocialPolicyDecisionLimits, type SocialPolicyDecisionRequest, type SocialPolicyDecisionResponse, type SocialPolicyIdentity, type SocialPolicyIdentityType, type SocialPolicyMuteRequest, type SocialPolicyPolicyPack, type SocialPolicyRelationship, type SocialPolicyRelationshipQuery, type SocialPolicyRelationshipRequest, type SocialPolicyReportRequest, SocialPolicyService, type SocialPolicySettings, type SocialPolicyUnblockRequest, type SocialPolicyUpdateSettingsRequest, type SocialPost, SocialService, type SocialUser, type SsoConfig, type StatusCallback, type StorageAdapter, StorageService, type StorageSettings, type StrategyResult, type StylePreset, 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 TtsAccessMode, type TtsAudioInfo, type TtsJobStatus, type TtsListVoicesParams, TtsService, type TtsSpeechMetadata, type TtsSpeechProfile, type TtsSynthesizeParams, type TtsSynthesizeQueuedResult, type TtsSynthesizeReadyResult, type TtsSynthesizeResult, type TtsVoice, type TtsVoicesResponse, type UnreadCountResponse, type UpdateFlagRequest, type UpdatePollInput, 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 VoteState, WEB_PUSH_SERVICE_WORKER, WebPushManager, type WebPushManagerOptions, type WebPushSubscriptionData, type Webhook, WebhooksService, type WebrtcStats, type Workflow, type WorkflowExecution, type Workspace$1 as Workspace, type WorkspaceInvitation, type WorkspaceMember, WorkspacesService, applyIntelligenceChanges, buildClientContextHeaders, calculateTotalParts, canPerform, createUploadPlan, ScaleMule as default, detectNetworkClass, ensureAnonymousId, extractClientContext, generateAnonymousId, generateUploadSessionId, getMeasuredBandwidthMbps, getPartRange, hasMinRoleLevel, pollSharePercent, pollVoterKey, prepareCommunityMapAttachment, readAnonymousId, resolveStrategy, startMediaCapture, uploadMultipartToS3, uploadSingleToS3, validateIP };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  export { PHONE_COUNTRIES, PhoneCountry, PhoneNormalizationResult, composePhoneNumber, countryFlag, detectCountryFromE164, findPhoneCountryByCode, findPhoneCountryByDialCode, isValidE164Phone, normalizeAndValidatePhone, normalizePhoneNumber } from '@scalemule/ui/phone';
2
+ import { E as ExperimentAssignment } from './experiments-RH_CTd1R.js';
3
+ export { a as EXPERIMENTS_PROPERTY, b as EXPERIMENT_EXPOSED_EVENT, c as ExperimentAssignments, d as ExperimentEvaluationLike, M as MAX_EXPERIMENTS_PER_EVENT, e as experimentVariant, f as exposureEvent, g as exposureStorageKey, i as isExperimentKey, h as isVariantKey, n as normalizeExperiments, w as withExperiments } from './experiments-RH_CTd1R.js';
2
4
 
3
5
  /**
4
6
  * ScaleMule SDK Types
@@ -3689,6 +3691,13 @@ declare class AnalyticsService extends ServiceModule {
3689
3691
  track(event: string, properties?: Record<string, unknown>, userId?: string, options?: RequestOptions): Promise<ApiResponse<{
3690
3692
  tracked: boolean;
3691
3693
  }>>;
3694
+ /**
3695
+ * Track that a visitor saw an experiment variant. Send it once per visitor and flag; the event
3696
+ * carries `properties.experiments` so the experiment report attributes it.
3697
+ */
3698
+ trackExposure(flagKey: string, variant: string, userId?: string, options?: RequestOptions): Promise<ApiResponse<{
3699
+ tracked: boolean;
3700
+ }>>;
3692
3701
  trackBatch(events: Array<{
3693
3702
  event: string;
3694
3703
  properties?: Record<string, unknown>;
@@ -3877,6 +3886,12 @@ interface UpsertEnvironmentRequest {
3877
3886
  declare class FlagsService extends ServiceModule {
3878
3887
  protected basePath: string;
3879
3888
  evaluate<T = unknown>(flagKey: string, context?: Record<string, unknown>, environment?: string, options?: RequestOptions): Promise<ApiResponse<FlagEvaluation<T>>>;
3889
+ /**
3890
+ * Assign a visitor to an experiment: a flag with weighted variants, evaluated with a stable
3891
+ * identifier (`session_id` or `user_id`) so the assignment is sticky. Attach the result to
3892
+ * analytics events with `withExperiments` and track one exposure with `analytics.trackExposure`.
3893
+ */
3894
+ experiment<T = unknown>(flagKey: string, context?: Record<string, unknown>, environment?: string, options?: RequestOptions): Promise<ApiResponse<ExperimentAssignment<T>>>;
3880
3895
  evaluateBatch(flagKeys: string[], context?: Record<string, unknown>, environment?: string, options?: RequestOptions): Promise<ApiResponse<Record<string, FlagEvaluation>>>;
3881
3896
  evaluateAll(context?: Record<string, unknown>, environment?: string, options?: RequestOptions): Promise<ApiResponse<Record<string, FlagEvaluation>>>;
3882
3897
  list(params?: {
@@ -8399,6 +8414,7 @@ declare class AgentSessionsService extends ServiceModule {
8399
8414
  listArtifacts(sessionId: string, options?: RequestOptions): Promise<ApiResponse<SessionArtifact[]>>;
8400
8415
  }
8401
8416
 
8417
+ /** Browser capture shared by applications. Capture starts only on a user gesture. */
8402
8418
  declare function prepareCommunityMapAttachment(file: File): Promise<File>;
8403
8419
  interface MediaCaptureSession {
8404
8420
  stream: MediaStream;
@@ -8558,4 +8574,4 @@ declare class ScaleMule {
8558
8574
  getClient(): ScaleMuleClient;
8559
8575
  }
8560
8576
 
8561
- export { type AcceptQuoteInput, type AccountBalance, type AccountSwitcherPrivacy, 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 AppointmentDepositValue, type Attachment, type Attendee, type AudioRegisterResult, AudioService, type AudioUploadViaStorageResult, type AuditLog, type AuthRegisterAgentRequest, type AuthRegisterAgentResponse, AuthService, type AuthSession, type AuthUser, type BackupCodes, BillingService, type BookingCompletionResult, BookingsService, type CacheEntry, CacheService, type CalendarEvent, type CallParticipant, type CallSession, type CatalogEntry, CatalogService, type ChatMessage, type ChatReaction, ChatService, type ClaimResult, type Client, type ClientContext, type Collection, type Comment, CommunicationService, type CommunityMapArea, type CommunityMapCanonicalArea, type CommunityMapCollection, type CommunityMapCollectionConfig, type CommunityMapComment, type CommunityMapCommentInput, type CommunityMapCommentPage, type CommunityMapConsent, type CommunityMapEditorialCollection, type CommunityMapEditorialComment, type CommunityMapEditorialFeature, type CommunityMapEditorialMedia, type CommunityMapFeature, type CommunityMapFeatureDraft, type CommunityMapFeatureQuery, type CommunityMapFeatureStatus, type CommunityMapGeometry, type CommunityMapMedia, type CommunityMapOwnSubmission, type CommunityMapOwnSubmissionPage, type CommunityMapPage, type CommunityMapPosition, type CommunityMapPrecision, type CommunityMapPrivateReport, type CommunityMapPrivateSubmission, type CommunityMapProposal, type CommunityMapPublicContent, type CommunityMapQueueQuery, type CommunityMapReactionDefinition, type CommunityMapReceipt, type CommunityMapReportInput, type CommunityMapReportReason, type CommunityMapRevision, type CommunityMapSource, type CommunityMapSubmissionInput, type CommunityMapSubmissionPolicy, type CommunityMapSubmissionStatus, type CommunityMapSubmissionUpdate, type CommunityMapView, type CommunityMapVote, CommunityMapsEditorialService, CommunityMapsGeographyService, CommunityMapsService, type CommunityValueOutcome, type CompletedPart, ComplianceService, type CompressionConfig, ConferenceService, type ConferenceSettings, type ConnectedAccount, type ConnectedAccountSubscription, type ConnectedSetupIntentResponse, type ConnectedSubscriptionListParams, type ConnectionStatus, type ContentFlag, type ContentPolicy, type Conversation, type CostReportDay, type CreateProjectInput as CreateCreatorProjectInput, type CreateFlagRequest, type CreateLeadInput, type CreatePollInput, type CreateQuoteInput, type CreateRuleRequest, type CreateSegmentRequest, type CreateSessionResponse, type CreateVariantRequest, type GenerationJob as CreatorJob, CreatorMakerService, type GenerationOutput as CreatorOutput, type CreatorProject, type CreatorUsage, type Credential, type CredentialScope, type Customer, type CustomerStats, type DataAccessPolicy, type DataExport, DataService, type DataSource, type DeadLetterJob, type DecisionBatchItem, type DecisionBatchResult, type DecisionEvaluateOptions, type DecisionOutcome, type DecisionProposedAction, type DecisionReceipt, type DecisionResult, type DecisionTraceLevel, type DecisionVersions, DecisionsService, type DeviceInfo, type DirectoryUser, type DirectoryUserDetail, type DirectoryUsersListResponse, type Document, type ErrorCode, ErrorCodes, type EventAggregation, EventsService, type FileInfo, type FileStatus, 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 GenerateInput, type GrantInfo, type GraphEdge, type GraphNode, GraphService, IdentityService, type IdentityType, type IncomingRequestLike, type IntelligenceAction, type IntelligenceCache, type IntelligenceChangePage, type IntelligenceClaim, type IntelligenceEvent, type IntelligenceKind, type IntelligenceRecordPage, type IntelligenceRelease, type IntelligenceReleaseReceipt, type IntelligenceSection, type IntelligenceSource, type IntelligenceStatus, type IntelligenceVerification, type Invoice, type JobExecution, type JobStats, type JoinCallResponse, type KnownAccount, type KnownAccountDisplay, LEGACY_ANONYMOUS_ID_KEYS, type Lead, type Leaderboard, type LeaderboardEntry, LeaderboardService, LeadsService, type Like, type ListNotificationsParams, type Listing, ListingsService, type LocalBriefing, type LocalIntelligencePreferences, type LocalIntelligenceRecord, LocalIntelligenceService, type LogEntry, type LogInput, type LogQueryParams, type LogQueryResponse, type LogRecord, LoggerService, type LoginActivitySummary, type LoginDeviceInfo, type LoginHistoryEntry, type LoginRiskInfo, MEDIA_PRESETS, type MediaAsset, type MediaCaptureSession, type MediaKind, type MediaManifest, type MediaManifestOptions, type MediaPolicy, type MediaPreset, type MediaPresetSpec, MediaService, type MediaUploadEvent, type MediaUploadOptions, type MediaUploadPhase, type MediaUploadResult, type MessageCallback, type MessagePin, 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 Notification, type NotificationListResponse, NotificationsService, 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 PinnedMessagesResponse, type Pipeline, type PipelineVersion, type Policy, type Poll, type PollBallot, type PollChoice, type PollChoiceInput, type PollListOptions, type PollMedia, type PollMediaKind, type PollStatus, PollsService, type PresenceCallback, type PresenceEvent, type PresignedUploadResponse, type Price, type Product, type Project, type ProjectDocument, type ProjectGrant, type ProjectMember, type PushApiFetcher, type PushPreferences, type PushSettings, type PushSubscriptionInfo, type PushToken, type PushTokenAssociationResult, type PushTopic, type QueryFilter, type QueryOptions, type QuerySort, type QueueJob, QueueService, type Quote, type QuoteDeposit, type QuoteState, type ReadStatus, RealtimeService, type ReceiptVerification, type RedeemResult, type ReferralAnalytics, type ReferralCampaign, type ReferralProfile, type ReferralStats, ReferralsService, type Refund, type RegisterAgentRequest, type RegisterAgentResponse, type RegisterPushTokenData, type RequestOptions, type ResolvedReferral, type ResumeSession, type Role, type RuntimeTemplate, type RuntimeTemplateVersion, type S3MultipartOptions, type S3MultipartResult, type S3SingleUploadOptions, type S3SingleUploadResult, type S3UploadProgress, STORAGE_KEYS, ScaleMule, ScaleMuleClient, type ScaleMuleConfig, type SchedulerJob, SchedulerService, type SearchResult, SearchService, type SearchUsersParams, type SecurityLayers, type ServerlessFunction, type ServiceHealth, ServiceModule, type Session, type SessionArtifact, type SessionInfo, type SessionLog, type SessionPoolEntry, type Severity, type ShareLink, type ShortestPathResult, type SignedUrlResponse, type SocialContentProjection, type SocialContentProjectionInput, type SocialDiscoveryCreatorInput, type SocialPolicyAction, type SocialPolicyBatchDecisionItem, type SocialPolicyBatchDecisionRequest, type SocialPolicyBatchDecisionResponse, type SocialPolicyBatchDecisionTarget, type SocialPolicyBlockRequest, type SocialPolicyContactRequest, type SocialPolicyContactRequestListItem, type SocialPolicyContactRequestQuery, type SocialPolicyContactRequestRequest, type SocialPolicyContext, type SocialPolicyDecision, type SocialPolicyDecisionLimits, type SocialPolicyDecisionRequest, type SocialPolicyDecisionResponse, type SocialPolicyIdentity, type SocialPolicyIdentityType, type SocialPolicyMuteRequest, type SocialPolicyPolicyPack, type SocialPolicyRelationship, type SocialPolicyRelationshipQuery, type SocialPolicyRelationshipRequest, type SocialPolicyReportRequest, SocialPolicyService, type SocialPolicySettings, type SocialPolicyUnblockRequest, type SocialPolicyUpdateSettingsRequest, type SocialPost, SocialService, type SocialUser, type SsoConfig, type StatusCallback, type StorageAdapter, StorageService, type StorageSettings, type StrategyResult, type StylePreset, 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 TtsAccessMode, type TtsAudioInfo, type TtsJobStatus, type TtsListVoicesParams, TtsService, type TtsSpeechMetadata, type TtsSpeechProfile, type TtsSynthesizeParams, type TtsSynthesizeQueuedResult, type TtsSynthesizeReadyResult, type TtsSynthesizeResult, type TtsVoice, type TtsVoicesResponse, type UnreadCountResponse, type UpdateFlagRequest, type UpdatePollInput, 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 VoteState, WEB_PUSH_SERVICE_WORKER, WebPushManager, type WebPushManagerOptions, type WebPushSubscriptionData, type Webhook, WebhooksService, type WebrtcStats, type Workflow, type WorkflowExecution, type Workspace$1 as Workspace, type WorkspaceInvitation, type WorkspaceMember, WorkspacesService, applyIntelligenceChanges, buildClientContextHeaders, calculateTotalParts, canPerform, createUploadPlan, ScaleMule as default, detectNetworkClass, ensureAnonymousId, extractClientContext, generateAnonymousId, generateUploadSessionId, getMeasuredBandwidthMbps, getPartRange, hasMinRoleLevel, pollSharePercent, pollVoterKey, prepareCommunityMapAttachment, readAnonymousId, resolveStrategy, startMediaCapture, uploadMultipartToS3, uploadSingleToS3, validateIP };
8577
+ export { type AcceptQuoteInput, type AccountBalance, type AccountSwitcherPrivacy, 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 AppointmentDepositValue, type Attachment, type Attendee, type AudioRegisterResult, AudioService, type AudioUploadViaStorageResult, type AuditLog, type AuthRegisterAgentRequest, type AuthRegisterAgentResponse, AuthService, type AuthSession, type AuthUser, type BackupCodes, BillingService, type BookingCompletionResult, BookingsService, type CacheEntry, CacheService, type CalendarEvent, type CallParticipant, type CallSession, type CatalogEntry, CatalogService, type ChatMessage, type ChatReaction, ChatService, type ClaimResult, type Client, type ClientContext, type Collection, type Comment, CommunicationService, type CommunityMapArea, type CommunityMapCanonicalArea, type CommunityMapCollection, type CommunityMapCollectionConfig, type CommunityMapComment, type CommunityMapCommentInput, type CommunityMapCommentPage, type CommunityMapConsent, type CommunityMapEditorialCollection, type CommunityMapEditorialComment, type CommunityMapEditorialFeature, type CommunityMapEditorialMedia, type CommunityMapFeature, type CommunityMapFeatureDraft, type CommunityMapFeatureQuery, type CommunityMapFeatureStatus, type CommunityMapGeometry, type CommunityMapMedia, type CommunityMapOwnSubmission, type CommunityMapOwnSubmissionPage, type CommunityMapPage, type CommunityMapPosition, type CommunityMapPrecision, type CommunityMapPrivateReport, type CommunityMapPrivateSubmission, type CommunityMapProposal, type CommunityMapPublicContent, type CommunityMapQueueQuery, type CommunityMapReactionDefinition, type CommunityMapReceipt, type CommunityMapReportInput, type CommunityMapReportReason, type CommunityMapRevision, type CommunityMapSource, type CommunityMapSubmissionInput, type CommunityMapSubmissionPolicy, type CommunityMapSubmissionStatus, type CommunityMapSubmissionUpdate, type CommunityMapView, type CommunityMapVote, CommunityMapsEditorialService, CommunityMapsGeographyService, CommunityMapsService, type CommunityValueOutcome, type CompletedPart, ComplianceService, type CompressionConfig, ConferenceService, type ConferenceSettings, type ConnectedAccount, type ConnectedAccountSubscription, type ConnectedSetupIntentResponse, type ConnectedSubscriptionListParams, type ConnectionStatus, type ContentFlag, type ContentPolicy, type Conversation, type CostReportDay, type CreateProjectInput as CreateCreatorProjectInput, type CreateFlagRequest, type CreateLeadInput, type CreatePollInput, type CreateQuoteInput, type CreateRuleRequest, type CreateSegmentRequest, type CreateSessionResponse, type CreateVariantRequest, type GenerationJob as CreatorJob, CreatorMakerService, type GenerationOutput as CreatorOutput, type CreatorProject, type CreatorUsage, type Credential, type CredentialScope, type Customer, type CustomerStats, type DataAccessPolicy, type DataExport, DataService, type DataSource, type DeadLetterJob, type DecisionBatchItem, type DecisionBatchResult, type DecisionEvaluateOptions, type DecisionOutcome, type DecisionProposedAction, type DecisionReceipt, type DecisionResult, type DecisionTraceLevel, type DecisionVersions, DecisionsService, type DeviceInfo, type DirectoryUser, type DirectoryUserDetail, type DirectoryUsersListResponse, type Document, type ErrorCode, ErrorCodes, type EventAggregation, EventsService, ExperimentAssignment, type FileInfo, type FileStatus, 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 GenerateInput, type GrantInfo, type GraphEdge, type GraphNode, GraphService, IdentityService, type IdentityType, type IncomingRequestLike, type IntelligenceAction, type IntelligenceCache, type IntelligenceChangePage, type IntelligenceClaim, type IntelligenceEvent, type IntelligenceKind, type IntelligenceRecordPage, type IntelligenceRelease, type IntelligenceReleaseReceipt, type IntelligenceSection, type IntelligenceSource, type IntelligenceStatus, type IntelligenceVerification, type Invoice, type JobExecution, type JobStats, type JoinCallResponse, type KnownAccount, type KnownAccountDisplay, LEGACY_ANONYMOUS_ID_KEYS, type Lead, type Leaderboard, type LeaderboardEntry, LeaderboardService, LeadsService, type Like, type ListNotificationsParams, type Listing, ListingsService, type LocalBriefing, type LocalIntelligencePreferences, type LocalIntelligenceRecord, LocalIntelligenceService, type LogEntry, type LogInput, type LogQueryParams, type LogQueryResponse, type LogRecord, LoggerService, type LoginActivitySummary, type LoginDeviceInfo, type LoginHistoryEntry, type LoginRiskInfo, MEDIA_PRESETS, type MediaAsset, type MediaCaptureSession, type MediaKind, type MediaManifest, type MediaManifestOptions, type MediaPolicy, type MediaPreset, type MediaPresetSpec, MediaService, type MediaUploadEvent, type MediaUploadOptions, type MediaUploadPhase, type MediaUploadResult, type MessageCallback, type MessagePin, 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 Notification, type NotificationListResponse, NotificationsService, 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 PinnedMessagesResponse, type Pipeline, type PipelineVersion, type Policy, type Poll, type PollBallot, type PollChoice, type PollChoiceInput, type PollListOptions, type PollMedia, type PollMediaKind, type PollStatus, PollsService, type PresenceCallback, type PresenceEvent, type PresignedUploadResponse, type Price, type Product, type Project, type ProjectDocument, type ProjectGrant, type ProjectMember, type PushApiFetcher, type PushPreferences, type PushSettings, type PushSubscriptionInfo, type PushToken, type PushTokenAssociationResult, type PushTopic, type QueryFilter, type QueryOptions, type QuerySort, type QueueJob, QueueService, type Quote, type QuoteDeposit, type QuoteState, type ReadStatus, RealtimeService, type ReceiptVerification, type RedeemResult, type ReferralAnalytics, type ReferralCampaign, type ReferralProfile, type ReferralStats, ReferralsService, type Refund, type RegisterAgentRequest, type RegisterAgentResponse, type RegisterPushTokenData, type RequestOptions, type ResolvedReferral, type ResumeSession, type Role, type RuntimeTemplate, type RuntimeTemplateVersion, type S3MultipartOptions, type S3MultipartResult, type S3SingleUploadOptions, type S3SingleUploadResult, type S3UploadProgress, STORAGE_KEYS, ScaleMule, ScaleMuleClient, type ScaleMuleConfig, type SchedulerJob, SchedulerService, type SearchResult, SearchService, type SearchUsersParams, type SecurityLayers, type ServerlessFunction, type ServiceHealth, ServiceModule, type Session, type SessionArtifact, type SessionInfo, type SessionLog, type SessionPoolEntry, type Severity, type ShareLink, type ShortestPathResult, type SignedUrlResponse, type SocialContentProjection, type SocialContentProjectionInput, type SocialDiscoveryCreatorInput, type SocialPolicyAction, type SocialPolicyBatchDecisionItem, type SocialPolicyBatchDecisionRequest, type SocialPolicyBatchDecisionResponse, type SocialPolicyBatchDecisionTarget, type SocialPolicyBlockRequest, type SocialPolicyContactRequest, type SocialPolicyContactRequestListItem, type SocialPolicyContactRequestQuery, type SocialPolicyContactRequestRequest, type SocialPolicyContext, type SocialPolicyDecision, type SocialPolicyDecisionLimits, type SocialPolicyDecisionRequest, type SocialPolicyDecisionResponse, type SocialPolicyIdentity, type SocialPolicyIdentityType, type SocialPolicyMuteRequest, type SocialPolicyPolicyPack, type SocialPolicyRelationship, type SocialPolicyRelationshipQuery, type SocialPolicyRelationshipRequest, type SocialPolicyReportRequest, SocialPolicyService, type SocialPolicySettings, type SocialPolicyUnblockRequest, type SocialPolicyUpdateSettingsRequest, type SocialPost, SocialService, type SocialUser, type SsoConfig, type StatusCallback, type StorageAdapter, StorageService, type StorageSettings, type StrategyResult, type StylePreset, 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 TtsAccessMode, type TtsAudioInfo, type TtsJobStatus, type TtsListVoicesParams, TtsService, type TtsSpeechMetadata, type TtsSpeechProfile, type TtsSynthesizeParams, type TtsSynthesizeQueuedResult, type TtsSynthesizeReadyResult, type TtsSynthesizeResult, type TtsVoice, type TtsVoicesResponse, type UnreadCountResponse, type UpdateFlagRequest, type UpdatePollInput, 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 VoteState, WEB_PUSH_SERVICE_WORKER, WebPushManager, type WebPushManagerOptions, type WebPushSubscriptionData, type Webhook, WebhooksService, type WebrtcStats, type Workflow, type WorkflowExecution, type Workspace$1 as Workspace, type WorkspaceInvitation, type WorkspaceMember, WorkspacesService, applyIntelligenceChanges, buildClientContextHeaders, calculateTotalParts, canPerform, createUploadPlan, ScaleMule as default, detectNetworkClass, ensureAnonymousId, extractClientContext, generateAnonymousId, generateUploadSessionId, getMeasuredBandwidthMbps, getPartRange, hasMinRoleLevel, pollSharePercent, pollVoterKey, prepareCommunityMapAttachment, readAnonymousId, resolveStrategy, startMediaCapture, uploadMultipartToS3, uploadSingleToS3, validateIP };
package/dist/index.js CHANGED
@@ -240,6 +240,7 @@ async function maybeCompressImage(file, userConfig, sessionId, telemetry) {
240
240
  maxWidthOrHeight: Math.max(config.maxWidth, config.maxHeight),
241
241
  initialQuality: config.quality,
242
242
  useWebWorker: true,
243
+ preserveExif: true,
243
244
  fileType: type === "image/png" ? "image/webp" : void 0
244
245
  });
245
246
  if (compressed.size >= file.size * 0.95) {
@@ -327,6 +328,8 @@ __export(index_exports, {
327
328
  CreatorMakerService: () => CreatorMakerService,
328
329
  DataService: () => DataService,
329
330
  DecisionsService: () => DecisionsService,
331
+ EXPERIMENTS_PROPERTY: () => EXPERIMENTS_PROPERTY,
332
+ EXPERIMENT_EXPOSED_EVENT: () => EXPERIMENT_EXPOSED_EVENT,
330
333
  ErrorCodes: () => ErrorCodes,
331
334
  EventsService: () => EventsService,
332
335
  FlagContentService: () => FlagContentService,
@@ -340,6 +343,7 @@ __export(index_exports, {
340
343
  ListingsService: () => ListingsService,
341
344
  LocalIntelligenceService: () => LocalIntelligenceService,
342
345
  LoggerService: () => LoggerService,
346
+ MAX_EXPERIMENTS_PER_EVENT: () => MAX_EXPERIMENTS_PER_EVENT,
343
347
  MEDIA_PRESETS: () => MEDIA_PRESETS,
344
348
  MediaService: () => MediaService,
345
349
  NotificationsService: () => NotificationsService,
@@ -381,6 +385,9 @@ __export(index_exports, {
381
385
  detectCountryFromE164: () => detectCountryFromE164,
382
386
  detectNetworkClass: () => detectNetworkClass,
383
387
  ensureAnonymousId: () => ensureAnonymousId,
388
+ experimentVariant: () => experimentVariant,
389
+ exposureEvent: () => exposureEvent,
390
+ exposureStorageKey: () => exposureStorageKey,
384
391
  extractClientContext: () => extractClientContext,
385
392
  findPhoneCountryByCode: () => findPhoneCountryByCode,
386
393
  findPhoneCountryByDialCode: () => findPhoneCountryByDialCode,
@@ -389,8 +396,11 @@ __export(index_exports, {
389
396
  getMeasuredBandwidthMbps: () => getMeasuredBandwidthMbps,
390
397
  getPartRange: () => getPartRange,
391
398
  hasMinRoleLevel: () => hasMinRoleLevel,
399
+ isExperimentKey: () => isExperimentKey,
392
400
  isValidE164Phone: () => isValidE164Phone,
401
+ isVariantKey: () => isVariantKey,
393
402
  normalizeAndValidatePhone: () => normalizeAndValidatePhone,
403
+ normalizeExperiments: () => normalizeExperiments,
394
404
  normalizePhoneNumber: () => normalizePhoneNumber,
395
405
  pollSharePercent: () => pollSharePercent,
396
406
  pollVoterKey: () => pollVoterKey,
@@ -400,7 +410,8 @@ __export(index_exports, {
400
410
  startMediaCapture: () => startMediaCapture,
401
411
  uploadMultipartToS3: () => uploadMultipartToS3,
402
412
  uploadSingleToS3: () => uploadSingleToS3,
403
- validateIP: () => validateIP
413
+ validateIP: () => validateIP,
414
+ withExperiments: () => withExperiments
404
415
  });
405
416
  module.exports = __toCommonJS(index_exports);
406
417
 
@@ -5810,6 +5821,58 @@ var BillingService = class extends ServiceModule {
5810
5821
  }
5811
5822
  };
5812
5823
 
5824
+ // src/experiments.ts
5825
+ var EXPERIMENTS_PROPERTY = "experiments";
5826
+ var EXPERIMENT_EXPOSED_EVENT = "experiment_exposed";
5827
+ var MAX_EXPERIMENTS_PER_EVENT = 10;
5828
+ var KEY_PATTERN = /^[a-z0-9][a-z0-9_.-]{0,63}$/;
5829
+ var VARIANT_PATTERN = /^[a-z0-9][a-z0-9_.:-]{0,63}$/;
5830
+ function isExperimentKey(value) {
5831
+ return typeof value === "string" && KEY_PATTERN.test(value);
5832
+ }
5833
+ function isVariantKey(value) {
5834
+ return typeof value === "string" && VARIANT_PATTERN.test(value);
5835
+ }
5836
+ function experimentVariant(evaluation) {
5837
+ if (!evaluation) return null;
5838
+ if (isVariantKey(evaluation.variant_key)) return evaluation.variant_key;
5839
+ if (isVariantKey(evaluation.value)) return evaluation.value;
5840
+ return null;
5841
+ }
5842
+ function normalizeExperiments(input) {
5843
+ const result = {};
5844
+ if (!input || typeof input !== "object" || Array.isArray(input)) return result;
5845
+ let count = 0;
5846
+ for (const [key, value] of Object.entries(input)) {
5847
+ if (count >= MAX_EXPERIMENTS_PER_EVENT) break;
5848
+ if (isExperimentKey(key) && isVariantKey(value)) {
5849
+ result[key] = value;
5850
+ count++;
5851
+ }
5852
+ }
5853
+ return result;
5854
+ }
5855
+ function withExperiments(properties, experiments) {
5856
+ const normalized = normalizeExperiments({
5857
+ ...normalizeExperiments(properties?.[EXPERIMENTS_PROPERTY]),
5858
+ ...experiments ?? {}
5859
+ });
5860
+ if (Object.keys(normalized).length === 0) return properties;
5861
+ return { ...properties ?? {}, [EXPERIMENTS_PROPERTY]: normalized };
5862
+ }
5863
+ function exposureEvent(flagKey, variant) {
5864
+ if (!isExperimentKey(flagKey)) throw new Error(`Invalid experiment flag key: ${flagKey}`);
5865
+ if (!isVariantKey(variant)) throw new Error(`Invalid experiment variant: ${variant}`);
5866
+ return {
5867
+ event_name: EXPERIMENT_EXPOSED_EVENT,
5868
+ event_category: "system",
5869
+ properties: { flag_key: flagKey, variant, [EXPERIMENTS_PROPERTY]: { [flagKey]: variant } }
5870
+ };
5871
+ }
5872
+ function exposureStorageKey(flagKey) {
5873
+ return `sm_experiment_exposed:${flagKey}`;
5874
+ }
5875
+
5813
5876
  // src/services/analytics.ts
5814
5877
  var AnalyticsService = class extends ServiceModule {
5815
5878
  constructor() {
@@ -5826,6 +5889,14 @@ var AnalyticsService = class extends ServiceModule {
5826
5889
  }
5827
5890
  return this.post("/v2/events", payload, options);
5828
5891
  }
5892
+ /**
5893
+ * Track that a visitor saw an experiment variant. Send it once per visitor and flag; the event
5894
+ * carries `properties.experiments` so the experiment report attributes it.
5895
+ */
5896
+ async trackExposure(flagKey, variant, userId, options) {
5897
+ const event = exposureEvent(flagKey, variant);
5898
+ return this.track(event.event_name, event.properties, userId, options);
5899
+ }
5829
5900
  async trackBatch(events, options) {
5830
5901
  const mapped = events.map(({ event, ...rest }) => ({ event_name: event, ...rest }));
5831
5902
  return this.post("/v2/events/batch", { events: mapped }, options);
@@ -5900,6 +5971,19 @@ var FlagsService = class extends ServiceModule {
5900
5971
  async evaluate(flagKey, context = {}, environment = "prod", options) {
5901
5972
  return this.post("/evaluate", { flag_key: flagKey, environment, context }, options);
5902
5973
  }
5974
+ /**
5975
+ * Assign a visitor to an experiment: a flag with weighted variants, evaluated with a stable
5976
+ * identifier (`session_id` or `user_id`) so the assignment is sticky. Attach the result to
5977
+ * analytics events with `withExperiments` and track one exposure with `analytics.trackExposure`.
5978
+ */
5979
+ async experiment(flagKey, context = {}, environment = "prod", options) {
5980
+ const response = await this.evaluate(flagKey, context, environment, options);
5981
+ if (response.error || !response.data) return { data: null, error: response.error };
5982
+ return {
5983
+ data: { flag_key: flagKey, variant: experimentVariant(response.data), evaluation: response.data },
5984
+ error: null
5985
+ };
5986
+ }
5903
5987
  async evaluateBatch(flagKeys, context = {}, environment = "prod", options) {
5904
5988
  return this.post(
5905
5989
  "/evaluate/batch",
@@ -9230,7 +9314,6 @@ var AgentSessionsService = class extends ServiceModule {
9230
9314
  };
9231
9315
 
9232
9316
  // src/browser-capture.ts
9233
- init_upload_compression();
9234
9317
  async function prepareCommunityMapAttachment(file) {
9235
9318
  const types = [
9236
9319
  "image/jpeg",
@@ -9252,21 +9335,7 @@ async function prepareCommunityMapAttachment(file) {
9252
9335
  );
9253
9336
  if (!file.size || file.size > 25 * 1024 * 1024)
9254
9337
  throw new Error("Choose a file up to 25 MiB. Record a shorter clip if needed.");
9255
- if (!file.type.startsWith("image/")) return file;
9256
- const compressed = await maybeCompressImage(
9257
- file,
9258
- { maxWidth: 2400, maxHeight: 2400, maxSizeMB: 2, quality: 0.82 },
9259
- "community-capture",
9260
- null
9261
- );
9262
- const result = compressed ? new File(
9263
- [compressed],
9264
- file.name.replace(/\.[^.]+$/, "") + (compressed.type === "image/webp" ? ".webp" : ".jpg"),
9265
- { type: compressed.type, lastModified: file.lastModified }
9266
- ) : file;
9267
- if (result.size > 8 * 1024 * 1024)
9268
- throw new Error("This photo is too large. Choose a photo up to 8 MiB or use a smaller camera setting.");
9269
- return result;
9338
+ return file;
9270
9339
  }
9271
9340
  async function startMediaCapture(kind, signal) {
9272
9341
  const candidates = kind === "video" ? ["video/mp4;codecs=h264,aac", "video/mp4", "video/webm;codecs=vp8,opus", "video/webm"] : ["audio/mp4", "audio/webm;codecs=opus", "audio/ogg;codecs=opus", "audio/webm"];
@@ -9558,6 +9627,8 @@ var index_default = ScaleMule;
9558
9627
  CreatorMakerService,
9559
9628
  DataService,
9560
9629
  DecisionsService,
9630
+ EXPERIMENTS_PROPERTY,
9631
+ EXPERIMENT_EXPOSED_EVENT,
9561
9632
  ErrorCodes,
9562
9633
  EventsService,
9563
9634
  FlagContentService,
@@ -9571,6 +9642,7 @@ var index_default = ScaleMule;
9571
9642
  ListingsService,
9572
9643
  LocalIntelligenceService,
9573
9644
  LoggerService,
9645
+ MAX_EXPERIMENTS_PER_EVENT,
9574
9646
  MEDIA_PRESETS,
9575
9647
  MediaService,
9576
9648
  NotificationsService,
@@ -9611,6 +9683,9 @@ var index_default = ScaleMule;
9611
9683
  detectCountryFromE164,
9612
9684
  detectNetworkClass,
9613
9685
  ensureAnonymousId,
9686
+ experimentVariant,
9687
+ exposureEvent,
9688
+ exposureStorageKey,
9614
9689
  extractClientContext,
9615
9690
  findPhoneCountryByCode,
9616
9691
  findPhoneCountryByDialCode,
@@ -9619,8 +9694,11 @@ var index_default = ScaleMule;
9619
9694
  getMeasuredBandwidthMbps,
9620
9695
  getPartRange,
9621
9696
  hasMinRoleLevel,
9697
+ isExperimentKey,
9622
9698
  isValidE164Phone,
9699
+ isVariantKey,
9623
9700
  normalizeAndValidatePhone,
9701
+ normalizeExperiments,
9624
9702
  normalizePhoneNumber,
9625
9703
  pollSharePercent,
9626
9704
  pollVoterKey,
@@ -9630,5 +9708,6 @@ var index_default = ScaleMule;
9630
9708
  startMediaCapture,
9631
9709
  uploadMultipartToS3,
9632
9710
  uploadSingleToS3,
9633
- validateIP
9711
+ validateIP,
9712
+ withExperiments
9634
9713
  });
package/dist/index.mjs CHANGED
@@ -218,6 +218,7 @@ async function maybeCompressImage(file, userConfig, sessionId, telemetry) {
218
218
  maxWidthOrHeight: Math.max(config.maxWidth, config.maxHeight),
219
219
  initialQuality: config.quality,
220
220
  useWebWorker: true,
221
+ preserveExif: true,
221
222
  fileType: type === "image/png" ? "image/webp" : void 0
222
223
  });
223
224
  if (compressed.size >= file.size * 0.95) {
@@ -5684,6 +5685,58 @@ var BillingService = class extends ServiceModule {
5684
5685
  }
5685
5686
  };
5686
5687
 
5688
+ // src/experiments.ts
5689
+ var EXPERIMENTS_PROPERTY = "experiments";
5690
+ var EXPERIMENT_EXPOSED_EVENT = "experiment_exposed";
5691
+ var MAX_EXPERIMENTS_PER_EVENT = 10;
5692
+ var KEY_PATTERN = /^[a-z0-9][a-z0-9_.-]{0,63}$/;
5693
+ var VARIANT_PATTERN = /^[a-z0-9][a-z0-9_.:-]{0,63}$/;
5694
+ function isExperimentKey(value) {
5695
+ return typeof value === "string" && KEY_PATTERN.test(value);
5696
+ }
5697
+ function isVariantKey(value) {
5698
+ return typeof value === "string" && VARIANT_PATTERN.test(value);
5699
+ }
5700
+ function experimentVariant(evaluation) {
5701
+ if (!evaluation) return null;
5702
+ if (isVariantKey(evaluation.variant_key)) return evaluation.variant_key;
5703
+ if (isVariantKey(evaluation.value)) return evaluation.value;
5704
+ return null;
5705
+ }
5706
+ function normalizeExperiments(input) {
5707
+ const result = {};
5708
+ if (!input || typeof input !== "object" || Array.isArray(input)) return result;
5709
+ let count = 0;
5710
+ for (const [key, value] of Object.entries(input)) {
5711
+ if (count >= MAX_EXPERIMENTS_PER_EVENT) break;
5712
+ if (isExperimentKey(key) && isVariantKey(value)) {
5713
+ result[key] = value;
5714
+ count++;
5715
+ }
5716
+ }
5717
+ return result;
5718
+ }
5719
+ function withExperiments(properties, experiments) {
5720
+ const normalized = normalizeExperiments({
5721
+ ...normalizeExperiments(properties?.[EXPERIMENTS_PROPERTY]),
5722
+ ...experiments ?? {}
5723
+ });
5724
+ if (Object.keys(normalized).length === 0) return properties;
5725
+ return { ...properties ?? {}, [EXPERIMENTS_PROPERTY]: normalized };
5726
+ }
5727
+ function exposureEvent(flagKey, variant) {
5728
+ if (!isExperimentKey(flagKey)) throw new Error(`Invalid experiment flag key: ${flagKey}`);
5729
+ if (!isVariantKey(variant)) throw new Error(`Invalid experiment variant: ${variant}`);
5730
+ return {
5731
+ event_name: EXPERIMENT_EXPOSED_EVENT,
5732
+ event_category: "system",
5733
+ properties: { flag_key: flagKey, variant, [EXPERIMENTS_PROPERTY]: { [flagKey]: variant } }
5734
+ };
5735
+ }
5736
+ function exposureStorageKey(flagKey) {
5737
+ return `sm_experiment_exposed:${flagKey}`;
5738
+ }
5739
+
5687
5740
  // src/services/analytics.ts
5688
5741
  var AnalyticsService = class extends ServiceModule {
5689
5742
  constructor() {
@@ -5700,6 +5753,14 @@ var AnalyticsService = class extends ServiceModule {
5700
5753
  }
5701
5754
  return this.post("/v2/events", payload, options);
5702
5755
  }
5756
+ /**
5757
+ * Track that a visitor saw an experiment variant. Send it once per visitor and flag; the event
5758
+ * carries `properties.experiments` so the experiment report attributes it.
5759
+ */
5760
+ async trackExposure(flagKey, variant, userId, options) {
5761
+ const event = exposureEvent(flagKey, variant);
5762
+ return this.track(event.event_name, event.properties, userId, options);
5763
+ }
5703
5764
  async trackBatch(events, options) {
5704
5765
  const mapped = events.map(({ event, ...rest }) => ({ event_name: event, ...rest }));
5705
5766
  return this.post("/v2/events/batch", { events: mapped }, options);
@@ -5774,6 +5835,19 @@ var FlagsService = class extends ServiceModule {
5774
5835
  async evaluate(flagKey, context = {}, environment = "prod", options) {
5775
5836
  return this.post("/evaluate", { flag_key: flagKey, environment, context }, options);
5776
5837
  }
5838
+ /**
5839
+ * Assign a visitor to an experiment: a flag with weighted variants, evaluated with a stable
5840
+ * identifier (`session_id` or `user_id`) so the assignment is sticky. Attach the result to
5841
+ * analytics events with `withExperiments` and track one exposure with `analytics.trackExposure`.
5842
+ */
5843
+ async experiment(flagKey, context = {}, environment = "prod", options) {
5844
+ const response = await this.evaluate(flagKey, context, environment, options);
5845
+ if (response.error || !response.data) return { data: null, error: response.error };
5846
+ return {
5847
+ data: { flag_key: flagKey, variant: experimentVariant(response.data), evaluation: response.data },
5848
+ error: null
5849
+ };
5850
+ }
5777
5851
  async evaluateBatch(flagKeys, context = {}, environment = "prod", options) {
5778
5852
  return this.post(
5779
5853
  "/evaluate/batch",
@@ -9104,7 +9178,6 @@ var AgentSessionsService = class extends ServiceModule {
9104
9178
  };
9105
9179
 
9106
9180
  // src/browser-capture.ts
9107
- init_upload_compression();
9108
9181
  async function prepareCommunityMapAttachment(file) {
9109
9182
  const types = [
9110
9183
  "image/jpeg",
@@ -9126,21 +9199,7 @@ async function prepareCommunityMapAttachment(file) {
9126
9199
  );
9127
9200
  if (!file.size || file.size > 25 * 1024 * 1024)
9128
9201
  throw new Error("Choose a file up to 25 MiB. Record a shorter clip if needed.");
9129
- if (!file.type.startsWith("image/")) return file;
9130
- const compressed = await maybeCompressImage(
9131
- file,
9132
- { maxWidth: 2400, maxHeight: 2400, maxSizeMB: 2, quality: 0.82 },
9133
- "community-capture",
9134
- null
9135
- );
9136
- const result = compressed ? new File(
9137
- [compressed],
9138
- file.name.replace(/\.[^.]+$/, "") + (compressed.type === "image/webp" ? ".webp" : ".jpg"),
9139
- { type: compressed.type, lastModified: file.lastModified }
9140
- ) : file;
9141
- if (result.size > 8 * 1024 * 1024)
9142
- throw new Error("This photo is too large. Choose a photo up to 8 MiB or use a smaller camera setting.");
9143
- return result;
9202
+ return file;
9144
9203
  }
9145
9204
  async function startMediaCapture(kind, signal) {
9146
9205
  const candidates = kind === "video" ? ["video/mp4;codecs=h264,aac", "video/mp4", "video/webm;codecs=vp8,opus", "video/webm"] : ["audio/mp4", "audio/webm;codecs=opus", "audio/ogg;codecs=opus", "audio/webm"];
@@ -9431,6 +9490,8 @@ export {
9431
9490
  CreatorMakerService,
9432
9491
  DataService,
9433
9492
  DecisionsService,
9493
+ EXPERIMENTS_PROPERTY,
9494
+ EXPERIMENT_EXPOSED_EVENT,
9434
9495
  ErrorCodes,
9435
9496
  EventsService,
9436
9497
  FlagContentService,
@@ -9444,6 +9505,7 @@ export {
9444
9505
  ListingsService,
9445
9506
  LocalIntelligenceService,
9446
9507
  LoggerService,
9508
+ MAX_EXPERIMENTS_PER_EVENT,
9447
9509
  MEDIA_PRESETS,
9448
9510
  MediaService,
9449
9511
  NotificationsService,
@@ -9485,6 +9547,9 @@ export {
9485
9547
  detectCountryFromE164,
9486
9548
  detectNetworkClass,
9487
9549
  ensureAnonymousId,
9550
+ experimentVariant,
9551
+ exposureEvent,
9552
+ exposureStorageKey,
9488
9553
  extractClientContext,
9489
9554
  findPhoneCountryByCode,
9490
9555
  findPhoneCountryByDialCode,
@@ -9493,8 +9558,11 @@ export {
9493
9558
  getMeasuredBandwidthMbps,
9494
9559
  getPartRange,
9495
9560
  hasMinRoleLevel,
9561
+ isExperimentKey,
9496
9562
  isValidE164Phone,
9563
+ isVariantKey,
9497
9564
  normalizeAndValidatePhone,
9565
+ normalizeExperiments,
9498
9566
  normalizePhoneNumber,
9499
9567
  pollSharePercent,
9500
9568
  pollVoterKey,
@@ -9504,5 +9572,6 @@ export {
9504
9572
  startMediaCapture,
9505
9573
  uploadMultipartToS3,
9506
9574
  uploadSingleToS3,
9507
- validateIP
9575
+ validateIP,
9576
+ withExperiments
9508
9577
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scalemule/sdk",
3
- "version": "0.0.76",
3
+ "version": "0.0.78",
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",