@jini-ai/cookie-consent 0.7.3-next.2 → 0.7.4

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 (41) hide show
  1. package/dist/client.min.js +1 -1
  2. package/dist/contract.d.ts +2 -78
  3. package/dist/extensions.min.js +1 -1
  4. package/dist/react/ConsentFields.d.ts +4 -1
  5. package/dist/react/ConsentFields.js +11 -5
  6. package/dist/render/css.d.ts +2 -12
  7. package/dist/site/config.d.ts +51 -0
  8. package/dist/site/config.js +75 -0
  9. package/dist/site/cookie-consent.d.ts +53 -0
  10. package/dist/site/cookie-consent.js +47 -0
  11. package/dist/site/document-assets.d.ts +44 -0
  12. package/dist/site/document-assets.js +78 -0
  13. package/dist/site/document-state.d.ts +71 -0
  14. package/dist/site/document-state.js +79 -0
  15. package/dist/site/ensure-privacy-defaults.d.ts +63 -0
  16. package/dist/site/ensure-privacy-defaults.js +44 -0
  17. package/dist/site/http.d.ts +281 -0
  18. package/dist/site/http.js +271 -0
  19. package/dist/site/pre-consent-cache.d.ts +33 -0
  20. package/dist/site/pre-consent-cache.js +43 -0
  21. package/dist/site/privacy-page-template.d.ts +9 -0
  22. package/dist/site/privacy-page-template.js +17 -0
  23. package/dist/site/readiness.d.ts +29 -0
  24. package/dist/site/readiness.js +91 -0
  25. package/dist/site/region-plugins.d.ts +90 -0
  26. package/dist/site/region-plugins.js +73 -0
  27. package/dist/site/request.d.ts +19 -0
  28. package/dist/site/request.js +29 -0
  29. package/dist/site/revisions.d.ts +33 -0
  30. package/dist/site/revisions.js +5 -0
  31. package/dist/site/revisions.repo.d.ts +20 -0
  32. package/dist/site/revisions.repo.js +53 -0
  33. package/dist/site/service.d.ts +204 -0
  34. package/dist/site/service.js +198 -0
  35. package/dist/site/settings.d.ts +54 -0
  36. package/dist/site/settings.js +100 -0
  37. package/dist/site/tool-registrations.d.ts +63 -0
  38. package/dist/site/tool-registrations.js +69 -0
  39. package/dist/site/validation.d.ts +21 -0
  40. package/dist/site/validation.js +77 -0
  41. package/package.json +143 -9
