@twilltac/compliance-sdk 0.5.0 → 1.0.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/README.md CHANGED
@@ -8,6 +8,24 @@ SDK for embedding the Twilltac Compliance Plugin into your application. The plug
8
8
  npm install @twilltac/compliance-sdk
9
9
  ```
10
10
 
11
+ Or load the Twilltac compliance script, which adds `twilltac.createCompliancePlugin` to the page:
12
+
13
+ ```html
14
+ <script src="https://plugins.twilltac.com/compliance/v1.js"></script>
15
+ ```
16
+
17
+ The package holds the types and a small loader that adds that script to the page the first time you call `createCompliancePlugin`. Either way your application always runs the latest release of the plugin, so there is no version to update for new behaviour. A new version of the package is published only when its types change.
18
+
19
+ ### Upgrading from 0.6
20
+
21
+ An application on 0.6 keeps working as it is: there is nothing you have to do. Moving to 1.x changes three things:
22
+
23
+ - The plugin's code is no longer bundled into your application. The package adds the compliance script to the page instead, so a Content Security Policy needs `script-src https://plugins.twilltac.com` as well as `frame-src https://compliance.plugins.twilltac.app`.
24
+ - `CompliancePlugin` is exported as a type only. Use it to type the plugin `createCompliancePlugin` returns; it can no longer be used with `instanceof`.
25
+ - `compliancePluginUrl` is no longer exported.
26
+
27
+ `createCompliancePlugin`, its options, the plugin's methods and every event are unchanged.
28
+
11
29
  ## Quick Start
12
30
 
