@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.
package/dist/index.d.ts CHANGED
@@ -1,740 +1,5 @@
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
- /**
154
- * A tool that can be stopped (and optionally resumed) at runtime when consent
155
- * for its category changes — no page reload needed. `stop()` is called when the
156
- * category is revoked; `resume()` (if provided) when it's re-granted.
157
- *
158
- * If `stop()` throws, that tool is treated as "couldn't be stopped cleanly" and
159
- * falls back to the reload notice for that one tool — it never breaks the page.
160
- */
161
- type StopHandler = {
162
- id: string;
163
- category: ConsentCategory;
164
- stop: () => void;
165
- resume?: (() => void) | undefined;
166
- };
167
- /**
168
- * A tool with no known clean runtime stop — revoking its category can only be
169
- * fully applied by reloading the page. Registering one means "if this category
170
- * is revoked, show the visitor the reload notice."
171
- */
172
- type ReloadOnlyHandler = {
173
- id: string;
174
- category: ConsentCategory;
175
- needsReload: true;
176
- };
177
- type AnyStopHandler = StopHandler | ReloadOnlyHandler;
178
- /**
179
- * Built-in, first-party integrations. Each maps to either a clean stop-handler
180
- * or a reload-only marker (see the audit in the README).
181
- *
182
- * Note: Google Analytics 4 and Google Tag Manager are **not** listed here.
183
- * They're governed by Google Consent Mode v2, which the SDK broadcasts
184
- * automatically whenever a `dataLayer` is present (see google-consent-mode.ts)
185
- * — on load and on every consent change, derived from each category's `gcm`
186
- * mapping. So you don't register them as integrations; just add the standard
187
- * Consent Mode default snippet and the SDK owns the updates.
188
- *
189
- * VERIFIED clean-stop vendors (documented, stable runtime opt-out):
190
- * - `meta` — `fbq('consent','revoke'|'grant')`, Meta's official consent API.
191
- *
192
- * The rest have no confident, documented runtime stop, so they're modelled as
193
- * reload-only (Story 1's honest answer). Upgrading any of them to a clean-stop
194
- * later is a one-line change here once a real API is confirmed.
195
- */
196
- type BuiltInIntegration = {
197
- vendor: "meta";
198
- category?: ConsentCategory | undefined;
199
- } | {
200
- vendor: "tiktok";
201
- category?: ConsentCategory | undefined;
202
- } | {
203
- vendor: "linkedin";
204
- category?: ConsentCategory | undefined;
205
- } | {
206
- vendor: "hotjar";
207
- category?: ConsentCategory | undefined;
208
- } | {
209
- vendor: "segment";
210
- category?: ConsentCategory | undefined;
211
- };
212
- declare function resolveBuiltInIntegration(cfg: BuiltInIntegration): AnyStopHandler;
213
- declare function registerStopHandler(handler: AnyStopHandler): void;
214
- /** Test-only: reset registry + transition state between cases. */
215
- declare function _clearStopHandlers(): void;
216
-
217
- /**
218
- * A consent category id. The five built-in ids are offered for autocomplete,
219
- * but any string is valid — customers can define their own taxonomy via
220
- * `categories` (see {@link CategoryDef}).
221
- */
222
- type ConsentCategory = "necessary" | "functional" | "analytics" | "performance" | "advertisement" | (string & {});
223
- type Regulation = "GDPR" | "CCPA" | "DEFAULT";
224
- /** Display text for one consent category. */
225
- type CategoryText = {
226
- label: string;
227
- description: string;
228
- };
229
- type TranslationMap = {
230
- bannerTitle: string;
231
- bannerDescription: string;
232
- acceptAll: string;
233
- rejectAll: string;
234
- managePreferences: string;
235
- savePreferences: string;
236
- doNotSell: string;
237
- ccpaDescription: string;
238
- accept: string;
239
- poweredBy: string;
240
- preferencesTitle: string;
241
- preferencesIntro: string;
242
- /** Shown in place of a toggle on a category marked `required: true`. */
243
- alwaysActive: string;
244
- /** Accessible name of the preferences dialog. */
245
- preferencesDialogLabel: string;
246
- /** Accessible name of the opt-out dialog. */
247
- optOutDialogLabel: string;
248
- /** Accessible name of the floating recall button. */
249
- recallButtonLabel: string;
250
- /** Accessible name of the banner's close button (rendered under CCPA only). */
251
- bannerCloseLabel: string;
252
- /** Accessible name of the preferences dialog's close button. */
253
- preferencesCloseLabel: string;
254
- /** Accessible name of the opt-out dialog's close button. */
255
- optOutCloseLabel: string;
256
- categories: {
257
- necessary: CategoryText;
258
- functional: CategoryText;
259
- analytics: CategoryText;
260
- performance: CategoryText;
261
- advertisement: CategoryText;
262
- } & Record<string, CategoryText>;
263
- optOut: {
264
- title: string;
265
- description: string;
266
- cancel: string;
267
- successText: string;
268
- successCountdown: string;
269
- };
270
- gatedFrame: {
271
- /** Placeholder shown in place of blocked embedded content. `{category}` is substituted. */
272
- placeholder: string;
273
- /** Label of the placeholder's button, which opens the preferences dialog. */
274
- action: string;
275
- };
276
- reloadNotice: {
277
- message: string;
278
- reloadButton: string;
279
- dismissButton: string;
280
- };
281
- };
282
- /** A subset of TranslationMap — lets a customer override just a few strings. */
283
- type DeepPartial<T> = T extends object ? {
284
- [K in keyof T]?: DeepPartial<T[K]>;
285
- } : T;
286
- type PartialTranslations = DeepPartial<TranslationMap>;
287
- /** Reading direction of a language. */
288
- type TextDirection = "ltr" | "rtl";
289
- /** The active language, its reading direction, and the languages currently loaded. */
290
- type LanguageInfo = {
291
- language: string;
292
- direction: TextDirection;
293
- languages: string[];
294
- };
295
- /** Returns the visitor's region synchronously, e.g. "DE" or "US-CA" (or undefined). */
296
- type RegionDetector = () => string | undefined;
297
- /** Optional geo-detection: pick the banner's regulation from the visitor's region. */
298
- type RegionConfig = {
299
- /** Return the visitor's region synchronously — e.g. from a hosting header you read. */
300
- detect?: RegionDetector | undefined;
301
- /** Which regulation each region maps to (you own this). Matched most-specific first: "US-CA" then "US". */
302
- map?: Record<string, Regulation> | undefined;
303
- /** Honour the browser's GPC "do not sell/share" signal (a CCPA opt-out). Default `true`. */
304
- honorGpc?: boolean | undefined;
305
- /** Regulation to apply when the region is unknown or detection fails. Default `"GDPR"`. */
306
- strictest?: Regulation | undefined;
307
- /** Log the region decision to the console at setup (for local debugging). Default `false`. */
308
- debug?: boolean | undefined;
309
- };
310
- /** How the active regulation was decided. */
311
- type RegionSource = "manual" | "detected" | "strictest";
312
- /** The outcome of geo-detection — the region seen and the regulation chosen. */
313
- type RegionDecision = {
314
- region: string | undefined;
315
- regulation: Regulation;
316
- source: RegionSource;
317
- confidence: "high" | "low";
318
- };
319
- type ThemeConfig = {
320
- primaryColor?: string | undefined;
321
- backgroundColor?: string | undefined;
322
- textColor?: string | undefined;
323
- mutedTextColor?: string | undefined;
324
- borderColor?: string | undefined;
325
- borderRadius?: string | undefined;
326
- fontFamily?: string | undefined;
327
- /**
328
- * Focus-ring color for interactive elements. Falls back to
329
- * `var(--cy-primary)` — the ring matches your brand color exactly like it
330
- * did before this field existed.
331
- */
332
- focusColor?: string | undefined;
333
- /**
334
- * Background color of the floating recall widget (the small circular
335
- * re-open button). Falls back to `"#0056a7"` in light mode. In dark mode,
336
- * this value is still respected if you set it; only when you don't set it
337
- * does a dark-mode default apply, the same way
338
- * backgroundColor/textColor/mutedTextColor/borderColor already work.
339
- */
340
- widgetBackgroundColor?: string | undefined;
341
- };
342
- type ScriptEntry = {
343
- id: string;
344
- src: string;
345
- category: ConsentCategory;
346
- onLoad?: (() => void) | undefined;
347
- };
348
- type I18nConfig = {
349
- /** Translations per language. Each may be partial — missing text falls back to English. */
350
- messages?: Record<string, PartialTranslations> | undefined;
351
- locale?: string | undefined;
352
- detectBrowserLanguage?: boolean | undefined;
353
- /**
354
- * Called when a language is switched to that isn't already in `messages` —
355
- * return its translations (fetch them from your own URL, import them, etc.).
356
- * Lets you load languages on demand instead of bundling them all upfront.
357
- */
358
- loadLanguage?: ((tag: string) => PartialTranslations | Promise<PartialTranslations>) | undefined;
359
- };
360
- type ConsentConfig = {
361
- apiUrl?: string | undefined;
362
- apiKey?: string | undefined;
363
- backend?: ConsentBackend | undefined;
364
- regulation?: Regulation | undefined;
365
- /**
366
- * Define your own category taxonomy. Omit to get the built-in five
367
- * (necessary, functional, analytics, performance, advertisement) unchanged.
368
- * At least one category must be `{ required: true }`. Invalid configs fall
369
- * back to the built-in five with a console warning. See {@link CategoryDef}.
370
- */
371
- categories?: CategoryDef[] | undefined;
372
- theme?: ThemeConfig | undefined;
373
- colorScheme?: ColorScheme | undefined;
374
- reloadOnRevoke?: boolean | undefined;
375
- /**
376
- * How to combine multiple categories that map to the same Google Consent Mode
377
- * signal: `"any"` (default) grants the signal if any maps-and-granted; `"all"`
378
- * requires every mapping category. Only affects custom overlapping mappings.
379
- */
380
- googleConsentMatch?: "all" | "any" | undefined;
381
- /**
382
- * Built-in, first-party integrations to stop cleanly (no reload) when their
383
- * category is revoked — e.g. `{ vendor: "meta" }`. (Google Analytics/Tag
384
- * Manager are handled automatically via the Consent Mode broadcast — no entry
385
- * needed.) Integrations with no clean runtime stop fall back to the reload notice.
386
- */
387
- integrations?: BuiltInIntegration[] | undefined;
388
- /**
389
- * Your own scripts' stop instructions, for anything without a built-in
390
- * integration. A handler that can stop cleanly provides `stop()`; one that
391
- * can't should be registered as a reload-only handler instead so revoking it
392
- * shows the reload notice rather than silently continuing to track.
393
- */
394
- customStopHandlers?: StopHandler[] | undefined;
395
- /** Detected region (e.g. "US-CA"), recorded on the consent-log payload. */
396
- region?: string | undefined;
397
- /**
398
- * Internal — set by the runtime when a CCPA visitor arrives with the browser's
399
- * GPC "do not sell" signal on. Starts them opted out (non-required categories
400
- * off) until they explicitly choose otherwise, so nothing is shared first.
401
- */
402
- gpcOptOut?: boolean | undefined;
403
- onConsentReady?: ((state: ConsentSnapshot) => void) | undefined;
404
- onConsentUpdate?: ((state: ConsentSnapshot) => void) | undefined;
405
- };
406
- /**
407
- * Surfaced when a revoked tool has no clean runtime stop and can only be fully
408
- * applied by reloading. `required` is false once dismissed; `reasons` lists the
409
- * handler ids that triggered it (e.g. `["hotjar"]`).
410
- */
411
- type ReloadNoticeState = {
412
- required: boolean;
413
- reasons: string[];
414
- };
415
- type ConsentSnapshot = {
416
- consentId: string;
417
- hasActed: boolean;
418
- /** Category id → granted. Keys are the configured taxonomy's ids. */
419
- categories: Record<string, boolean>;
420
- regulation: Regulation;
421
- lastRenewed?: number | undefined;
422
- /**
423
- * Signature of the category taxonomy in effect when this consent was
424
- * recorded. Lets us (and the customer) tell what a returning visitor
425
- * actually agreed to, and drives re-request when the taxonomy changes.
426
- */
427
- taxonomyHash?: string | undefined;
428
- };
429
- type ConsentManager = ConsentSnapshot & {
430
- /**
431
- * Consent in effect — changes only on a real decision (accept / reject / save
432
- * / reset), never on a dialog toggle. Gate scripts/embeds on this. (`categories`
433
- * is the live value that drives the dialog checkboxes.)
434
- */
435
- committedCategories: Record<string, boolean>;
436
- acceptAll: () => void;
437
- rejectAll: () => void;
438
- acceptSelected: (categories: ConsentCategory[]) => void;
439
- updateCategory: (category: ConsentCategory, value: boolean) => void;
440
- savePreferences: () => void;
441
- resetConsent: () => void;
442
- showPreferences: () => void;
443
- hidePreferences: () => void;
444
- isPreferencesOpen: boolean;
445
- subscribe: (listener: (state: ConsentSnapshot) => void) => () => void;
446
- registerScript: (entry: ScriptEntry) => void;
447
- /** Current reload-notice state (see {@link ReloadNoticeState}). */
448
- reloadNotice: ReloadNoticeState;
449
- /** Dismiss the reload notice; it won't reappear until a new revoke needs one. */
450
- dismissReloadNotice: () => void;
451
- };
452
- /**
453
- * Shape of the JSON body POSTed to the customer's `apiUrl`
454
- * on every consent decision (Accept All / Reject All / Save Preferences).
455
- *
456
- * Customers building a TypeScript backend can import this type to get
457
- * full type safety on their request handler.
458
- */
459
- type ConsentPayload = {
460
- consentId: string;
461
- categories: Record<string, boolean>;
462
- regulation: Regulation;
463
- domain: string;
464
- /** Detected region when geo-detection is on (e.g. "US-CA"); omitted otherwise. */
465
- region?: string | undefined;
466
- };
467
- /**
468
- * Customer-implemented adapter that decides how a consent decision
469
- * reaches their backend. Provide this when `mode: "self-hosted"` and you
470
- * need full control over the request shape, headers, auth, transport,
471
- * batching, retries, etc. — anything you can't express with `apiUrl`.
472
- *
473
- * The SDK hands you a standardised `ConsentPayload`; you transform and
474
- * dispatch it however your backend expects.
475
- */
476
- interface ConsentBackend {
477
- persist(payload: ConsentPayload): Promise<void> | void;
478
- }
479
- /**
480
- * @deprecated Use `"cookie-only"` instead — identical behavior, clearer name.
481
- * `"offline"` still works but will be removed after three release cycles.
482
- */
483
- type DeprecatedOfflineMode = "offline";
484
- type ConsentRuntimeMode = "self-hosted" | "cookie-only" | DeprecatedOfflineMode;
485
- type ColorScheme = "light" | "dark" | "system";
486
- /**
487
- * Fields shared by every {@link CookieYesConfig} regardless of `mode`.
488
- * This is the one canonical config surface — both `@cookieyes/core` and
489
- * `@cookieyes/react` consume the exact same object, so a config is
490
- * copy-pasteable between them with zero edits.
491
- */
492
- type CookieYesConfigCommon = {
493
- /**
494
- * Which privacy regulation applies. Top-level and identical across every
495
- * package (replaces the builder's `.regulation()` and core's former
496
- * nested `overrides.regulation`).
497
- */
498
- regulation?: Regulation | undefined;
499
- /**
500
- * Optional geo-detection: choose the regulation from the visitor's region.
501
- * Fully optional — omit it and nothing changes. A manual `regulation` (above)
502
- * always wins over detection. See {@link RegionConfig}.
503
- */
504
- region?: RegionConfig | undefined;
505
- colorScheme?: ColorScheme | undefined;
506
- theme?: ThemeConfig | undefined;
507
- i18n?: I18nConfig | undefined;
508
- /**
509
- * Define your own category taxonomy. Omit to get the built-in five
510
- * (necessary, functional, analytics, performance, advertisement) unchanged.
511
- * At least one category must be `{ required: true }`. Invalid configs fall
512
- * back to the built-in five with a console warning. See {@link CategoryDef}.
513
- */
514
- categories?: CategoryDef[] | undefined;
515
- networkBlocker?: NetworkBlockerConfig | undefined;
516
- reloadOnRevoke?: boolean | undefined;
517
- /**
518
- * How to combine multiple categories that map to the same Google Consent Mode
519
- * signal: `"any"` (default) or `"all"`. Only matters for a custom taxonomy
520
- * where more than one category maps to the same signal.
521
- */
522
- googleConsentMatch?: "all" | "any" | undefined;
523
- /**
524
- * Ready-made third-party integrations to gate behind consent — Segment, Meta,
525
- * Google, and more — using a preset from `@cookieyes/scripts`. Each preset
526
- * returns an {@link Integration}: it loads only once its category is granted
527
- * (or, for Google Consent Mode, loads immediately and denies by default), and
528
- * is removed or silenced on withdrawal.
529
- *
530
- * @example integrations: [segment({ writeKey: "..." })]
531
- */
532
- integrations?: Integration[] | undefined;
533
- /**
534
- * @deprecated Renamed from `integrations`. Built-in stop-handlers for a few
535
- * first-party vendors — e.g. `{ vendor: "meta" }` — stopped cleanly (no
536
- * reload) when their category is revoked. Prefer the new `integrations` field
537
- * with a preset from `@cookieyes/scripts`; this will be removed after three
538
- * release cycles.
539
- */
540
- builtInIntegrations?: BuiltInIntegration[] | undefined;
541
- /**
542
- * Your own scripts' stop instructions, for anything without a built-in
543
- * integration. A handler that can stop cleanly provides `stop()`; one that
544
- * can't should be registered as a reload-only handler instead so revoking it
545
- * shows the reload notice rather than silently continuing to track.
546
- */
547
- customStopHandlers?: StopHandler[] | undefined;
548
- /** 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. */
549
- onConsentReady?: ((state: ConsentSnapshot) => void) | undefined;
550
- /** 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. */
551
- onConsentUpdate?: ((state: ConsentSnapshot) => void) | undefined;
552
- /**
553
- * @deprecated Set `regulation` at the top level instead. This nested form
554
- * still works and maps to the top-level field; if both are given, the
555
- * top-level `regulation` wins. Retained for back-compat and removed after
556
- * three release cycles, per the SDK deprecation policy.
557
- */
558
- overrides?: {
559
- regulation?: Regulation | undefined;
560
- } | undefined;
561
- };
562
- /**
563
- * Cookie-only mode — consent is stored client-side only; no backend keys are
564
- * permitted (they fail at the type level). `mode: "cookie-only"` is the
565
- * canonical value; `mode: "offline"` is a deprecated alias with identical
566
- * behavior that emits a one-time-per-page-load deprecation warning.
567
- */
568
- type CookieYesOfflineConfig = CookieYesConfigCommon & {
569
- mode: "cookie-only" | DeprecatedOfflineMode;
570
- };
571
- /** Self-hosted mode — consent decisions are persisted to your own backend. */
572
- type CookieYesSelfHostedConfig = CookieYesConfigCommon & {
573
- mode: "self-hosted";
574
- /** Endpoint the {@link ConsentPayload} is POSTed to. Canonical key. */
575
- apiUrl?: string | undefined;
576
- apiKey?: string | undefined;
577
- /** Custom persistence adapter — full control over transport/headers/retries. */
578
- backend?: ConsentBackend | undefined;
579
- /**
580
- * @deprecated Renamed to `apiUrl`. This alias still works and maps to
581
- * `apiUrl`; if both are given, `apiUrl` wins. Retained for back-compat and
582
- * removed after three release cycles, per the SDK deprecation policy.
583
- */
584
- backendURL?: string | undefined;
585
- };
586
- /**
587
- * The canonical configuration object for the CookieYes SDK, discriminated on
588
- * `mode`. Passed identically to `initCookieYes()` /
589
- * `getOrCreateConsentRuntime()` in `@cookieyes/core` and `initCookieYes()` in
590
- * `@cookieyes/react`.
591
- *
592
- * The discriminated union guarantees invalid combinations fail at compile time
593
- * — e.g. supplying `apiUrl`/`backend` under `mode: "cookie-only"` is a type error.
594
- */
595
- type CookieYesConfig = CookieYesOfflineConfig | CookieYesSelfHostedConfig;
596
- /**
597
- * @deprecated Renamed to {@link CookieYesConfig}. Retained as a type alias for
598
- * back-compat and removed after three release cycles, per the SDK deprecation
599
- * policy.
600
- */
601
- type ConsentRuntimeOptions = CookieYesConfig;
602
- type ConsentChangePayload = {
603
- allowedCategories: ConsentCategory[];
604
- deniedCategories: ConsentCategory[];
605
- };
606
- /** Which consent event to listen for. See {@link ConsentStore.on}. */
607
- type ConsentEventType = "save" | "change";
608
- type ConsentEventPayload = {
609
- /** The full committed consent map in effect when the event fired. */
610
- categories: Record<string, boolean>;
611
- /** Categories whose value differed from before. Empty on the initial replay. */
612
- changedCategories: ConsentCategory[];
613
- /**
614
- * `true` when this is the one-off replay a listener gets on attach (here's
615
- * the current state), `false` when the visitor actually just acted.
616
- */
617
- isInitial: boolean;
618
- };
619
- type ConsentEventListener = (payload: ConsentEventPayload) => void;
620
- /** Restrict a listener to a single category (fires only when it changes). */
621
- type ConsentEventOptions = {
622
- category?: ConsentCategory;
623
- };
624
- type ActiveUI = "banner" | "dialog" | null;
625
- type ConsentStoreState = ConsentSnapshot & {
626
- activeUI: ActiveUI;
627
- /** Live/working values — reflect in-progress dialog toggles. Drive checkboxes. */
628
- consents: Record<string, boolean>;
629
- /**
630
- * Consent in effect — changes only on a saved decision, not a toggle. Gate
631
- * scripts/embeds on this (or {@link ConsentStoreState.has}).
632
- */
633
- committedConsents: Record<string, boolean>;
634
- /** True when `category` is committed-granted (a saved decision), not just toggled. */
635
- has: (category: ConsentCategory) => boolean;
636
- saveConsents: (target: "all" | "necessary" | ConsentCategory[]) => Promise<void>;
637
- setConsent: (category: ConsentCategory, value: boolean) => void;
638
- /** Low-level: fires only on *saved* preference changes, not transient UI toggles — see `ConsentStore.subscribe` for the recommended, general-purpose subscription. */
639
- subscribeToConsentChanges: (listener: (payload: ConsentChangePayload) => void) => () => void;
640
- };
641
- /**
642
- * The recommended way to read consent state outside React. `subscribe` fires
643
- * on every state change (including transient UI toggles, e.g. a checkbox
644
- * flip before saving); for saved-changes-only, see
645
- * `ConsentStoreState.subscribeToConsentChanges`.
646
- */
647
- type ConsentStore = {
648
- subscribe: (listener: (state: ConsentStoreState) => void) => () => void;
649
- getState: () => ConsentStoreState;
650
- /** Text for the active language (English fills gaps). Swaps on `setLanguage`. */
651
- translations: TranslationMap;
652
- /** The active language, its reading direction, and the languages loaded. */
653
- getLanguageInfo: () => LanguageInfo;
654
- /**
655
- * Switch language live (no reload) — `subscribe` listeners fire so a custom UI
656
- * can re-render. Loads the language via `i18n.loadLanguage` if not bundled.
657
- */
658
- setLanguage: (tag: string) => Promise<void>;
659
- /** Customer-provided text for a category in the active language, if any. */
660
- getCategoryText: (id: string) => Partial<CategoryText> | undefined;
661
- /**
662
- * The category taxonomy in effect (custom list or the built-in five) — its
663
- * ids, which are `required`, etc. Use it to render categories in a custom UI
664
- * so it follows whatever taxonomy is configured.
665
- */
666
- categories: ResolvedCategories;
667
- /** How the active regulation was decided (region, source, confidence). */
668
- getRegion: () => RegionDecision;
669
- /**
670
- * React to consent decisions. `"save"` fires on every save (even an
671
- * unchanged re-confirm); `"change"` fires only when a category actually
672
- * differs — use it to (re)load a script without re-running on a re-confirm.
673
- * The listener fires once immediately with the current state
674
- * (`isInitial: true`). Pass `{ category }` to only hear about one category.
675
- * Returns an unsubscribe function.
676
- */
677
- on: (type: ConsentEventType, listener: ConsentEventListener, options?: ConsentEventOptions) => () => void;
678
- };
679
- type ConsentRuntime = {
680
- consentManager: ConsentManager;
681
- consentStore: ConsentStore;
682
- /** Config + live status for each script integration — data for a debug view. */
683
- getIntegrations: () => IntegrationDebugInfo[];
684
- };
685
-
686
- /**
687
- * Google Consent Mode v2 storage/signal types. A category can declare which of
688
- * these it represents via {@link CategoryDef.gcm}; the SDK then broadcasts them
689
- * (see google-consent-mode.ts). `security_storage` is always granted and is
690
- * handled by the broadcast itself, so it never needs to be mapped.
691
- */
692
- type GoogleConsentSignal = "ad_storage" | "ad_user_data" | "ad_personalization" | "analytics_storage" | "functionality_storage" | "personalization_storage" | "security_storage";
693
- /**
694
- * A single consent category. `id` is the stable key stored in the cookie and
695
- * used everywhere (banner, preferences, read APIs, integrations). Exactly one
696
- * category should be marked `required` — the always-on, non-optional one (like
697
- * the default "necessary") — flagged explicitly here, never inferred from a
698
- * name, so it survives full renaming.
699
- */
700
- type CategoryDef = {
701
- id: ConsentCategory;
702
- /** The always-on, non-optional category. At least one is required. */
703
- required?: boolean | undefined;
704
- /** Display label. Falls back to the translation for built-in ids. */
705
- label?: string | undefined;
706
- /** Display description. Falls back to the translation for built-in ids. */
707
- description?: string | undefined;
708
- /** Google Consent Mode signals this category governs (see {@link GoogleConsentSignal}). */
709
- gcm?: GoogleConsentSignal[] | undefined;
710
- };
711
- /**
712
- * The built-in five, used verbatim when a customer configures nothing. GCM
713
- * mapping mirrors production's `_ckySetGoogleConsentMode` (analytics →
714
- * analytics_storage, advertisement → the ad_* signals, functional →
715
- * functionality/personalization; performance maps to nothing; security_storage
716
- * is always granted by the broadcast).
717
- */
718
- declare const DEFAULT_CATEGORIES: CategoryDef[];
719
- type ResolvedCategories = {
720
- /** Ordered category definitions actually in effect. */
721
- list: CategoryDef[];
722
- /** Ordered ids (fast access). */
723
- ids: ConsentCategory[];
724
- /** Ids marked `required` (always granted, never toggleable). */
725
- requiredIds: Set<ConsentCategory>;
726
- /** Stable signature of this taxonomy; a change here re-requests consent. */
727
- taxonomyHash: string;
728
- /** True when the built-in five are in effect (configured or fallback). */
729
- isDefault: boolean;
730
- };
731
- /**
732
- * Resolve the category list from config. Returns the built-in five when nothing
733
- * is configured. On an invalid custom config (empty, duplicate/reserved ids, or
734
- * no `required` category) it warns and falls back to the built-in five, rather
735
- * than leaving the visitor a broken/empty or unprotected setup.
736
- */
737
- declare function resolveCategories(defs?: CategoryDef[]): ResolvedCategories;
1
+ import { C as ConsentRuntimeMode, R as Regulation, a as RegionConfig, b as ColorScheme, T as ThemeConfig, I as I18nConfig, c as CategoryDef, N as NetworkBlockerConfig, d as Integration, B as BuiltInIntegration, S as StopHandler, e as ConsentSnapshot, f as ConsentBackend, g as CookieYesConfig, h as ConsentEventType, i as ConsentEventListener, j as ConsentEventOptions, k as ResolvedCategories, G as GoogleConsentSignal, l as TranslationMap, m as TextDirection, P as PartialTranslations, n as IntegrationHost, o as IntegrationRunner, L as LanguageInfo, p as CategoryText, q as ConsentConfig, r as ConsentManager, s as ConsentCategory, t as RegionDecision, u as ConsentRuntime } from './categories-DMBKo4Eb.js';
2
+ export { A as ActiveUI, v as AnyStopHandler, w as BlockedRequestInfo, x as Cleanup, y as ConsentChangePayload, z as ConsentEventPayload, D as ConsentPayload, E as ConsentRuntimeOptions, F as ConsentStore, H as ConsentStoreState, J as CookieYesOfflineConfig, K as CookieYesSelfHostedConfig, M as DEFAULT_CATEGORIES, O as INTEGRATION_FORMAT_VERSION, Q as IntegrationDebugInfo, U as IntegrationStatus, V as NetworkBlockerRule, W as RegionDetector, X as RegionSource, Y as ReloadNoticeState, Z as ReloadOnlyHandler, _ as ScriptEntry, $ as SetupCtx, a0 as SilenceControl, a1 as _clearStopHandlers, a2 as installNetworkBlocker, a3 as registerNetworkBlocker, a4 as registerStopHandler, a5 as resolveBuiltInIntegration, a6 as resolveCategories, a7 as runIntegrations, a8 as uninstallNetworkBlocker, a9 as warnOverlappingVendors, aa as warnUnknownCategories } from './categories-DMBKo4Eb.js';
738
3
 