@@ -0,0 +1,100 @@
1
+ import { observed } from "@jini-ai/core/errors/idioms";
2
+ import { ensureSettingDefinitions, getEffective } from '@jini-ai/core/settings';
3
+ import { SITE_CONSENT_DEFAULTS, SITE_CONSENT_NAMESPACE, SITE_CONSENT_PLACEMENTS, SITE_CONSENT_REGION_MODES } from './config.js';
4
+ const ENUM_VALUES = { regionMode: SITE_CONSENT_REGION_MODES, placement: SITE_CONSENT_PLACEMENTS };
5
+ /** What a site serves when consent is not on: the default copy with the banner off. */
6
+ export const SITE_CONSENT_OFF = { ...SITE_CONSENT_DEFAULTS, enabled: false };
7
+ /** The ledger's `enabled` default stays OFF: its default layer only means "no owner choice yet",
8
+ * which {@link resolveSiteConsentActivation} turns into the product default (off since 2026-11-02).
9
+ * Keeping it unchanged also means no boot-time rewrite of existing sites' enabled ledgers.
10
+ * The blank privacy ledger lets bootstrap choose an existing site page before saving its URL. */
11
+ const LEDGER_DEFAULTS = { ...SITE_CONSENT_OFF, privacyPolicyUrl: '' };
12
+ /** The shared registrar owns legacy scalar definitions and their ledger revisions.
13
+ * Complete published policies use the site snapshot adapter, avoiding partial field publication.
14
+ * @complexity O(1), thirteen bounded settings definitions. */
15
+ export async function ensureSiteConsentDefinitions(required, { systemPrincipalId }) {
16
+ const definitions = Object.entries(LEDGER_DEFAULTS).map(([key, defaultValue]) => {
17
+ const values = ENUM_VALUES[key];
18
+ return { key, schema: values ? { type: 'enum', values: [...values] } : { type: typeof defaultValue === 'boolean' ? 'boolean' : 'string' }, defaultValue };
19
+ });
20
+ await ensureSettingDefinitions(required, { namespace: SITE_CONSENT_NAMESPACE, definitions, systemPrincipalId });
21
+ }
22
+ /** Consent owns readiness, without extending WebMCP's failure chain.
23
+ * The shared boot chain serializes ledger writes on the site's single connection.
24
+ * Definition failures block readiness; CMS defaults failures are reported and retried next open.
25
+ * @complexity Registration is O(1); injected CMS defaults inherit their workspace scan cost. */
26
+ export function createSiteConsentReadiness({ after, systemPrincipalId, ...required }, repair = {}) {
27
+ // Visitor cookie consent's `core.consent.*` definitions; registration never writes an owner choice.
28
+ const ready = after.then(() => ensureSiteConsentDefinitions(required, { systemPrincipalId })).then(async () => {
29
+ if (!repair.ensurePrivacyDefaults)
30
+ return;
31
+ // An optional content repair must not prevent the owner opening consent settings to fix it.
32
+ try {
33
+ await repair.ensurePrivacyDefaults();
34
+ }
35
+ catch (error) {
36
+ repair.reportPrivacyDefaultsFailure({ error });
37
+ }
38
+ });
39
+ // Attach a rejection observer now; a request may arrive long after registration fails.
40
+ observed({ promise: ready });
41
+ return ready;
42
+ }
43
+ /** @complexity O(1), one ledger read. */
44
+ async function readSetting({ settingsRepo, workspaceId }, key) {
45
+ return getEffective({ deps: { repo: settingsRepo }, namespace: SITE_CONSENT_NAMESPACE, key, scopeContext: { workspaceId } });
46
+ }
47
+ /** Resolve whether consent applies, honoring an explicit owner choice over the product default.
48
+ * The privacy link is not a precondition for activation; publishing still requires one (validation.ts).
49
+ * @throws Error when the stored flag is not a boolean (never guesses on or off).
50
+ * @complexity O(1), one ledger read. */
51
+ export async function resolveSiteConsentActivation(deps, _options = {}) {
52
+ const enabled = await readSetting(deps, 'enabled');
53
+ if (enabled !== null && enabled.sourceLayer !== 'default') {
54
+ if (typeof enabled.value !== 'boolean')
55
+ throw new Error('Invalid cookie consent setting: enabled.');
56
+ return { enabled: enabled.value, source: 'owner' };
57
+ }
58
+ return { enabled: SITE_CONSENT_DEFAULTS.enabled, source: 'default' };
59
+ }
60
+ /** Read every non-flag value with type and length checks. @complexity O(1), twelve ledger reads. */
61
+ async function readValues(deps) {
62
+ const entries = await Promise.all(Object.entries(SITE_CONSENT_DEFAULTS).filter(([key]) => key !== 'enabled').map(async ([key, fallback]) => {
63
+ const resolved = await readSetting(deps, key);
64
+ const value = resolved === null || (['regionMode', 'privacyPolicyUrl'].includes(key) && resolved.sourceLayer === 'default') ? fallback : resolved.value;
65
+ if (typeof value !== typeof fallback)
66
+ throw new Error(`Invalid cookie consent setting: ${key}.`);
67
+ if (typeof value === 'string' && value.length > 2000)
68
+ throw new Error(`Cookie consent setting ${key} exceeds 2000 characters.`);
69
+ return [key, value];
70
+ }));
71
+ return Object.fromEntries(entries);
72
+ }
73
+ /** Bind workspace settings to the mechanism. Missing definitions use the product default.
74
+ * Malformed values throw rather than bypass an enabled policy. @complexity O(1), thirteen reads. */
75
+ export function createSiteConsentConfig({ settingsRepo, workspaceId }, _options = {}) {
76
+ return {
77
+ async get(_input = {}, _optional = {}) {
78
+ // Disabling remains a working rollback even if another consent setting is malformed.
79
+ const activation = await resolveSiteConsentActivation({ settingsRepo, workspaceId });
80
+ if (!activation.enabled)
81
+ return { ...SITE_CONSENT_OFF, reopen: 'link' };
82
+ const values = await readValues({ settingsRepo, workspaceId });
83
+ if (!SITE_CONSENT_REGION_MODES.includes(values.regionMode))
84
+ throw new Error('Choose automatic, opt-in, or opt-out cookie consent region mode.');
85
+ if (!SITE_CONSENT_PLACEMENTS.includes(values.placement))
86
+ throw new Error(`Choose a cookie banner placement: ${SITE_CONSENT_PLACEMENTS.join(', ')}.`);
87
+ if (!values.policyVersion.trim() || values.policyVersion.length > 128)
88
+ throw new Error('Cookie consent policy version must contain 1–128 characters.');
89
+ return { ...values, enabled: true, reopen: 'link' };
90
+ },
91
+ };
92
+ }
93
+ /** Authoring reads retain saved copy even while consent is disabled; public rollback still uses get().
94
+ * @example readSiteConsentAuthoringSettings({ settingsRepo, workspaceId })
95
+ * @complexity O(1), one bounded set of existing ledger reads; performs no writes. */
96
+ export async function readSiteConsentAuthoringSettings(deps, _options = {}) {
97
+ const activation = await resolveSiteConsentActivation(deps);
98
+ return { ...await readValues(deps), enabled: activation.enabled };
99
+ }
100
+ //# sourceMappingURL=settings.js.map
@@ -0,0 +1,63 @@
1
+ /** @file Consent tools share the HTTP service and Jini's held confirmation lifecycle. */
2
+ import { type AgentToolDefinition, type AgentToolSideEffect, type ToolExecutionContext, type ToolHandler, type ToolRegistration } from '@jini-ai/core';
3
+ import type { AssistantSurfaceDeps } from '@jini-ai/core/contracts/site/daemon-surface-exchanges';
4
+ import type { SurfaceDetail } from '@jini-ai/core/contracts/cards';
5
+ import type { ToolContributor } from '@jini-ai/core';
6
+ import type { SiteConsentService } from './service.js';
7
+ export interface ConsentToolDeps {
8
+ siteConsent?: SiteConsentService;
9
+ }
10
+ /** The confirmation card a write describes; the host renders it and routes the click back to `toolId`. */
11
+ export interface ConsentApprovalDescription {
12
+ toolId: string;
13
+ errorCode: string;
14
+ title: string;
15
+ details: SurfaceDetail[];
16
+ warning?: string;
17
+ confirmLabel: string;
18
+ }
19
+ /** The host's held-confirmation lifecycle: it freezes the prepared input, asks a human, then runs. */
20
+ export type ConsentApprovalToolHandler = <TPrepared>(required: {
21
+ surfaces: AssistantSurfaceDeps;
22
+ prepare: (required: {
23
+ ctx: ToolExecutionContext;
24
+ }) => Promise<TPrepared>;
25
+ describe: (required: {
26
+ prepared: TPrepared;
27
+ }) => ConsentApprovalDescription;
28
+ run: (required: {
29
+ ctx: ToolExecutionContext;
30
+ prepared: TPrepared;
31
+ }) => Promise<unknown>;
32
+ }, optional: {
33
+ flag: string;
34
+ }) => ToolHandler;
35
+ /** Host collaborators bound once at composition: the approval lifecycle and the closed request contract
36
+ * shared with the host's HTTP transport (`readConsentRequest` rejects unknown fields; `consentRevisionToken`
37
+ * reads a required nullable revision id). Both throw `ToolInputError` on refusal. */
38
+ export interface ConsentToolHost {
39
+ bannerModeRefusal?: string | undefined;
40
+ approvalToolHandler: ConsentApprovalToolHandler;
41
+ readConsentRequest(required: {
42
+ body: unknown;
43
+ fields: readonly string[];
44
+ }, optional?: Record<string, never>): Record<string, unknown>;
45
+ consentRevisionToken(required: {
46
+ input: Record<string, unknown>;
47
+ key: string;
48
+ }, optional?: Record<string, never>): string | null;
49
+ }
50
+ /** Full schemas are also checked inside the shared service; no input can approve its own write. */
51
+ export declare const consentAgentToolCatalog: AgentToolDefinition[];
52
+ export declare const consentDerivedRisk: ReadonlyMap<string, AgentToolSideEffect>;
53
+ /** Builds five tools; every write uses an immutable prepared input and a fresh service check.
54
+ * @example buildConsentRegistrations({ siteConsent, host }, surfaces)
55
+ * @complexity O(1) setup; effects/limits belong to the injected service. */
56
+ export declare function buildConsentRegistrations(deps: ConsentToolDeps & {
57
+ host: ConsentToolHost;
58
+ }, surfaces: AssistantSurfaceDeps): ToolRegistration[];
59
+ /** Explicit composition contribution; no import-time registration or separate tool lifecycle. */
60
+ export declare function contributeConsentTools({ host }: {
61
+ host: ConsentToolHost;
62
+ }, _options?: {}): ToolContributor<ConsentToolDeps, AssistantSurfaceDeps>;
63
+ //# sourceMappingURL=tool-registrations.d.ts.map
@@ -0,0 +1,69 @@
1
+ /** @file Consent tools share the HTTP service and Jini's held confirmation lifecycle. */
2
+ import { buildDomainRegistrations, indexCatalogById, ToolInputError } from '@jini-ai/core';
3
+ import { toolMetadata } from '@jini-ai/core/tool-metadata/consent';
4
+ import { parseConsentConfig } from './validation.js';
5
+ const PATH = { type: 'string', description: 'One local public page path, default /; no external URL.' };
6
+ const TOKEN = { type: ['string', 'null'], description: 'The exact revision id from consent_get_settings, or null for no revision.' };
7
+ const CONFIG = { type: 'object', description: 'Full ConsentConfig: banner text, enabled, policyVersion, links, placement, regionMode, appearance tokens, customCss, optional legacy allowUnsafeEval boolean retained without effect. Four engine-owned categories cannot be changed.' };
8
+ /** Full schemas are also checked inside the shared service; no input can approve its own write. */
9
+ export const consentAgentToolCatalog = [
10
+ ...['consent_get_readiness', 'consent_explain_blocked'].map(name => ({ name, description: 'Read a side-effect-free cookie consent dry run for one local rendered page: fixed categories, gated scripts/resources, placement, blocking problems. A sample is not a whole-site compliance verdict.', sideEffects: 'none', authorization: { permission: 'settings.read' }, inputSchema: { type: 'object', properties: { path: PATH }, additionalProperties: false } })),
11
+ { name: 'consent_get_settings', description: 'Read cookie banner draft, published revision and effective settings. Use returned ids for conflict-safe draft saves and publication.', sideEffects: 'none', authorization: { permission: 'settings.read' }, inputSchema: { type: 'object', properties: {}, additionalProperties: false } },
12
+ { name: 'consent_update_settings', description: 'Save a new cookie consent draft after a human confirmation card. Leaves published enforcement in place. Read consent_get_settings first; pass full config and expectedDraftId. Invalid CSS remains an editable draft and blocks publication.', sideEffects: 'mutates-durable-state', authorization: { permission: 'settings.workspace.write' }, inputSchema: { type: 'object', required: ['config', 'expectedDraftId'], properties: { config: CONFIG, expectedDraftId: TOKEN }, additionalProperties: false } },
13
+ { name: 'consent_publish_settings', description: 'Publish exactly the saved cookie consent draft after a human confirmation card. Rechecks permission and revision freshness. Enabled changes re-ask visitors under a new immutable policy revision. To publish without a banner, save enabled:false, publish it explicitly, then retry deployment; optional scripts will run without banner enforcement.', sideEffects: 'mutates-durable-state', authorization: { permission: 'settings.workspace.write' }, inputSchema: { type: 'object', required: ['draftId', 'expectedPublishedId'], properties: { draftId: { type: 'string' }, expectedPublishedId: TOKEN }, additionalProperties: false } },
14
+ ];
15
+ export const consentDerivedRisk = new Map([
16
+ ['consent_get_settings', 'none'], ['consent_get_readiness', 'none'], ['consent_explain_blocked', 'none'],
17
+ // saveDraft appends an immutable policy; publish atomically changes the public pointer.
18
+ ['consent_update_settings', 'mutates-durable-state'], ['consent_publish_settings', 'mutates-durable-state'],
19
+ ]);
20
+ /** Builds five tools; every write uses an immutable prepared input and a fresh service check.
21
+ * @example buildConsentRegistrations({ siteConsent, host }, surfaces)
22
+ * @complexity O(1) setup; effects/limits belong to the injected service. */
23
+ export function buildConsentRegistrations(deps, surfaces) {
24
+ const { approvalToolHandler, readConsentRequest, consentRevisionToken, bannerModeRefusal } = deps.host;
25
+ /** Missing bindings are never replaced by a permissive in-memory store. */
26
+ const service = (_input = {}, _options = {}) => {
27
+ if (!deps.siteConsent)
28
+ throw new ToolInputError({ message: 'The site consent service is unavailable. Nothing was changed.' });
29
+ return deps.siteConsent;
30
+ };
31
+ /** Closed page input shared by both read diagnostics. */
32
+ const diagnostic = async ({ principalId, input }, _options = {}) => {
33
+ const raw = readConsentRequest({ body: input === undefined ? {} : input, fields: ['path'] });
34
+ if (raw.path !== undefined && typeof raw.path !== 'string')
35
+ throw new ToolInputError({ message: 'path must be a local page path.' });
36
+ return service().readiness({ principalId, path: raw.path });
37
+ };
38
+ return buildDomainRegistrations({ metadata: toolMetadata, domain: 'consent', catalogModule: 'features/consent/tool-registrations.ts', catalog: indexCatalogById({ catalog: consentAgentToolCatalog }), derivedRisk: consentDerivedRisk, handlers: {
39
+ consent_get_settings: async (ctx) => { readConsentRequest({ body: ctx.input === undefined ? {} : ctx.input, fields: [] }); return service().read({ principalId: ctx.principal.id }); },
40
+ consent_get_readiness: ctx => diagnostic({ principalId: ctx.principal.id, input: ctx.input }),
41
+ consent_explain_blocked: async (ctx) => { const result = await diagnostic({ principalId: ctx.principal.id, input: ctx.input }); return { ...result, explanation: 'Declared optional scripts wait until all their consent categories are effectively allowed. Unmanaged content and missing runtime slots need review; they are not automatically controlled. Durable grants wait for receipt confirmation.' }; },
42
+ consent_update_settings: approvalToolHandler({ surfaces,
43
+ prepare: async ({ ctx }) => {
44
+ const input = readConsentRequest({ body: ctx.input, fields: ['config', 'expectedDraftId'] });
45
+ const state = await service().read({ principalId: ctx.principal.id });
46
+ return { config: parseConsentConfig({ value: input.config, bannerModeRefusal }), previous: state.draft?.config ?? state.effective, expectedDraftId: consentRevisionToken({ input, key: 'expectedDraftId' }) };
47
+ },
48
+ describe: ({ prepared }) => ({ toolId: 'consent_update_settings', errorCode: 'CONSENT', title: 'Save this cookie consent draft?', details: [{ label: 'Configuration', value: prepared.config, previous: prepared.previous }], confirmLabel: 'Save draft' }),
49
+ run: ({ ctx, prepared }) => service().saveDraft({ principalId: ctx.principal.id, config: prepared.config, expectedDraftId: prepared.expectedDraftId, signal: ctx.signal }),
50
+ }, { flag: 'saved' }),
51
+ consent_publish_settings: approvalToolHandler({ surfaces,
52
+ prepare: async ({ ctx }) => {
53
+ const input = readConsentRequest({ body: ctx.input, fields: ['draftId', 'expectedPublishedId'] });
54
+ const state = await service().read({ principalId: ctx.principal.id });
55
+ const draftId = consentRevisionToken({ input, key: 'draftId' });
56
+ if (!draftId || state.draft?.id !== draftId)
57
+ throw new ToolInputError({ message: 'Reload the saved consent draft before publishing.' });
58
+ return { draftId, expectedPublishedId: consentRevisionToken({ input, key: 'expectedPublishedId' }), config: parseConsentConfig({ value: state.draft.config, bannerModeRefusal }), previous: state.effective };
59
+ },
60
+ describe: ({ prepared }) => ({ toolId: 'consent_publish_settings', errorCode: 'CONSENT', title: 'Publish this cookie consent policy?', details: [{ label: 'Revision', value: prepared.draftId }, { label: 'Configuration', value: prepared.config, previous: prepared.previous }], warning: prepared.config.enabled ? 'Visitors will be asked again for this policy revision.' : 'The banner and declared-script consent will be disabled. Optional scripts may run without a visitor choice.', confirmLabel: 'Publish policy' }),
61
+ run: ({ ctx, prepared }) => service().publish({ principalId: ctx.principal.id, draftId: prepared.draftId, expectedPublishedId: prepared.expectedPublishedId, signal: ctx.signal }),
62
+ }, { flag: 'published' }),
63
+ } });
64
+ }
65
+ /** Explicit composition contribution; no import-time registration or separate tool lifecycle. */
66
+ export function contributeConsentTools({ host }, _options = {}) {
67
+ return { domain: 'consent', build: (deps, surfaces) => buildConsentRegistrations({ ...deps, host }, surfaces), risk: consentDerivedRisk };
68
+ }
69
+ //# sourceMappingURL=tool-registrations.js.map
@@ -0,0 +1,21 @@
1
+ /** @file Site copy bounds plus Jini's policy-link and appearance validators. */
2
+ import type { ConsentConfig } from '../contract.js';
3
+ import type { ConsentProblem } from '@jini-ai/core/contracts/site/core-consent-refusal';
4
+ /** Strict full configuration input; every host field is explicit, including the on/off choice.
5
+ * Missing fields, unknown fields and type mismatches never reach persistence.
6
+ * Appearance values remain untrusted until Jini compiles them. O(n), n <= 32 KiB.
7
+ * @example parseConsentConfig({ value: { ...SITE_CONSENT_DEFAULTS, message: 'Our cookie policy.' } }) */
8
+ export declare function parseConsentConfig({ value, bannerModeRefusal }: {
9
+ value: unknown;
10
+ bannerModeRefusal?: string | undefined;
11
+ }, _options?: {}): ConsentConfig;
12
+ /** Readiness and publication share this decision. Jini is the only CSS/link authority. O(n). */
13
+ /** `cssBlocks: false` (cookie-consent engine): a bad CSS rule is dropped on its own and reported by the
14
+ * preview, so it never blocks publishing. */
15
+ export declare function consentConfigProblems({ config }: {
16
+ config: ConsentConfig;
17
+ trustedRegion: boolean;
18
+ }, { cssBlocks }?: {
19
+ cssBlocks?: boolean;
20
+ }): ConsentProblem[];
21
+ //# sourceMappingURL=validation.d.ts.map
@@ -0,0 +1,77 @@
1
+ import { compileConsentCss, safeHref } from '../render/index.js';
2
+ import { ToolInputError } from '@jini-ai/core';
3
+ import { SITE_CONSENT_BANNER_MODES, SITE_CONSENT_DEFAULTS, SITE_CONSENT_PLACEMENTS, SITE_CONSENT_REGION_MODES, SITE_CONSENT_TEXT_LIMITS } from './config.js';
4
+ const FIELDS = [...Object.keys(SITE_CONSENT_DEFAULTS), 'appearance', 'customCss', 'allowUnsafeEval', 'reopen', 'bannerMode'];
5
+ /** Strict full configuration input; every host field is explicit, including the on/off choice.
6
+ * Missing fields, unknown fields and type mismatches never reach persistence.
7
+ * Appearance values remain untrusted until Jini compiles them. O(n), n <= 32 KiB.
8
+ * @example parseConsentConfig({ value: { ...SITE_CONSENT_DEFAULTS, message: 'Our cookie policy.' } }) */
9
+ export function parseConsentConfig({ value, bannerModeRefusal }, _options = {}) {
10
+ if (!value || typeof value !== 'object' || Array.isArray(value))
11
+ throw new ToolInputError({ message: 'config must be a JSON object.' });
12
+ const raw = value;
13
+ if (Object.keys(raw).some(key => !FIELDS.includes(key)))
14
+ throw new ToolInputError({ message: 'Unknown consent configuration field. Categories are fixed by the consent engine.' });
15
+ for (const [key, fallback] of Object.entries(SITE_CONSENT_DEFAULTS)) {
16
+ if (!Object.prototype.hasOwnProperty.call(raw, key) || typeof raw[key] !== typeof fallback)
17
+ throw new ToolInputError({ message: `Invalid consent field: ${key}.` });
18
+ }
19
+ validateConsentOptions({ raw, bannerModeRefusal });
20
+ const config = { ...raw };
21
+ validateConsentCopy({ config });
22
+ validateConsentAppearanceShape({ raw });
23
+ if (JSON.stringify(config).length > 32_768)
24
+ throw new ToolInputError({ message: 'Consent configuration exceeds 32 KiB.' });
25
+ return config;
26
+ }
27
+ /** Host copy has bounded plain text and fixed engine-supported presets; never trusted markup. */
28
+ function validateConsentCopy({ config }, _options = {}) {
29
+ if (!SITE_CONSENT_REGION_MODES.includes(config.regionMode) || !SITE_CONSENT_PLACEMENTS.includes(config.placement))
30
+ throw new ToolInputError({ message: 'Choose a supported region mode and placement.' });
31
+ if (config.policyVersion.trim().length < 1 || config.policyVersion.length > 64)
32
+ throw new ToolInputError({ message: 'policyVersion must contain 1–64 characters.' });
33
+ validateConsentTextFields({ config });
34
+ if (config.privacyPolicyUrl.length > 2000 || config.secondaryLinkUrl.length > 2000)
35
+ throw new ToolInputError({ message: 'Policy links must be at most 2000 characters.' });
36
+ }
37
+ /** Banner fields share copy bounds; only the secondary link label may be empty. */
38
+ function validateConsentTextFields({ config }, _options = {}) {
39
+ for (const [key, max] of Object.entries(SITE_CONSENT_TEXT_LIMITS)) {
40
+ const text = config[key];
41
+ const emptyAllowed = key === 'secondaryLinkLabel' && text.length === 0;
42
+ if (text.length > max || (!emptyAllowed && !text.trim()))
43
+ throw new ToolInputError({ message: `${key} must contain 1–${max} characters.` });
44
+ }
45
+ }
46
+ /** The engine diagnoses CSS semantics; the boundary caps its input and refuses non-object tokens. */
47
+ function validateConsentAppearanceShape({ raw }, _options = {}) {
48
+ if (raw.customCss !== undefined && (typeof raw.customCss !== 'string' || raw.customCss.length > 16_384))
49
+ throw new ToolInputError({ message: 'customCss must be a string of at most 16384 characters.' });
50
+ if (raw.appearance !== undefined && (!raw.appearance || typeof raw.appearance !== 'object' || Array.isArray(raw.appearance)))
51
+ throw new ToolInputError({ message: 'appearance must be a token object.' });
52
+ }
53
+ /** The compiler's own defaults ('' and {}), spelled out for exact optional property types. O(1). */
54
+ const cssSource = ({ config }, _optional = {}) => ({ css: config.customCss ?? '', tokens: config.appearance ?? {} });
55
+ /** Readiness and publication share this decision. Jini is the only CSS/link authority. O(n). */
56
+ /** `cssBlocks: false` (cookie-consent engine): a bad CSS rule is dropped on its own and reported by the
57
+ * preview, so it never blocks publishing. */
58
+ export function consentConfigProblems({ config }, { cssBlocks = true } = {}) {
59
+ const problems = cssBlocks ? compileConsentCss(cssSource({ config })).problems.map(problem => ({ ...problem, field: 'appearance' })) : [];
60
+ if (config.enabled && !safeHref({ url: config.privacyPolicyUrl }))
61
+ problems.push({ code: 'PRIVACY_LINK_REQUIRED', field: 'privacyPolicyUrl', message: 'Link a published privacy page or a credential-free HTTPS privacy policy.' });
62
+ if (Boolean(config.secondaryLinkLabel) !== Boolean(config.secondaryLinkUrl) || (config.secondaryLinkUrl && !safeHref({ url: config.secondaryLinkUrl })))
63
+ problems.push({ code: 'SECONDARY_LINK_INVALID', field: 'secondaryLinkUrl', message: 'Supply both a secondary link label and a local or HTTPS link.' });
64
+ if (config.regionMode === 'opt-out')
65
+ problems.push({ code: 'GLOBAL_OPT_OUT_REFUSED', field: 'regionMode', message: 'Use automatic region mode for US opt-out. EU, UK and unknown regions must keep Reject.' });
66
+ return problems;
67
+ }
68
+ /** Optional engine fields stay outside required defaults so older snapshots still parse. */
69
+ function validateConsentOptions({ raw, bannerModeRefusal }, _options = {}) {
70
+ if ('allowUnsafeEval' in raw && typeof raw.allowUnsafeEval !== 'boolean')
71
+ throw new ToolInputError({ message: 'allowUnsafeEval must be a boolean.' });
72
+ if ('reopen' in raw && raw.reopen !== 'link')
73
+ throw new ToolInputError({ message: 'Cookie preferences reopen through a link.' });
74
+ if ('bannerMode' in raw && !SITE_CONSENT_BANNER_MODES.includes(raw.bannerMode))
75
+ throw new ToolInputError({ message: bannerModeRefusal ?? 'Choose the built-in banner, your own banner, or none.' });
76
+ }
77
+ //# sourceMappingURL=validation.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/cookie-consent",
3
- "version": "0.7.3-next.2",
3
+ "version": "0.7.4",
4
4
  "description": "Standalone, vendor-free cookie consent: a consent-state contract any banner can drive, a ~3 KB browser client, a pure-string banner renderer with owner CSS, web-standard receipts and open plugin slots.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -15,8 +15,25 @@