13
31
  ```typescript
package/index.cjs CHANGED
@@ -18,349 +18,75 @@ var __copyProps = (to, from, except, desc) => {
18
18
  };
19
19
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
20
 
21
- // libs/twilltac/plugins/compliance/sdk/src/index.ts
22
- var index_exports = {};
23
- __export(index_exports, {
24
- CompliancePlugin: () => CompliancePlugin,
21
+ // libs/twilltac/operator/plugins/compliance/sdk/src/index.package.ts
22
+ var index_package_exports = {};
23
+ __export(index_package_exports, {
25
24
  createCompliancePlugin: () => createCompliancePlugin
26
25
  });
27
- module.exports = __toCommonJS(index_exports);
26
+ module.exports = __toCommonJS(index_package_exports);
28
27
 
29
- // libs/twilltac/plugins/compliance/types/src/lib/compliance-plugin-initialisation.data.ts
30
- var CompliancePluginFlow = /* @__PURE__ */ ((CompliancePluginFlow2) => {
31
- CompliancePluginFlow2["JOURNEY"] = "journey";
32
- CompliancePluginFlow2["HANDOVER"] = "handover";
33
- return CompliancePluginFlow2;
34
- })(CompliancePluginFlow || {});
35
- var CompliancePluginThemeAppearance = /* @__PURE__ */ ((CompliancePluginThemeAppearance2) => {
36
- CompliancePluginThemeAppearance2["LIGHT"] = "light";
37
- CompliancePluginThemeAppearance2["DARK"] = "dark";
38
- return CompliancePluginThemeAppearance2;
39
- })(CompliancePluginThemeAppearance || {});
40
-
41
- // libs/twilltac/plugins/utils/typed-event-emitter/src/lib/typed-event-emitter.ts
42
- var TypedEventEmitter = class {
43
- _handlers = /* @__PURE__ */ new Map();
44
- on(event, handler) {
45
- if (!this._handlers.has(event)) {
46
- this._handlers.set(event, /* @__PURE__ */ new Set());
47
- }
48
- this._handlers.get(event).add(handler);
49
- return () => this.off(event, handler);
50
- }
51
- off(event, handler) {
52
- const handlers = this._handlers.get(event);
53
- if (handlers) {
54
- handlers.delete(handler);
55
- if (handlers.size === 0) {
56
- this._handlers.delete(event);
57
- }
58
- }
59
- }
60
- once(event, handler) {
61
- const wrappedHandler = (data) => {
62
- this.off(event, wrappedHandler);
63
- handler(data);
64
- };
65
- return this.on(event, wrappedHandler);
66
- }
67
- emit(event, ...args) {
68
- const handlers = this._handlers.get(event);
69
- if (handlers) {
70
- handlers.forEach((handler) => handler(args[0]));
71
- }
72
- }
73
- clear() {
74
- this._handlers.clear();
75
- }
76
- };
77
-
78
- // libs/twilltac/plugins/compliance/sdk/src/lib/compliance.plugin.ts
79
- var CompliancePlugin = class {
80
- _events = new TypedEventEmitter();
81
- _wildcardHandlers = /* @__PURE__ */ new Set();
82
- _postMessageBus;
83
- _theme;
84
- constructor(opts) {
85
- this._postMessageBus = opts.postMessageBus;
86
- this._theme = opts.initialisationOptions.theme;
87
- opts.iframeElement.style.visibility = "visible";
88
- if (opts.initialisationOptions.sizing === "content" /* CONTENT */) {
89
- opts.iframeElement.style.minHeight = `${opts.initialisationData.documentHeight}px`;
90
- opts.postMessageBus.on("window:resize", (data) => opts.iframeElement.style.minHeight = `${data.height}px`);
91
- opts.postMessageBus.on("navigation:start", () => opts.iframeElement.style.minHeight = "");
92
- }
93
- opts.postMessageBus.on("session:expired-token", () => this._events.emit("session:expired"));
94
- opts.postMessageBus.on("journey:started", () => this._events.emit("flow.journey.started"));
95
- opts.postMessageBus.on("journey.section:started", (data) => this._events.emit("flow.journey.section:started", data));
96
- opts.postMessageBus.on("journey.section:completed", (data) => this._events.emit("flow.journey.section:completed", data));
97
- opts.postMessageBus.on("journey:completed", () => this._events.emit("flow.journey:completed"));
98
- const eventNames = [
99
- "session:expired",
100
- "flow.journey.started",
101
- "flow.journey.section:started",
102
- "flow.journey.section:completed",
103
- "flow.journey:completed"
104
- ];
105
- for (const eventName of eventNames) {
106
- this._events.on(eventName, ((...args) => {
107
- this._wildcardHandlers.forEach((handler) => handler(eventName, args[0]));
108
- }));
109
- }
110
- }
111
- on(eventOrHandler, handler) {
112
- if (typeof eventOrHandler === "function") {
113
- this._wildcardHandlers.add(eventOrHandler);
114
- return () => this._wildcardHandlers.delete(eventOrHandler);
115
- }
116
- return this._events.on(eventOrHandler, handler);
117
- }
118
- get theme() {
119
- return this._theme;
120
- }
121
- setTheme(theme) {
122
- this._theme = theme;
123
- this._postMessageBus.send("theme:change", { theme });
124
- }
125
- destroy() {
126
- this._events.clear();
127
- this._wildcardHandlers.clear();
128
- this._postMessageBus.destroy();
129
- }
130
- };
131
-
132
- // libs/twilltac/plugins/utils/post-messenger/src/lib/post-message.bus.ts
133
- var PostMessageBus = class {
134
- _channel;
135
- _targetOrigin;
136
- _targetWindow;
137
- _defaultTimeout;
138
- _handlers = /* @__PURE__ */ new Map();
139
- _requestHandlers = /* @__PURE__ */ new Map();
140
- _pendingRequests = /* @__PURE__ */ new Map();
141
- _boundMessageHandler;
142
- constructor(options) {
143
- this._channel = options.channel;
144
- this._targetOrigin = options.targetOrigin ?? "*";
145
- this._targetWindow = options.targetWindow ?? window.parent;
146
- this._defaultTimeout = options.defaultTimeout ?? 3e4;
147
- this._boundMessageHandler = (event) => this.handleMessage(event);
148
- window.addEventListener("message", this._boundMessageHandler);
149
- }
150
- send(type, ...args) {
151
- const payload = args[0];
152
- const envelope = {
153
- channel: this._channel,
154
- type,
155
- payload
156
- };
157
- this._targetWindow.postMessage(envelope, this._targetOrigin);
158
- }
159
- on(type, handler) {
160
- if (!this._handlers.has(type)) {
161
- this._handlers.set(type, /* @__PURE__ */ new Set());
162
- }
163
- this._handlers.get(type).add(handler);
164
- return () => this.off(type, handler);
165
- }
166
- off(type, handler) {
167
- const handlers = this._handlers.get(type);
168
- if (handlers) {
169
- handlers.delete(handler);
170
- if (handlers.size === 0) {
171
- this._handlers.delete(type);
172
- }
173
- }
174
- }
175
- once(type, handler) {
176
- const wrappedHandler = (payload) => {
177
- this.off(type, wrappedHandler);
178
- handler(payload);
179
- };
180
- return this.on(type, wrappedHandler);
181
- }
182
- request(type, ...args) {
183
- return new Promise((resolve, reject) => {
184
- const [firstArg, secondArg] = args;
185
- const payload = typeof firstArg === "number" ? void 0 : firstArg;
186
- const timeout = typeof firstArg === "number" ? firstArg : secondArg;
187
- const correlationId = this.generateCorrelationId();
188
- const timeoutMs = timeout ?? this._defaultTimeout;
189
- const timeoutId = setTimeout(() => {
190
- this._pendingRequests.delete(correlationId);
191
- reject(new Error(`Request '${type}' timed out after ${timeoutMs}ms`));
192
- }, timeoutMs);
193
- this._pendingRequests.set(correlationId, {
194
- resolve,
195
- reject,
196
- timeoutId
197
- });
198
- const envelope = {
199
- channel: this._channel,
200
- type,
201
- payload,
202
- correlationId
203
- };
204
- this._targetWindow.postMessage(envelope, this._targetOrigin);
205
- });
206
- }
207
- onRequest(type, handler) {
208
- this._requestHandlers.set(type, handler);
209
- return () => this._requestHandlers.delete(type);
210
- }
211
- destroy() {
212
- window.removeEventListener("message", this._boundMessageHandler);
213
- this._handlers.clear();
214
- this._requestHandlers.clear();
215
- this._pendingRequests.forEach((pending) => {
216
- clearTimeout(pending.timeoutId);
217
- pending.reject(new Error("PostMessageBus destroyed"));
218
- });
219
- this._pendingRequests.clear();
220
- }
221
- handleMessage(event) {
222
- const envelope = event.data;
223
- if (!envelope || envelope.channel !== this._channel) {
224
- return;
225
- }
226
- if (envelope.isResponse && envelope.correlationId) {
227
- this.handleResponse(envelope);
228
- return;
229
- }
230
- if (envelope.correlationId && !envelope.isResponse) {
231
- this.handleRequest(envelope);
232
- return;
233
- }
234
- const handlers = this._handlers.get(envelope.type);
235
- if (handlers) {
236
- handlers.forEach((handler) => handler(envelope.payload));
237
- }
238
- }
239
- handleResponse(envelope) {
240
- const pending = this._pendingRequests.get(envelope.correlationId);
241
- if (!pending) {
242
- return;
243
- }
244
- clearTimeout(pending.timeoutId);
245
- this._pendingRequests.delete(envelope.correlationId);
246
- if (envelope.isError) {
247
- pending.reject(envelope.payload);
248
- } else {
249
- pending.resolve(envelope.payload);
250
- }
251
- }
252
- handleRequest(envelope) {
253
- const handler = this._requestHandlers.get(envelope.type);
254
- if (!handler) {
255
- this.sendResponse(envelope.correlationId, null, true, `No handler registered for '${envelope.type}'`);
256
- return;
257
- }
258
- Promise.resolve().then(() => handler(envelope.payload)).then((result) => {
259
- this.sendResponse(envelope.correlationId, result, false);
260
- }).catch((error) => {
261
- const errorMessage = error instanceof Error ? error.message : String(error);
262
- this.sendResponse(envelope.correlationId, null, true, errorMessage);
263
- });
264
- }
265
- sendResponse(correlationId, payload, isError, errorMessage) {
266
- const envelope = {
267
- channel: this._channel,
268
- type: "__response__",
269
- payload: isError ? { error: errorMessage } : payload,
270
- correlationId,
271
- isResponse: true,
272
- isError
273
- };
274
- this._targetWindow.postMessage(envelope, this._targetOrigin);
275
- }
276
- generateCorrelationId() {
277
- return `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
278
- }
279
- };
280
-
281
- // libs/twilltac/plugins/compliance/sdk/src/lib/create-compliance.plugin.ts
282
- function validateOptions(options) {
283
- if (!options.containerElement) {
284
- throw new Error("[CompliancePlugin] containerElement is required.");
285
- }
286
- if (!(options.containerElement instanceof HTMLElement)) {
287
- throw new Error("[CompliancePlugin] containerElement must be an HTMLElement.");
288
- }
289
- if (!options.data) {
290
- throw new Error("[CompliancePlugin] data is required.");
291
- }
292
- if (!options.data.workspaceSubdomain && !options.data.workspaceReference) {
293
- throw new Error("[CompliancePlugin] one of data.workspaceSubdomain or data.workspaceReference is required.");
294
- }
295
- const validFlows = Object.values(CompliancePluginFlow);
296
- if (!options.data.flow || !validFlows.includes(options.data.flow)) {
297
- throw new Error(`[CompliancePlugin] data.flow is required and must be one of: ${validFlows.join(", ")}.`);
298
- }
299
- if (!options.data.customerReference) {
300
- throw new Error("[CompliancePlugin] data.customerReference is required.");
301
- }
302
- if (!options.data.offerReference) {
303
- throw new Error("[CompliancePlugin] data.offerReference is required.");
28
+ // libs/twilltac/operator/plugins/compliance/sdk/src/lib/compliance-script-loader.ts
29
+ var LIVE_COMPLIANCE_SCRIPT_URL = "https://plugins.twilltac.com/compliance/v1.js";
30
+ var LOCAL_COMPLIANCE_SCRIPT_URL = "https://sdks.plugins.mynextvehicle.app.ngserve/compliance/v1.js";
31
+ var LOCAL_HOSTNAME_SUFFIX = ".ngserve";
32
+ var CREATOR_NAME = "createCompliancePlugin";
33
+ var scriptBeingLoaded = null;
34
+ function complianceScriptUrlFor(pageHostname) {
35
+ return pageHostname.endsWith(LOCAL_HOSTNAME_SUFFIX) ? LOCAL_COMPLIANCE_SCRIPT_URL : LIVE_COMPLIANCE_SCRIPT_URL;
36
+ }
37
+ function creatorOnThePage() {
38
+ const offered = window.twilltac?.[CREATOR_NAME];
39
+ return typeof offered === "function" ? offered : null;
40
+ }
41
+ function scriptOnThePage(url) {
42
+ const existing = Array.from(document.scripts).find((script2) => script2.src === url);
43
+ if (existing) {
44
+ return existing;
45
+ }
46
+ const script = document.createElement("script");
47
+ script.src = url;
48
+ script.async = true;
49
+ (document.head ?? document.documentElement).appendChild(script);
50
+ return script;
51
+ }
52
+ function complianceScriptLoaded(url) {
53
+ if (scriptBeingLoaded) {
54
+ return scriptBeingLoaded;
55
+ }
56
+ const loaded = new Promise((resolveLoaded, rejectLoaded) => {
57
+ const script = scriptOnThePage(url);
58
+ script.addEventListener("load", () => resolveLoaded());
59
+ script.addEventListener("error", () => rejectLoaded(new Error(`[Twilltac] The compliance script could not be loaded from ${url}.`)));
60
+ });
61
+ scriptBeingLoaded = loaded;
62
+ loaded.catch(() => {
63
+ scriptBeingLoaded = null;
64
+ });
65
+ return loaded;
66
+ }
67
+ async function compliancePluginCreator() {
68
+ if (typeof window === "undefined" || typeof document === "undefined") {
69
+ throw new Error("[Twilltac] A plugin can only be created in a browser.");
304
70
  }
305
- if (!options.data.authToken) {
306
- throw new Error("[CompliancePlugin] data.authToken is required.");
71
+ const alreadyOffered = creatorOnThePage();
72
+ if (alreadyOffered) {
73
+ return alreadyOffered;
307
74
  }
308
- const validThemeAppearances = Object.values(CompliancePluginThemeAppearance);
309
- if (options.data.theme !== void 0 && !validThemeAppearances.includes(options.data.theme.appearance)) {
310
- throw new Error(`[CompliancePlugin] data.theme.appearance must be one of: ${validThemeAppearances.join(", ")}.`);
75
+ const url = complianceScriptUrlFor(window.location.hostname);
76
+ await complianceScriptLoaded(url);
77
+ const offered = creatorOnThePage();
78
+ if (!offered) {
79
+ throw new Error(`[Twilltac] The compliance script at ${url} does not offer ${CREATOR_NAME}.`);
311
80
  }
81
+ return offered;
312
82
  }
313
- function createCompliancePlugin(options) {
314
- validateOptions(options);
315
- const sizing = options.data.sizing ?? "content" /* CONTENT */;
316
- const theme = options.data.theme ?? { appearance: "light" /* LIGHT */ };
317
- const resolvedData = { ...options.data, sizing, theme };
318
- const production = !window.location.hostname.endsWith(".ngserve");
319
- const baseUrl = "https://compliance.plugins.twilltac.app";
320
- const url = production ? baseUrl : `${baseUrl}.ngserve`;
321
- const iframe = document.createElement("iframe");
322
- iframe.name = "compliance-plugin-iframe";
323
- iframe.style.width = "100%";
324
- iframe.style.height = "100%";
325
- iframe.style.border = "none";
326
- iframe.style.overflow = "hidden";
327
- iframe.style.visibility = "hidden";
328
- if (sizing === "content" /* CONTENT */) {
329
- iframe.setAttribute("scrolling", "no");
330
- }
331
- const form = document.createElement("form");
332
- form.method = "POST";
333
- form.action = `${url}/en-gb`;
334
- form.target = iframe.name;
335
- form.style.display = "none";
336
- const input = document.createElement("input");
337
- input.type = "hidden";
338
- input.name = "data";
339
- input.value = JSON.stringify(resolvedData);
340
- form.appendChild(input);
341
- options.containerElement.innerHTML = "";
342
- options.containerElement.appendChild(iframe);
343
- options.containerElement.appendChild(form);
344
- const postMessageBus = new PostMessageBus({ channel: "compliance-plugin", targetWindow: iframe.contentWindow });
345
- return new Promise((resolve, rejects) => {
346
- postMessageBus.on("initialisation:success", (data) => {
347
- resolve(
348
- new CompliancePlugin({
349
- initialisationData: data,
350
- initialisationOptions: resolvedData,
351
- postMessageBus,
352
- iframeElement: iframe
353
- })
354
- );
355
- });
356
- postMessageBus.on("initialisation:error", (data) => {
357
- rejects(data.error);
358
- });
359
- form.submit();
360
- });
83
+
84
+ // libs/twilltac/operator/plugins/compliance/sdk/src/lib/create-compliance.package.ts
85
+ async function createCompliancePlugin(options) {
86
+ const create = await compliancePluginCreator();
87
+ return create(options);
361
88
  }
362
89
  // Annotate the CommonJS export names for ESM import in node:
363
90
  0 && (module.exports = {
364
- CompliancePlugin,
365
91
  createCompliancePlugin
366
92
  });
package/index.d.ts ADDED
@@ -0,0 +1,78 @@
1
+ declare enum CompliancePluginFlow {
2
+ JOURNEY = "journey",
3
+ HANDOVER = "handover"
4
+ }
5
+ declare enum PluginInitialisationSizing {
6
+ CONTAINER = "container",
7
+ CONTENT = "content"
8
+ }
9
+ declare enum CompliancePluginThemeAppearance {
10
+ LIGHT = "light",
11
+ DARK = "dark"
12
+ }
13
+ interface CompliancePluginTheme {
14
+ readonly appearance: `${CompliancePluginThemeAppearance}`;
15
+ }
16
+ interface CompliancePluginInitialisationData {
17
+ readonly workspaceSubdomain?: string;
18
+ readonly workspaceReference?: string;
19
+ readonly flow: `${CompliancePluginFlow}`;
20
+ readonly customerReference: string;
21
+ readonly offerReference: string;
22
+ readonly authToken: string;
23
+ readonly sizing: `${PluginInitialisationSizing}`;
24
+ readonly theme: CompliancePluginTheme;
25
+ readonly scriptRelease?: string;
26
+ }
27
+
28
+ interface SectionStartedEvent {
29
+ readonly name: string;
30
+ readonly reference: string;
31
+ }
32
+ interface SectionEndedEvent {
33
+ readonly name: string;
34
+ readonly reference: string;
35
+ readonly recommendations: {
36
+ readonly externalReference: string;
37
+ readonly price: number | null;
38
+ readonly regulated: boolean;
39
+ readonly title: string;
40
+ readonly description: string;
41
+ }[];
42
+ }
43
+ interface CompliancePluginEvents {
44
+ /** Emits when the user starts the journey and Initial Disclosure Document is generated. */
45
+ ['flow.journey.started']: void;
46
+ /** Emits when the user starts a section. */
47
+ ['flow.journey.section:started']: SectionStartedEvent;
48
+ /** Emits when the user completes the question set and submits their recommendations. */
49
+ ['flow.journey.section:completed']: SectionEndedEvent;
50
+ /** Emits when the user completes the journey and summary page is presented. */
51
+ ['flow.journey:completed']: void;
52
+ /** Emits when the session has expired. This would typically trigger your auth flow followed by re-initialising the plugin. */
53
+ ['session:expired']: void;
54
+ }
55
+
56
+ type CompliancePluginEventName = keyof CompliancePluginEvents;
57
+ type CompliancePluginEventHandler<TName extends CompliancePluginEventName> = (data: CompliancePluginEvents[TName]) => void;
58
+ type CompliancePluginAnyEventHandler = (event: CompliancePluginEventName, data: CompliancePluginEvents[CompliancePluginEventName]) => void;
59
+ interface CompliancePluginContract {
60
+ readonly theme: CompliancePluginTheme;
61
+ on(handler: CompliancePluginAnyEventHandler): () => void;
62
+ on<TName extends CompliancePluginEventName>(event: TName, handler: CompliancePluginEventHandler<TName>): () => void;
63
+ setTheme(theme: CompliancePluginTheme): void;
64
+ destroy(): void;
65
+ }
66
+
67
+ interface CompliancePluginInitialisationOptions {
68
+ readonly containerElement: HTMLElement;
69
+ readonly data: Omit<CompliancePluginInitialisationData, 'sizing' | 'theme' | 'scriptRelease'> & {
70
+ readonly sizing?: `${PluginInitialisationSizing}`;
71
+ readonly theme?: CompliancePluginTheme;
72
+ };
73
+ }
74
+
75
+ declare function createCompliancePlugin(options: CompliancePluginInitialisationOptions): Promise<CompliancePluginContract>;
76
+
77
+ export { createCompliancePlugin };
78
+ export type { CompliancePluginContract as CompliancePlugin, CompliancePluginEvents, CompliancePluginInitialisationOptions };
package/index.js CHANGED
@@ -1,339 +1,66 @@
1
1
  "use client";
2
2
 
3
- // libs/twilltac/plugins/compliance/types/src/lib/compliance-plugin-initialisation.data.ts
4
- var CompliancePluginFlow = /* @__PURE__ */ ((CompliancePluginFlow2) => {
5
- CompliancePluginFlow2["JOURNEY"] = "journey";
6
- CompliancePluginFlow2["HANDOVER"] = "handover";
7
- return CompliancePluginFlow2;
8
- })(CompliancePluginFlow || {});
9
- var CompliancePluginThemeAppearance = /* @__PURE__ */ ((CompliancePluginThemeAppearance2) => {
10
- CompliancePluginThemeAppearance2["LIGHT"] = "light";
11
- CompliancePluginThemeAppearance2["DARK"] = "dark";
12
- return CompliancePluginThemeAppearance2;
13
- })(CompliancePluginThemeAppearance || {});
14
-
15
- // libs/twilltac/plugins/utils/typed-event-emitter/src/lib/typed-event-emitter.ts
16
- var TypedEventEmitter = class {
17
- _handlers = /* @__PURE__ */ new Map();
18
- on(event, handler) {
19
- if (!this._handlers.has(event)) {
20
- this._handlers.set(event, /* @__PURE__ */ new Set());
21
- }
22
- this._handlers.get(event).add(handler);
23
- return () => this.off(event, handler);
24
- }
25
- off(event, handler) {
26
- const handlers = this._handlers.get(event);
27
- if (handlers) {
28
- handlers.delete(handler);
29
- if (handlers.size === 0) {
30
- this._handlers.delete(event);
31
- }
32
- }
33
- }
34
- once(event, handler) {
35
- const wrappedHandler = (data) => {
36
- this.off(event, wrappedHandler);
37
- handler(data);
38
- };
39
- return this.on(event, wrappedHandler);
40
- }
41
- emit(event, ...args) {
42
- const handlers = this._handlers.get(event);
43
- if (handlers) {
44
- handlers.forEach((handler) => handler(args[0]));
45
- }
46
- }
47
- clear() {
48
- this._handlers.clear();
49
- }
50
- };
51
-
52
- // libs/twilltac/plugins/compliance/sdk/src/lib/compliance.plugin.ts
53
- var CompliancePlugin = class {
54
- _events = new TypedEventEmitter();
55
- _wildcardHandlers = /* @__PURE__ */ new Set();
56
- _postMessageBus;
57
- _theme;
58
- constructor(opts) {
59
- this._postMessageBus = opts.postMessageBus;
60
- this._theme = opts.initialisationOptions.theme;
61
- opts.iframeElement.style.visibility = "visible";
62
- if (opts.initialisationOptions.sizing === "content" /* CONTENT */) {
63
- opts.iframeElement.style.minHeight = `${opts.initialisationData.documentHeight}px`;
64
- opts.postMessageBus.on("window:resize", (data) => opts.iframeElement.style.minHeight = `${data.height}px`);
65
- opts.postMessageBus.on("navigation:start", () => opts.iframeElement.style.minHeight = "");
66
- }
67
- opts.postMessageBus.on("session:expired-token", () => this._events.emit("session:expired"));
68
- opts.postMessageBus.on("journey:started", () => this._events.emit("flow.journey.started"));
69
- opts.postMessageBus.on("journey.section:started", (data) => this._events.emit("flow.journey.section:started", data));
70
- opts.postMessageBus.on("journey.section:completed", (data) => this._events.emit("flow.journey.section:completed", data));
71
- opts.postMessageBus.on("journey:completed", () => this._events.emit("flow.journey:completed"));
72
- const eventNames = [
73
- "session:expired",
74
- "flow.journey.started",
75
- "flow.journey.section:started",
76
- "flow.journey.section:completed",
77
- "flow.journey:completed"
78
- ];
79
- for (const eventName of eventNames) {
80
- this._events.on(eventName, ((...args) => {
81
- this._wildcardHandlers.forEach((handler) => handler(eventName, args[0]));
82
- }));
83
- }
84
- }
85
- on(eventOrHandler, handler) {
86
- if (typeof eventOrHandler === "function") {
87
- this._wildcardHandlers.add(eventOrHandler);
88
- return () => this._wildcardHandlers.delete(eventOrHandler);
89
- }
90
- return this._events.on(eventOrHandler, handler);
91
- }
92
- get theme() {
93
- return this._theme;
94
- }
95
- setTheme(theme) {
96
- this._theme = theme;
97
- this._postMessageBus.send("theme:change", { theme });
98
- }
99
- destroy() {
100
- this._events.clear();
101
- this._wildcardHandlers.clear();
102
- this._postMessageBus.destroy();
103
- }
104
- };
105
-
106
- // libs/twilltac/plugins/utils/post-messenger/src/lib/post-message.bus.ts
107
- var PostMessageBus = class {
108
- _channel;
109
- _targetOrigin;
110
- _targetWindow;
111
- _defaultTimeout;
112
- _handlers = /* @__PURE__ */ new Map();
113
- _requestHandlers = /* @__PURE__ */ new Map();
114
- _pendingRequests = /* @__PURE__ */ new Map();
115
- _boundMessageHandler;
116
- constructor(options) {
117
- this._channel = options.channel;
118
- this._targetOrigin = options.targetOrigin ?? "*";
119
- this._targetWindow = options.targetWindow ?? window.parent;
120
- this._defaultTimeout = options.defaultTimeout ?? 3e4;
121
- this._boundMessageHandler = (event) => this.handleMessage(event);
122
- window.addEventListener("message", this._boundMessageHandler);
123
- }
124
- send(type, ...args) {
125
- const payload = args[0];
126
- const envelope = {
127
- channel: this._channel,
128
- type,
129
- payload
130
- };
131
- this._targetWindow.postMessage(envelope, this._targetOrigin);
132
- }
133
- on(type, handler) {
134
- if (!this._handlers.has(type)) {
135
- this._handlers.set(type, /* @__PURE__ */ new Set());
136
- }
137
- this._handlers.get(type).add(handler);
138
- return () => this.off(type, handler);
139
- }
140
- off(type, handler) {
141
- const handlers = this._handlers.get(type);
142
- if (handlers) {
143
- handlers.delete(handler);
144
- if (handlers.size === 0) {
145
- this._handlers.delete(type);
146
- }
147
- }
148
- }
149
- once(type, handler) {
150
- const wrappedHandler = (payload) => {
151
- this.off(type, wrappedHandler);
152
- handler(payload);
153
- };
154
- return this.on(type, wrappedHandler);
155
- }
156
- request(type, ...args) {
157
- return new Promise((resolve, reject) => {
158
- const [firstArg, secondArg] = args;
159
- const payload = typeof firstArg === "number" ? void 0 : firstArg;
160
- const timeout = typeof firstArg === "number" ? firstArg : secondArg;
161
- const correlationId = this.generateCorrelationId();
162
- const timeoutMs = timeout ?? this._defaultTimeout;
163
- const timeoutId = setTimeout(() => {
164
- this._pendingRequests.delete(correlationId);
165
- reject(new Error(`Request '${type}' timed out after ${timeoutMs}ms`));
166
- }, timeoutMs);
167
- this._pendingRequests.set(correlationId, {
168
- resolve,
169
- reject,
170
- timeoutId
171
- });
172
- const envelope = {
173
- channel: this._channel,
174
- type,
175
- payload,
176
- correlationId
177
- };
178
- this._targetWindow.postMessage(envelope, this._targetOrigin);
179
- });
180
- }
181
- onRequest(type, handler) {
182
- this._requestHandlers.set(type, handler);
183
- return () => this._requestHandlers.delete(type);
184
- }
185
- destroy() {
186
- window.removeEventListener("message", this._boundMessageHandler);
187
- this._handlers.clear();
188
- this._requestHandlers.clear();
189
- this._pendingRequests.forEach((pending) => {
190
- clearTimeout(pending.timeoutId);
191
- pending.reject(new Error("PostMessageBus destroyed"));
192
- });
193
- this._pendingRequests.clear();
194
- }
195
- handleMessage(event) {
196
- const envelope = event.data;
197
- if (!envelope || envelope.channel !== this._channel) {
198
- return;
199
- }
200
- if (envelope.isResponse && envelope.correlationId) {
201
- this.handleResponse(envelope);
202
- return;
203
- }
204
- if (envelope.correlationId && !envelope.isResponse) {
205
- this.handleRequest(envelope);
206
- return;
207
- }
208
- const handlers = this._handlers.get(envelope.type);
209
- if (handlers) {
210
- handlers.forEach((handler) => handler(envelope.payload));
211
- }
212
- }
213
- handleResponse(envelope) {
214
- const pending = this._pendingRequests.get(envelope.correlationId);
215
- if (!pending) {
216
- return;
217
- }
218
- clearTimeout(pending.timeoutId);
219
- this._pendingRequests.delete(envelope.correlationId);
220
- if (envelope.isError) {
221
- pending.reject(envelope.payload);
222
- } else {
223
- pending.resolve(envelope.payload);
224
- }
225
- }
226
- handleRequest(envelope) {
227
- const handler = this._requestHandlers.get(envelope.type);
228
- if (!handler) {
229
- this.sendResponse(envelope.correlationId, null, true, `No handler registered for '${envelope.type}'`);
230
- return;
231
- }
232
- Promise.resolve().then(() => handler(envelope.payload)).then((result) => {
233
- this.sendResponse(envelope.correlationId, result, false);
234
- }).catch((error) => {
235
- const errorMessage = error instanceof Error ? error.message : String(error);
236
- this.sendResponse(envelope.correlationId, null, true, errorMessage);
237
- });
238
- }
239
- sendResponse(correlationId, payload, isError, errorMessage) {
240
- const envelope = {
241
- channel: this._channel,
242
- type: "__response__",
243
- payload: isError ? { error: errorMessage } : payload,
244
- correlationId,
245
- isResponse: true,
246
- isError
247
- };
248
- this._targetWindow.postMessage(envelope, this._targetOrigin);
249
- }
250
- generateCorrelationId() {
251
- return `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
252
- }
253
- };
254
-
255
- // libs/twilltac/plugins/compliance/sdk/src/lib/create-compliance.plugin.ts
256
- function validateOptions(options) {
257
- if (!options.containerElement) {
258
- throw new Error("[CompliancePlugin] containerElement is required.");
259
- }
260
- if (!(options.containerElement instanceof HTMLElement)) {
261
- throw new Error("[CompliancePlugin] containerElement must be an HTMLElement.");
262
- }
263
- if (!options.data) {
264
- throw new Error("[CompliancePlugin] data is required.");
265
- }
266
- if (!options.data.workspaceSubdomain && !options.data.workspaceReference) {
267
- throw new Error("[CompliancePlugin] one of data.workspaceSubdomain or data.workspaceReference is required.");
268
- }
269
- const validFlows = Object.values(CompliancePluginFlow);
270
- if (!options.data.flow || !validFlows.includes(options.data.flow)) {
271
- throw new Error(`[CompliancePlugin] data.flow is required and must be one of: ${validFlows.join(", ")}.`);
272
- }
273
- if (!options.data.customerReference) {
274
- throw new Error("[CompliancePlugin] data.customerReference is required.");
275
- }
276
- if (!options.data.offerReference) {
277
- throw new Error("[CompliancePlugin] data.offerReference is required.");
3
+ // libs/twilltac/operator/plugins/compliance/sdk/src/lib/compliance-script-loader.ts
4
+ var LIVE_COMPLIANCE_SCRIPT_URL = "https://plugins.twilltac.com/compliance/v1.js";
5
+ var LOCAL_COMPLIANCE_SCRIPT_URL = "https://sdks.plugins.mynextvehicle.app.ngserve/compliance/v1.js";
6
+ var LOCAL_HOSTNAME_SUFFIX = ".ngserve";
7
+ var CREATOR_NAME = "createCompliancePlugin";
8
+ var scriptBeingLoaded = null;
9
+ function complianceScriptUrlFor(pageHostname) {
10
+ return pageHostname.endsWith(LOCAL_HOSTNAME_SUFFIX) ? LOCAL_COMPLIANCE_SCRIPT_URL : LIVE_COMPLIANCE_SCRIPT_URL;
11
+ }
12
+ function creatorOnThePage() {
13
+ const offered = window.twilltac?.[CREATOR_NAME];
14
+ return typeof offered === "function" ? offered : null;
15
+ }
16
+ function scriptOnThePage(url) {
17
+ const existing = Array.from(document.scripts).find((script2) => script2.src === url);
18
+ if (existing) {
19
+ return existing;
20
+ }
21
+ const script = document.createElement("script");
22
+ script.src = url;
23
+ script.async = true;
24
+ (document.head ?? document.documentElement).appendChild(script);
25
+ return script;
26
+ }
27
+ function complianceScriptLoaded(url) {
28
+ if (scriptBeingLoaded) {
29
+ return scriptBeingLoaded;
30
+ }
31
+ const loaded = new Promise((resolveLoaded, rejectLoaded) => {
32
+ const script = scriptOnThePage(url);
33
+ script.addEventListener("load", () => resolveLoaded());
34
+ script.addEventListener("error", () => rejectLoaded(new Error(`[Twilltac] The compliance script could not be loaded from ${url}.`)));
35
+ });
36
+ scriptBeingLoaded = loaded;
37
+ loaded.catch(() => {
38
+ scriptBeingLoaded = null;
39
+ });
40
+ return loaded;
41
+ }
42
+ async function compliancePluginCreator() {
43
+ if (typeof window === "undefined" || typeof document === "undefined") {
44
+ throw new Error("[Twilltac] A plugin can only be created in a browser.");
278
45
  }
279
- if (!options.data.authToken) {
280
- throw new Error("[CompliancePlugin] data.authToken is required.");
46
+ const alreadyOffered = creatorOnThePage();
47
+ if (alreadyOffered) {
48
+ return alreadyOffered;
281
49
  }
282
- const validThemeAppearances = Object.values(CompliancePluginThemeAppearance);
283
- if (options.data.theme !== void 0 && !validThemeAppearances.includes(options.data.theme.appearance)) {
284
- throw new Error(`[CompliancePlugin] data.theme.appearance must be one of: ${validThemeAppearances.join(", ")}.`);
50
+ const url = complianceScriptUrlFor(window.location.hostname);
51
+ await complianceScriptLoaded(url);
52
+ const offered = creatorOnThePage();
53
+ if (!offered) {
54
+ throw new Error(`[Twilltac] The compliance script at ${url} does not offer ${CREATOR_NAME}.`);
285
55
  }
56
+ return offered;
286
57
  }
287
- function createCompliancePlugin(options) {
288
- validateOptions(options);
289
- const sizing = options.data.sizing ?? "content" /* CONTENT */;
290
- const theme = options.data.theme ?? { appearance: "light" /* LIGHT */ };
291
- const resolvedData = { ...options.data, sizing, theme };
292
- const production = !window.location.hostname.endsWith(".ngserve");
293
- const baseUrl = "https://compliance.plugins.twilltac.app";
294
- const url = production ? baseUrl : `${baseUrl}.ngserve`;
295
- const iframe = document.createElement("iframe");
296
- iframe.name = "compliance-plugin-iframe";
297
- iframe.style.width = "100%";
298
- iframe.style.height = "100%";
299
- iframe.style.border = "none";
300
- iframe.style.overflow = "hidden";
301
- iframe.style.visibility = "hidden";
302
- if (sizing === "content" /* CONTENT */) {
303
- iframe.setAttribute("scrolling", "no");
304
- }
305
- const form = document.createElement("form");
306
- form.method = "POST";
307
- form.action = `${url}/en-gb`;
308
- form.target = iframe.name;
309
- form.style.display = "none";
310
- const input = document.createElement("input");
311
- input.type = "hidden";
312
- input.name = "data";
313
- input.value = JSON.stringify(resolvedData);
314
- form.appendChild(input);
315
- options.containerElement.innerHTML = "";
316
- options.containerElement.appendChild(iframe);
317
- options.containerElement.appendChild(form);
318
- const postMessageBus = new PostMessageBus({ channel: "compliance-plugin", targetWindow: iframe.contentWindow });
319
- return new Promise((resolve, rejects) => {
320
- postMessageBus.on("initialisation:success", (data) => {
321
- resolve(
322
- new CompliancePlugin({
323
- initialisationData: data,
324
- initialisationOptions: resolvedData,
325
- postMessageBus,
326
- iframeElement: iframe
327
- })
328
- );
329
- });
330
- postMessageBus.on("initialisation:error", (data) => {
331
- rejects(data.error);
332
- });
333
- form.submit();
334
- });
58
+
59
+ // libs/twilltac/operator/plugins/compliance/sdk/src/lib/create-compliance.package.ts
60
+ async function createCompliancePlugin(options) {
61
+ const create = await compliancePluginCreator();
62
+ return create(options);
335
63
  }
336
64
  export {
337
- CompliancePlugin,
338
65
  createCompliancePlugin
339
66
  };
package/package.json CHANGED
@@ -1,8 +1,24 @@
1
1
  {
2
2
  "name": "@twilltac/compliance-sdk",
3
- "version": "0.5.0",
3
+ "version": "1.0.0",
4
+ "description": "The Twilltac compliance plugin for partner applications: types and a loader for the Twilltac compliance script.",
5
+ "sideEffects": false,
4
6
  "type": "module",
5
- "main": "./src/index.js",
6
- "types": "./src/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./index.d.ts",
10
+ "import": "./index.js",
11
+ "require": "./index.cjs"
12
+ }
13
+ },
14
+ "main": "./index.cjs",
15
+ "module": "./index.js",
16
+ "types": "./index.d.ts",
17
+ "files": [
18
+ "index.js",
19
+ "index.cjs",
20
+ "index.d.ts",
21
+ "README.md"
22
+ ],
7
23
  "dependencies": {}
8
24
  }
@@ -1 +0,0 @@
1
- 29591325450-1
@@ -1,2 +0,0 @@
1
- export { CompliancePlugin } from './lib/compliance.plugin';
2
- export { createCompliancePlugin } from './lib/create-compliance.plugin';
@@ -1,28 +0,0 @@
1
- interface SectionStartedEvent {
2
- readonly name: string;
3
- readonly reference: string;
4
- }
5
- interface SectionEndedEvent {
6
- readonly name: string;
7
- readonly reference: string;
8
- readonly recommendations: {
9
- readonly externalReference: string;
10
- readonly price: number | null;
11
- readonly regulated: boolean;
12
- readonly title: string;
13
- readonly description: string;
14
- }[];
15
- }
16
- export interface CompliancePluginEvents {
17
- /** Emits when the user starts the journey and Initial Disclosure Document is generated. */
18
- ['flow.journey.started']: void;
19
- /** Emits when the user starts a section. */
20
- ['flow.journey.section:started']: SectionStartedEvent;
21
- /** Emits when the user completes the question set and submits their recommendations. */
22
- ['flow.journey.section:completed']: SectionEndedEvent;
23
- /** Emits when the user completes the journey and summary page is presented. */
24
- ['flow.journey:completed']: void;
25
- /** Emits when the session has expired. This would typically trigger your auth flow followed by re-initialising the plugin. */
26
- ['session:expired']: void;
27
- }
28
- export {};
@@ -1,24 +0,0 @@
1
- import { CompliancePluginInitialisationData, CompliancePluginPostMessages, CompliancePluginTheme, InitialisationData } from '@twilltac/compliance-plugin-types';
2
- import { EventHandler, ExtractEventData } from '@twilltac/plugin-skd-event-emitter';
3
- import { PostMessageBus } from '@twilltac/plugin-skd-post-messenger';
4
- import { CompliancePluginEvents } from './compliance-plugin.events';
5
- type WildcardHandler = (event: keyof CompliancePluginEvents & string, data: ExtractEventData<CompliancePluginEvents[keyof CompliancePluginEvents]>) => void;
6
- interface CompliancePluginData {
7
- postMessageBus: PostMessageBus<CompliancePluginPostMessages>;
8
- initialisationData: InitialisationData;
9
- initialisationOptions: CompliancePluginInitialisationData;
10
- iframeElement: HTMLIFrameElement;
11
- }
12
- export declare class CompliancePlugin {
13
- private readonly _events;
14
- private readonly _wildcardHandlers;
15
- private readonly _postMessageBus;
16
- private _theme;
17
- constructor(opts: CompliancePluginData);
18
- on(handler: WildcardHandler): () => void;
19
- on<K extends keyof CompliancePluginEvents & string>(event: K, handler: EventHandler<ExtractEventData<CompliancePluginEvents[K]>>): () => void;
20
- get theme(): CompliancePluginTheme;
21
- setTheme(theme: CompliancePluginTheme): void;
22
- destroy(): void;
23
- }
24
- export {};
@@ -1,11 +0,0 @@
1
- import { CompliancePluginInitialisationData, CompliancePluginTheme, PluginInitialisationSizing } from '@twilltac/compliance-plugin-types';
2
- import { CompliancePlugin } from './compliance.plugin';
3
- interface InitialisationOptions {
4
- readonly containerElement: HTMLElement;
5
- readonly data: Omit<CompliancePluginInitialisationData, 'sizing' | 'theme'> & {
6
- readonly sizing?: PluginInitialisationSizing;
7
- readonly theme?: CompliancePluginTheme;
8
- };
9
- }
10
- export declare function createCompliancePlugin(options: InitialisationOptions): Promise<CompliancePlugin>;
11
- export {};
@@ -1,2 +0,0 @@
1
- export * from './lib/compliance-plugin-initialisation.data';
2
- export * from './lib/compliance-plugin-post.messages';
@@ -1,25 +0,0 @@
1
- export declare enum CompliancePluginFlow {
2
- JOURNEY = "journey",
3
- HANDOVER = "handover"
4
- }
5
- export declare enum PluginInitialisationSizing {
6
- CONTAINER = "container",
7
- CONTENT = "content"
8
- }
9
- export declare enum CompliancePluginThemeAppearance {
10
- LIGHT = "light",
11
- DARK = "dark"
12
- }
13
- export interface CompliancePluginTheme {
14
- readonly appearance: CompliancePluginThemeAppearance;
15
- }
16
- export interface CompliancePluginInitialisationData {
17
- readonly workspaceSubdomain?: string;
18
- readonly workspaceReference?: string;
19
- readonly flow: CompliancePluginFlow;
20
- readonly customerReference: string;
21
- readonly offerReference: string;
22
- readonly authToken: string;
23
- readonly sizing: PluginInitialisationSizing;
24
- readonly theme: CompliancePluginTheme;
25
- }
@@ -1,65 +0,0 @@
1
- import { CompliancePluginTheme } from './compliance-plugin-initialisation.data';
2
- export interface InitialisationData {
3
- readonly appInstanceId: string;
4
- readonly documentHeight: number;
5
- }
6
- export interface StandardPluginPostMessages {
7
- ['window:resize']: {
8
- payload: {
9
- height: number;
10
- };
11
- };
12
- ['theme:change']: {
13
- payload: {
14
- theme: CompliancePluginTheme;
15
- };
16
- };
17
- ['navigation:start']: void;
18
- ['navigation:end']: void;
19
- ['initialisation:success']: {
20
- payload: InitialisationData;
21
- };
22
- ['initialisation:error']: {
23
- payload: {
24
- error: Error;
25
- };
26
- response: {
27
- error: Error;
28
- };
29
- };
30
- }
31
- interface SectionStartedEvent {
32
- readonly name: string;
33
- readonly reference: string;
34
- }
35
- interface SectionEndedEvent {
36
- readonly name: string;
37
- readonly reference: string;
38
- readonly recommendations: ProductRecommendation[];
39
- }
40
- interface ProductRecommendation {
41
- readonly externalReference: string;
42
- readonly price: number | null;
43
- readonly regulated: boolean;
44
- readonly title: string;
45
- readonly description: string;
46
- }
47
- interface ComplianceDocument {
48
- readonly name: string;
49
- readonly reference: string;
50
- }
51
- export interface CompliancePluginPostMessages extends StandardPluginPostMessages {
52
- ['session:expired-token']: void;
53
- ['journey:started']: void;
54
- ['journey:completed']: void;
55
- ['journey.section:started']: {
56
- payload: SectionStartedEvent;
57
- };
58
- ['journey.section:completed']: {
59
- payload: SectionEndedEvent;
60
- };
61
- ['documents:loaded']: {
62
- payload: ComplianceDocument[];
63
- };
64
- }
65
- export {};
@@ -1,3 +0,0 @@
1
- export { NoopPostMessageBus } from './lib/noop-post-message.bus';
2
- export type { ExtractPayload, HasPayload, IPostMessageBus } from './lib/post-message-bus.interface';
3
- export { PostMessageBus } from './lib/post-message.bus';
@@ -1,13 +0,0 @@
1
- import { ExtractPayload, ExtractResponse, HasPayload, IPostMessageBus, MessageHandler, SendArgs } from './post-message-bus.interface';
2
- export declare class NoopPostMessageBus<TMessages = Record<string, {
3
- payload: unknown;
4
- response?: unknown;
5
- }>> implements IPostMessageBus<TMessages> {
6
- send<K extends keyof TMessages & string>(_type: K, ..._args: SendArgs<TMessages[K]>): void;
7
- on<K extends keyof TMessages & string>(_type: K, _handler: MessageHandler<ExtractPayload<TMessages[K]>>): () => void;
8
- off<K extends keyof TMessages & string>(_type: K, _handler: MessageHandler<ExtractPayload<TMessages[K]>>): void;
9
- once<K extends keyof TMessages & string>(_type: K, _handler: MessageHandler<ExtractPayload<TMessages[K]>>): () => void;
10
- request<K extends keyof TMessages & string>(_type: K, ..._args: HasPayload<TMessages[K]> extends true ? [payload: ExtractPayload<TMessages[K]>, timeout?: number] : [timeout?: number]): Promise<ExtractResponse<TMessages[K]>>;
11
- onRequest(): () => void;
12
- destroy(): void;
13
- }
@@ -1,45 +0,0 @@
1
- export type MessageHandler<T = unknown> = (payload: T) => void;
2
- export type RequestHandler<TRequest = unknown, TResponse = unknown> = (payload: TRequest) => TResponse | Promise<TResponse>;
3
- export type ExtractPayload<T> = T extends {
4
- payload: infer P;
5
- } ? P : never;
6
- export type ExtractResponse<T> = T extends {
7
- response: infer R;
8
- } ? R : undefined;
9
- export type HasPayload<T> = T extends {
10
- payload: unknown;
11
- } ? true : false;
12
- export type SendArgs<T> = T extends {
13
- payload: infer P;
14
- } ? [payload: P] : [];
15
- export interface PostMessageEnvelope<T = unknown> {
16
- channel: string;
17
- type: string;
18
- payload: T;
19
- correlationId?: string;
20
- isResponse?: boolean;
21
- isError?: boolean;
22
- }
23
- export interface PendingRequest<T> {
24
- resolve: (value: T) => void;
25
- reject: (reason: unknown) => void;
26
- timeoutId: ReturnType<typeof setTimeout>;
27
- }
28
- export interface PostMessageBusOptions {
29
- channel: string;
30
- targetOrigin?: string;
31
- targetWindow?: Window;
32
- defaultTimeout?: number;
33
- }
34
- export interface IPostMessageBus<TMessages = Record<string, {
35
- payload: unknown;
36
- response?: unknown;
37
- }>> {
38
- send<K extends keyof TMessages & string>(type: K, ...args: SendArgs<TMessages[K]>): void;
39
- on<K extends keyof TMessages & string>(type: K, handler: MessageHandler<ExtractPayload<TMessages[K]>>): () => void;
40
- off<K extends keyof TMessages & string>(type: K, handler: MessageHandler<ExtractPayload<TMessages[K]>>): void;
41
- once<K extends keyof TMessages & string>(type: K, handler: MessageHandler<ExtractPayload<TMessages[K]>>): () => void;
42
- request<K extends keyof TMessages & string>(type: K, ...args: HasPayload<TMessages[K]> extends true ? [payload: ExtractPayload<TMessages[K]>, timeout?: number] : [timeout?: number]): Promise<ExtractResponse<TMessages[K]>>;
43
- onRequest<K extends keyof TMessages & string>(type: K, handler: RequestHandler<ExtractPayload<TMessages[K]>, ExtractResponse<TMessages[K]>>): () => void;
44
- destroy(): void;
45
- }
@@ -1,28 +0,0 @@
1
- import { ExtractPayload, ExtractResponse, HasPayload, IPostMessageBus, MessageHandler, PostMessageBusOptions, RequestHandler, SendArgs } from './post-message-bus.interface';
2
- /** @internal */
3
- export declare class PostMessageBus<TMessages = Record<string, {
4
- payload: unknown;
5
- response?: unknown;
6
- }>> implements IPostMessageBus<TMessages> {
7
- private readonly _channel;
8
- private readonly _targetOrigin;
9
- private readonly _targetWindow;
10
- private readonly _defaultTimeout;
11
- private readonly _handlers;
12
- private readonly _requestHandlers;
13
- private readonly _pendingRequests;
14
- private readonly _boundMessageHandler;
15
- constructor(options: PostMessageBusOptions);
16
- send<K extends keyof TMessages & string>(type: K, ...args: SendArgs<TMessages[K]>): void;
17
- on<K extends keyof TMessages & string>(type: K, handler: MessageHandler<ExtractPayload<TMessages[K]>>): () => void;
18
- off<K extends keyof TMessages & string>(type: K, handler: MessageHandler<ExtractPayload<TMessages[K]>>): void;
19
- once<K extends keyof TMessages & string>(type: K, handler: MessageHandler<ExtractPayload<TMessages[K]>>): () => void;
20
- request<K extends keyof TMessages & string>(type: K, ...args: HasPayload<TMessages[K]> extends true ? [payload: ExtractPayload<TMessages[K]>, timeout?: number] : [timeout?: number]): Promise<ExtractResponse<TMessages[K]>>;
21
- onRequest<K extends keyof TMessages & string>(type: K, handler: RequestHandler<ExtractPayload<TMessages[K]>, ExtractResponse<TMessages[K]>>): () => void;
22
- destroy(): void;
23
- private handleMessage;
24
- private handleResponse;
25
- private handleRequest;
26
- private sendResponse;
27
- private generateCorrelationId;
28
- }
@@ -1,2 +0,0 @@
1
- export * from './lib/typed-event-emitter';
2
- export * from './lib/typed-event-emitter.interface';
@@ -1,11 +0,0 @@
1
- import { EventHandler, ExtractEventData, ITypedEventEmitter, OptionalIfVoid } from './typed-event-emitter.interface';
2
- export declare class TypedEventEmitter<TEvents = Record<string, {
3
- data: unknown;
4
- }>> implements ITypedEventEmitter<TEvents> {
5
- private readonly _handlers;
6
- on<K extends keyof TEvents & string>(event: K, handler: EventHandler<ExtractEventData<TEvents[K]>>): () => void;
7
- off<K extends keyof TEvents & string>(event: K, handler: EventHandler<ExtractEventData<TEvents[K]>>): void;
8
- once<K extends keyof TEvents & string>(event: K, handler: EventHandler<ExtractEventData<TEvents[K]>>): () => void;
9
- emit<K extends keyof TEvents & string>(event: K, ...args: OptionalIfVoid<ExtractEventData<TEvents[K]>>): void;
10
- clear(): void;
11
- }
@@ -1,11 +0,0 @@
1
- export type EventHandler<T = unknown> = (data: T) => void;
2
- export type ExtractEventData<T> = T extends void ? void : T;
3
- export type OptionalIfVoid<T> = T extends void ? [] : [data: T];
4
- export interface ITypedEventEmitter<TEvents = Record<string, {
5
- data: unknown;
6
- }>> {
7
- on<K extends keyof TEvents & string>(event: K, handler: EventHandler<ExtractEventData<TEvents[K]>>): () => void;
8
- off<K extends keyof TEvents & string>(event: K, handler: EventHandler<ExtractEventData<TEvents[K]>>): void;
9
- once<K extends keyof TEvents & string>(event: K, handler: EventHandler<ExtractEventData<TEvents[K]>>): () => void;
10
- emit<K extends keyof TEvents & string>(event: K, ...args: OptionalIfVoid<ExtractEventData<TEvents[K]>>): void;
11
- }