739
4
  /**
740
5
  * The canonical config with every deprecated alias already collapsed into its
@@ -806,6 +71,8 @@ declare function generateConsentId(): string;
806
71
  * One-time-per-page-load console warning for `mode: "offline"`.
807
72
  * Both @cookieyes/core and @cookieyes/react call this so the wording and the
808
73
  * "once" behavior stay identical no matter which package reads the setting.
74
+ *
75
+ * No-op in a production bundle; see the note at the top of this file.
809
76
  */
810
77
  declare function _warnOfflineModeDeprecated(): void;
811
78
  /** @internal test-only — resets the one-time warning guard between test cases. */
@@ -814,6 +81,8 @@ declare function _resetOfflineModeWarning(): void;
814
81
  * One-time-per-page-load console warning for the deprecated `builtInIntegrations`
815
82
  * config field (formerly `integrations`). Both packages call this so the wording
816
83
  * and the "once" behavior stay identical.
84
+ *
85
+ * No-op in a production bundle; see the note at the top of this file.
817
86
  */
818
87
  declare function _warnBuiltInIntegrationsDeprecated(): void;
819
88
  /** @internal test-only — resets the one-time warning guard between test cases. */
@@ -880,6 +149,30 @@ declare function pickLanguage(i18n?: I18nConfig): string;
880
149
  /** Full translations for the resolved starting language, English filling any gaps. */
