@cookieyes/core 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,778 @@
1
+ /**
2
+ * The integration format — the shared contract between the consent engine and
3
+ * every vendor preset (Google, Segment, Meta, …). It carries no vendor
4
+ * knowledge; a preset in `@cookieyes/scripts` fills it in.
5
+ *
6
+ * Two plain axes describe every vendor:
7
+ * - `load`: when the vendor starts — right away, or only after consent.
8
+ * - `onRevoke`: what happens when consent is withdrawn — one of three modes.
9
+ *
10
+ * `onRevoke` is declarative (readable without running `setup`, so a debug view
11
+ * or a version check can inspect it), and it's a discriminated union so the
12
+ * compiler forces the matching handler — you can't declare `"silence"` with no
13
+ * way to actually silence.
14
+ */
15
+ type Cleanup = () => void;
16
+ type SilenceControl = {
17
+ silence: () => void;
18
+ resume: () => void;
19
+ };
20
+ /** What a vendor's `setup` receives from the engine. */
21
+ type SetupCtx = {
22
+ /** Is this integration's category currently committed-granted? */
23
+ granted: () => boolean;
24
+ /**
25
+ * Subscribe to committed-consent changes; returns an unsubscribe function.
26
+ * `keep` vendors (e.g. Google Consent Mode) use this to emit their own
27
+ * updates on every change. The engine also releases these automatically when
28
+ * the integration is torn down, so a vendor listener never outlives it.
29
+ */
30
+ onConsentChange: (fn: () => void) => () => void;
31
+ /** Resolved region/regulation — for a vendor's US-state privacy switch. */
32
+ region: RegionDecision;
33
+ };
34
+ type Base = {
35
+ id: string;
36
+ /**
37
+ * The consent category (or categories) that gate this integration. Pass an
38
+ * array to require more than one — combined with {@link Base.match}.
39
+ */
40
+ category: ConsentCategory | ConsentCategory[];
41
+ /**
42
+ * How to combine multiple categories: `"all"` (default) needs every one
43
+ * granted; `"any"` needs at least one. Ignored for a single category.
44
+ */
45
+ match?: "all" | "any";
46
+ /** Format version; an unknown version is refused (see {@link runIntegrations}). */
47
+ version: number;
48
+ /**
49
+ * When to start. Note: `setup` always runs on a microtask, so `immediately`
50
+ * is *very early* but not synchronous / same-tick. The truly-first-thing case
51
+ * (Consent Mode's deny-default before any tag fires) is the server `<head>`
52
+ * snippet's job, not the engine's.
53
+ */
54
+ load: "immediately" | "afterConsent";
55
+ };
56
+ type Integration = Base & ({
57
+ onRevoke: "keep";
58
+ setup: (ctx: SetupCtx) => void | Promise<void>;
59
+ } | {
60
+ onRevoke: "remove";
61
+ setup: (ctx: SetupCtx) => Cleanup | Promise<Cleanup>;
62
+ } | {
63
+ onRevoke: "silence";
64
+ setup: (ctx: SetupCtx) => SilenceControl | Promise<SilenceControl>;
65
+ });
66
+ /** The format version this engine understands. Bump on a breaking format change. */
67
+ declare const INTEGRATION_FORMAT_VERSION = 1;
68
+ /**
69
+ * Warn when a vendor is configured on both sides — a new `integrations` preset
70
+ * whose id matches a deprecated `builtInIntegrations` vendor. Both would run,
71
+ * which for a tracker means double-counted events (the DEVP-38 double-pixel).
72
+ * Preset ids are the vendor's canonical name (`"segment"`, `"meta"`, …), which
73
+ * is exactly the built-in vendor name, so the match is a plain id === vendor.
74
+ */
75
+ declare function warnOverlappingVendors(integrationIds: string[], builtInVendors: string[]): void;
76
+ /**
77
+ * Warn when an `afterConsent` integration is gated on a category that isn't in
78
+ * the configured taxonomy — otherwise it waits for consent that can never be
79
+ * granted and silently never loads. A common trap with a custom `categories`
80
+ * list plus a preset left on its default category (e.g. `segment()` → "analytics").
81
+ * `immediately` integrations aren't gated by category, so they're not checked.
82
+ */
83
+ declare function warnUnknownCategories(integrations: Integration[], knownCategoryIds: string[]): void;
84
+ /** Live status of one integration — read by the debug/self-check view. */
85
+ type IntegrationStatus = "idle" | "loading" | "active" | "silenced" | "removed" | "error";
86
+ /** What the engine needs from the consent runtime — framework-agnostic. */
87
+ type IntegrationHost = {
88
+ /** Committed-granted state for a category (never the unsaved toggle). */
89
+ granted: (category: ConsentCategory) => boolean;
90
+ /** Subscribe to committed-consent changes; returns unsubscribe. */
91
+ subscribe: (fn: () => void) => () => void;
92
+ region: RegionDecision;
93
+ };
94
+ /** One row for a debug view: an integration's config plus its live status. */
95
+ type IntegrationDebugInfo = {
96
+ id: string;
97
+ category: ConsentCategory | ConsentCategory[];
98
+ load: "immediately" | "afterConsent";
99
+ onRevoke: "keep" | "remove" | "silence";
100
+ status: IntegrationStatus;
101
+ };
102
+ type IntegrationRunner = {
103
+ /** Current status per integration id — the debug/self-check view reads this. */
104
+ status: () => Record<string, IntegrationStatus>;
105
+ /**
106
+ * Config + live status for every registered integration, in order — the data
107
+ * for a debug view (e.g. `console.table(runner.list())`).
108
+ */
109
+ list: () => IntegrationDebugInfo[];
110
+ /**
111
+ * Tear the runner down: stop reconciling, release every vendor's
112
+ * consent-change listener, and undo each loaded vendor — `remove` runs its
113
+ * cleanup, `silence` is silenced. `keep` vendors' scripts stay (that's the
114
+ * mode), but their listeners are still released. Safe to call more than once.
115
+ */
116
+ stop: () => void;
117
+ };
118
+ /**
119
+ * Run a set of integrations against the consent runtime. Reconciles each one on
120
+ * load and on every committed-consent change:
121
+ * - not loaded → load it (immediately, or once its category is granted)
122
+ * - `keep` → nothing on revoke (the vendor manages its own update)
123
+ * - `remove` → run cleanup on revoke; re-load on re-grant
124
+ * - `silence` → call `silence()` on revoke; `resume()` on re-grant
125
+ *
126
+ * `setup` may be async and may fail; a failure marks the integration `error`
127
+ * and is retried on the next trigger (never loops on its own). Nothing here
128
+ * throws into the host.
129
+ */
130
+ declare function runIntegrations(integrations: Integration[], host: IntegrationHost): IntegrationRunner;
131
+
132
+ type NetworkBlockerRule = {
133
+ id: string;
134
+ domain: string;
135
+ pathIncludes?: string | undefined;
136
+ methods?: string[] | undefined;
137
+ category: ConsentCategory;
138
+ };
139
+ type BlockedRequestInfo = {
140
+ rule: NetworkBlockerRule;
141
+ url: string;
142
+ method: string;
143
+ };
144
+ type NetworkBlockerConfig = {
145
+ rules: NetworkBlockerRule[];
146
+ onRequestBlocked?: ((info: BlockedRequestInfo) => void) | undefined;
147
+ logBlockedRequests?: boolean | undefined;
148
+ };
149
+ type ConsentChecker = (category: ConsentCategory) => boolean;
150
+ declare function installNetworkBlocker(config: NetworkBlockerConfig, hasConsent: ConsentChecker): () => void;
151
+ declare function uninstallNetworkBlocker(): void;
152
+ /**
153
+ * Register the network blocker so that a configured `networkBlocker` actually
154
+ * installs. Call it once, before your setup call:
155
+ *
156
+ * ```ts
157
+ * import { initCookieYes } from "@cookieyes/core";
158
+ * import { registerNetworkBlocker } from "@cookieyes/core/network-blocker";
159
+ *
160
+ * registerNetworkBlocker();
161
+ * initCookieYes({ mode: "cookie-only", networkBlocker: { rules: [...] } });
162
+ * ```
163
+ *
164
+ * This indirection is what keeps the blocker out of the download for everyone
165
+ * who does not use it. Because it is reached by an ordinary static import, the
166
+ * blocker is already loaded when setup runs and patches the browser's
167
+ * networking immediately — there is no window in which requests slip through,
168
+ * which is the flaw a dynamic import would have introduced. See
169
+ * `network-blocker-slot.ts` for the full reasoning.
170
+ *
171
+ * Idempotent: calling it more than once replaces the registration with the same
172
+ * installer and changes nothing.
173
+ */
174
+ declare function registerNetworkBlocker(): void;
175
+
176
+ /**
177
+ * A tool that can be stopped (and optionally resumed) at runtime when consent
178
+ * for its category changes — no page reload needed. `stop()` is called when the
179
+ * category is revoked; `resume()` (if provided) when it's re-granted.
180
+ *
181
+ * If `stop()` throws, that tool is treated as "couldn't be stopped cleanly" and
182
+ * falls back to the reload notice for that one tool — it never breaks the page.
183
+ */
184
+ type StopHandler = {
185
+ id: string;
186
+ category: ConsentCategory;
187
+ stop: () => void;
188
+ resume?: (() => void) | undefined;
189
+ };
190
+ /**
191
+ * A tool with no known clean runtime stop — revoking its category can only be
192
+ * fully applied by reloading the page. Registering one means "if this category
193
+ * is revoked, show the visitor the reload notice."
194
+ */
195
+ type ReloadOnlyHandler = {
196
+ id: string;
197
+ category: ConsentCategory;
198
+ needsReload: true;
199
+ };
200
+ type AnyStopHandler = StopHandler | ReloadOnlyHandler;
201
+ /**
202
+ * Built-in, first-party integrations. Each maps to either a clean stop-handler
203
+ * or a reload-only marker (see the audit in the README).
204
+ *
205
+ * Note: Google Analytics 4 and Google Tag Manager are **not** listed here.
206
+ * They're governed by Google Consent Mode v2, which the SDK broadcasts
207
+ * automatically whenever a `dataLayer` is present (see google-consent-mode.ts)
208
+ * — on load and on every consent change, derived from each category's `gcm`
209
+ * mapping. So you don't register them as integrations; just add the standard
210
+ * Consent Mode default snippet and the SDK owns the updates.
211
+ *
212
+ * VERIFIED clean-stop vendors (documented, stable runtime opt-out):
213
+ * - `meta` — `fbq('consent','revoke'|'grant')`, Meta's official consent API.
214
+ *
215
+ * The rest have no confident, documented runtime stop, so they're modelled as
216
+ * reload-only (Story 1's honest answer). Upgrading any of them to a clean-stop
217
+ * later is a one-line change here once a real API is confirmed.
218
+ */
219
+ type BuiltInIntegration = {
220
+ vendor: "meta";
221
+ category?: ConsentCategory | undefined;
222
+ } | {
223
+ vendor: "tiktok";
224
+ category?: ConsentCategory | undefined;
225
+ } | {
226
+ vendor: "linkedin";
227
+ category?: ConsentCategory | undefined;
228
+ } | {
229
+ vendor: "hotjar";
230
+ category?: ConsentCategory | undefined;
231
+ } | {
232
+ vendor: "segment";
233
+ category?: ConsentCategory | undefined;
234
+ };
235
+ declare function resolveBuiltInIntegration(cfg: BuiltInIntegration): AnyStopHandler;
236
+ declare function registerStopHandler(handler: AnyStopHandler): void;
237
+ /** Test-only: reset registry + transition state between cases. */
238
+ declare function _clearStopHandlers(): void;
239
+
240
+ /**
241
+ * A consent category id. The five built-in ids are offered for autocomplete,
242
+ * but any string is valid — customers can define their own taxonomy via
243
+ * `categories` (see {@link CategoryDef}).
244
+ */
245
+ type ConsentCategory = "necessary" | "functional" | "analytics" | "performance" | "advertisement" | (string & {});
246
+ type Regulation = "GDPR" | "CCPA" | "DEFAULT";
247
+ /** Display text for one consent category. */
248
+ type CategoryText = {
249
+ label: string;
250
+ description: string;
251
+ };
252
+ type TranslationMap = {
253
+ bannerTitle: string;
254
+ bannerDescription: string;
255
+ acceptAll: string;
256
+ rejectAll: string;
257
+ managePreferences: string;
258
+ savePreferences: string;
259
+ doNotSell: string;
260
+ ccpaDescription: string;
261
+ accept: string;
262
+ poweredBy: string;
263
+ /** Appended to the branding link's accessible name; that link opens a new tab. */
264
+ opensInNewTab: string;
265
+ preferencesTitle: string;
266
+ preferencesIntro: string;
267
+ /** Shown in place of a toggle on a category marked `required: true`. */
268
+ alwaysActive: string;
269
+ /** Accessible name of the preferences dialog. */
270
+ preferencesDialogLabel: string;
271
+ /** Accessible name of the opt-out dialog. */
272
+ optOutDialogLabel: string;
273
+ /** Accessible name of the floating recall button. */
274
+ recallButtonLabel: string;
275
+ /** Accessible name of the banner's close button (rendered under CCPA only). */
276
+ bannerCloseLabel: string;
277
+ /** Accessible name of the preferences dialog's close button. */
278
+ preferencesCloseLabel: string;
279
+ /** Accessible name of the opt-out dialog's close button. */
280
+ optOutCloseLabel: string;
281
+ categories: {
282
+ necessary: CategoryText;
283
+ functional: CategoryText;
284
+ analytics: CategoryText;
285
+ performance: CategoryText;
286
+ advertisement: CategoryText;
287
+ } & Record<string, CategoryText>;
288
+ optOut: {
289
+ title: string;
290
+ description: string;
291
+ cancel: string;
292
+ successText: string;
293
+ successCountdown: string;
294
+ };
295
+ gatedFrame: {
296
+ /** Placeholder shown in place of blocked embedded content. `{category}` is substituted. */
297
+ placeholder: string;
298
+ /** Label of the placeholder's button, which opens the preferences dialog. */
299
+ action: string;
300
+ };
301
+ reloadNotice: {
302
+ message: string;
303
+ reloadButton: string;
304
+ dismissButton: string;
305
+ };
306
+ };
307
+ /** A subset of TranslationMap — lets a customer override just a few strings. */
308
+ type DeepPartial<T> = T extends object ? {
309
+ [K in keyof T]?: DeepPartial<T[K]>;
310
+ } : T;
311
+ type PartialTranslations = DeepPartial<TranslationMap>;
312
+ /** Reading direction of a language. */
313
+ type TextDirection = "ltr" | "rtl";
314
+ /** The active language, its reading direction, and the languages currently loaded. */
315
+ type LanguageInfo = {
316
+ language: string;
317
+ direction: TextDirection;
318
+ languages: string[];
319
+ };
320
+ /** Returns the visitor's region synchronously, e.g. "DE" or "US-CA" (or undefined). */
321
+ type RegionDetector = () => string | undefined;
322
+ /** Optional geo-detection: pick the banner's regulation from the visitor's region. */
323
+ type RegionConfig = {
324
+ /** Return the visitor's region synchronously — e.g. from a hosting header you read. */
325
+ detect?: RegionDetector | undefined;
326
+ /** Which regulation each region maps to (you own this). Matched most-specific first: "US-CA" then "US". */
327
+ map?: Record<string, Regulation> | undefined;
328
+ /** Honour the browser's GPC "do not sell/share" signal (a CCPA opt-out). Default `true`. */
329
+ honorGpc?: boolean | undefined;
330
+ /** Regulation to apply when the region is unknown or detection fails. Default `"GDPR"`. */
331
+ strictest?: Regulation | undefined;
332
+ /** Log the region decision to the console at setup (for local debugging). Default `false`. */
333
+ debug?: boolean | undefined;
334
+ };
335
+ /** How the active regulation was decided. */
336
+ type RegionSource = "manual" | "detected" | "strictest";
337
+ /** The outcome of geo-detection — the region seen and the regulation chosen. */
338
+ type RegionDecision = {
339
+ region: string | undefined;
340
+ regulation: Regulation;
341
+ source: RegionSource;
342
+ confidence: "high" | "low";
343
+ };
344
+ type ThemeConfig = {
345
+ primaryColor?: string | undefined;
346
+ backgroundColor?: string | undefined;
347
+ textColor?: string | undefined;
348
+ mutedTextColor?: string | undefined;
349
+ borderColor?: string | undefined;
350
+ borderRadius?: string | undefined;
351
+ fontFamily?: string | undefined;
352
+ /**
353
+ * Focus-ring color for interactive elements. Falls back to
354
+ * `var(--cy-primary)` — the ring matches your brand color exactly like it
355
+ * did before this field existed.
356
+ */
357
+ focusColor?: string | undefined;
358
+ /**
359
+ * Background color of the floating recall widget (the small circular
360
+ * re-open button). Falls back to `"#0056a7"` in light mode. In dark mode,
361
+ * this value is still respected if you set it; only when you don't set it
362
+ * does a dark-mode default apply, the same way
363
+ * backgroundColor/textColor/mutedTextColor/borderColor already work.
364
+ */
365
+ widgetBackgroundColor?: string | undefined;
366
+ };
367
+ type ScriptEntry = {
368
+ id: string;
369
+ src: string;
370
+ category: ConsentCategory;
371
+ onLoad?: (() => void) | undefined;
372
+ };
373
+ type I18nConfig = {
374
+ /** Translations per language. Each may be partial — missing text falls back to English. */
375
+ messages?: Record<string, PartialTranslations> | undefined;
376
+ locale?: string | undefined;
377
+ detectBrowserLanguage?: boolean | undefined;
378
+ /**
379
+ * Called when a language is switched to that isn't already in `messages` —
380
+ * return its translations (fetch them from your own URL, import them, etc.).
381
+ * Lets you load languages on demand instead of bundling them all upfront.
382
+ */
383
+ loadLanguage?: ((tag: string) => PartialTranslations | Promise<PartialTranslations>) | undefined;
384
+ };
385
+ type ConsentConfig = {
386
+ apiUrl?: string | undefined;
387
+ apiKey?: string | undefined;
388
+ backend?: ConsentBackend | undefined;
389
+ regulation?: Regulation | undefined;
390
+ /**
391
+ * Define your own category taxonomy. Omit to get the built-in five
392
+ * (necessary, functional, analytics, performance, advertisement) unchanged.
393
+ * At least one category must be `{ required: true }`. Invalid configs fall
394
+ * back to the built-in five with a console warning. See {@link CategoryDef}.
395
+ */
396
+ categories?: CategoryDef[] | undefined;
397
+ theme?: ThemeConfig | undefined;
398
+ colorScheme?: ColorScheme | undefined;
399
+ reloadOnRevoke?: boolean | undefined;
400
+ /**
401
+ * How to combine multiple categories that map to the same Google Consent Mode
402
+ * signal: `"any"` (default) grants the signal if any maps-and-granted; `"all"`
403
+ * requires every mapping category. Only affects custom overlapping mappings.
404
+ */
405
+ googleConsentMatch?: "all" | "any" | undefined;
406
+ /**
407
+ * Built-in, first-party integrations to stop cleanly (no reload) when their
408
+ * category is revoked — e.g. `{ vendor: "meta" }`. (Google Analytics/Tag
409
+ * Manager are handled automatically via the Consent Mode broadcast — no entry
410
+ * needed.) Integrations with no clean runtime stop fall back to the reload notice.
411
+ */
412
+ integrations?: BuiltInIntegration[] | undefined;
413
+ /**
414
+ * Your own scripts' stop instructions, for anything without a built-in
415
+ * integration. A handler that can stop cleanly provides `stop()`; one that
416
+ * can't should be registered as a reload-only handler instead so revoking it
417
+ * shows the reload notice rather than silently continuing to track.
418
+ */
419
+ customStopHandlers?: StopHandler[] | undefined;
420
+ /** Detected region (e.g. "US-CA"), recorded on the consent-log payload. */
421
+ region?: string | undefined;
422
+ /**
423
+ * Internal — set by the runtime when a CCPA visitor arrives with the browser's
424
+ * GPC "do not sell" signal on. Starts them opted out (non-required categories
425
+ * off) until they explicitly choose otherwise, so nothing is shared first.
426
+ */
427
+ gpcOptOut?: boolean | undefined;
428
+ onConsentReady?: ((state: ConsentSnapshot) => void) | undefined;
429
+ onConsentUpdate?: ((state: ConsentSnapshot) => void) | undefined;
430
+ };
431
+ /**
432
+ * Surfaced when a revoked tool has no clean runtime stop and can only be fully
433
+ * applied by reloading. `required` is false once dismissed; `reasons` lists the
434
+ * handler ids that triggered it (e.g. `["hotjar"]`).
435
+ */
436
+ type ReloadNoticeState = {
437
+ required: boolean;
438
+ reasons: string[];
439
+ };
440
+ type ConsentSnapshot = {
441
+ consentId: string;
442
+ hasActed: boolean;
443
+ /** Category id → granted. Keys are the configured taxonomy's ids. */
444
+ categories: Record<string, boolean>;
445
+ regulation: Regulation;
446
+ lastRenewed?: number | undefined;
447
+ /**
448
+ * Signature of the category taxonomy in effect when this consent was
449
+ * recorded. Lets us (and the customer) tell what a returning visitor
450
+ * actually agreed to, and drives re-request when the taxonomy changes.
451
+ */
452
+ taxonomyHash?: string | undefined;
453
+ };
454
+ type ConsentManager = ConsentSnapshot & {
455
+ /**
456
+ * Consent in effect — changes only on a real decision (accept / reject / save
457
+ * / reset), never on a dialog toggle. Gate scripts/embeds on this. (`categories`
458
+ * is the live value that drives the dialog checkboxes.)
459
+ */
460
+ committedCategories: Record<string, boolean>;
461
+ acceptAll: () => void;
462
+ rejectAll: () => void;
463
+ acceptSelected: (categories: ConsentCategory[]) => void;
464
+ updateCategory: (category: ConsentCategory, value: boolean) => void;
465
+ savePreferences: () => void;
466
+ resetConsent: () => void;
467
+ showPreferences: () => void;
468
+ hidePreferences: () => void;
469
+ isPreferencesOpen: boolean;
470
+ subscribe: (listener: (state: ConsentSnapshot) => void) => () => void;
471
+ registerScript: (entry: ScriptEntry) => void;
472
+ /** Current reload-notice state (see {@link ReloadNoticeState}). */
473
+ reloadNotice: ReloadNoticeState;
474
+ /** Dismiss the reload notice; it won't reappear until a new revoke needs one. */
475
+ dismissReloadNotice: () => void;
476
+ };
477
+ /**
478
+ * Shape of the JSON body POSTed to the customer's `apiUrl`
479
+ * on every consent decision (Accept All / Reject All / Save Preferences).
480
+ *
481
+ * Customers building a TypeScript backend can import this type to get
482
+ * full type safety on their request handler.
483
+ */
484
+ type ConsentPayload = {
485
+ consentId: string;
486
+ categories: Record<string, boolean>;
487
+ regulation: Regulation;
488
+ domain: string;
489
+ /** Detected region when geo-detection is on (e.g. "US-CA"); omitted otherwise. */
490
+ region?: string | undefined;
491
+ };
492
+ /**
493
+ * Customer-implemented adapter that decides how a consent decision
494
+ * reaches their backend. Provide this when `mode: "self-hosted"` and you
495
+ * need full control over the request shape, headers, auth, transport,
496
+ * batching, retries, etc. — anything you can't express with `apiUrl`.
497
+ *
498
+ * The SDK hands you a standardised `ConsentPayload`; you transform and
499
+ * dispatch it however your backend expects.
500
+ */
501
+ interface ConsentBackend {
502
+ persist(payload: ConsentPayload): Promise<void> | void;
503
+ }
504
+ /**
505
+ * @deprecated Use `"cookie-only"` instead — identical behavior, clearer name.
506
+ * `"offline"` still works but will be removed after three release cycles.
507
+ */
508
+ type DeprecatedOfflineMode = "offline";
509
+ type ConsentRuntimeMode = "self-hosted" | "cookie-only" | DeprecatedOfflineMode;
510
+ type ColorScheme = "light" | "dark" | "system";
511
+ /**
512
+ * Fields shared by every {@link CookieYesConfig} regardless of `mode`.
513
+ * This is the one canonical config surface — both `@cookieyes/core` and
514
+ * `@cookieyes/react` consume the exact same object, so a config is
515
+ * copy-pasteable between them with zero edits.
516
+ */
517
+ type CookieYesConfigCommon = {
518
+ /**
519
+ * Which privacy regulation applies. Top-level and identical across every
520
+ * package (replaces the builder's `.regulation()` and core's former
521
+ * nested `overrides.regulation`).
522
+ */
523
+ regulation?: Regulation | undefined;
524
+ /**
525
+ * Optional geo-detection: choose the regulation from the visitor's region.
526
+ * Fully optional — omit it and nothing changes. A manual `regulation` (above)
527
+ * always wins over detection. See {@link RegionConfig}.
528
+ */
529
+ region?: RegionConfig | undefined;
530
+ colorScheme?: ColorScheme | undefined;
531
+ theme?: ThemeConfig | undefined;
532
+ i18n?: I18nConfig | undefined;
533
+ /**
534
+ * Define your own category taxonomy. Omit to get the built-in five
535
+ * (necessary, functional, analytics, performance, advertisement) unchanged.
536
+ * At least one category must be `{ required: true }`. Invalid configs fall
537
+ * back to the built-in five with a console warning. See {@link CategoryDef}.
538
+ */
539
+ categories?: CategoryDef[] | undefined;
540
+ networkBlocker?: NetworkBlockerConfig | undefined;
541
+ reloadOnRevoke?: boolean | undefined;
542
+ /**
543
+ * How to combine multiple categories that map to the same Google Consent Mode
544
+ * signal: `"any"` (default) or `"all"`. Only matters for a custom taxonomy
545
+ * where more than one category maps to the same signal.
546
+ */
547
+ googleConsentMatch?: "all" | "any" | undefined;
548
+ /**
549
+ * Ready-made third-party integrations to gate behind consent — Segment, Meta,
550
+ * Google, and more — using a preset from `@cookieyes/scripts`. Each preset
551
+ * returns an {@link Integration}: it loads only once its category is granted
552
+ * (or, for Google Consent Mode, loads immediately and denies by default), and
553
+ * is removed or silenced on withdrawal.
554
+ *
555
+ * @example integrations: [segment({ writeKey: "..." })]
556
+ */
557
+ integrations?: Integration[] | undefined;
558
+ /**
559
+ * @deprecated Renamed from `integrations`. Built-in stop-handlers for a few
560
+ * first-party vendors — e.g. `{ vendor: "meta" }` — stopped cleanly (no
561
+ * reload) when their category is revoked. Prefer the new `integrations` field
562
+ * with a preset from `@cookieyes/scripts`; this will be removed after three
563
+ * release cycles.
564
+ */
565
+ builtInIntegrations?: BuiltInIntegration[] | undefined;
566
+ /**
567
+ * Your own scripts' stop instructions, for anything without a built-in
568
+ * integration. A handler that can stop cleanly provides `stop()`; one that
569
+ * can't should be registered as a reload-only handler instead so revoking it
570
+ * shows the reload notice rather than silently continuing to track.
571
+ */
572
+ customStopHandlers?: StopHandler[] | undefined;
573
+ /** Low-level: fires once, after the runtime's initial state is known (e.g. to conditionally load analytics on first load). For ongoing updates, use `consentStore.subscribeToConsentChanges` instead. */
574
+ onConsentReady?: ((state: ConsentSnapshot) => void) | undefined;
575
+ /** Low-level: fires on every saved consent change, for the lifetime of this config. If you need to subscribe/unsubscribe dynamically after mount, use `consentStore.getState().subscribeToConsentChanges` instead. */
576
+ onConsentUpdate?: ((state: ConsentSnapshot) => void) | undefined;
577
+ /**
578
+ * @deprecated Set `regulation` at the top level instead. This nested form
579
+ * still works and maps to the top-level field; if both are given, the
580
+ * top-level `regulation` wins. Retained for back-compat and removed after
581
+ * three release cycles, per the SDK deprecation policy.
582
+ */
583
+ overrides?: {
584
+ regulation?: Regulation | undefined;
585
+ } | undefined;
586
+ };
587
+ /**
588
+ * Cookie-only mode — consent is stored client-side only; no backend keys are
589
+ * permitted (they fail at the type level). `mode: "cookie-only"` is the
590
+ * canonical value; `mode: "offline"` is a deprecated alias with identical
591
+ * behavior that emits a one-time-per-page-load deprecation warning.
592
+ */
593
+ type CookieYesOfflineConfig = CookieYesConfigCommon & {
594
+ mode: "cookie-only" | DeprecatedOfflineMode;
595
+ };
596
+ /** Self-hosted mode — consent decisions are persisted to your own backend. */
597
+ type CookieYesSelfHostedConfig = CookieYesConfigCommon & {
598
+ mode: "self-hosted";
599
+ /** Endpoint the {@link ConsentPayload} is POSTed to. Canonical key. */
600
+ apiUrl?: string | undefined;
601
+ apiKey?: string | undefined;
602
+ /** Custom persistence adapter — full control over transport/headers/retries. */
603
+ backend?: ConsentBackend | undefined;
604
+ /**
605
+ * @deprecated Renamed to `apiUrl`. This alias still works and maps to
606
+ * `apiUrl`; if both are given, `apiUrl` wins. Retained for back-compat and
607
+ * removed after three release cycles, per the SDK deprecation policy.
608
+ */
609
+ backendURL?: string | undefined;
610
+ };
611
+ /**
612
+ * The canonical configuration object for the CookieYes SDK, discriminated on
613
+ * `mode`. Passed identically to `initCookieYes()` /
614
+ * `getOrCreateConsentRuntime()` in `@cookieyes/core` and `initCookieYes()` in
615
+ * `@cookieyes/react`.
616
+ *
617
+ * The discriminated union guarantees invalid combinations fail at compile time
618
+ * — e.g. supplying `apiUrl`/`backend` under `mode: "cookie-only"` is a type error.
619
+ */
620
+ type CookieYesConfig = CookieYesOfflineConfig | CookieYesSelfHostedConfig;
621
+ /**
622
+ * @deprecated Renamed to {@link CookieYesConfig}. Retained as a type alias for
623
+ * back-compat and removed after three release cycles, per the SDK deprecation
624
+ * policy.
625
+ */
626
+ type ConsentRuntimeOptions = CookieYesConfig;
627
+ type ConsentChangePayload = {
628
+ allowedCategories: ConsentCategory[];
629
+ deniedCategories: ConsentCategory[];
630
+ };
631
+ /** Which consent event to listen for. See {@link ConsentStore.on}. */
632
+ type ConsentEventType = "save" | "change";
633
+ type ConsentEventPayload = {
634
+ /** The full committed consent map in effect when the event fired. */
635
+ categories: Record<string, boolean>;
636
+ /** Categories whose value differed from before. Empty on the initial replay. */
637
+ changedCategories: ConsentCategory[];
638
+ /**
639
+ * `true` when this is the one-off replay a listener gets on attach (here's
640
+ * the current state), `false` when the visitor actually just acted.
641
+ */
642
+ isInitial: boolean;
643
+ };
644
+ type ConsentEventListener = (payload: ConsentEventPayload) => void;
645
+ /** Restrict a listener to a single category (fires only when it changes). */
646
+ type ConsentEventOptions = {
647
+ category?: ConsentCategory;
648
+ };
649
+ type ActiveUI = "banner" | "dialog" | null;
650
+ type ConsentStoreState = ConsentSnapshot & {
651
+ activeUI: ActiveUI;
652
+ /** Live/working values — reflect in-progress dialog toggles. Drive checkboxes. */
653
+ consents: Record<string, boolean>;
654
+ /**
655
+ * Consent in effect — changes only on a saved decision, not a toggle. Gate
656
+ * scripts/embeds on this (or {@link ConsentStoreState.has}).
657
+ */
658
+ committedConsents: Record<string, boolean>;
659
+ /** True when `category` is committed-granted (a saved decision), not just toggled. */
660
+ has: (category: ConsentCategory) => boolean;
661
+ saveConsents: (target: "all" | "necessary" | ConsentCategory[]) => Promise<void>;
662
+ setConsent: (category: ConsentCategory, value: boolean) => void;
663
+ /** Low-level: fires only on *saved* preference changes, not transient UI toggles — see `ConsentStore.subscribe` for the recommended, general-purpose subscription. */
664
+ subscribeToConsentChanges: (listener: (payload: ConsentChangePayload) => void) => () => void;
665
+ };
666
+ /**
667
+ * The recommended way to read consent state outside React. `subscribe` fires
668
+ * on every state change (including transient UI toggles, e.g. a checkbox
669
+ * flip before saving); for saved-changes-only, see
670
+ * `ConsentStoreState.subscribeToConsentChanges`.
671
+ */
672
+ type ConsentStore = {
673
+ subscribe: (listener: (state: ConsentStoreState) => void) => () => void;
674
+ getState: () => ConsentStoreState;
675
+ /** Text for the active language (English fills gaps). Swaps on `setLanguage`. */
676
+ translations: TranslationMap;
677
+ /** The active language, its reading direction, and the languages loaded. */
678
+ getLanguageInfo: () => LanguageInfo;
679
+ /**
680
+ * Switch language live (no reload) — `subscribe` listeners fire so a custom UI
681
+ * can re-render. Loads the language via `i18n.loadLanguage` if not bundled.
682
+ */
683
+ setLanguage: (tag: string) => Promise<void>;
684
+ /** Customer-provided text for a category in the active language, if any. */
685
+ getCategoryText: (id: string) => Partial<CategoryText> | undefined;
686
+ /**
687
+ * The category taxonomy in effect (custom list or the built-in five) — its
688
+ * ids, which are `required`, etc. Use it to render categories in a custom UI
689
+ * so it follows whatever taxonomy is configured.
690
+ */
691
+ categories: ResolvedCategories;
692
+ /** How the active regulation was decided (region, source, confidence). */
693
+ getRegion: () => RegionDecision;
694
+ /**
695
+ * React to consent decisions. `"save"` fires on every save (even an
696
+ * unchanged re-confirm); `"change"` fires only when a category actually
697
+ * differs — use it to (re)load a script without re-running on a re-confirm.
698
+ * The listener fires once immediately with the current state
699
+ * (`isInitial: true`). Pass `{ category }` to only hear about one category.
700
+ * Returns an unsubscribe function.
701
+ */
702
+ on: (type: ConsentEventType, listener: ConsentEventListener, options?: ConsentEventOptions) => () => void;
703
+ };
704
+ type ConsentRuntime = {
705
+ consentManager: ConsentManager;
706
+ consentStore: ConsentStore;
707
+ /** Config + live status for each script integration — data for a debug view. */
708
+ getIntegrations: () => IntegrationDebugInfo[];
709
+ /**
710
+ * Resolves once configured integrations have been loaded and wired up.
711
+ *
712
+ * The integration runner is loaded on demand — it is the largest subsystem in
713
+ * the package and does nothing unless `integrations` is configured — so there
714
+ * is a short window after setup in which `getIntegrations()` returns `[]` and
715
+ * no integration has been set up yet. Await this to act after that window;
716
+ * it resolves immediately when no integrations are configured.
717
+ *
718
+ * Nothing about consent gating depends on it: an integration cannot run
719
+ * before its category is granted whether or not it has loaded yet.
720
+ */
721
+ integrationsReady: Promise<void>;
722
+ };
723
+
724
+ /**
725
+ * Google Consent Mode v2 storage/signal types. A category can declare which of
726
+ * these it represents via {@link CategoryDef.gcm}; the SDK then broadcasts them
727
+ * (see google-consent-mode.ts). `security_storage` is always granted and is
728
+ * handled by the broadcast itself, so it never needs to be mapped.
729
+ */
730
+ type GoogleConsentSignal = "ad_storage" | "ad_user_data" | "ad_personalization" | "analytics_storage" | "functionality_storage" | "personalization_storage" | "security_storage";
731
+ /**
732
+ * A single consent category. `id` is the stable key stored in the cookie and
733
+ * used everywhere (banner, preferences, read APIs, integrations). Exactly one
734
+ * category should be marked `required` — the always-on, non-optional one (like
735
+ * the default "necessary") — flagged explicitly here, never inferred from a
736
+ * name, so it survives full renaming.
737
+ */
738
+ type CategoryDef = {
739
+ id: ConsentCategory;
740
+ /** The always-on, non-optional category. At least one is required. */
741
+ required?: boolean | undefined;
742
+ /** Display label. Falls back to the translation for built-in ids. */
743
+ label?: string | undefined;
744
+ /** Display description. Falls back to the translation for built-in ids. */
745
+ description?: string | undefined;
746
+ /** Google Consent Mode signals this category governs (see {@link GoogleConsentSignal}). */
747
+ gcm?: GoogleConsentSignal[] | undefined;
748
+ };
749
+ /**
750
+ * The built-in five, used verbatim when a customer configures nothing. GCM
751
+ * mapping mirrors production's `_ckySetGoogleConsentMode` (analytics →
752
+ * analytics_storage, advertisement → the ad_* signals, functional →
753
+ * functionality/personalization; performance maps to nothing; security_storage
754
+ * is always granted by the broadcast).
755
+ */
756
+ declare const DEFAULT_CATEGORIES: CategoryDef[];
757
+ type ResolvedCategories = {
758
+ /** Ordered category definitions actually in effect. */
759
+ list: CategoryDef[];
760
+ /** Ordered ids (fast access). */
761
+ ids: ConsentCategory[];
762
+ /** Ids marked `required` (always granted, never toggleable). */
763
+ requiredIds: Set<ConsentCategory>;
764
+ /** Stable signature of this taxonomy; a change here re-requests consent. */
765
+ taxonomyHash: string;
766
+ /** True when the built-in five are in effect (configured or fallback). */
767
+ isDefault: boolean;
768
+ };
769
+ /**
770
+ * Resolve the category list from config. Returns the built-in five when nothing
771
+ * is configured. On an invalid custom config (empty, duplicate/reserved ids, or
772
+ * no `required` category) it warns and falls back to the built-in five, rather
773
+ * than leaving the visitor a broken/empty or unprotected setup.
774
+ */
775
+ declare function resolveCategories(defs?: CategoryDef[]): ResolvedCategories;
776
+
777
+ export { DEFAULT_CATEGORIES as M, INTEGRATION_FORMAT_VERSION as O, _clearStopHandlers as a1, installNetworkBlocker as a2, registerNetworkBlocker as a3, registerStopHandler as a4, resolveBuiltInIntegration as a5, resolveCategories as a6, runIntegrations as a7, uninstallNetworkBlocker as a8, warnOverlappingVendors as a9, warnUnknownCategories as aa };
778
+ export type { SetupCtx as $, ActiveUI as A, BuiltInIntegration as B, ConsentRuntimeMode as C, ConsentPayload as D, ConsentRuntimeOptions as E, ConsentStore as F, GoogleConsentSignal as G, ConsentStoreState as H, I18nConfig as I, CookieYesOfflineConfig as J, CookieYesSelfHostedConfig as K, LanguageInfo as L, NetworkBlockerConfig as N, PartialTranslations as P, IntegrationDebugInfo as Q, Regulation as R, StopHandler as S, ThemeConfig as T, IntegrationStatus as U, NetworkBlockerRule as V, RegionDetector as W, RegionSource as X, ReloadNoticeState as Y, ReloadOnlyHandler as Z, ScriptEntry as _, RegionConfig as a, SilenceControl as a0, ColorScheme as b, CategoryDef as c, Integration as d, ConsentSnapshot as e, ConsentBackend as f, CookieYesConfig as g, ConsentEventType as h, ConsentEventListener as i, ConsentEventOptions as j, ResolvedCategories as k, TranslationMap as l, TextDirection as m, IntegrationHost as n, IntegrationRunner as o, CategoryText as p, ConsentConfig as q, ConsentManager as r, ConsentCategory as s, RegionDecision as t, ConsentRuntime as u, AnyStopHandler as v, BlockedRequestInfo as w, Cleanup as x, ConsentChangePayload as y, ConsentEventPayload as z };