@truzyx/consent-widget 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Truzyx
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,147 @@
1
- # Temporary Holding Version
1
+ # @truzyx/consent-widget
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Framework-agnostic consent + preferences widget for third-party sites. Opens the Truzyx consent gateway (consent dialog or preferences dialog) in a modal iframe overlay. Zero runtime dependencies for the vanilla entry; the React entry needs only `react` (optional peer).
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @truzyx/consent-widget
9
+ ```
10
+
11
+ No bundler? Use the script-tag build served from your gateway host instead (global `window.ConsentWidget`, same API):
12
+
13
+ ```html
14
+ <script src="https://<gateway-host>/consent-widget.js"></script>
15
+ ```
16
+
17
+ ## What you need before integrating
18
+
19
+ | Value | Where it comes from |
20
+ |-----------|---------------------|
21
+ | `baseUrl` | Your gateway origin, e.g. `https://consent.truzyx.com`. Optional — defaults to the origin of the `<script src=".../consent-widget.js">` tag, or `window.location.origin`. |
22
+ | `token` | Principal JWT for the end user, issued by your backend. Sent to the gateway as `?auth_token=` and via `postMessage`. |
23
+ | `requestId` | Consent request id created via the gateway API. Required for the consent dialog only. |
24
+
25
+ ## Usage
26
+
27
+ ### Plain JS / Vue / Angular / Svelte (vanilla entry)
28
+
29
+ ```ts
30
+ import { ConsentWidget } from "@truzyx/consent-widget";
31
+
32
+ // Consent dialog for a request
33
+ ConsentWidget.openConsent("req_123", "<principal-jwt>", {
34
+ baseUrl: "https://consent.truzyx.com", // optional
35
+ });
36
+
37
+ // Or preferences dialog (my consents + grievances, no requestId)
38
+ ConsentWidget.openPreferences("<principal-jwt>", {
39
+ baseUrl: "https://consent.truzyx.com",
40
+ });
41
+
42
+ // React to flow completion
43
+ const off = ConsentWidget.onCallback((event) => {
44
+ console.log(event.type, event);
45
+ if (event.type === "consent_accepted") {
46
+ // refresh your UI, then optionally:
47
+ // ConsentWidget.close();
48
+ }
49
+ });
50
+ // off(); // unsubscribe later
51
+
52
+ // Programmatic close
53
+ ConsentWidget.close();
54
+ ```
55
+
56
+ ### React (hook entry)
57
+
58
+ ```tsx
59
+ import { useConsentWidget } from "@truzyx/consent-widget/react";
60
+
61
+ function CheckoutButton() {
62
+ const { openConsent, close } = useConsentWidget({
63
+ onEvent: (e) => {
64
+ if (e.type === "consent_accepted") console.log("accepted:", e.requestId);
65
+ if (e.type === "error") console.error(e.message);
66
+ },
67
+ });
68
+
69
+ return (
70
+ <button onClick={() => openConsent("req_123", "<principal-jwt>", { baseUrl: "https://consent.truzyx.com" })}>
71
+ Review consent
72
+ </button>
73
+ );
74
+ }
75
+ ```
76
+
77
+ The hook subscribes/unsubscribes the callback automatically and closes the dialog if the component unmounts (`closeOnUnmount: true` by default; set `false` to opt out). No JSX component is provided — the dialog is imperative by design so it behaves identically in any tree.
78
+
79
+ ### Script tag (no build step)
80
+
81
+ ```html
82
+ <script src="https://<gateway-host>/consent-widget.js"></script>
83
+ <script>
84
+ ConsentWidget.openConsent("req_123", "<principal-jwt>");
85
+ ConsentWidget.onCallback((e) => console.log(e.type, e));
86
+ // ConsentWidget.close();
87
+ </script>
88
+ ```
89
+
90
+ ## API reference
91
+
92
+ ### Methods (vanilla singleton and hook return value)
93
+
94
+ | Method | Signature | Description |
95
+ |--------|-----------|-------------|
96
+ | `openConsent` | `(requestId, token, opts?) => void` | Open the consent dialog for a request. Replaces any open dialog. |
97
+ | `openPreferences` | `(token, opts?) => void` | Open the preferences dialog. Replaces any open dialog. |
98
+ | `openDirectConsent` | `(purposeIds, token, opts?) => void` | Open the direct-consent dialog for one or more purpose ids (`string \| string[]`, sent as `?purpose_id=`). `opts` adds `orgId` (`?org_id=`) and `locale` (`?locale=`). |
99
+ | `onCallback` | `(cb: WidgetCallback) => () => void` | Subscribe to every flow event. Returns an unsubscribe function. |
100
+ | `close` | `(event?) => void` | Close the dialog; emits a `closed` event if one was open. |
101
+ | `destroy` | `() => void` | Clear all callbacks and close without emitting. |
102
+ | `isOpen` | `() => boolean` | Whether the dialog is open. |
103
+
104
+ ### `WidgetInitOptions`
105
+
106
+ | Field | Type | Default | Description |
107
+ |-------|------|---------|-------------|
108
+ | `token` | `string` | — (required) | Principal JWT. |
109
+ | `requestId` | `string` | — | Consent request id. Required for `mode: "consent"`. |
110
+ | `mode` | `"consent" \| "preferences"` | `"consent"` if `requestId` is set, else `"preferences"` | Which dialog to open. |
111
+ | `baseUrl` | `string` | script-tag origin, else current origin | Gateway origin. Optional — when provided it wins and `env` is ignored. |
112
+ | `env` | `"live" \| "sandbox"` | — (no default) | Picks the gateway host when `baseUrl` is omitted: live → `https://ui.gateway.nodbook.in`, sandbox → `https://sandbox-ui.gateway.nodbook.in`. |
113
+ | `autoClose` | `boolean` | `true` | Auto-close on terminal events (`consent_accepted`, `consent_declined`, `already_resolved`, `redirecting`). |
114
+ | `allowClose` | `boolean` | `true` | Show × button; allow ESC and backdrop click to close. |
115
+ | `width` / `height` | `number` | `600` / `640` | Dialog size in px, capped to the viewport. |
116
+
117
+ ### `WidgetEvent` (delivered to `onCallback`)
118
+
119
+ | `type` | Extra fields | Meaning |
120
+ |--------|--------------|---------|
121
+ | `opened` | `requestId?` | Dialog opened. |
122
+ | `consent_accepted` | `requestId?` | User accepted (all or selected purposes). |
123
+ | `consent_declined` | `requestId?` | User declined/cancelled. |
124
+ | `already_resolved` | `requestId?` | Request was already approved/declined. |
125
+ | `redirecting` | `requestId?`, `redirectUrl` | Gateway is redirecting (e.g. back to your site). |
126
+ | `error` | `requestId?`, `message?` | Load/submit failure. |
127
+ | `closed` | `requestId?` | Dialog closed (×, ESC, backdrop, or `close()`). |
128
+
129
+ ## How it works
130
+
131
+ - The widget renders a modal overlay with an `<iframe>` pointing at `{baseUrl}/consent_manager/consent/{requestId}` or `{baseUrl}/consent_manager/preferences`, with `?auth_token=<token>&embed=true&origin=<your-origin>`.
132
+ - The token is also delivered via `postMessage` (`PRINCIPAL_TOKEN`) when the iframe signals readiness.
133
+ - Flow completion is reported back as `CONSENT_WIDGET_EVENT` messages, validated against the gateway origin, and fanned out to your callbacks. In embed mode the gateway pages render chromeless (no extra card/background) so only the widget's single card is visible.
134
+ - Because the dialog is an iframe, there is no CSS leakage in either direction.
135
+
136
+ ## Trying it locally
137
+
138
+ The gateway repo ships a dev harness at `/consent_manager/check` (query params `requestId`, `token`/`auth_token`, `baseUrl`) that drives this same core and logs every callback event — useful to validate your `requestId`/`token` before integrating.
139
+
140
+ ## Package layout
141
+
142
+ | Entry | Files | Use |
143
+ |-------|-------|-----|
144
+ | `.` | `dist/index.js` (ESM), `dist/index.cjs` (CJS), `dist/index.d.ts` | Any framework / plain JS. |
145
+ | `./react` | `dist/react.js`, `dist/react.cjs`, `dist/react.d.ts` | `useConsentWidget` hook (`react` stays external). |
146
+
147
+ Source of truth is `src/core/` (`widget.ts`, `types.ts`). Version: `0.1.0`.
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Shared types + message contract for the third-party consent widget.
3
+ *
4
+ * This is the source of truth, published via `@truzyx/consent-widget`.
5
+ * The widget itself runs on the THIRD-PARTY site (IIFE script-tag build or
6
+ * npm ESM/CJS import) and opens the gateway consent / preferences pages in
7
+ * an iframe overlay.
8
+ *
9
+ * `bridge.ts` (gateway side, NOT published) posts completion events back to
10
+ * the parent so `onCallback` fires.
11
+ */
12
+ export type WidgetMode = "consent" | "preferences" | "direct_consent";
13
+ /** Gateway environment. Maps to a default `baseUrl` (see `GATEWAY_BASE_URLS`). */
14
+ export type WidgetEnv = "live" | "sandbox";
15
+ export declare const GATEWAY_BASE_URLS: Record<WidgetEnv, string>;
16
+ export type WidgetEventType = "opened" | "closed" | "consent_accepted" | "consent_declined" | "already_resolved" | "redirecting" | "error";
17
+ export interface WidgetEvent {
18
+ type: WidgetEventType;
19
+ requestId?: string;
20
+ /** redirect target when type === "redirecting" */
21
+ redirectUrl?: string | null;
22
+ /** raw error message when type === "error" */
23
+ message?: string;
24
+ /** passthrough of any extra data the gateway page attaches */
25
+ data?: unknown;
26
+ }
27
+ export type WidgetCallback = (event: WidgetEvent) => void;
28
+ export interface WidgetInitOptions {
29
+ /** Consent request id. Required for mode "consent", omitted for "preferences". */
30
+ requestId?: string;
31
+ /** Principal JWT used by the gateway APIs (sent as ?auth_token= + postMessage). */
32
+ token: string;
33
+ /** Which dialog to open. Defaults to "consent" when requestId is present. */
34
+ mode?: WidgetMode;
35
+ /**
36
+ * Gateway origin, e.g. "https://consent.truzyx.com".
37
+ * Optional. When provided it wins and `env` is ignored.
38
+ * When omitted, resolved from `env`, else from the
39
+ * <script src=".../consent-widget.js"> tag origin.
40
+ */
41
+ baseUrl?: string;
42
+ /** Gateway environment used when `baseUrl` is omitted. No default. */
43
+ env?: WidgetEnv;
44
+ /** Auto-close the overlay after a terminal event (accepted/declined/resolved). Default true. */
45
+ autoClose?: boolean;
46
+ /** Show an × button + allow ESC/backdrop click to close. Default true. */
47
+ allowClose?: boolean;
48
+ /** Dialog width/height. Defaults 600x640, capped to viewport. */
49
+ width?: number;
50
+ height?: number;
51
+ }
52
+ export interface OpenConsentOptions extends Omit<WidgetInitOptions, "requestId" | "mode" | "token"> {
53
+ token?: WidgetInitOptions["token"];
54
+ }
55
+ export interface OpenPreferencesOptions extends Omit<WidgetInitOptions, "requestId" | "mode" | "token"> {
56
+ token?: WidgetInitOptions["token"];
57
+ }
58
+ export interface OpenDirectConsentOptions extends Omit<WidgetInitOptions, "requestId" | "mode" | "token"> {
59
+ token?: WidgetInitOptions["token"];
60
+ /** Organisation id, sent as `?org_id=`. */
61
+ orgId?: string | null;
62
+ /** Locale hint, sent as `?locale=`. */
63
+ locale?: string;
64
+ }
65
+ /** postMessage wire format: iframe (gateway) -> parent (third-party site). */
66
+ export declare const WIDGET_EVENT_MESSAGE = "CONSENT_WIDGET_EVENT";
67
+ /** postMessage wire format: iframe -> parent "i am ready, send me the token". */
68
+ export declare const GATEWAY_UI_READY = "GATEWAY_UI_READY";
69
+ /** postMessage wire format: parent -> iframe token delivery. */
70
+ export declare const PRINCIPAL_TOKEN_MESSAGE = "PRINCIPAL_TOKEN";
71
+ export interface WidgetWireMessage {
72
+ type: typeof WIDGET_EVENT_MESSAGE;
73
+ event: WidgetEvent;
74
+ }
75
+ export interface ReadyWireMessage {
76
+ type: typeof GATEWAY_UI_READY;
77
+ }
78
+ export interface TokenWireMessage {
79
+ type: typeof PRINCIPAL_TOKEN_MESSAGE;
80
+ token: string;
81
+ }
82
+ export declare function isWidgetWireMessage(data: unknown): data is WidgetWireMessage;
83
+ export declare function isReadyWireMessage(data: unknown): data is ReadyWireMessage;
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Third-party embed widget (vanilla TS, zero dependencies).
3
+ *
4
+ * Published via `@truzyx/consent-widget` as framework-agnostic ESM/CJS
5
+ * (works in React, Vue, Angular, Svelte, plain JS):
6
+ *
7
+ * import { ConsentWidget } from "@truzyx/consent-widget";
8
+ * ConsentWidget.openConsent("req_123", "jwt...");
9
+ * ConsentWidget.onCallback((e) => console.log(e.type, e));
10
+ * // ConsentWidget.close();
11
+ *
12
+ * Also bundled as a self-sufficient IIFE file (`dist/consent-widget.js`) for
13
+ * plain <script> inclusion (see `vite.widget.config.ts` at the repo root).
14
+ *
15
+ * How it works: opens the gateway consent / preferences page in a modal
16
+ * iframe overlay. Auth token travels as `?auth_token=` (already supported by
17
+ * `usePrincipalTokenHandshake`) and via postMessage PRINCIPAL_TOKEN.
18
+ * Completion events flow back as CONSENT_WIDGET_EVENT messages and are
19
+ * fanned out to `onCallback`.
20
+ */
21
+ import { type OpenConsentOptions, type OpenDirectConsentOptions, type OpenPreferencesOptions, type WidgetCallback, type WidgetEvent, type WidgetInitOptions } from "./types";
22
+ declare class ConsentWidgetImpl {
23
+ private overlay;
24
+ private iframe;
25
+ private session;
26
+ private callbacks;
27
+ private listening;
28
+ private escHandler;
29
+ private messageHandler;
30
+ /** Open the consent dialog for a request. */
31
+ openConsent(requestId: string, token: string, opts?: OpenConsentOptions): void;
32
+ /** Open the preferences (my consents + grievances) dialog. */
33
+ openPreferences(token: string, opts?: OpenPreferencesOptions): void;
34
+ /** Open the direct-consent (permission-style) dialog for purpose(s). */
35
+ openDirectConsent(purposeIds: string | string[], token: string, opts?: OpenDirectConsentOptions): void;
36
+ /**
37
+ * Shared opener behind `openConsent` / `openPreferences` / `openDirectConsent`.
38
+ * The view follows `mode`, defaulting from `requestId`: set → consent
39
+ * dialog, omitted → preferences dialog.
40
+ */
41
+ private openDialog;
42
+ /**
43
+ * Register a callback invoked on every flow event
44
+ * (opened / consent_accepted / consent_declined / already_resolved /
45
+ * redirecting / error / closed). Returns an unsubscribe function.
46
+ */
47
+ onCallback(cb: WidgetCallback): () => void;
48
+ /** Programmatically close the dialog (emits a `closed` event). */
49
+ close(event?: WidgetEvent): void;
50
+ /** Alias of close() without emitting when already closed. */
51
+ destroy(): void;
52
+ isOpen(): boolean;
53
+ private open;
54
+ private ensureListening;
55
+ private render;
56
+ private teardown;
57
+ private emit;
58
+ }
59
+ export declare const ConsentWidget: ConsentWidgetImpl;
60
+ export type { WidgetInitOptions, WidgetEvent, WidgetCallback };
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";var p=Object.defineProperty;var y=(n,e,t)=>e in n?p(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var s=(n,e,t)=>y(n,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const c={live:"https://ui.gateway.nodbook.in",sandbox:"https://sandbox-ui.gateway.nodbook.in"},b="CONSENT_WIDGET_EVENT",h="GATEWAY_UI_READY",u="PRINCIPAL_TOKEN";function E(n){return typeof n=="object"&&n!==null&&n.type===b&&typeof n.event=="object"}function _(n){return typeof n=="object"&&n!==null&&n.type===h}const I="__consent_widget_overlay__",k=600,x=640;function A(n,e){var t;if(n)return n.replace(/\/$/,"");if(e&&c[e])return c[e];try{const r=document.getElementsByTagName("script");for(let i=r.length-1;i>=0;i--){const a=((t=r[i])==null?void 0:t.getAttribute("src"))??"";if(a.includes("consent-widget"))return new URL(a,window.location.href).origin}const o=document.currentScript;if(o!=null&&o.src)return new URL(o.src,window.location.href).origin}catch{}return window.location.origin}function C(n){var t;const e=new URLSearchParams({auth_token:n.token,embed:"true",origin:window.location.origin});return n.mode==="preferences"?`${n.baseUrl}/consent_manager/preferences?${e.toString()}`:n.mode==="direct_consent"?((t=n.purposeIds)!=null&&t.length&&e.set("purpose_id",n.purposeIds.join(",")),n.orgId&&e.set("org_id",n.orgId),n.locale&&e.set("locale",n.locale),`${n.baseUrl}/consent_manager/direct_consent?${e.toString()}`):`${n.baseUrl}/consent_manager/consent/${encodeURIComponent(n.requestId??"")}?${e.toString()}`}class v{constructor(){s(this,"overlay",null);s(this,"iframe",null);s(this,"session",null);s(this,"callbacks",new Set);s(this,"listening",!1);s(this,"escHandler",e=>{var t;e.key==="Escape"&&this.close({type:"closed",requestId:(t=this.session)==null?void 0:t.requestId})});s(this,"messageHandler",e=>{var r,o;if(!this.session||!this.iframe)return;let t="";try{t=new URL(this.session.baseUrl).origin}catch{t=""}if(!(t&&e.origin!==t)&&e.source===this.iframe.contentWindow){if(_(e.data)){try{(r=this.iframe.contentWindow)==null||r.postMessage({type:u,token:this.session.token},t||"*")}catch{}return}if(typeof e.data=="object"&&e.data!==null&&e.data.type===h){try{(o=this.iframe.contentWindow)==null||o.postMessage({type:u,token:this.session.token},t||"*")}catch{}return}if(E(e.data)){const i=e.data.event;this.emit(i),this.session.autoClose&&(i.type==="consent_accepted"||i.type==="consent_declined"||i.type==="already_resolved"||i.type==="redirecting")&&this.teardown()}}})}openConsent(e,t,r){this.openDialog({...r,requestId:e,token:(r==null?void 0:r.token)??t})}openPreferences(e,t){this.openDialog({...t,token:(t==null?void 0:t.token)??e})}openDirectConsent(e,t,r){const o=(Array.isArray(e)?e:[e]).map(i=>i.trim()).filter(Boolean);if(o.length===0)throw new Error("ConsentWidget.openDirectConsent: at least one `purposeId` is required.");this.openDialog({...r,purposeIds:o,token:(r==null?void 0:r.token)??t,mode:"direct_consent"})}openDialog(e){var r;if(!e||typeof e.token!="string"||e.token.length===0)throw new Error("ConsentWidget: `token` is required.");const t=e.mode??(e.requestId?"consent":"preferences");if(t==="consent"&&!e.requestId)throw new Error("ConsentWidget: `requestId` is required for the consent dialog.");this.open({requestId:e.requestId,token:e.token,mode:t,purposeIds:e.purposeIds,orgId:e.orgId??null,locale:e.locale,baseUrl:A(e.baseUrl,e.env),autoClose:e.autoClose??!0}),this.render(e.allowClose??!0,e.width??k,e.height??x),this.emit({type:"opened",requestId:e.requestId,data:(r=e.purposeIds)!=null&&r.length?{purposeIds:e.purposeIds}:void 0})}onCallback(e){return this.callbacks.add(e),()=>{this.callbacks.delete(e)}}close(e){var o;const t=e??{type:"closed",requestId:(o=this.session)==null?void 0:o.requestId},r=this.overlay!==null;this.teardown(),r&&this.emit(t)}destroy(){this.callbacks.clear(),this.teardown()}isOpen(){return this.overlay!==null}open(e){this.teardown(),this.session=e,this.ensureListening()}ensureListening(){this.listening||(window.addEventListener("message",this.messageHandler),window.addEventListener("keydown",this.escHandler),this.listening=!0)}render(e,t,r){if(!this.session)return;const o=C(this.session),i=document.createElement("div");i.id=I,i.setAttribute("role","dialog"),i.setAttribute("aria-modal","true"),i.style.cssText=["position:fixed","inset:0","z-index:2147483647","display:flex","align-items:center","justify-content:center","background:rgba(15,23,42,0.55)","padding:16px","box-sizing:border-box"].join(";");const a=document.createElement("div"),f=Math.min(t,window.innerWidth-32),m=Math.min(r,window.innerHeight-32);if(a.style.cssText=[`width:${f}px`,"max-width:100%",`height:${m}px`,"max-height:100%","background:#fff","border-radius:16px","overflow:hidden","position:relative","box-shadow:0 25px 50px -12px rgba(0,0,0,0.35)","display:flex","flex-direction:column"].join(";"),e){const l=document.createElement("button");l.setAttribute("aria-label","Close"),l.textContent="×",l.style.cssText=["position:absolute","top:8px","right:12px","z-index:2","width:28px","height:28px","border-radius:9999px","border:none","background:rgba(15,23,42,0.06)","color:#475569","font-size:18px","line-height:1","cursor:pointer"].join(";"),l.onclick=()=>this.close(),a.appendChild(l),i.addEventListener("mousedown",w=>{w.target===i&&this.close()})}const d=document.createElement("iframe");d.src=o,d.title="Consent manager",d.setAttribute("allow","clipboard-write"),d.style.cssText=["flex:1","width:100%","height:100%","border:0","background:#fff"].join(";"),a.appendChild(d),i.appendChild(a),document.body.appendChild(i),document.documentElement.style.overflow="hidden",this.overlay=i,this.iframe=d}teardown(){var e;(e=this.overlay)!=null&&e.parentNode&&this.overlay.parentNode.removeChild(this.overlay),this.overlay=null,this.iframe=null,this.session=null,this.listening&&(window.removeEventListener("message",this.messageHandler),window.removeEventListener("keydown",this.escHandler),this.listening=!1);try{document.documentElement.style.overflow=""}catch{}}emit(e){this.callbacks.forEach(t=>{try{t(e)}catch{}})}}const g=new v;exports.ConsentWidget=g;exports.GATEWAY_BASE_URLS=c;exports.default=g;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Framework-agnostic npm entry for `@truzyx/consent-widget`.
3
+ *
4
+ * Works in React, Vue, Angular, Svelte, or plain JS via ESM/CJS import
5
+ * (no global side effects — unlike the IIFE `dist/consent-widget.js`
6
+ * script-tag build, this entry does NOT touch `window` on import):
7
+ *
8
+ * import { ConsentWidget } from "@truzyx/consent-widget";
9
+ * ConsentWidget.openConsent("req_123", "jwt...");
10
+ * const off = ConsentWidget.onCallback((e) => console.log(e.type, e));
11
+ * // ConsentWidget.close();
12
+ *
13
+ * Zero runtime dependencies.
14
+ */
15
+ export { ConsentWidget } from "./core/widget";
16
+ import { ConsentWidget as ConsentWidgetDefault } from "./core/widget";
17
+ export default ConsentWidgetDefault;
18
+ export { GATEWAY_BASE_URLS } from "./core/types";
19
+ export type { WidgetCallback, WidgetEnv, WidgetEvent, WidgetEventType, WidgetInitOptions, WidgetMode, OpenConsentOptions, OpenDirectConsentOptions, OpenPreferencesOptions, } from "./core/types";
package/dist/index.js ADDED
@@ -0,0 +1,258 @@
1
+ var w = Object.defineProperty;
2
+ var p = (n, e, t) => e in n ? w(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t;
3
+ var s = (n, e, t) => p(n, typeof e != "symbol" ? e + "" : e, t);
4
+ const c = {
5
+ live: "https://ui.gateway.nodbook.in",
6
+ sandbox: "https://sandbox-ui.gateway.nodbook.in"
7
+ }, y = "CONSENT_WIDGET_EVENT", u = "GATEWAY_UI_READY", h = "PRINCIPAL_TOKEN";
8
+ function b(n) {
9
+ return typeof n == "object" && n !== null && n.type === y && typeof n.event == "object";
10
+ }
11
+ function E(n) {
12
+ return typeof n == "object" && n !== null && n.type === u;
13
+ }
14
+ const I = "__consent_widget_overlay__", _ = 600, k = 640;
15
+ function x(n, e) {
16
+ var t;
17
+ if (n) return n.replace(/\/$/, "");
18
+ if (e && c[e]) return c[e];
19
+ try {
20
+ const r = document.getElementsByTagName("script");
21
+ for (let i = r.length - 1; i >= 0; i--) {
22
+ const a = ((t = r[i]) == null ? void 0 : t.getAttribute("src")) ?? "";
23
+ if (a.includes("consent-widget"))
24
+ return new URL(a, window.location.href).origin;
25
+ }
26
+ const o = document.currentScript;
27
+ if (o != null && o.src) return new URL(o.src, window.location.href).origin;
28
+ } catch {
29
+ }
30
+ return window.location.origin;
31
+ }
32
+ function C(n) {
33
+ var t;
34
+ const e = new URLSearchParams({
35
+ auth_token: n.token,
36
+ embed: "true",
37
+ origin: window.location.origin
38
+ });
39
+ return n.mode === "preferences" ? `${n.baseUrl}/consent_manager/preferences?${e.toString()}` : n.mode === "direct_consent" ? ((t = n.purposeIds) != null && t.length && e.set("purpose_id", n.purposeIds.join(",")), n.orgId && e.set("org_id", n.orgId), n.locale && e.set("locale", n.locale), `${n.baseUrl}/consent_manager/direct_consent?${e.toString()}`) : `${n.baseUrl}/consent_manager/consent/${encodeURIComponent(n.requestId ?? "")}?${e.toString()}`;
40
+ }
41
+ class A {
42
+ constructor() {
43
+ s(this, "overlay", null);
44
+ s(this, "iframe", null);
45
+ s(this, "session", null);
46
+ s(this, "callbacks", /* @__PURE__ */ new Set());
47
+ s(this, "listening", !1);
48
+ s(this, "escHandler", (e) => {
49
+ var t;
50
+ e.key === "Escape" && this.close({ type: "closed", requestId: (t = this.session) == null ? void 0 : t.requestId });
51
+ });
52
+ s(this, "messageHandler", (e) => {
53
+ var r, o;
54
+ if (!this.session || !this.iframe) return;
55
+ let t = "";
56
+ try {
57
+ t = new URL(this.session.baseUrl).origin;
58
+ } catch {
59
+ t = "";
60
+ }
61
+ if (!(t && e.origin !== t) && e.source === this.iframe.contentWindow) {
62
+ if (E(e.data)) {
63
+ try {
64
+ (r = this.iframe.contentWindow) == null || r.postMessage(
65
+ { type: h, token: this.session.token },
66
+ t || "*"
67
+ );
68
+ } catch {
69
+ }
70
+ return;
71
+ }
72
+ if (typeof e.data == "object" && e.data !== null && e.data.type === u) {
73
+ try {
74
+ (o = this.iframe.contentWindow) == null || o.postMessage(
75
+ { type: h, token: this.session.token },
76
+ t || "*"
77
+ );
78
+ } catch {
79
+ }
80
+ return;
81
+ }
82
+ if (b(e.data)) {
83
+ const i = e.data.event;
84
+ this.emit(i), this.session.autoClose && (i.type === "consent_accepted" || i.type === "consent_declined" || i.type === "already_resolved" || i.type === "redirecting") && this.teardown();
85
+ }
86
+ }
87
+ });
88
+ }
89
+ /** Open the consent dialog for a request. */
90
+ openConsent(e, t, r) {
91
+ this.openDialog({
92
+ ...r,
93
+ requestId: e,
94
+ token: (r == null ? void 0 : r.token) ?? t
95
+ });
96
+ }
97
+ /** Open the preferences (my consents + grievances) dialog. */
98
+ openPreferences(e, t) {
99
+ this.openDialog({
100
+ ...t,
101
+ token: (t == null ? void 0 : t.token) ?? e
102
+ });
103
+ }
104
+ /** Open the direct-consent (permission-style) dialog for purpose(s). */
105
+ openDirectConsent(e, t, r) {
106
+ const o = (Array.isArray(e) ? e : [e]).map((i) => i.trim()).filter(Boolean);
107
+ if (o.length === 0)
108
+ throw new Error("ConsentWidget.openDirectConsent: at least one `purposeId` is required.");
109
+ this.openDialog({
110
+ ...r,
111
+ purposeIds: o,
112
+ token: (r == null ? void 0 : r.token) ?? t,
113
+ mode: "direct_consent"
114
+ });
115
+ }
116
+ /**
117
+ * Shared opener behind `openConsent` / `openPreferences` / `openDirectConsent`.
118
+ * The view follows `mode`, defaulting from `requestId`: set → consent
119
+ * dialog, omitted → preferences dialog.
120
+ */
121
+ openDialog(e) {
122
+ var r;
123
+ if (!e || typeof e.token != "string" || e.token.length === 0)
124
+ throw new Error("ConsentWidget: `token` is required.");
125
+ const t = e.mode ?? (e.requestId ? "consent" : "preferences");
126
+ if (t === "consent" && !e.requestId)
127
+ throw new Error("ConsentWidget: `requestId` is required for the consent dialog.");
128
+ this.open({
129
+ requestId: e.requestId,
130
+ token: e.token,
131
+ mode: t,
132
+ purposeIds: e.purposeIds,
133
+ orgId: e.orgId ?? null,
134
+ locale: e.locale,
135
+ baseUrl: x(e.baseUrl, e.env),
136
+ autoClose: e.autoClose ?? !0
137
+ }), this.render(
138
+ e.allowClose ?? !0,
139
+ e.width ?? _,
140
+ e.height ?? k
141
+ ), this.emit({
142
+ type: "opened",
143
+ requestId: e.requestId,
144
+ data: (r = e.purposeIds) != null && r.length ? { purposeIds: e.purposeIds } : void 0
145
+ });
146
+ }
147
+ /**
148
+ * Register a callback invoked on every flow event
149
+ * (opened / consent_accepted / consent_declined / already_resolved /
150
+ * redirecting / error / closed). Returns an unsubscribe function.
151
+ */
152
+ onCallback(e) {
153
+ return this.callbacks.add(e), () => {
154
+ this.callbacks.delete(e);
155
+ };
156
+ }
157
+ /** Programmatically close the dialog (emits a `closed` event). */
158
+ close(e) {
159
+ var o;
160
+ const t = e ?? {
161
+ type: "closed",
162
+ requestId: (o = this.session) == null ? void 0 : o.requestId
163
+ }, r = this.overlay !== null;
164
+ this.teardown(), r && this.emit(t);
165
+ }
166
+ /** Alias of close() without emitting when already closed. */
167
+ destroy() {
168
+ this.callbacks.clear(), this.teardown();
169
+ }
170
+ isOpen() {
171
+ return this.overlay !== null;
172
+ }
173
+ // ---- internals ----
174
+ open(e) {
175
+ this.teardown(), this.session = e, this.ensureListening();
176
+ }
177
+ ensureListening() {
178
+ this.listening || (window.addEventListener("message", this.messageHandler), window.addEventListener("keydown", this.escHandler), this.listening = !0);
179
+ }
180
+ render(e, t, r) {
181
+ if (!this.session) return;
182
+ const o = C(this.session), i = document.createElement("div");
183
+ i.id = I, i.setAttribute("role", "dialog"), i.setAttribute("aria-modal", "true"), i.style.cssText = [
184
+ "position:fixed",
185
+ "inset:0",
186
+ "z-index:2147483647",
187
+ "display:flex",
188
+ "align-items:center",
189
+ "justify-content:center",
190
+ "background:rgba(15,23,42,0.55)",
191
+ "padding:16px",
192
+ "box-sizing:border-box"
193
+ ].join(";");
194
+ const a = document.createElement("div"), g = Math.min(t, window.innerWidth - 32), f = Math.min(r, window.innerHeight - 32);
195
+ if (a.style.cssText = [
196
+ `width:${g}px`,
197
+ "max-width:100%",
198
+ `height:${f}px`,
199
+ "max-height:100%",
200
+ "background:#fff",
201
+ "border-radius:16px",
202
+ "overflow:hidden",
203
+ "position:relative",
204
+ "box-shadow:0 25px 50px -12px rgba(0,0,0,0.35)",
205
+ "display:flex",
206
+ "flex-direction:column"
207
+ ].join(";"), e) {
208
+ const l = document.createElement("button");
209
+ l.setAttribute("aria-label", "Close"), l.textContent = "×", l.style.cssText = [
210
+ "position:absolute",
211
+ "top:8px",
212
+ "right:12px",
213
+ "z-index:2",
214
+ "width:28px",
215
+ "height:28px",
216
+ "border-radius:9999px",
217
+ "border:none",
218
+ "background:rgba(15,23,42,0.06)",
219
+ "color:#475569",
220
+ "font-size:18px",
221
+ "line-height:1",
222
+ "cursor:pointer"
223
+ ].join(";"), l.onclick = () => this.close(), a.appendChild(l), i.addEventListener("mousedown", (m) => {
224
+ m.target === i && this.close();
225
+ });
226
+ }
227
+ const d = document.createElement("iframe");
228
+ d.src = o, d.title = "Consent manager", d.setAttribute("allow", "clipboard-write"), d.style.cssText = [
229
+ "flex:1",
230
+ "width:100%",
231
+ "height:100%",
232
+ "border:0",
233
+ "background:#fff"
234
+ ].join(";"), a.appendChild(d), i.appendChild(a), document.body.appendChild(i), document.documentElement.style.overflow = "hidden", this.overlay = i, this.iframe = d;
235
+ }
236
+ teardown() {
237
+ var e;
238
+ (e = this.overlay) != null && e.parentNode && this.overlay.parentNode.removeChild(this.overlay), this.overlay = null, this.iframe = null, this.session = null, this.listening && (window.removeEventListener("message", this.messageHandler), window.removeEventListener("keydown", this.escHandler), this.listening = !1);
239
+ try {
240
+ document.documentElement.style.overflow = "";
241
+ } catch {
242
+ }
243
+ }
244
+ emit(e) {
245
+ this.callbacks.forEach((t) => {
246
+ try {
247
+ t(e);
248
+ } catch {
249
+ }
250
+ });
251
+ }
252
+ }
253
+ const T = new A();
254
+ export {
255
+ T as ConsentWidget,
256
+ c as GATEWAY_BASE_URLS,
257
+ T as default
258
+ };
package/dist/react.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";var E=Object.defineProperty;var k=(n,e,t)=>e in n?E(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var h=(n,e,t)=>k(n,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("react"),w={live:"https://ui.gateway.nodbook.in",sandbox:"https://sandbox-ui.gateway.nodbook.in"},C="CONSENT_WIDGET_EVENT",y="GATEWAY_UI_READY",b="PRINCIPAL_TOKEN";function I(n){return typeof n=="object"&&n!==null&&n.type===C&&typeof n.event=="object"}function _(n){return typeof n=="object"&&n!==null&&n.type===y}const x="__consent_widget_overlay__",v=600,A=640;function T(n,e){var t;if(n)return n.replace(/\/$/,"");if(e&&w[e])return w[e];try{const r=document.getElementsByTagName("script");for(let s=r.length-1;s>=0;s--){const c=((t=r[s])==null?void 0:t.getAttribute("src"))??"";if(c.includes("consent-widget"))return new URL(c,window.location.href).origin}const i=document.currentScript;if(i!=null&&i.src)return new URL(i.src,window.location.href).origin}catch{}return window.location.origin}function W(n){var t;const e=new URLSearchParams({auth_token:n.token,embed:"true",origin:window.location.origin});return n.mode==="preferences"?`${n.baseUrl}/consent_manager/preferences?${e.toString()}`:n.mode==="direct_consent"?((t=n.purposeIds)!=null&&t.length&&e.set("purpose_id",n.purposeIds.join(",")),n.orgId&&e.set("org_id",n.orgId),n.locale&&e.set("locale",n.locale),`${n.baseUrl}/consent_manager/direct_consent?${e.toString()}`):`${n.baseUrl}/consent_manager/consent/${encodeURIComponent(n.requestId??"")}?${e.toString()}`}class U{constructor(){h(this,"overlay",null);h(this,"iframe",null);h(this,"session",null);h(this,"callbacks",new Set);h(this,"listening",!1);h(this,"escHandler",e=>{var t;e.key==="Escape"&&this.close({type:"closed",requestId:(t=this.session)==null?void 0:t.requestId})});h(this,"messageHandler",e=>{var r,i;if(!this.session||!this.iframe)return;let t="";try{t=new URL(this.session.baseUrl).origin}catch{t=""}if(!(t&&e.origin!==t)&&e.source===this.iframe.contentWindow){if(_(e.data)){try{(r=this.iframe.contentWindow)==null||r.postMessage({type:b,token:this.session.token},t||"*")}catch{}return}if(typeof e.data=="object"&&e.data!==null&&e.data.type===y){try{(i=this.iframe.contentWindow)==null||i.postMessage({type:b,token:this.session.token},t||"*")}catch{}return}if(I(e.data)){const s=e.data.event;this.emit(s),this.session.autoClose&&(s.type==="consent_accepted"||s.type==="consent_declined"||s.type==="already_resolved"||s.type==="redirecting")&&this.teardown()}}})}openConsent(e,t,r){this.openDialog({...r,requestId:e,token:(r==null?void 0:r.token)??t})}openPreferences(e,t){this.openDialog({...t,token:(t==null?void 0:t.token)??e})}openDirectConsent(e,t,r){const i=(Array.isArray(e)?e:[e]).map(s=>s.trim()).filter(Boolean);if(i.length===0)throw new Error("ConsentWidget.openDirectConsent: at least one `purposeId` is required.");this.openDialog({...r,purposeIds:i,token:(r==null?void 0:r.token)??t,mode:"direct_consent"})}openDialog(e){var r;if(!e||typeof e.token!="string"||e.token.length===0)throw new Error("ConsentWidget: `token` is required.");const t=e.mode??(e.requestId?"consent":"preferences");if(t==="consent"&&!e.requestId)throw new Error("ConsentWidget: `requestId` is required for the consent dialog.");this.open({requestId:e.requestId,token:e.token,mode:t,purposeIds:e.purposeIds,orgId:e.orgId??null,locale:e.locale,baseUrl:T(e.baseUrl,e.env),autoClose:e.autoClose??!0}),this.render(e.allowClose??!0,e.width??v,e.height??A),this.emit({type:"opened",requestId:e.requestId,data:(r=e.purposeIds)!=null&&r.length?{purposeIds:e.purposeIds}:void 0})}onCallback(e){return this.callbacks.add(e),()=>{this.callbacks.delete(e)}}close(e){var i;const t=e??{type:"closed",requestId:(i=this.session)==null?void 0:i.requestId},r=this.overlay!==null;this.teardown(),r&&this.emit(t)}destroy(){this.callbacks.clear(),this.teardown()}isOpen(){return this.overlay!==null}open(e){this.teardown(),this.session=e,this.ensureListening()}ensureListening(){this.listening||(window.addEventListener("message",this.messageHandler),window.addEventListener("keydown",this.escHandler),this.listening=!0)}render(e,t,r){if(!this.session)return;const i=W(this.session),s=document.createElement("div");s.id=x,s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.style.cssText=["position:fixed","inset:0","z-index:2147483647","display:flex","align-items:center","justify-content:center","background:rgba(15,23,42,0.55)","padding:16px","box-sizing:border-box"].join(";");const c=document.createElement("div"),g=Math.min(t,window.innerWidth-32),p=Math.min(r,window.innerHeight-32);if(c.style.cssText=[`width:${g}px`,"max-width:100%",`height:${p}px`,"max-height:100%","background:#fff","border-radius:16px","overflow:hidden","position:relative","box-shadow:0 25px 50px -12px rgba(0,0,0,0.35)","display:flex","flex-direction:column"].join(";"),e){const o=document.createElement("button");o.setAttribute("aria-label","Close"),o.textContent="×",o.style.cssText=["position:absolute","top:8px","right:12px","z-index:2","width:28px","height:28px","border-radius:9999px","border:none","background:rgba(15,23,42,0.06)","color:#475569","font-size:18px","line-height:1","cursor:pointer"].join(";"),o.onclick=()=>this.close(),c.appendChild(o),s.addEventListener("mousedown",l=>{l.target===s&&this.close()})}const u=document.createElement("iframe");u.src=i,u.title="Consent manager",u.setAttribute("allow","clipboard-write"),u.style.cssText=["flex:1","width:100%","height:100%","border:0","background:#fff"].join(";"),c.appendChild(u),s.appendChild(c),document.body.appendChild(s),document.documentElement.style.overflow="hidden",this.overlay=s,this.iframe=u}teardown(){var e;(e=this.overlay)!=null&&e.parentNode&&this.overlay.parentNode.removeChild(this.overlay),this.overlay=null,this.iframe=null,this.session=null,this.listening&&(window.removeEventListener("message",this.messageHandler),window.removeEventListener("keydown",this.escHandler),this.listening=!1);try{document.documentElement.style.overflow=""}catch{}}emit(e){this.callbacks.forEach(t=>{try{t(e)}catch{}})}}const a=new U;function q(n){const{onEvent:e,closeOnUnmount:t=!0}=n??{};d.useEffect(()=>{if(e)return a.onCallback(e)},[e]),d.useEffect(()=>{if(t)return()=>{a.isOpen()&&a.close()}},[t]);const r=d.useCallback(o=>{const{requestId:l,token:f,...m}=o;l?a.openConsent(l,f,{...m,token:f}):a.openPreferences(f,m)},[]),i=d.useCallback((o,l,f)=>{a.openConsent(o,l,f)},[]),s=d.useCallback((o,l)=>{a.openPreferences(o,l)},[]),c=d.useCallback((o,l,f)=>{a.openDirectConsent(o,l,f)},[]),g=d.useCallback(o=>{a.close(o)},[]),p=d.useCallback(o=>a.onCallback(o),[]),u=d.useCallback(()=>a.isOpen(),[]);return{open:r,openConsent:i,openPreferences:s,openDirectConsent:c,close:g,onEvent:p,isOpen:u}}exports.useConsentWidget=q;
@@ -0,0 +1,25 @@
1
+ import type { OpenConsentOptions, OpenDirectConsentOptions, OpenPreferencesOptions, WidgetCallback, WidgetEvent, WidgetInitOptions } from "./core/types";
2
+ export interface UseConsentWidgetOptions {
3
+ /** Called on every widget event (opened / accepted / declined / ... / closed). */
4
+ onEvent?: WidgetCallback;
5
+ /** Close the dialog if the consuming component unmounts. Default true. */
6
+ closeOnUnmount?: boolean;
7
+ }
8
+ export interface UseConsentWidgetApi {
9
+ /** Open consent or preferences dialog (mode defaults from requestId). */
10
+ open: (options: WidgetInitOptions) => void;
11
+ /** Open the consent dialog for a request. */
12
+ openConsent: (requestId: string, token: string, opts?: OpenConsentOptions) => void;
13
+ /** Open the preferences (my consents + grievances) dialog. */
14
+ openPreferences: (token: string, opts?: OpenPreferencesOptions) => void;
15
+ /** Open the direct-consent (permission-style) dialog for purpose(s). */
16
+ openDirectConsent: (purposeIds: string | string[], token: string, opts?: OpenDirectConsentOptions) => void;
17
+ /** Programmatically close the dialog (emits a `closed` event). */
18
+ close: (event?: WidgetEvent) => void;
19
+ /** Subscribe to flow events. Returns an unsubscribe function. */
20
+ onEvent: (cb: WidgetCallback) => () => void;
21
+ /** Whether the dialog is currently open. */
22
+ isOpen: () => boolean;
23
+ }
24
+ export declare function useConsentWidget(options?: UseConsentWidgetOptions): UseConsentWidgetApi;
25
+ export type { WidgetCallback, WidgetEvent, WidgetInitOptions, OpenConsentOptions, OpenDirectConsentOptions, OpenPreferencesOptions, };
package/dist/react.js ADDED
@@ -0,0 +1,291 @@
1
+ var I = Object.defineProperty;
2
+ var k = (n, e, t) => e in n ? I(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t;
3
+ var u = (n, e, t) => k(n, typeof e != "symbol" ? e + "" : e, t);
4
+ import { useEffect as w, useCallback as f } from "react";
5
+ const y = {
6
+ live: "https://ui.gateway.nodbook.in",
7
+ sandbox: "https://sandbox-ui.gateway.nodbook.in"
8
+ }, C = "CONSENT_WIDGET_EVENT", E = "GATEWAY_UI_READY", b = "PRINCIPAL_TOKEN";
9
+ function _(n) {
10
+ return typeof n == "object" && n !== null && n.type === C && typeof n.event == "object";
11
+ }
12
+ function x(n) {
13
+ return typeof n == "object" && n !== null && n.type === E;
14
+ }
15
+ const v = "__consent_widget_overlay__", A = 600, T = 640;
16
+ function U(n, e) {
17
+ var t;
18
+ if (n) return n.replace(/\/$/, "");
19
+ if (e && y[e]) return y[e];
20
+ try {
21
+ const r = document.getElementsByTagName("script");
22
+ for (let i = r.length - 1; i >= 0; i--) {
23
+ const l = ((t = r[i]) == null ? void 0 : t.getAttribute("src")) ?? "";
24
+ if (l.includes("consent-widget"))
25
+ return new URL(l, window.location.href).origin;
26
+ }
27
+ const o = document.currentScript;
28
+ if (o != null && o.src) return new URL(o.src, window.location.href).origin;
29
+ } catch {
30
+ }
31
+ return window.location.origin;
32
+ }
33
+ function W(n) {
34
+ var t;
35
+ const e = new URLSearchParams({
36
+ auth_token: n.token,
37
+ embed: "true",
38
+ origin: window.location.origin
39
+ });
40
+ return n.mode === "preferences" ? `${n.baseUrl}/consent_manager/preferences?${e.toString()}` : n.mode === "direct_consent" ? ((t = n.purposeIds) != null && t.length && e.set("purpose_id", n.purposeIds.join(",")), n.orgId && e.set("org_id", n.orgId), n.locale && e.set("locale", n.locale), `${n.baseUrl}/consent_manager/direct_consent?${e.toString()}`) : `${n.baseUrl}/consent_manager/consent/${encodeURIComponent(n.requestId ?? "")}?${e.toString()}`;
41
+ }
42
+ class L {
43
+ constructor() {
44
+ u(this, "overlay", null);
45
+ u(this, "iframe", null);
46
+ u(this, "session", null);
47
+ u(this, "callbacks", /* @__PURE__ */ new Set());
48
+ u(this, "listening", !1);
49
+ u(this, "escHandler", (e) => {
50
+ var t;
51
+ e.key === "Escape" && this.close({ type: "closed", requestId: (t = this.session) == null ? void 0 : t.requestId });
52
+ });
53
+ u(this, "messageHandler", (e) => {
54
+ var r, o;
55
+ if (!this.session || !this.iframe) return;
56
+ let t = "";
57
+ try {
58
+ t = new URL(this.session.baseUrl).origin;
59
+ } catch {
60
+ t = "";
61
+ }
62
+ if (!(t && e.origin !== t) && e.source === this.iframe.contentWindow) {
63
+ if (x(e.data)) {
64
+ try {
65
+ (r = this.iframe.contentWindow) == null || r.postMessage(
66
+ { type: b, token: this.session.token },
67
+ t || "*"
68
+ );
69
+ } catch {
70
+ }
71
+ return;
72
+ }
73
+ if (typeof e.data == "object" && e.data !== null && e.data.type === E) {
74
+ try {
75
+ (o = this.iframe.contentWindow) == null || o.postMessage(
76
+ { type: b, token: this.session.token },
77
+ t || "*"
78
+ );
79
+ } catch {
80
+ }
81
+ return;
82
+ }
83
+ if (_(e.data)) {
84
+ const i = e.data.event;
85
+ this.emit(i), this.session.autoClose && (i.type === "consent_accepted" || i.type === "consent_declined" || i.type === "already_resolved" || i.type === "redirecting") && this.teardown();
86
+ }
87
+ }
88
+ });
89
+ }
90
+ /** Open the consent dialog for a request. */
91
+ openConsent(e, t, r) {
92
+ this.openDialog({
93
+ ...r,
94
+ requestId: e,
95
+ token: (r == null ? void 0 : r.token) ?? t
96
+ });
97
+ }
98
+ /** Open the preferences (my consents + grievances) dialog. */
99
+ openPreferences(e, t) {
100
+ this.openDialog({
101
+ ...t,
102
+ token: (t == null ? void 0 : t.token) ?? e
103
+ });
104
+ }
105
+ /** Open the direct-consent (permission-style) dialog for purpose(s). */
106
+ openDirectConsent(e, t, r) {
107
+ const o = (Array.isArray(e) ? e : [e]).map((i) => i.trim()).filter(Boolean);
108
+ if (o.length === 0)
109
+ throw new Error("ConsentWidget.openDirectConsent: at least one `purposeId` is required.");
110
+ this.openDialog({
111
+ ...r,
112
+ purposeIds: o,
113
+ token: (r == null ? void 0 : r.token) ?? t,
114
+ mode: "direct_consent"
115
+ });
116
+ }
117
+ /**
118
+ * Shared opener behind `openConsent` / `openPreferences` / `openDirectConsent`.
119
+ * The view follows `mode`, defaulting from `requestId`: set → consent
120
+ * dialog, omitted → preferences dialog.
121
+ */
122
+ openDialog(e) {
123
+ var r;
124
+ if (!e || typeof e.token != "string" || e.token.length === 0)
125
+ throw new Error("ConsentWidget: `token` is required.");
126
+ const t = e.mode ?? (e.requestId ? "consent" : "preferences");
127
+ if (t === "consent" && !e.requestId)
128
+ throw new Error("ConsentWidget: `requestId` is required for the consent dialog.");
129
+ this.open({
130
+ requestId: e.requestId,
131
+ token: e.token,
132
+ mode: t,
133
+ purposeIds: e.purposeIds,
134
+ orgId: e.orgId ?? null,
135
+ locale: e.locale,
136
+ baseUrl: U(e.baseUrl, e.env),
137
+ autoClose: e.autoClose ?? !0
138
+ }), this.render(
139
+ e.allowClose ?? !0,
140
+ e.width ?? A,
141
+ e.height ?? T
142
+ ), this.emit({
143
+ type: "opened",
144
+ requestId: e.requestId,
145
+ data: (r = e.purposeIds) != null && r.length ? { purposeIds: e.purposeIds } : void 0
146
+ });
147
+ }
148
+ /**
149
+ * Register a callback invoked on every flow event
150
+ * (opened / consent_accepted / consent_declined / already_resolved /
151
+ * redirecting / error / closed). Returns an unsubscribe function.
152
+ */
153
+ onCallback(e) {
154
+ return this.callbacks.add(e), () => {
155
+ this.callbacks.delete(e);
156
+ };
157
+ }
158
+ /** Programmatically close the dialog (emits a `closed` event). */
159
+ close(e) {
160
+ var o;
161
+ const t = e ?? {
162
+ type: "closed",
163
+ requestId: (o = this.session) == null ? void 0 : o.requestId
164
+ }, r = this.overlay !== null;
165
+ this.teardown(), r && this.emit(t);
166
+ }
167
+ /** Alias of close() without emitting when already closed. */
168
+ destroy() {
169
+ this.callbacks.clear(), this.teardown();
170
+ }
171
+ isOpen() {
172
+ return this.overlay !== null;
173
+ }
174
+ // ---- internals ----
175
+ open(e) {
176
+ this.teardown(), this.session = e, this.ensureListening();
177
+ }
178
+ ensureListening() {
179
+ this.listening || (window.addEventListener("message", this.messageHandler), window.addEventListener("keydown", this.escHandler), this.listening = !0);
180
+ }
181
+ render(e, t, r) {
182
+ if (!this.session) return;
183
+ const o = W(this.session), i = document.createElement("div");
184
+ i.id = v, i.setAttribute("role", "dialog"), i.setAttribute("aria-modal", "true"), i.style.cssText = [
185
+ "position:fixed",
186
+ "inset:0",
187
+ "z-index:2147483647",
188
+ "display:flex",
189
+ "align-items:center",
190
+ "justify-content:center",
191
+ "background:rgba(15,23,42,0.55)",
192
+ "padding:16px",
193
+ "box-sizing:border-box"
194
+ ].join(";");
195
+ const l = document.createElement("div"), g = Math.min(t, window.innerWidth - 32), p = Math.min(r, window.innerHeight - 32);
196
+ if (l.style.cssText = [
197
+ `width:${g}px`,
198
+ "max-width:100%",
199
+ `height:${p}px`,
200
+ "max-height:100%",
201
+ "background:#fff",
202
+ "border-radius:16px",
203
+ "overflow:hidden",
204
+ "position:relative",
205
+ "box-shadow:0 25px 50px -12px rgba(0,0,0,0.35)",
206
+ "display:flex",
207
+ "flex-direction:column"
208
+ ].join(";"), e) {
209
+ const s = document.createElement("button");
210
+ s.setAttribute("aria-label", "Close"), s.textContent = "×", s.style.cssText = [
211
+ "position:absolute",
212
+ "top:8px",
213
+ "right:12px",
214
+ "z-index:2",
215
+ "width:28px",
216
+ "height:28px",
217
+ "border-radius:9999px",
218
+ "border:none",
219
+ "background:rgba(15,23,42,0.06)",
220
+ "color:#475569",
221
+ "font-size:18px",
222
+ "line-height:1",
223
+ "cursor:pointer"
224
+ ].join(";"), s.onclick = () => this.close(), l.appendChild(s), i.addEventListener("mousedown", (c) => {
225
+ c.target === i && this.close();
226
+ });
227
+ }
228
+ const d = document.createElement("iframe");
229
+ d.src = o, d.title = "Consent manager", d.setAttribute("allow", "clipboard-write"), d.style.cssText = [
230
+ "flex:1",
231
+ "width:100%",
232
+ "height:100%",
233
+ "border:0",
234
+ "background:#fff"
235
+ ].join(";"), l.appendChild(d), i.appendChild(l), document.body.appendChild(i), document.documentElement.style.overflow = "hidden", this.overlay = i, this.iframe = d;
236
+ }
237
+ teardown() {
238
+ var e;
239
+ (e = this.overlay) != null && e.parentNode && this.overlay.parentNode.removeChild(this.overlay), this.overlay = null, this.iframe = null, this.session = null, this.listening && (window.removeEventListener("message", this.messageHandler), window.removeEventListener("keydown", this.escHandler), this.listening = !1);
240
+ try {
241
+ document.documentElement.style.overflow = "";
242
+ } catch {
243
+ }
244
+ }
245
+ emit(e) {
246
+ this.callbacks.forEach((t) => {
247
+ try {
248
+ t(e);
249
+ } catch {
250
+ }
251
+ });
252
+ }
253
+ }
254
+ const a = new L();
255
+ function S(n) {
256
+ const { onEvent: e, closeOnUnmount: t = !0 } = n ?? {};
257
+ w(() => {
258
+ if (e)
259
+ return a.onCallback(e);
260
+ }, [e]), w(() => {
261
+ if (t)
262
+ return () => {
263
+ a.isOpen() && a.close();
264
+ };
265
+ }, [t]);
266
+ const r = f((s) => {
267
+ const { requestId: c, token: h, ...m } = s;
268
+ c ? a.openConsent(c, h, { ...m, token: h }) : a.openPreferences(h, m);
269
+ }, []), o = f(
270
+ (s, c, h) => {
271
+ a.openConsent(s, c, h);
272
+ },
273
+ []
274
+ ), i = f(
275
+ (s, c) => {
276
+ a.openPreferences(s, c);
277
+ },
278
+ []
279
+ ), l = f(
280
+ (s, c, h) => {
281
+ a.openDirectConsent(s, c, h);
282
+ },
283
+ []
284
+ ), g = f((s) => {
285
+ a.close(s);
286
+ }, []), p = f((s) => a.onCallback(s), []), d = f(() => a.isOpen(), []);
287
+ return { open: r, openConsent: o, openPreferences: i, openDirectConsent: l, close: g, onEvent: p, isOpen: d };
288
+ }
289
+ export {
290
+ S as useConsentWidget
291
+ };
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "@truzyx/consent-widget",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Framework-agnostic consent + preferences widget (iframe overlay) with React hook. Reuses the gateway embed core, zero runtime dependencies for the vanilla entry.",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.cjs"
14
+ },
15
+ "./react": {
16
+ "types": "./dist/react.d.ts",
17
+ "import": "./dist/react.js",
18
+ "require": "./dist/react.cjs"
19
+ }
20
+ },
21
+ "files": [
22
+ "dist"
23
+ ],
24
+ "scripts": {
25
+ "build": "vite build --config vite.config.ts && vite build --config vite.react.config.ts && tsc -p tsconfig.json",
26
+ "prepublishOnly": "npm run build"
27
+ },
28
+ "peerDependencies": {
29
+ "react": ">=16.8.0"
30
+ },
31
+ "peerDependenciesMeta": {
32
+ "react": {
33
+ "optional": true
34
+ }
35
+ },
36
+ "devDependencies": {
37
+ "typescript": "~5.8.3",
38
+ "vite": "^6.3.5"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "license": "MIT"
44
+ }