@sentientui/core 0.16.1 → 0.16.2

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.
Files changed (43) hide show
  1. package/LICENSE +21 -0
  2. package/dist/{chunk-KZHVBFG7.mjs → chunk-CD2A55US.mjs} +1 -0
  3. package/dist/chunk-CD2A55US.mjs.map +1 -0
  4. package/dist/chunk-I2QGVQI6.mjs +2 -0
  5. package/dist/chunk-I2QGVQI6.mjs.map +1 -0
  6. package/dist/{chunk-P5ZTJLZE.mjs → chunk-L5TA3FAB.mjs} +2 -1
  7. package/dist/chunk-L5TA3FAB.mjs.map +1 -0
  8. package/dist/{chunk-HGGX55FR.mjs → chunk-TMCGHANO.mjs} +1 -0
  9. package/dist/chunk-TMCGHANO.mjs.map +1 -0
  10. package/dist/index-C247KMBw.d.ts +394 -0
  11. package/dist/index-CZLjrtM4.d.cts +394 -0
  12. package/dist/index-engagement.js +2 -1
  13. package/dist/index-engagement.js.map +1 -0
  14. package/dist/index-engagement.mjs +2 -1
  15. package/dist/index-engagement.mjs.map +1 -0
  16. package/dist/index-graph.d.cts +38 -3
  17. package/dist/index-graph.d.ts +38 -3
  18. package/dist/index-graph.js +2 -1
  19. package/dist/index-graph.js.map +1 -0
  20. package/dist/index-graph.mjs +2 -1
  21. package/dist/index-graph.mjs.map +1 -0
  22. package/dist/index-local-stub.js +1 -0
  23. package/dist/index-local-stub.js.map +1 -0
  24. package/dist/index-local-stub.mjs +2 -1
  25. package/dist/index-local-stub.mjs.map +1 -0
  26. package/dist/index-local.d.cts +1 -1
  27. package/dist/index-local.d.ts +1 -1
  28. package/dist/index-local.js +1 -0
  29. package/dist/index-local.js.map +1 -0
  30. package/dist/index-local.mjs +2 -1
  31. package/dist/index-local.mjs.map +1 -0
  32. package/dist/index-server.js +1 -0
  33. package/dist/index-server.js.map +1 -0
  34. package/dist/index-server.mjs +2 -1
  35. package/dist/index-server.mjs.map +1 -0
  36. package/dist/index.d.cts +2 -430
  37. package/dist/index.d.ts +2 -430
  38. package/dist/index.js +2 -1
  39. package/dist/index.js.map +1 -0
  40. package/dist/index.mjs +2 -1
  41. package/dist/index.mjs.map +1 -0
  42. package/package.json +21 -2
  43. package/dist/chunk-CWUFS37B.mjs +0 -1