15
15
  "isolation": {
16
16
  "entries": {
17
17
  "./client.min.js": "client",
18
- "./extensions.min.js": "client"
19
- }
18
+ "./extensions.min.js": "client",
19
+ "./site/cookie-consent": "render",
20
+ "./site/http": "render",
21
+ "./site/validation": "render",
22
+ "./site/service": "render",
23
+ "./site/tool-registrations": "render",
24
+ "./site/document-state": "render",
25
+ "./site/document-assets": "render"
26
+ },
27
+ "shared": [
28
+ "src/site/config.ts",
29
+ "src/site/validation.ts",
30
+ "src/site/cookie-consent.ts",
31
+ "src/render/css.ts",
32
+ "src/server/region.ts",
33
+ "src/server/receipt.ts",
34
+ "src/site/revisions.ts",
35
+ "src/site/readiness.ts"
36
+ ]
20
37
  },
21
38
  "entries": {
22
39
  ".": "universal",
@@ -29,10 +46,29 @@
29
46
  "./banner.css": "browser",
30
47
  "./server": "universal",
31
48
  "./node": "node",
32
- "./extensions.min.js": "browser"
49
+ "./extensions.min.js": "browser",
50
+ "./site/config": "universal",
51
+ "./site/pre-consent-cache": "universal",
52
+ "./site/cookie-consent": "universal",
53
+ "./site/http": "universal",
54
+ "./site/validation": "universal",
55
+ "./site/revisions": "universal",
56
+ "./site/privacy-page-template": "universal",
57
+ "./site/settings": "universal",
58
+ "./site/readiness": "node",
59
+ "./site/service": "node",
60
+ "./site/region-plugins": "universal",
61
+ "./site/ensure-privacy-defaults": "universal",
62
+ "./site/tool-registrations": "node",
63
+ "./site/request": "universal",
64
+ "./site/revisions.repo": "node",
65
+ "./site/document-state": "universal",
66
+ "./site/document-assets": "universal",
67
+ "./contract": "universal"
33
68
  },