881
150
  declare function resolveTranslations(i18n?: I18nConfig): TranslationMap;
882
151
 
152
+ /**
153
+ * Load the integration runner on demand.
154
+ *
155
+ * The runner is the largest single subsystem in `@cookieyes/core` — 1.2 KB of
156
+ * gzip, measured — and it does nothing at all unless `integrations` is
157
+ * configured, which most consumers never do. `integrations.ts` is a separate
158
+ * build entry (see `sdk/core/rollup.config.mjs`) so that this stays a real
159
+ * `import()` in the published output rather than being flattened back into the
160
+ * main chunk, and a bundler can therefore keep it out of the initial download.
161
+ *
162
+ * This indirection exists so that `@cookieyes/react` does not need a static
163
+ * import of `runIntegrations` to do the same thing. A dynamic
164
+ * `import("@cookieyes/core")` from the adapter would pull the whole barrel and
165
+ * defeat the split; a static import of *this* function costs a few bytes and
166
+ * leaves the heavy module behind one `import()` that only core knows about.
167
+ *
168
+ * @internal — consumed by framework adapters, not part of the public API.
169
+ */
170
+ declare function _loadIntegrations(): Promise<{
171
+ runIntegrations: (list: Integration[], host: IntegrationHost) => IntegrationRunner;
172
+ warnOverlappingVendors: (ids: string[], vendors: string[]) => void;
173
+ warnUnknownCategories: (list: Integration[], known: string[]) => void;
174
+ }>;
175
+
883
176
  type LanguageController = {
884
177
  /** Text for the active language (English fills any gaps). */
885
178
  getTranslations: () => TranslationMap;
@@ -905,6 +198,34 @@ declare function createLanguageController(i18n: I18nConfig | undefined, onChange
905
198
 
906
199
  declare function createConsentManager(config: ConsentConfig): ConsentManager;
907
200
 
201
+ /** @internal Test-only — empties the slot so one test cannot leak into the next. */
202
+ declare function _clearNetworkBlockerInstaller(): void;
203
+ /** True when a customer has registered the blocker. @internal */
204
+ declare function _hasNetworkBlockerInstaller(): boolean;
205
+ /**
206
+ * Install the registered blocker, or complain loudly that there isn't one.
207
+ *
208
+ * The failure mode this guards against is the dangerous one: a customer who
209
+ * configured `networkBlocker` before this change and upgrades would otherwise
210
+ * find their requests silently no longer blocked, which on a consent product is
211
+ * worse than a crash. `console.error` rather than `throw` because taking the
212
+ * page down is not proportionate, and the message names the exact two lines
213
+ * needed to fix it.
214
+ *
215
+ * @internal — consumed by core's runtime and by framework adapters.
216
+ */
217
+ declare function _installRegisteredNetworkBlocker(config: NetworkBlockerConfig, hasConsent: (category: ConsentCategory) => boolean): void;
218
+ /**
219
+ * Restore the browser's networking functions, if the blocker was installed.
220
+ *
221
+ * Idempotent, and a no-op when nothing was installed — which is why the runtime
222
+ * can call it unconditionally on reset without dragging the blocker back into
223
+ * the bundle.
224
+ *
225
+ * @internal
226
+ */
227
+ declare function _uninstallRegisteredNetworkBlocker(): void;
228
+
908
229
  /** Anything with a header getter — a `Headers` object, Next's `headers()`, etc. */
909
230
  type HeaderSource = {
910
231
  get(name: string): string | null | undefined;
@@ -1019,5 +340,5 @@ declare function readServerConsent(cookieHeader: string, options?: ServerConsent
1019
340
  */
1020
341
  declare const CORE_VERSION = "0.0.0-dev";
1021
342
 
1022
- export { CORE_VERSION, DEFAULT_CATEGORIES, INTEGRATION_FORMAT_VERSION, _clearScriptRegistry, _clearStopHandlers, _logRegionDecision, _normalizeConfig, _resetBuiltInIntegrationsWarning, _resetOfflineModeWarning, _warnBuiltInIntegrationsDeprecated, _warnOfflineModeDeprecated, broadcastGoogleConsent, computeGoogleConsent, createConsentEmitter, createConsentManager, createLanguageController, en as defaultTranslations, generateConsentId, getOrCreateConsentRuntime, getTextDirection, initCookieYes, installNetworkBlocker, mergeTranslations, parseCookie, parseCookieHeader, pickLanguage, primaryOf, readGpc, readServerConsent, regionFromHeaders, registerStopHandler, resetConsentRuntime, resolveBuiltInIntegration, resolveCategories, resolveRegion, resolveTranslations, runIntegrations, serializeCookie, uninstallNetworkBlocker, warnOverlappingVendors, warnUnknownCategories };
1023
- export type { ActiveUI, AnyStopHandler, BlockedRequestInfo, BuiltInIntegration, CategoryDef, CategoryText, Cleanup, ColorScheme, ConsentBackend, ConsentCategory, ConsentChangePayload, ConsentConfig, ConsentEmitter, ConsentEventListener, ConsentEventOptions, ConsentEventPayload, ConsentEventType, ConsentManager, ConsentPayload, ConsentRuntime, ConsentRuntimeMode, ConsentRuntimeOptions, ConsentSnapshot, ConsentStore, ConsentStoreState, CookieYesConfig, CookieYesOfflineConfig, CookieYesSelfHostedConfig, GoogleConsentSignal, HeaderSource, I18nConfig, Integration, IntegrationDebugInfo, IntegrationHost, IntegrationRunner, IntegrationStatus, LanguageController, LanguageInfo, NetworkBlockerConfig, NetworkBlockerRule, PartialTranslations, RegionConfig, RegionDecision, RegionDetector, RegionSource, Regulation, ReloadNoticeState, ReloadOnlyHandler, ResolvedCategories, ScriptEntry, ServerConsentOptions, SetupCtx, SilenceControl, StopHandler, TextDirection, ThemeConfig, TranslationMap, _NormalizedConfig };
343
+ export { BuiltInIntegration, CORE_VERSION, CategoryDef, CategoryText, ColorScheme, ConsentBackend, ConsentCategory, ConsentConfig, ConsentEventListener, ConsentEventOptions, ConsentEventType, ConsentManager, ConsentRuntime, ConsentRuntimeMode, ConsentSnapshot, CookieYesConfig, GoogleConsentSignal, I18nConfig, Integration, IntegrationHost, IntegrationRunner, LanguageInfo, NetworkBlockerConfig, PartialTranslations, RegionConfig, RegionDecision, Regulation, ResolvedCategories, StopHandler, TextDirection, ThemeConfig, TranslationMap, _clearNetworkBlockerInstaller, _clearScriptRegistry, _hasNetworkBlockerInstaller, _installRegisteredNetworkBlocker, _loadIntegrations, _logRegionDecision, _normalizeConfig, _resetBuiltInIntegrationsWarning, _resetOfflineModeWarning, _uninstallRegisteredNetworkBlocker, _warnBuiltInIntegrationsDeprecated, _warnOfflineModeDeprecated, broadcastGoogleConsent, computeGoogleConsent, createConsentEmitter, createConsentManager, createLanguageController, en as defaultTranslations, generateConsentId, getOrCreateConsentRuntime, getTextDirection, initCookieYes, mergeTranslations, parseCookie, parseCookieHeader, pickLanguage, primaryOf, readGpc, readServerConsent, regionFromHeaders, resetConsentRuntime, resolveRegion, resolveTranslations, serializeCookie };
344
+ export type { ConsentEmitter, HeaderSource, LanguageController, ServerConsentOptions, _NormalizedConfig };