@@ -0,0 +1,394 @@
1
+ import { a as SlotDeclInput } from './session-meta-DU_3mY7U.js';
2
+ import { SlotResult } from '@sentientui/policy';
3
+
4
+ /** Manages anonymous session identity with cookie + localStorage layers. */
5
+ type SessionConfig = {
6
+ cookieName?: string;
7
+ cookieTTLDays?: number;
8
+ /**
9
+ * Session ID generated during SSR (e.g. from `loadAdaptiveAssignments`).
10
+ * Used as the fallback when no existing cookie or localStorage entry is found,
11
+ * so the client adopts the same session the server used for variant assignment
12
+ * on first visit rather than generating a new, orphaned ID.
13
+ */
14
+ ssrSessionId?: string;
15
+ };
16
+ type SessionManager = {
17
+ getSessionId(): string | null;
18
+ /** True when neither cookie nor localStorage could be written — id is in-memory only. */
19
+ isEphemeral(): boolean;
20
+ destroy(): void;
21
+ };
22
+
23
+ /** Batched event queue with reliable transport (fetch + keepalive, localStorage retry). */
24
+ type EventType = 'variant_assigned' | 'goal_achieved' | 'scroll_depth' | 'dwell' | 'cursor_signal' | 'component_visible' | 'component_exited' | 'micro_signal';
25
+ type SentientEvent = {
26
+ id: string;
27
+ sessionId: string;
28
+ projectId: string;
29
+ componentId: string;
30
+ variantId?: string;
31
+ eventType: EventType;
32
+ goalType?: string;
33
+ payload: Record<string, unknown>;
34
+ timestamp: number;
35
+ timeInSession: number;
36
+ };
37
+ type QueueConfig = {
38
+ ingestUrl: string;
39
+ apiKey: string;
40
+ flushIntervalMs?: number;
41
+ maxBatchSize?: number;
42
+ maxRetrySize?: number;
43
+ };
44
+ type EventQueue = {
45
+ push(event: SentientEvent): void;
46
+ flush(): void;
47
+ destroy(): void;
48
+ };
49
+
50
+ /** Synchronous variant assignment cache (memory + localStorage). */
51
+ type Assignment = {
52
+ variantId: string;
53
+ assignedAt: number;
54
+ segment: string;
55
+ confidence: number;
56
+ content?: string;
57
+ };
58
+ type AssignmentCache = {
59
+ get(componentId: string, segment: string): Assignment | null;
60
+ set(componentId: string, segment: string, assignment: Assignment): void;
61
+ invalidate(componentId: string): void;
62
+ clear(): void;
63
+ };
64
+
65
+ /** In-memory context graph with persistence and backend sync. */
66
+ type PageNode = {
67
+ id: string;
68
+ componentId: string;
69
+ semanticType: string;
70
+ answers: string[];
71
+ prominenceScore: number;
72
+ depth: number;
73
+ };
74
+ type GraphSnapshot = {
75
+ pageNodes: PageNode[];
76
+ capturedAt: number;
77
+ };
78
+ type GraphConfig = {
79
+ syncUrl?: string;
80
+ apiKey?: string;
81
+ projectId?: string;
82
+ sessionId?: string;
83
+ };
84
+ type StructuralEdge = {
85
+ fromComponentId: string;
86
+ toComponentId: string;
87
+ weight: number;
88
+ };
89
+ type GraphClient = {
90
+ addPageNode(node: PageNode): void;
91
+ /** Record a DOM-derived parent/child or sibling relationship between two components. */
92
+ addStructuralEdge(edge: StructuralEdge): void;
93
+ /** One-shot batch sync of all current page nodes to the backend. */
94
+ syncOnce(): void;
95
+ snapshot(): GraphSnapshot;
96
+ serialize(): string;
97
+ restore(data: string): void;
98
+ destroy(): void;
99
+ };
100
+
101
+ /**
102
+ * Decision snapshot: the SPA / return-visit pre-paint source. Written after
103
+ * every successful decide; read by the inline pre-paint script (before any
104
+ * framework code runs) and by init() to seed slot/persona state.
105
+ */
106
+
107
+ declare const SNAPSHOT_STORAGE_KEY_PREFIX = "_snt_snap:";
108
+ /** Versioned compound locator: resolve id → dataAttr → selector, then verify
109
+ * against fingerprint. Lets a slot survive DOM/markup drift. */
110
+ type CompoundLocator = {
111
+ v?: number;
112
+ id?: string;
113
+ dataAttr?: {
114
+ name: string;
115
+ value: string;
116
+ };
117
+ selector?: string;
118
+ urlMatch?: string;
119
+ fingerprint?: {
120
+ tag?: string;
121
+ text?: string;
122
+ };
123
+ semanticId?: string;
124
+ };
125
+ /** Bounded, declarative operations a registry arm may apply to its element.
126
+ * The style set is a fixed whitelist (validated server-side); no arbitrary CSS,
127
+ * HTML, or JS ever. `text` is applied via textContent; https-only URLs.
128
+ * moveBefore/moveAfter (exactly one) reposition the element relative to a
129
+ * uniquely-resolving sibling anchor — post-decide only, never pre-paint. */
130
+ type SlotOps = {
131
+ text?: string;
132
+ style?: Record<string, string>;
133
+ hidden?: boolean;
134
+ href?: string;
135
+ imageSrc?: string;
136
+ imageAlt?: string;
137
+ moveBefore?: CompoundLocator;
138
+ moveAfter?: CompoundLocator;
139
+ };
140
+ /** Registry-mode apply info per slot: where to apply and what to set. Stored so
141
+ * a returning visitor's pre-paint can reapply it. `target` is the Phase-2 bare
142
+ * selector; `locator` (Phase 3) is the compound locator, preferred when present. */
143
+ type SlotConfigEntry = {
144
+ kind: 'tokens' | 'arms';
145
+ target?: string;
146
+ locator?: CompoundLocator;
147
+ content?: string;
148
+ ops?: SlotOps;
149
+ };
150
+ type DecisionSnapshot = {
151
+ v: 1;
152
+ persona: string;
153
+ band: 'low' | 'medium' | 'high';
154
+ slots: Record<string, SlotResult>;
155
+ layoutOrder: string[] | null;
156
+ savedAt: number;
157
+ slotConfig?: Record<string, SlotConfigEntry>;
158
+ };
159
+ /** Returns null on missing, corrupt, or wrong-version data — never throws. */
160
+ declare function readSnapshot(apiKey: string): DecisionSnapshot | null;
161
+ /** Best-effort persist — storage failures are swallowed. */
162
+ declare function writeSnapshot(apiKey: string, snap: DecisionSnapshot): void;
163
+ /**
164
+ * Inline pre-paint script (Rung 1a): reads the snapshot and sets
165
+ * `data-sentient-persona` / `data-sentient-confidence` on <html> before
166
+ * first paint. Single-writer: it never overwrites attributes already set.
167
+ *
168
+ * Safety properties (pinned by tests):
169
+ * - apiKey goes through JSON.stringify, then '<' is escaped to <, so a
170
+ * hostile key can neither break the JS string nor terminate the <script>.
171
+ * - Built by string concatenation and contains no backticks, so the output
172
+ * survives being embedded in template-literal-based renderers.
173
+ */
174
+ declare function renderPrePaintScript(apiKey: string): string;
175
+
176
+ declare const PROD_KEYLESS_ERROR = "[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.";
177
+ declare const LOCAL_MODE_BANNER = "[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.";
178
+
179
+ type MicroSignalEmitter = (signalType: 'rage_click' | 'text_copy' | 'scroll_hesitation' | 'tab_loss', extra?: Record<string, unknown>) => void;
180
+ type MicroSignalType = Parameters<MicroSignalEmitter>[0];
181
+ /**
182
+ * Attaches passive behavioral detectors to `node`. Calls `emit` when a signal
183
+ * fires. Each signal type fires at most once per call to this function.
184
+ * Returns a cleanup function that removes all listeners.
185
+ */
186
+ declare function attachMicroSignalDetectors(emit: MicroSignalEmitter, node: Element, variantAssignedAt?: number): () => void;
187
+
188
+ type SentientConfig = {
189
+ apiKey: string;
190
+ context: 'landing' | 'ecommerce' | 'saas' | 'marketplace';
191
+ /** @internal — not exposed to users; defaults to the hosted SentientUI API. */
192
+ ingestUrl?: string;
193
+ debug?: boolean;
194
+ /**
195
+ * Pre-seeded assignments from `preloadAssignments()` (SSR).
196
+ * Seeds the local cache so `assign()` returns without a network call for
197
+ * listed code variants, guaranteeing server and client render the same
198
+ * variant on first paint. Managed-text components (assign with no
199
+ * variantIds) still fetch once when the seed carries no content.
200
+ */
201
+ initialAssignments?: Record<string, string>;
202
+ /**
203
+ * Segment used for SSR preload (`device:source`). When set with `initialAssignments`,
204
+ * seeds the assignment cache under this key so hydration matches the server bandit row.
205
+ */
206
+ sessionSegment?: string;
207
+ /**
208
+ * Consent gate. When `false`, returns a no-op client and performs no tracking.
209
+ * Defaults to `true`. Re-call `init()` (via `AdaptiveProvider` consent prop) when
210
+ * the user grants or revokes consent mid-session.
211
+ */
212
+ consent?: boolean;
213
+ /**
214
+ * Behavior before consent is granted. `'statistical_winner'` fetches the
215
+ * best-performing variant via `GET /v1/winner` — no session or tracking data
216
+ * is stored. `'control'` (default) shows `variantIds[0]` with no API call.
217
+ * Applies when tracking is gated off — either `consent: false` or an active
218
+ * Do Not Track signal.
219
+ */
220
+ preConsentBehavior?: 'statistical_winner' | 'control';
221
+ /**
222
+ * Whether to honor the browser's Do Not Track (DNT) signal. Defaults to `true`.
223
+ * When `true` and the visitor has DNT enabled, the SDK sets no cookies and
224
+ * sends no tracking data — behaving exactly as `consent: false` (still serving
225
+ * the read-only `preConsentBehavior` winner if configured), and `grantConsent()`
226
+ * will not upgrade it. Set `false` to make your own consent gate authoritative.
227
+ */
228
+ respectDoNotTrack?: boolean;
229
+ userId?: string;
230
+ /**
231
+ * Session ID generated server-side (from `loadAdaptiveAssignments` / `loadAdaptiveDecision`).
232
+ * When provided, the client adopts this ID on first visit instead of generating a new one,
233
+ * ensuring events and goals are attributed to the same session the server used for assignment.
234
+ */
235
+ ssrSessionId?: string;
236
+ /**
237
+ * ISO 3166-1 alpha-2 country code for the visitor. When provided (e.g. from
238
+ * the `CF-IPCountry` header in a Next.js server component), it is included in
239
+ * the session upsert so country-based segmentation works without client-side
240
+ * geo lookup.
241
+ */
242
+ country?: string;
243
+ /**
244
+ * Pre-seeded slot results from `preloadDecisions()` / `loadAdaptiveDecision()`
245
+ * (SSR). Seeds the local slot state so `getSlotResult()` agrees with the
246
+ * server-rendered markup on first paint.
247
+ */
248
+ initialSlots?: Record<string, SlotResult>;
249
+ /**
250
+ * Persona decided during SSR. Takes priority over the html-attribute
251
+ * adoption and the local snapshot.
252
+ */
253
+ initialPersona?: {
254
+ persona: string;
255
+ confidence: number;
256
+ };
257
+ /**
258
+ * Keyless local mode. 'auto' (default) simulates decisions on-device when no
259
+ * valid API key is configured — but only in development builds (the
260
+ * `development` export condition); production bundles physically exclude the
261
+ * engine. `true` forces the local engine regardless of key (escape hatch);
262
+ * `false` restores the silent keyless no-op.
263
+ */
264
+ localMode?: 'auto' | boolean;
265
+ };
266
+ type AssignResult = {
267
+ variantId: string;
268
+ assignmentTtlMs: number;
269
+ content?: string;
270
+ };
271
+
272
+ /** An editor-defined goal delivered with a registry-mode decision, for the
273
+ * snippet to install delegated listeners from. */
274
+ type GoalDefinition = {
275
+ goalId: string;
276
+ event: 'click' | 'form_submit' | 'url_reached';
277
+ locator?: CompoundLocator;
278
+ urlPattern?: string;
279
+ slotId?: string;
280
+ };
281
+ type DecideOutcome = {
282
+ layoutOrder: string[] | null;
283
+ assignments: Record<string, string>;
284
+ slots: Record<string, SlotResult>;
285
+ persona: string;
286
+ confidence: number;
287
+ slotConfig?: Record<string, SlotConfigEntry>;
288
+ goals?: GoalDefinition[];
289
+ };
290
+ type DecideInput = {
291
+ sections?: string[];
292
+ components?: Array<{
293
+ id: string;
294
+ variantIds?: string[];
295
+ }>;
296
+ slots?: SlotDeclInput[];
297
+ slotsFrom?: 'request' | 'registry';
298
+ /**
299
+ * Caller's build version (e.g. the snippet's `__SNIPPET_VERSION__`), sent
300
+ * as `v` on the wire. Additive/best-effort: the server persists it for
301
+ * version-skew reporting (see apps/api decide route) and ignores it
302
+ * entirely on older deployments. Omit if the caller has no version to report.
303
+ */
304
+ v?: string;
305
+ };
306
+ type WeightEntry = {
307
+ variantId: string;
308
+ pulls: number;
309
+ avgReward: number | null;
310
+ };
311
+ type ComponentWeightEntry = {
312
+ componentId: string;
313
+ updatedAt: number;
314
+ variants: WeightEntry[];
315
+ };
316
+ type ComponentGoalOptions = {
317
+ /** Reward credited to the served variant (0–1). Defaults to 1. */
318
+ reward?: number;
319
+ /** Extra fields merged into the event payload. */
320
+ metadata?: Record<string, unknown>;
321
+ };
322
+ type SentientClient = {
323
+ track(event: Omit<SentientEvent, 'id' | 'sessionId' | 'timestamp' | 'timeInSession'>): void;
324
+ goal(name: string, metadata?: Record<string, unknown>, weight?: number, stepIndex?: number): void;
325
+ /**
326
+ * Records a conversion attributed to the variant currently served for
327
+ * `componentId`, so it feeds the per-variant CVR funnel. Resolves the served
328
+ * variant from the local assignment cache — no need to pass variantId or
329
+ * projectId. No-ops if the component has not been assigned yet (render its
330
+ * `<Adaptive>`/call `assign()` first). Prefer this over bare `goal()` for
331
+ * variant experiments; `goal()` is session-level only (no component attribution).
332
+ */
333
+ componentGoal(componentId: string, goalType: string, opts?: ComponentGoalOptions): void;
334
+ identify(userId: string): void;
335
+ getAssignment(componentId: string, segment: string): Assignment | null;
336
+ /** Server-side variant assignment. Caches the result locally per (component, segment). */
337
+ assign(componentId: string, variantIds?: string[], agentData?: unknown, agentDataByVariant?: Record<string, unknown>): Promise<AssignResult | null>;
338
+ /**
339
+ * Single-roundtrip decision for layout sections, component variants, and
340
+ * adaptive slots. Awaits the session upsert (like `assign`) so the server
341
+ * never decides for a session row that doesn't exist yet. A response
342
+ * without a `slots` field means the server predates slots — every declared
343
+ * slot resolves to its baseline and no retry is made.
344
+ */
345
+ decide(input: DecideInput): Promise<DecideOutcome | null>;
346
+ /** Slot result served this session (decide result, SSR seed, snapshot, or failure baseline). Null when unknown. */
347
+ getSlotResult(slotId: string): SlotResult | null;
348
+ /** Current persona estimate. Band is always `confidenceBand(confidence)`. Null when nothing is known yet. */
349
+ getPersona(): {
350
+ persona: string;
351
+ confidence: number;
352
+ band: 'low' | 'medium' | 'high';
353
+ } | null;
354
+ /** Fetches current bandit weights for all components in this project. Used by the provider to keep live-weight polling fresh. */
355
+ fetchWeights(): Promise<ComponentWeightEntry[]>;
356
+ getGraph(): GraphSnapshot;
357
+ /**
358
+ * Routine teardown: stops timers/listeners and flushes pending events, but
359
+ * KEEPS the visitor identity, decision snapshot, and retry bucket. Use for
360
+ * component unmount / re-init (framework providers call this on cleanup).
361
+ */
362
+ dispose(): void;
363
+ /**
364
+ * Consent-revocation / forget-me teardown: everything `dispose()` does,
365
+ * plus deletion of the visitor identity (`_snt_uid`), the decision
366
+ * snapshot, and the persisted retry bucket. The next visit starts as a
367
+ * brand-new visitor.
368
+ */
369
+ destroy(): void;
370
+ /** True when this client is the keyless local-mode client (dev only). */
371
+ readonly isLocal?: boolean;
372
+ };
373
+
374
+ /**
375
+ * Detects whether the visitor has signalled a tracking opt-out. Honors Global
376
+ * Privacy Control (`navigator.globalPrivacyControl`) — the legally-enforceable
377
+ * CCPA/CPRA signal — as well as Do Not Track (`navigator.doNotTrack`, the legacy
378
+ * `window.doNotTrack` on older Firefox, and `navigator.msDoNotTrack` on old
379
+ * IE/Edge). GPC is a boolean; DNT is opt-out only when explicitly `'1'`/`'yes'`.
380
+ */
381
+ declare function isDoNotTrackEnabled(): boolean;
382
+ /**
383
+ * Upgrades a pre-consent client (created with `consent: false, preConsentBehavior: 'statistical_winner'`)
384
+ * to a fully-tracking client. Call this from your consent management platform callback.
385
+ * For React apps, prefer updating the `consent` prop on `<AdaptiveProvider>`.
386
+ * Pass `apiKey` to target a specific project; omit to upgrade the most-recently-initialized client.
387
+ */
388
+ declare function grantConsent(apiKey?: string): void;
389
+ /**
390
+ * Initializes the Sentient client. Returns a no-op client during SSR.
391
+ */
392
+ declare function init(config: SentientConfig): SentientClient;
393
+
394
+ export { type AssignResult as A, type ComponentGoalOptions as C, type DecideInput as D, type EventQueue as E, type GoalDefinition as G, LOCAL_MODE_BANNER as L, type MicroSignalEmitter as M, PROD_KEYLESS_ERROR as P, type QueueConfig as Q, SNAPSHOT_STORAGE_KEY_PREFIX as S, type WeightEntry as W, type Assignment as a, type AssignmentCache as b, type ComponentWeightEntry as c, type CompoundLocator as d, type DecideOutcome as e, type DecisionSnapshot as f, type EventType as g, type GraphClient as h, type GraphConfig as i, type GraphSnapshot as j, type MicroSignalType as k, type PageNode as l, type SentientClient as m, type SentientConfig as n, type SentientEvent as o, type SessionConfig as p, type SessionManager as q, type SlotConfigEntry as r, type SlotOps as s, attachMicroSignalDetectors as t, grantConsent as u, init as v, isDoNotTrackEnabled as w, readSnapshot as x, renderPrePaintScript as y, writeSnapshot as z };