34
69
  "optionalPeers": {
35
- "react": "opt-in: react consent settings; import @jini-ai/cookie-consent/react — React consent settings could not load react. Install react to enable this feature, or check its installed version."
70
+ "react": "opt-in: react consent settings; import @jini-ai/cookie-consent/react — React consent settings could not load react. Install react to enable this feature, or check its installed version.",
71
+ "kysely": "opt-in: SQL consent revisions; import @jini-ai/cookie-consent/site/revisions.repo — Install kysely to use the site consent SQL store."
36
72
  }
37
73
  },
38
74
  "type": "module",
@@ -43,6 +79,11 @@
43
79
  "main": "./dist/contract.js",
44
80
  "types": "./dist/contract.d.ts",
45
81
  "exports": {
82
+ "./site/pre-consent-cache": {
83
+ "types": "./dist/site/pre-consent-cache.d.ts",
84
+ "import": "./dist/site/pre-consent-cache.js",
85
+ "default": "./dist/site/pre-consent-cache.js"
86
+ },
46
87
  ".": {
47
88
  "types": "./dist/contract.d.ts",
48
89
  "import": "./dist/contract.js",
@@ -85,7 +126,92 @@
85
126
  "import": "./dist/node/index.js",
86
127
  "default": "./dist/node/index.js"
87
128
  },
88
- "./extensions.min.js": "./dist/extensions.min.js"
129
+ "./extensions.min.js": "./dist/extensions.min.js",
130
+ "./site/config": {
131
+ "types": "./dist/site/config.d.ts",
132
+ "import": "./dist/site/config.js",
133
+ "default": "./dist/site/config.js"
134
+ },
135
+ "./site/http": {
136
+ "types": "./dist/site/http.d.ts",
137
+ "import": "./dist/site/http.js",
138
+ "default": "./dist/site/http.js"
139
+ },
140
+ "./site/cookie-consent": {
141
+ "types": "./dist/site/cookie-consent.d.ts",
142
+ "import": "./dist/site/cookie-consent.js",
143
+ "default": "./dist/site/cookie-consent.js"
144
+ },
145
+ "./site/validation": {
146
+ "types": "./dist/site/validation.d.ts",
147
+ "import": "./dist/site/validation.js",
148
+ "default": "./dist/site/validation.js"
149
+ },
150
+ "./site/revisions": {
151
+ "types": "./dist/site/revisions.d.ts",
152
+ "import": "./dist/site/revisions.js",
153
+ "default": "./dist/site/revisions.js"
154
+ },
155
+ "./site/privacy-page-template": {
156
+ "types": "./dist/site/privacy-page-template.d.ts",
157
+ "import": "./dist/site/privacy-page-template.js",
158
+ "default": "./dist/site/privacy-page-template.js"
159
+ },
160
+ "./site/settings": {
161
+ "types": "./dist/site/settings.d.ts",
162
+ "import": "./dist/site/settings.js",
163
+ "default": "./dist/site/settings.js"
164
+ },
165
+ "./site/readiness": {
166
+ "types": "./dist/site/readiness.d.ts",
167
+ "import": "./dist/site/readiness.js",
168
+ "default": "./dist/site/readiness.js"
169
+ },
170
+ "./site/service": {
171
+ "types": "./dist/site/service.d.ts",
172
+ "import": "./dist/site/service.js",
173
+ "default": "./dist/site/service.js"
174
+ },
175
+ "./site/region-plugins": {
176
+ "types": "./dist/site/region-plugins.d.ts",
177
+ "import": "./dist/site/region-plugins.js",
178
+ "default": "./dist/site/region-plugins.js"
179
+ },
180
+ "./site/ensure-privacy-defaults": {
181
+ "types": "./dist/site/ensure-privacy-defaults.d.ts",
182
+ "import": "./dist/site/ensure-privacy-defaults.js",
183
+ "default": "./dist/site/ensure-privacy-defaults.js"
184
+ },
185
+ "./site/tool-registrations": {
186
+ "types": "./dist/site/tool-registrations.d.ts",
187
+ "import": "./dist/site/tool-registrations.js",
188
+ "default": "./dist/site/tool-registrations.js"
189
+ },
190
+ "./site/request": {
191
+ "types": "./dist/site/request.d.ts",
192
+ "import": "./dist/site/request.js",
193
+ "default": "./dist/site/request.js"
194
+ },
195
+ "./site/revisions.repo": {
196
+ "types": "./dist/site/revisions.repo.d.ts",
197
+ "import": "./dist/site/revisions.repo.js",
198
+ "default": "./dist/site/revisions.repo.js"
199
+ },
200
+ "./site/document-state": {
201
+ "types": "./dist/site/document-state.d.ts",
202
+ "import": "./dist/site/document-state.js",
203
+ "default": "./dist/site/document-state.js"
204
+ },
205
+ "./site/document-assets": {
206
+ "types": "./dist/site/document-assets.d.ts",
207
+ "import": "./dist/site/document-assets.js",
208
+ "default": "./dist/site/document-assets.js"
209
+ },
210
+ "./contract": {
211
+ "types": "./dist/contract.d.ts",
212
+ "import": "./dist/contract.js",
213
+ "default": "./dist/contract.js"
214
+ }
89
215
  },
90
216
  "files": [
91
217
  "dist",
@@ -98,7 +224,10 @@
98
224
  "access": "public",
99
225
  "registry": "https://registry.npmjs.org"
100
226
  },
101
- "dependencies": {},
227
+ "dependencies": {
228
+ "parse5": "^7.3.0",
229
+ "@jini-ai/core": "^0.7.4"
230
+ },
102
231
  "devDependencies": {
103
232
  "@testing-library/jest-dom": "^6.6.3",
104
233
  "@testing-library/react": "^16.3.0",
@@ -111,14 +240,19 @@
111
240
  "react": "^19.2.0",
112
241
  "react-dom": "^19.2.0",
113
242
  "typescript": "^5.6.0",
114
- "vitest": "^3.2.6"
243
+ "vitest": "^3.2.6",
244
+ "kysely": "^0.29.6"
115
245
  },
116
246
  "peerDependencies": {
117
- "react": "^18.3.0 || ^19.0.0"
247
+ "react": "^18.3.0 || ^19.0.0",
248
+ "kysely": "^0.29.6"
118
249
  },
119
250
  "peerDependenciesMeta": {
120
251
  "react": {
121
252
  "optional": true
253
+ },
254
+ "kysely": {
255
+ "optional": true
122
256
  }
123
257
  },
124
258
  "scripts": {