@knot-technologies/seatmap 0.3.1-dev.0 → 0.4.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -20,1101 +20,809 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
- mountSeatmap: () => mountSeatmap,
24
- resolveSeatmapEnvironment: () => import_seatmap_types6.resolveSeatmapEnvironment
23
+ getSeatmapEngineOrigin: () => getSeatmapEngineOrigin,
24
+ mountSeatmap: () => mountSeatmap
25
25
  });
26
26
  module.exports = __toCommonJS(index_exports);
27
27
 
28
- // ../seatmap-rpc/src/envelope.ts
29
- var RPC_PROTOCOL_VERSION = 1;
30
- function isRecord(value) {
31
- return typeof value === "object" && value !== null;
32
- }
33
- function hasOwn(value, key) {
34
- return Object.prototype.hasOwnProperty.call(value, key);
35
- }
36
- function isRpcErrorShape(value) {
37
- return isRecord(value) && typeof value.code === "string" && typeof value.message === "string";
38
- }
39
- function isRpcRequest(value) {
40
- return value.kind === "request" && typeof value.id === "string" && typeof value.method === "string" && hasOwn(value, "args") && typeof value.channelId === "string" && value.channelId.length > 0 && value.version === RPC_PROTOCOL_VERSION;
41
- }
42
- function isRpcResponse(value) {
43
- if (value.kind !== "response" || typeof value.id !== "string" || typeof value.ok !== "boolean" || typeof value.channelId !== "string" || value.channelId.length === 0 || value.version !== RPC_PROTOCOL_VERSION) {
28
+ // ../seatmap-rpc/dist/envelope.js
29
+ var PROTOCOL_VERSION = 1;
30
+ var ENVELOPE_TYPES = [
31
+ "request",
32
+ "reply",
33
+ "event",
34
+ "hello"
35
+ ];
36
+ function isEnvelopeType(value) {
37
+ return ENVELOPE_TYPES.includes(value);
38
+ }
39
+ function isEnvelope(value) {
40
+ if (typeof value !== "object" || value === null) {
44
41
  return false;
45
42
  }
46
- if (value.ok) return hasOwn(value, "result");
47
- return isRpcErrorShape(value.error);
48
- }
49
- function isRpcEvent(value) {
50
- return value.kind === "event" && typeof value.name === "string" && hasOwn(value, "payload") && typeof value.channelId === "string" && value.channelId.length > 0 && value.version === RPC_PROTOCOL_VERSION;
51
- }
52
- function isRpcHello(value) {
53
- return value.kind === "hello" && (value.role === "engine" || value.role === "facade") && typeof value.build === "string" && typeof value.channelId === "string" && value.channelId.length > 0 && typeof value.version === "number" && Number.isFinite(value.version);
54
- }
55
- function isRpcMessage(value) {
56
- if (!isRecord(value)) return false;
57
- return isRpcRequest(value) || isRpcResponse(value) || isRpcEvent(value) || isRpcHello(value);
43
+ const candidate = value;
44
+ return candidate.protocolVersion === PROTOCOL_VERSION && typeof candidate.channelId === "string" && isEnvelopeType(candidate.type);
58
45
  }
59
46
 
60
- // ../seatmap-rpc/src/errors.ts
47
+ // ../seatmap-rpc/dist/endpoint.js
61
48
  var RpcError = class extends Error {
62
49
  code;
63
- data;
64
- constructor(shape) {
65
- super(shape.message);
50
+ method;
51
+ constructor(code, message, method) {
52
+ super(message);
66
53
  this.name = "RpcError";
67
- this.code = shape.code;
68
- this.data = shape.data;
69
- }
70
- toShape() {
71
- return { code: this.code, message: this.message, data: this.data };
54
+ this.code = code;
55
+ this.method = method;
72
56
  }
73
57
  };
74
- var RpcTimeoutError = class extends RpcError {
75
- constructor(method, ms) {
76
- super({
77
- code: "RPC_TIMEOUT",
78
- message: `RPC '${method}' timed out after ${ms}ms`
79
- });
80
- this.name = "RpcTimeoutError";
81
- }
82
- };
83
- var RpcVersionError = class extends RpcError {
84
- constructor(local, remote) {
85
- super({
86
- code: "RPC_VERSION_MISMATCH",
87
- message: `RPC protocol mismatch: local v${local}, remote v${remote}`,
88
- data: { local, remote }
89
- });
90
- this.name = "RpcVersionError";
91
- }
92
- };
93
- function fromShape(shape) {
94
- return new RpcError(shape);
95
- }
96
-
97
- // ../seatmap-rpc/src/windowTransport.ts
98
- function createWindowTransport(opts) {
99
- if (opts.targetOrigin === "*") {
100
- throw new Error("window transport targetOrigin must not be '*'");
101
- }
102
- return {
103
- post(message) {
104
- opts.target.postMessage(message, opts.targetOrigin);
105
- },
106
- onMessage(handler) {
107
- const listener = (event) => {
108
- if (!opts.acceptOrigin(event.origin)) return;
109
- if (event.source !== opts.target) return;
110
- if (!isRpcMessage(event.data)) return;
111
- handler(event.data);
112
- };
113
- opts.local.addEventListener("message", listener);
114
- return () => opts.local.removeEventListener("message", listener);
115
- }
116
- };
117
- }
118
-
119
- // ../seatmap-rpc/src/endpoint.ts
120
- var RpcEndpoint = class {
121
- transport;
122
- role;
123
- build;
124
- channelId;
125
- timeoutMs;
126
- off;
127
- pending = /* @__PURE__ */ new Map();
128
- handlers = /* @__PURE__ */ new Map();
129
- listeners = /* @__PURE__ */ new Map();
130
- helloFromPeer = null;
131
- helloWaiters = /* @__PURE__ */ new Set();
132
- seq = 0;
133
- disposed = false;
134
- constructor(opts) {
135
- this.transport = opts.transport;
136
- this.role = opts.role;
137
- this.build = opts.build;
138
- this.channelId = opts.channelId ?? "default";
139
- this.timeoutMs = opts.timeoutMs ?? 1e4;
140
- this.off = this.transport.onMessage((m) => this.onMessage(m));
141
- }
142
- request(method, args) {
143
- if (this.disposed) {
144
- return Promise.reject(
145
- new RpcError({ code: "RPC_DISPOSED", message: "endpoint disposed" })
146
- );
58
+ function createEndpoint({ transport, channelId, requestTimeoutMs = 1e4 }) {
59
+ const pending = /* @__PURE__ */ new Map();
60
+ const eventHandlers = /* @__PURE__ */ new Map();
61
+ const requestHandlers = /* @__PURE__ */ new Map();
62
+ let nextId = 1;
63
+ let closed = false;
64
+ const detach = transport.onMessage((message) => {
65
+ if (!isEnvelope(message) || message.channelId !== channelId) {
66
+ return;
147
67
  }
148
- const id = `${this.role}:${++this.seq}`;
149
- const req = {
150
- kind: "request",
151
- id,
152
- method,
153
- args,
154
- channelId: this.channelId,
155
- version: RPC_PROTOCOL_VERSION
156
- };
157
- return new Promise((resolve, reject) => {
158
- const timer = setTimeout(() => {
159
- this.pending.delete(id);
160
- reject(new RpcTimeoutError(method, this.timeoutMs));
161
- }, this.timeoutMs);
162
- this.pending.set(id, {
163
- resolve,
164
- reject,
165
- timer,
166
- method
167
- });
168
- try {
169
- this.transport.post(req);
170
- } catch (err) {
171
- clearTimeout(timer);
172
- this.pending.delete(id);
173
- reject(err);
174
- }
175
- });
176
- }
177
- handle(method, handler) {
178
- this.assertActive();
179
- this.handlers.set(method, handler);
180
- }
181
- emit(name, payload) {
182
- this.assertActive();
183
- this.transport.post({
184
- kind: "event",
185
- name,
186
- payload,
187
- channelId: this.channelId,
188
- version: RPC_PROTOCOL_VERSION
189
- });
190
- }
191
- on(name, listener) {
192
- this.assertActive();
193
- let set = this.listeners.get(name);
194
- if (!set) {
195
- set = /* @__PURE__ */ new Set();
196
- this.listeners.set(name, set);
68
+ if (message.type === "reply") {
69
+ settleReply(message);
70
+ return;
197
71
  }
198
- set.add(listener);
199
- return () => {
200
- set.delete(listener);
201
- };
202
- }
203
- handshake() {
204
- if (this.disposed) {
205
- return Promise.reject(this.disposedError());
72
+ if (message.type === "request") {
73
+ void serveRequest(message);
74
+ return;
206
75
  }
207
- try {
208
- this.transport.post({
209
- kind: "hello",
210
- role: this.role,
211
- build: this.build,
212
- channelId: this.channelId,
213
- version: RPC_PROTOCOL_VERSION
214
- });
215
- } catch (err) {
216
- return Promise.reject(err);
76
+ if (message.type === "event" && typeof message.event === "string") {
77
+ eventHandlers.get(message.event)?.forEach((handler) => handler(message.payload));
217
78
  }
218
- if (this.helloFromPeer) {
219
- const hello = this.helloFromPeer;
220
- return Promise.resolve().then(() => this.settleHello(hello));
79
+ });
80
+ function settleReply(message) {
81
+ if (typeof message.id !== "number") {
82
+ return;
221
83
  }
222
- return new Promise((resolve, reject) => {
223
- this.helloWaiters.add({ resolve, reject });
224
- });
225
- }
226
- dispose() {
227
- if (this.disposed) return;
228
- this.disposed = true;
229
- this.off();
230
- const err = this.disposedError();
231
- for (const p of this.pending.values()) {
232
- clearTimeout(p.timer);
233
- p.reject(err);
84
+ const settlers = pending.get(message.id);
85
+ if (!settlers) {
86
+ return;
234
87
  }
235
- this.pending.clear();
236
- for (const waiter of this.helloWaiters) {
237
- waiter.reject(err);
88
+ pending.delete(message.id);
89
+ clearTimeout(settlers.timeout);
90
+ if (message.error) {
91
+ settlers.reject(new RpcError(message.error.code, message.error.message, message.error.method));
92
+ return;
238
93
  }
239
- this.helloWaiters.clear();
240
- this.handlers.clear();
241
- this.listeners.clear();
94
+ settlers.resolve(message.result);
242
95
  }
243
- disposedError() {
244
- return new RpcError({ code: "RPC_DISPOSED", message: "endpoint disposed" });
245
- }
246
- assertActive() {
247
- if (this.disposed) throw this.disposedError();
96
+ function sendMethodError(message, error) {
97
+ transport.send({
98
+ protocolVersion: PROTOCOL_VERSION,
99
+ channelId,
100
+ type: "reply",
101
+ id: message.id,
102
+ error: {
103
+ code: error.code,
104
+ message: error.message,
105
+ method: error.method ?? message.method
106
+ }
107
+ });
248
108
  }
249
- settleHello(hello) {
250
- if (hello.version !== RPC_PROTOCOL_VERSION) {
251
- throw new RpcVersionError(RPC_PROTOCOL_VERSION, hello.version);
109
+ async function serveRequest(message) {
110
+ if (typeof message.id !== "number" || typeof message.method !== "string") {
111
+ return;
252
112
  }
253
- return { build: hello.build };
254
- }
255
- onMessage(message) {
256
- if (this.disposed) return;
257
- if (!isRpcMessage(message)) return;
258
- if (message.channelId !== this.channelId) return;
259
- if (message.kind === "request") void this.onRequest(message);
260
- else if (message.kind === "response") this.onResponse(message);
261
- else if (message.kind === "event") this.onEvent(message);
262
- else if (message.kind === "hello") this.onHello(message);
263
- }
264
- async onRequest(req) {
265
- if (this.disposed) return;
266
- const handler = this.handlers.get(req.method);
113
+ const handler = requestHandlers.get(message.method);
267
114
  if (!handler) {
268
- if (this.disposed) return;
269
- this.transport.post({
270
- kind: "response",
271
- id: req.id,
272
- ok: false,
273
- error: {
274
- code: "RPC_METHOD_NOT_FOUND",
275
- message: `no handler for '${req.method}'`
276
- },
277
- channelId: this.channelId,
278
- version: RPC_PROTOCOL_VERSION
279
- });
115
+ sendMethodError(message, new RpcError("METHOD_NOT_IMPLEMENTED", `Method '${message.method}' is not implemented`, message.method));
280
116
  return;
281
117
  }
282
118
  try {
283
- const result = await handler(req.args);
284
- if (this.disposed) return;
285
- this.transport.post({
286
- kind: "response",
287
- id: req.id,
288
- ok: true,
289
- result,
290
- channelId: this.channelId,
291
- version: RPC_PROTOCOL_VERSION
292
- });
293
- } catch (err) {
294
- if (this.disposed) return;
295
- const shape = err instanceof RpcError ? err.toShape() : { code: "RPC_HANDLER_ERROR", message: String(err) };
296
- this.transport.post({
297
- kind: "response",
298
- id: req.id,
299
- ok: false,
300
- error: shape,
301
- channelId: this.channelId,
302
- version: RPC_PROTOCOL_VERSION
119
+ const result = await handler(message.params);
120
+ transport.send({
121
+ protocolVersion: PROTOCOL_VERSION,
122
+ channelId,
123
+ type: "reply",
124
+ id: message.id,
125
+ result
303
126
  });
127
+ } catch (error) {
128
+ sendMethodError(message, error instanceof RpcError ? error : new RpcError("ENGINE_INCOMPATIBLE", error instanceof Error ? error.message : "RPC handler failed", message.method));
304
129
  }
305
130
  }
306
- onResponse(res) {
307
- if (this.disposed) return;
308
- const pending = this.pending.get(res.id);
309
- if (!pending) return;
310
- clearTimeout(pending.timer);
311
- this.pending.delete(res.id);
312
- if (res.ok) pending.resolve(res.result);
313
- else pending.reject(fromShape(res.error));
314
- }
315
- onEvent(evt) {
316
- if (this.disposed) return;
317
- const set = this.listeners.get(evt.name);
318
- if (!set) return;
319
- for (const l of [...set]) l(evt.payload);
320
- }
321
- onHello(hello) {
322
- if (this.disposed) return;
323
- this.helloFromPeer = { build: hello.build, version: hello.version };
324
- try {
325
- const peer = this.settleHello(this.helloFromPeer);
326
- for (const waiter of this.helloWaiters) {
327
- waiter.resolve(peer);
131
+ return {
132
+ request(method, params) {
133
+ if (closed) {
134
+ return Promise.reject(new RpcError("CHART_DESTROYED", "The chart has been destroyed", method));
135
+ }
136
+ const id = nextId++;
137
+ return new Promise((resolve, reject) => {
138
+ const timeout = setTimeout(() => {
139
+ pending.delete(id);
140
+ reject(new RpcError("ENGINE_UNREACHABLE", `Engine did not reply to '${method}' within ${requestTimeoutMs}ms`, method));
141
+ }, requestTimeoutMs);
142
+ pending.set(id, { resolve, reject, method, timeout });
143
+ try {
144
+ transport.send({
145
+ protocolVersion: PROTOCOL_VERSION,
146
+ channelId,
147
+ type: "request",
148
+ id,
149
+ method,
150
+ params
151
+ });
152
+ } catch {
153
+ clearTimeout(timeout);
154
+ pending.delete(id);
155
+ reject(new RpcError("ENGINE_UNREACHABLE", `Engine is unreachable for '${method}'`, method));
156
+ }
157
+ });
158
+ },
159
+ handle(method, handler) {
160
+ requestHandlers.set(method, handler);
161
+ return () => {
162
+ if (requestHandlers.get(method) === handler) {
163
+ requestHandlers.delete(method);
164
+ }
165
+ };
166
+ },
167
+ emit(event, payload) {
168
+ if (closed) {
169
+ return;
328
170
  }
329
- } catch (err) {
330
- for (const waiter of this.helloWaiters) {
331
- waiter.reject(err);
171
+ transport.send({
172
+ protocolVersion: PROTOCOL_VERSION,
173
+ channelId,
174
+ type: "event",
175
+ event,
176
+ payload
177
+ });
178
+ },
179
+ on(event, handler) {
180
+ const forEvent = eventHandlers.get(event) ?? /* @__PURE__ */ new Set();
181
+ forEvent.add(handler);
182
+ eventHandlers.set(event, forEvent);
183
+ return () => {
184
+ forEvent.delete(handler);
185
+ };
186
+ },
187
+ close() {
188
+ if (closed) {
189
+ return;
332
190
  }
191
+ closed = true;
192
+ detach();
193
+ pending.forEach(({ reject, method, timeout }) => {
194
+ clearTimeout(timeout);
195
+ reject(new RpcError("CHART_DESTROYED", "The chart has been destroyed", method));
196
+ });
197
+ pending.clear();
198
+ eventHandlers.clear();
199
+ requestHandlers.clear();
200
+ transport.close();
333
201
  }
334
- this.helloWaiters.clear();
335
- }
336
- };
337
-
338
- // ../seatmap-rpc/src/internal.ts
339
- var ENGINE_RESIZED = "engineResized";
340
- function isEngineResizedPayload(value) {
341
- return typeof value === "object" && value !== null && "height" in value && typeof value.height === "number" && Number.isFinite(value.height) && value.height > 0;
202
+ };
342
203
  }
343
204
 
344
- // src/mountSeatmap.ts
345
- var import_seatmap_types5 = require("@knot-technologies/seatmap-types");
346
-
347
- // src/createChart.ts
348
- var import_seatmap_types = require("@knot-technologies/seatmap-types");
349
-
350
- // src/configSerialization.ts
351
- var ON_CALLBACK_KEY = /^on[A-Z]/;
352
- var FUNCTION_HATCHES = /* @__PURE__ */ new Set(["objectColor", "tooltipText"]);
353
- var FACADE_ONLY_KEYS = /* @__PURE__ */ new Set(["environment"]);
354
- function stringifyFunctionHatch(key, value) {
355
- if (typeof value !== "function") {
356
- throw new TypeError(
357
- `@knot-technologies/seatmap: ${key} must be a function`
358
- );
359
- }
360
- return value.toString();
361
- }
362
- function serializePricing(pricing) {
363
- const out = { ...pricing };
364
- if (pricing.priceFormatter !== void 0) {
365
- out.priceFormatter = stringifyFunctionHatch(
366
- "pricing.priceFormatter",
367
- pricing.priceFormatter
368
- );
369
- }
370
- return out;
371
- }
372
- function serializeConfigForWire(config, options = {}) {
373
- const out = {};
374
- for (const [key, value] of Object.entries(config)) {
375
- if (ON_CALLBACK_KEY.test(key)) continue;
376
- if (FACADE_ONLY_KEYS.has(key)) continue;
377
- if (value === void 0 && options.skipUndefined) continue;
378
- if (FUNCTION_HATCHES.has(key)) {
379
- out[key] = value === void 0 ? void 0 : stringifyFunctionHatch(key, value);
380
- continue;
205
+ // ../seatmap-rpc/dist/windowTransport.js
206
+ function createWindowTransport({ target, targetOrigin, channelId }) {
207
+ if (targetOrigin === "*") {
208
+ throw new Error("A wildcard target origin is not allowed; pass the exact engine origin");
209
+ }
210
+ const listeners = /* @__PURE__ */ new Set();
211
+ const receive = (event) => {
212
+ if (event.origin !== targetOrigin || event.source !== target) {
213
+ return;
381
214
  }
382
- if (key === "pricing") {
383
- out.pricing = value === void 0 ? void 0 : serializePricing(value);
384
- continue;
215
+ if (!isEnvelope(event.data) || event.data.channelId !== channelId) {
216
+ return;
385
217
  }
386
- out[key] = value;
387
- }
388
- return out;
389
- }
390
-
391
- // src/createChart.ts
392
- function createChart(deps) {
393
- const { endpoint, getHoldState, holdBestAvailable: holdBestAvailable2, teardown, changeConfig } = deps;
394
- const req = (method, args) => endpoint.request(method, args);
218
+ listeners.forEach((listener) => listener(event.data));
219
+ };
220
+ window.addEventListener("message", receive);
395
221
  return {
396
- selectObjects: (ids) => req("selectObjects", ids),
397
- deselectObjects: (ids) => req("deselectObjects", ids),
398
- clearSelection: () => req("clearSelection", void 0),
399
- listSelectedObjects: () => req("listSelectedObjects", void 0),
400
- trySelectObjects: (ids) => req("trySelectObjects", ids),
401
- doSelectObjects: (ids) => req("doSelectObjects", ids),
402
- setObjectQuantity: (id, quantity) => req("setObjectQuantity", [id, quantity]),
403
- highlightObjects: (ids, color) => req("highlightObjects", [ids, color]),
404
- clearHighlights: () => req("clearHighlights", void 0),
405
- pulse: (ids) => req("pulse", ids),
406
- unpulse: (ids) => req("unpulse", ids),
407
- spotlight: (ids) => req("spotlight", ids),
408
- clearSpotlight: () => req("clearSpotlight", void 0),
409
- setSpotlightObjects: (ids) => req("setSpotlightObjects", ids),
410
- disableObjects: (ids) => req("disableObjects", ids),
411
- enableObjects: (ids) => req("enableObjects", ids),
412
- setMetadata: (entries) => req("setMetadata", entries),
413
- setCategoryMetadata: (entries) => req("setCategoryMetadata", entries),
414
- selectCategories: (keys) => req("selectCategories", keys),
415
- deselectCategories: (keys) => req("deselectCategories", keys),
416
- listCategories: () => req(
417
- "listCategories",
418
- void 0
419
- ),
420
- findObject: (label) => req("findObject", label),
421
- holdBestAvailable: holdBestAvailable2,
422
- resetView: () => req("resetView", void 0),
423
- zoomToObjects: (ids) => req("zoomToObjects", ids),
424
- zoomToSelectedObjects: () => req("zoomToSelectedObjects", void 0),
425
- zoomToSection: (sectionId) => req("zoomToSection", sectionId),
426
- changeConfig: async (patch) => {
427
- (0, import_seatmap_types.runtimeConfigPatchKeys)(patch);
428
- if (changeConfig !== void 0) {
429
- await changeConfig(patch);
430
- return;
431
- }
432
- await req("changeConfig", serializeConfigForWire(patch));
222
+ send(envelope) {
223
+ target.postMessage(envelope, targetOrigin);
224
+ },
225
+ onMessage(listener) {
226
+ listeners.add(listener);
227
+ return () => {
228
+ listeners.delete(listener);
229
+ };
433
230
  },
434
- destroy: () => teardown(),
435
- get holdState() {
436
- return getHoldState();
231
+ close() {
232
+ window.removeEventListener("message", receive);
233
+ listeners.clear();
437
234
  }
438
235
  };
439
236
  }
440
237
 
441
- // src/dom.ts
442
- var defaultDomFactory = {
443
- createFrame(container, src) {
444
- const iframe = container.ownerDocument.createElement("iframe");
445
- iframe.src = src;
446
- iframe.setAttribute("allow", "fullscreen");
447
- iframe.setAttribute("sandbox", "allow-scripts allow-same-origin");
448
- iframe.setAttribute("title", "KNOT Seatmap");
449
- iframe.style.border = "0";
450
- iframe.style.background = "transparent";
451
- iframe.style.display = "block";
452
- iframe.style.width = "100%";
453
- iframe.style.height = "100%";
454
- iframe.style.overflow = "hidden";
455
- iframe.style.colorScheme = "normal";
456
- container.appendChild(iframe);
457
- const contentWindow = iframe.contentWindow;
458
- if (!contentWindow) {
459
- iframe.remove();
460
- throw new Error(
461
- "@knot-technologies/seatmap: iframe.contentWindow is null"
462
- );
463
- }
464
- return {
465
- iframe,
466
- contentWindow,
467
- remove: () => iframe.remove()
468
- };
238
+ // src/chartHandle.ts
239
+ function isRecord(value) {
240
+ return typeof value === "object" && value !== null && !Array.isArray(value);
241
+ }
242
+ function isObjectRef(value) {
243
+ if (!isRecord(value)) {
244
+ return false;
469
245
  }
246
+ return (value.type === "seat" || value.type === "gaArea" || value.type === "table") && typeof value.id === "string" && value.id.length > 0;
247
+ }
248
+ function isObjectRefArray(value) {
249
+ return Array.isArray(value) && value.every(isObjectRef);
250
+ }
251
+ function isInventorySelection(value) {
252
+ if (!isRecord(value)) {
253
+ return false;
254
+ }
255
+ return Object.keys(value).every((key) => key === "seatIds" || key === "gaAreas") && Array.isArray(value.seatIds) && value.seatIds.every((id) => typeof id === "string") && Array.isArray(value.gaAreas) && value.gaAreas.every(
256
+ (area) => isRecord(area) && Object.keys(area).every((key) => key === "id" || key === "quantity") && typeof area.id === "string" && typeof area.quantity === "number" && Number.isSafeInteger(area.quantity) && area.quantity >= 1
257
+ );
258
+ }
259
+ function toInventorySelection(selection) {
260
+ return {
261
+ seatIds: [...selection.seatIds],
262
+ gaAreas: selection.gaAreas.map((area) => ({
263
+ id: area.id,
264
+ quantity: area.quantity
265
+ }))
266
+ };
267
+ }
268
+ var SEASON_HOLD_OPERATIONS = ["create", "replace", "renew", "release"];
269
+ var SEASON_HOLD_TERMINAL_STATUSES = ["released", "expired", "booked"];
270
+ var SEASON_HOLD_ALLOWED_KEYS = {
271
+ idle: ["status", "seasonKey"],
272
+ updating: ["status", "seasonKey", "operation", "holdId"],
273
+ active: ["status", "seasonKey", "holdId", "selection", "expiresAt"],
274
+ released: ["status", "seasonKey", "holdId"],
275
+ expired: ["status", "seasonKey", "holdId"],
276
+ booked: ["status", "seasonKey", "holdId"]
470
277
  };
471
-
472
- // src/endpoints.ts
473
- var import_seatmap_types2 = require("@knot-technologies/seatmap-types");
474
- var DEFAULT_API_BASE_URL = "";
475
- var DEFAULT_SSE_BASE_URL = "";
476
- var PREDEV_API_BASE_URL = "";
477
- var PREDEV_SSE_BASE_URL = "";
478
- var DEVELOPMENT_API_BASE_URL = "https://d88f7h1ehc1xa.cloudfront.net";
479
- var DEVELOPMENT_SSE_BASE_URL = "https://d272va20q3venb.cloudfront.net";
480
- function requireBaseUrl(name, value) {
481
- if (typeof value !== "string" || value.trim().length === 0) {
482
- throw new Error(`@knot-technologies/seatmap: ${name} must be configured`);
278
+ function hasOnlyApprovedKeys(value, status) {
279
+ const allowed = SEASON_HOLD_ALLOWED_KEYS[status];
280
+ if (!allowed) {
281
+ return false;
483
282
  }
484
- return value.replace(/\/+$/, "");
283
+ return Object.keys(value).every((key) => allowed.includes(key));
485
284
  }
486
- function resolveSdkEndpoints(environment) {
487
- const profile = (0, import_seatmap_types2.resolveSeatmapEnvironment)(environment);
488
- switch (profile) {
489
- case "production":
490
- return {
491
- apiBaseUrl: requireBaseUrl(
492
- "production API base URL",
493
- DEFAULT_API_BASE_URL
494
- ),
495
- sseBaseUrl: requireBaseUrl(
496
- "production SSE base URL",
497
- DEFAULT_SSE_BASE_URL
498
- )
285
+ function isSeasonHoldState(value) {
286
+ if (!isRecord(value) || typeof value.seasonKey !== "string") {
287
+ return false;
288
+ }
289
+ if (typeof value.status !== "string") {
290
+ return false;
291
+ }
292
+ switch (value.status) {
293
+ case "idle":
294
+ break;
295
+ case "updating":
296
+ if (typeof value.operation !== "string" || !SEASON_HOLD_OPERATIONS.includes(value.operation) || value.holdId !== void 0 && typeof value.holdId !== "string") {
297
+ return false;
298
+ }
299
+ break;
300
+ case "active":
301
+ if (typeof value.holdId !== "string" || typeof value.selection !== "object" || value.selection === null || !isInventorySelection(value.selection) || typeof value.expiresAt !== "string") {
302
+ return false;
303
+ }
304
+ break;
305
+ default:
306
+ if (!SEASON_HOLD_TERMINAL_STATUSES.includes(value.status) || typeof value.holdId !== "string") {
307
+ return false;
308
+ }
309
+ break;
310
+ }
311
+ return hasOnlyApprovedKeys(value, value.status);
312
+ }
313
+ function toPublicSeasonHoldState(value) {
314
+ switch (value.status) {
315
+ case "idle":
316
+ return { status: "idle", seasonKey: value.seasonKey };
317
+ case "updating": {
318
+ const updating = {
319
+ status: "updating",
320
+ seasonKey: value.seasonKey,
321
+ operation: value.operation
499
322
  };
500
- case "predev":
323
+ if (value.holdId !== void 0) {
324
+ updating.holdId = value.holdId;
325
+ }
326
+ return updating;
327
+ }
328
+ case "active":
501
329
  return {
502
- apiBaseUrl: requireBaseUrl("predev API base URL", PREDEV_API_BASE_URL),
503
- sseBaseUrl: requireBaseUrl("predev SSE base URL", PREDEV_SSE_BASE_URL)
330
+ status: "active",
331
+ seasonKey: value.seasonKey,
332
+ holdId: value.holdId,
333
+ selection: toInventorySelection(value.selection),
334
+ expiresAt: value.expiresAt
504
335
  };
505
- case "development":
506
- return {
507
- apiBaseUrl: requireBaseUrl(
508
- "development API base URL",
509
- DEVELOPMENT_API_BASE_URL
510
- ),
511
- sseBaseUrl: requireBaseUrl(
512
- "development SSE base URL",
513
- DEVELOPMENT_SSE_BASE_URL
514
- )
336
+ default: {
337
+ const terminal = {
338
+ status: value.status,
339
+ seasonKey: value.seasonKey,
340
+ holdId: value.holdId
515
341
  };
342
+ return terminal;
343
+ }
516
344
  }
517
345
  }
518
-
519
- // src/engineUrl.ts
520
- var import_seatmap_types3 = require("@knot-technologies/seatmap-types");
521
- var DEFAULT_ENGINE_URL = "";
522
- var PREDEV_ENGINE_URL = "";
523
- var DEVELOPMENT_ENGINE_URL = "https://dev-seatmap.knottech.ai/seatmap/sdk/dev/0.3.1-dev.0/engine.html";
524
- var DEFAULT_CDN_BASE = "".length > 0 ? `${"".replace(/\/+$/, "")}/seatmap/sdk` : "";
525
- function requireEngineUrl(name, value) {
526
- if (typeof value !== "string" || value.trim().length === 0) {
527
- throw new Error(`@knot-technologies/seatmap: ${name} must be configured`);
528
- }
529
- return value;
530
- }
531
- function resolveEngineUrl(environment) {
532
- const profile = (0, import_seatmap_types3.resolveSeatmapEnvironment)(environment);
533
- switch (profile) {
534
- case "production":
535
- return requireEngineUrl("production engine URL", DEFAULT_ENGINE_URL);
536
- case "predev":
537
- return requireEngineUrl("predev engine URL", PREDEV_ENGINE_URL);
538
- case "development":
539
- return requireEngineUrl("development engine URL", DEVELOPMENT_ENGINE_URL);
540
- }
541
- }
542
- function engineChannelUrl(channel) {
543
- const base = requireEngineUrl("production CDN base URL", DEFAULT_CDN_BASE);
544
- return `${base}/${channel}/engine.html`;
545
- }
546
- function originOf(url) {
547
- return new URL(url).origin;
548
- }
549
-
550
- // src/names.ts
551
- var import_seatmap_types4 = require("@knot-technologies/seatmap-types");
552
-
553
- // src/wireEvents.ts
554
- function fail(eventName, message) {
555
- throw new Error(
556
- `@knot-technologies/seatmap: invalid ${eventName} payload (${message})`
346
+ function isEventPayload(event, payload) {
347
+ switch (event) {
348
+ case "chartRendered":
349
+ return payload === void 0;
350
+ case "chartRenderingFailed":
351
+ return isRecord(payload) && typeof payload.message === "string";
352
+ case "selectionChanged":
353
+ return isRecord(payload) && isObjectRefArray(payload.selected);
354
+ case "seasonHoldChanged":
355
+ return isRecord(payload) && isSeasonHoldState(payload);
356
+ case "objectClicked":
357
+ case "objectSelected":
358
+ case "objectDeselected":
359
+ case "objectMouseOver":
360
+ case "objectMouseOut":
361
+ return isObjectRef(payload);
362
+ }
363
+ }
364
+ function destroyedError(method) {
365
+ return new RpcError(
366
+ "CHART_DESTROYED",
367
+ "The chart has been destroyed",
368
+ method
557
369
  );
558
370
  }
559
- function isRecord2(value) {
560
- return typeof value === "object" && value !== null;
561
- }
562
- function record(value, eventName) {
563
- if (!isRecord2(value)) fail(eventName, "expected object");
564
- return value;
565
- }
566
- function stringField(source, key, eventName) {
567
- const value = source[key];
568
- if (typeof value !== "string") fail(eventName, `${key} must be string`);
569
- return value;
570
- }
571
- function numberField(source, key, eventName) {
572
- const value = source[key];
573
- if (typeof value !== "number") fail(eventName, `${key} must be number`);
574
- return value;
575
- }
576
- function booleanField(source, key, eventName) {
577
- const value = source[key];
578
- if (typeof value !== "boolean") fail(eventName, `${key} must be boolean`);
579
- return value;
580
- }
581
- function optionalString(target, source, key, eventName) {
582
- const value = source[key];
583
- if (value === void 0) return;
584
- if (typeof value !== "string") fail(eventName, `${key} must be string`);
585
- target[key] = value;
586
- }
587
- function optionalNumber(target, source, key, eventName) {
588
- const value = source[key];
589
- if (value === void 0) return;
590
- if (typeof value !== "number") fail(eventName, `${key} must be number`);
591
- target[key] = value;
371
+ async function requestVoid(endpoint, method, params) {
372
+ await endpoint.request(method, params);
592
373
  }
593
- function optionalBoolean(target, source, key, eventName) {
594
- const value = source[key];
595
- if (value === void 0) return;
596
- if (typeof value !== "boolean") fail(eventName, `${key} must be boolean`);
597
- target[key] = value;
598
- }
599
- function objectType(value, eventName) {
600
- if (value === "seat" || value === "table" || value === "booth" || value === "generalAdmission" || value === "section") {
601
- return value;
374
+ function createChartHandle(endpoint, removeIframe, options) {
375
+ let destroyed = false;
376
+ let chartRendered = false;
377
+ let currentSeasonHold = options?.initialSeasonHold;
378
+ const subscriptions = [];
379
+ const unsubscribeChartRendered = endpoint.on("chartRendered", () => {
380
+ chartRendered = true;
381
+ });
382
+ const unsubscribeSeasonHoldChanged = endpoint.on(
383
+ "seasonHoldChanged",
384
+ (payload) => {
385
+ if (isRecord(payload) && isSeasonHoldState(payload)) {
386
+ currentSeasonHold = toPublicSeasonHoldState(payload);
387
+ }
388
+ }
389
+ );
390
+ function assertActive(method) {
391
+ if (destroyed) {
392
+ throw destroyedError(method);
393
+ }
602
394
  }
603
- fail(eventName, "type must be a contract ObjectType");
604
- }
605
- function stringArray(source, key, eventName) {
606
- const value = source[key];
607
- if (!Array.isArray(value) || !value.every((item) => typeof item === "string")) {
608
- fail(eventName, `${key} must be string[]`);
395
+ function onSeasonHoldChanged(handler) {
396
+ if (subscriptions.some(
397
+ (subscription2) => subscription2.event === "seasonHoldChanged" && subscription2.handler === handler
398
+ )) {
399
+ return;
400
+ }
401
+ let liveEventSeen = false;
402
+ const unsubscribe = endpoint.on("seasonHoldChanged", (payload) => {
403
+ if (isRecord(payload) && isSeasonHoldState(payload)) {
404
+ liveEventSeen = true;
405
+ handler(toPublicSeasonHoldState(payload));
406
+ }
407
+ });
408
+ let active = true;
409
+ const subscription = {
410
+ event: "seasonHoldChanged",
411
+ handler,
412
+ unsubscribe() {
413
+ active = false;
414
+ unsubscribe();
415
+ }
416
+ };
417
+ subscriptions.push(subscription);
418
+ if (currentSeasonHold !== void 0) {
419
+ const stickyState = toPublicSeasonHoldState(currentSeasonHold);
420
+ queueMicrotask(() => {
421
+ if (active && !liveEventSeen) {
422
+ handler(stickyState);
423
+ }
424
+ });
425
+ }
609
426
  }
610
- return value;
611
- }
612
- function toSeatmapObject(value, eventName) {
613
- const source = record(value, eventName);
614
- const target = {
615
- id: stringField(source, "id", eventName),
616
- label: stringField(source, "label", eventName),
617
- type: objectType(source.type, eventName),
618
- status: source.status === "available" || source.status === "unavailable" ? source.status : fail(eventName, "status must be available|unavailable"),
619
- selectable: booleanField(source, "selectable", eventName)
620
- };
621
- optionalString(target, source, "categoryKey", eventName);
622
- optionalString(target, source, "sectionId", eventName);
623
- return target;
624
- }
625
- function toTicketType(value, eventName) {
626
- const source = record(value, eventName);
627
- const target = {
628
- ticketType: stringField(source, "ticketType", eventName),
629
- label: stringField(source, "label", eventName),
630
- price: numberField(source, "price", eventName)
631
- };
632
- optionalString(target, source, "description", eventName);
633
- optionalNumber(target, source, "originalPrice", eventName);
634
- optionalBoolean(target, source, "primary", eventName);
635
- optionalBoolean(target, source, "unavailable", eventName);
636
- optionalString(target, source, "unavailableReason", eventName);
637
- return target;
638
- }
639
- function toSelectedObject(value, eventName) {
640
- const source = record(value, eventName);
641
- const target = {
642
- id: stringField(source, "id", eventName),
643
- label: stringField(source, "label", eventName),
644
- type: objectType(source.type, eventName)
645
- };
646
- optionalString(target, source, "ticketType", eventName);
647
- optionalNumber(target, source, "price", eventName);
648
- optionalNumber(target, source, "quantity", eventName);
649
- return target;
650
- }
651
- function toSelectionChange(value, eventName) {
652
- const source = record(value, eventName);
653
- const objects = source.objects;
654
- if (!Array.isArray(objects)) fail(eventName, "objects must be array");
655
- return {
656
- objects: objects.map((item) => toSelectedObject(item, eventName))
657
- };
658
- }
659
- function toHoldState(value, eventName) {
660
- const source = record(value, eventName);
661
427
  return {
662
- holdToken: stringField(source, "holdToken", eventName),
663
- expiresAt: stringField(source, "expiresAt", eventName),
664
- expiresInSeconds: numberField(source, "expiresInSeconds", eventName),
665
- objects: stringArray(source, "objects", eventName)
666
- };
667
- }
668
- function toSdkError(value, eventName) {
669
- const source = record(value, eventName);
670
- return {
671
- code: stringField(source, "code", eventName),
672
- message: stringField(source, "message", eventName)
673
- };
674
- }
675
- function toObjectSelected(value, eventName) {
676
- const source = record(value, eventName);
677
- const result = {
678
- object: toSeatmapObject(source.object, eventName)
679
- };
680
- if (source.selectedTicketType !== void 0) {
681
- result.selectedTicketType = toTicketType(
682
- source.selectedTicketType,
683
- eventName
684
- );
685
- }
686
- return result;
687
- }
688
- function wireEvents(deps) {
689
- const { endpoint, config, getChart, setHoldState } = deps;
690
- const handlers = {
691
- chartRendered: () => config.onChartRendered?.(getChart()),
692
- chartRenderingFailed: (payload) => config.onChartRenderingFailed?.(
693
- toSdkError(payload, "chartRenderingFailed")
694
- ),
695
- objectClicked: (payload) => config.onObjectClicked?.(toSeatmapObject(payload, "objectClicked")),
696
- objectHovered: (payload) => config.onObjectHovered?.(toSeatmapObject(payload, "objectHovered")),
697
- objectMouseOut: (payload) => config.onObjectMouseOut?.(toSeatmapObject(payload, "objectMouseOut")),
698
- objectSelected: (payload) => {
699
- const selected = toObjectSelected(payload, "objectSelected");
700
- config.onObjectSelected?.(selected.object, selected.selectedTicketType);
428
+ get isDestroyed() {
429
+ return destroyed;
701
430
  },
702
- objectDeselected: (payload) => config.onObjectDeselected?.(toSeatmapObject(payload, "objectDeselected")),
703
- selectionChanged: (payload) => config.onSelectionChanged?.(
704
- toSelectionChange(payload, "selectionChanged")
705
- ),
706
- holdSucceeded: (payload) => {
707
- const state = toHoldState(payload, "holdSucceeded");
708
- setHoldState(state);
709
- config.onHoldSucceeded?.(state);
431
+ async selectObjects(objects) {
432
+ assertActive("selectObjects");
433
+ await requestVoid(endpoint, "selectObjects", { objects });
710
434
  },
711
- holdFailed: (payload) => config.onHoldFailed?.(toSdkError(payload, "holdFailed")),
712
- holdChanged: (payload) => {
713
- const state = toHoldState(payload, "holdChanged");
714
- setHoldState(state);
715
- config.onHoldChanged?.(state);
435
+ async deselectObjects(objects) {
436
+ assertActive("deselectObjects");
437
+ await requestVoid(endpoint, "deselectObjects", { objects });
716
438
  },
717
- holdExpired: () => {
718
- setHoldState(null);
719
- config.onHoldExpired?.();
439
+ async clearSelection() {
440
+ assertActive("clearSelection");
441
+ await requestVoid(endpoint, "clearSelection", {});
720
442
  },
721
- releaseHoldSucceeded: () => {
722
- setHoldState(null);
723
- config.onReleaseHoldSucceeded?.();
443
+ async listSelectedObjects() {
444
+ assertActive("listSelectedObjects");
445
+ const result = await endpoint.request("listSelectedObjects", {});
446
+ if (!isObjectRefArray(result)) {
447
+ throw new RpcError(
448
+ "ENGINE_INCOMPATIBLE",
449
+ "Engine returned an invalid selection",
450
+ "listSelectedObjects"
451
+ );
452
+ }
453
+ return result;
724
454
  },
725
- releaseHoldFailed: (payload) => config.onReleaseHoldFailed?.(toSdkError(payload, "releaseHoldFailed"))
726
- };
727
- const offs = import_seatmap_types4.EVENT_NAMES.map((name) => endpoint.on(name, handlers[name]));
728
- return () => {
729
- for (const off of offs.splice(0)) off();
730
- };
731
- }
732
-
733
- // src/mountSeatmap.ts
734
- var DEFAULT_SDK_TIMEOUT_MS = 1e4;
735
- function defaultLocalWindow() {
736
- if (typeof window === "undefined") {
737
- throw new Error("@knot-technologies/seatmap: window is not available");
738
- }
739
- return window;
740
- }
741
- function isRecord3(value) {
742
- return typeof value === "object" && value !== null;
743
- }
744
- function createFacadeAutoHeightController(endpoint, iframe, initialFitTo) {
745
- const fillHeight = iframe.style.height;
746
- let disposed = false;
747
- let autoHeightActive = false;
748
- let detach = () => {
749
- };
750
- const setFitTo = (fitTo) => {
751
- if (disposed) return;
752
- const nextAutoHeight = fitTo === "width";
753
- if (nextAutoHeight === autoHeightActive) return;
754
- const detachPrevious = detach;
755
- detach = () => {
756
- };
757
- autoHeightActive = nextAutoHeight;
758
- detachPrevious();
759
- if (!nextAutoHeight) {
760
- iframe.style.height = fillHeight;
761
- return;
762
- }
763
- detach = endpoint.on(ENGINE_RESIZED, (payload) => {
764
- if (disposed || !autoHeightActive || !isEngineResizedPayload(payload)) {
455
+ async setObjectQuantity(object, quantity) {
456
+ assertActive("setObjectQuantity");
457
+ await requestVoid(endpoint, "setObjectQuantity", { object, quantity });
458
+ },
459
+ async highlightObjects(objects, color) {
460
+ assertActive("highlightObjects");
461
+ await requestVoid(
462
+ endpoint,
463
+ "highlightObjects",
464
+ color === void 0 ? { objects } : { objects, color }
465
+ );
466
+ },
467
+ async clearHighlights() {
468
+ assertActive("clearHighlights");
469
+ await requestVoid(endpoint, "clearHighlights", {});
470
+ },
471
+ async setMetadata(metadata) {
472
+ assertActive("setMetadata");
473
+ await requestVoid(endpoint, "setMetadata", { metadata });
474
+ },
475
+ async setCategoryMetadata(metadata) {
476
+ assertActive("setCategoryMetadata");
477
+ await requestVoid(endpoint, "setCategoryMetadata", { metadata });
478
+ },
479
+ async holdBestAvailable() {
480
+ assertActive("holdBestAvailable");
481
+ await requestVoid(endpoint, "holdBestAvailable", {});
482
+ },
483
+ async pulse() {
484
+ assertActive("pulse");
485
+ await requestVoid(endpoint, "pulse", {});
486
+ },
487
+ async unpulse() {
488
+ assertActive("unpulse");
489
+ await requestVoid(endpoint, "unpulse", {});
490
+ },
491
+ async spotlight() {
492
+ assertActive("spotlight");
493
+ await requestVoid(endpoint, "spotlight", {});
494
+ },
495
+ async clearSpotlight() {
496
+ assertActive("clearSpotlight");
497
+ await requestVoid(endpoint, "clearSpotlight", {});
498
+ },
499
+ async disableObjects() {
500
+ assertActive("disableObjects");
501
+ await requestVoid(endpoint, "disableObjects", {});
502
+ },
503
+ async enableObjects() {
504
+ assertActive("enableObjects");
505
+ await requestVoid(endpoint, "enableObjects", {});
506
+ },
507
+ async selectCategories() {
508
+ assertActive("selectCategories");
509
+ await requestVoid(endpoint, "selectCategories", {});
510
+ },
511
+ async deselectCategories() {
512
+ assertActive("deselectCategories");
513
+ await requestVoid(endpoint, "deselectCategories", {});
514
+ },
515
+ async listCategories() {
516
+ assertActive("listCategories");
517
+ await requestVoid(endpoint, "listCategories", {});
518
+ },
519
+ async findObject() {
520
+ assertActive("findObject");
521
+ await requestVoid(endpoint, "findObject", {});
522
+ },
523
+ async zoomToObjects() {
524
+ assertActive("zoomToObjects");
525
+ await requestVoid(endpoint, "zoomToObjects", {});
526
+ },
527
+ async zoomToSection() {
528
+ assertActive("zoomToSection");
529
+ await requestVoid(endpoint, "zoomToSection", {});
530
+ },
531
+ async resetView() {
532
+ assertActive("resetView");
533
+ await requestVoid(endpoint, "resetView", {});
534
+ },
535
+ async changeConfig() {
536
+ assertActive("changeConfig");
537
+ await requestVoid(endpoint, "changeConfig", {});
538
+ },
539
+ async destroy() {
540
+ assertActive("destroy");
541
+ destroyed = true;
542
+ subscriptions.splice(0).forEach((subscription) => subscription.unsubscribe());
543
+ unsubscribeChartRendered();
544
+ unsubscribeSeasonHoldChanged();
545
+ endpoint.close();
546
+ removeIframe();
547
+ },
548
+ on(event, handler) {
549
+ assertActive("on");
550
+ if (event === "seasonHoldChanged") {
551
+ onSeasonHoldChanged(
552
+ handler
553
+ );
765
554
  return;
766
555
  }
767
- iframe.style.height = `${payload.height}px`;
768
- });
769
- };
770
- setFitTo(initialFitTo);
771
- return {
772
- setFitTo,
773
- dispose() {
774
- if (disposed) return;
775
- disposed = true;
776
- autoHeightActive = false;
777
- const detachCurrent = detach;
778
- detach = () => {
779
- };
780
- detachCurrent();
556
+ if (subscriptions.some(
557
+ (subscription) => subscription.event === event && subscription.handler === handler
558
+ )) {
559
+ return;
560
+ }
561
+ if (event === "chartRendered" && chartRendered) {
562
+ let active = true;
563
+ const subscription = {
564
+ event,
565
+ handler,
566
+ unsubscribe() {
567
+ active = false;
568
+ }
569
+ };
570
+ subscriptions.push(subscription);
571
+ const chartRenderedHandler = handler;
572
+ queueMicrotask(() => {
573
+ if (active) {
574
+ chartRenderedHandler();
575
+ }
576
+ });
577
+ return;
578
+ }
579
+ const unsubscribe = endpoint.on(event, (payload) => {
580
+ if (isEventPayload(event, payload)) {
581
+ handler(payload);
582
+ }
583
+ });
584
+ subscriptions.push({ event, handler, unsubscribe });
585
+ },
586
+ off(event, handler) {
587
+ assertActive("off");
588
+ const index = subscriptions.findIndex(
589
+ (subscription) => subscription.event === event && subscription.handler === handler
590
+ );
591
+ if (index < 0) {
592
+ return;
593
+ }
594
+ subscriptions.splice(index, 1)[0]?.unsubscribe();
781
595
  }
782
596
  };
783
597
  }
784
- function defaultFetch(input, init) {
785
- if (typeof fetch === "undefined") {
786
- throw new Error("@knot-technologies/seatmap: fetch is not available");
787
- }
788
- return fetch(input, init);
789
- }
790
- function redactSecrets(message, secrets) {
791
- let redacted = message;
792
- for (const secret of secrets) {
793
- if (secret.length > 0) redacted = redacted.replaceAll(secret, "[redacted]");
794
- }
795
- return redacted;
796
- }
797
- function toSdkError2(error, secrets = []) {
798
- if (isRecord3(error) && typeof error.code === "string" && typeof error.message === "string") {
799
- return { code: error.code, message: redactSecrets(error.message, secrets) };
800
- }
801
- if (error instanceof Error) {
802
- return {
803
- code: "SDK_ERROR",
804
- message: redactSecrets(error.message, secrets)
805
- };
806
- }
807
- return {
808
- code: "SDK_ERROR",
809
- message: redactSecrets(String(error), secrets)
810
- };
811
- }
812
- function toInitPayload(config, endpoints, environment) {
813
- return {
814
- environment,
815
- apiBaseUrl: endpoints.apiBaseUrl,
816
- sseBaseUrl: endpoints.sseBaseUrl,
817
- ...serializeConfigForWire(config, { skipUndefined: true })
818
- };
819
- }
820
- function engineSrc(deps, environment) {
821
- if (deps.channel !== void 0) {
822
- return engineChannelUrl(deps.channel);
823
- }
824
- return resolveEngineUrl(environment);
825
- }
826
- function createChannelId(local) {
827
- const crypto = local.crypto;
828
- if (typeof crypto?.randomUUID === "function") {
829
- return crypto.randomUUID();
830
- }
831
- if (typeof crypto?.getRandomValues === "function") {
832
- const bytes = new Uint8Array(16);
833
- crypto.getRandomValues(bytes);
834
- return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(
835
- ""
836
- );
837
- }
838
- throw new Error(
839
- "@knot-technologies/seatmap: crypto is required to create RPC channel"
598
+
599
+ // src/engineUrl.ts
600
+ var ENGINE_ARTIFACT = "f509dddb477e0234";
601
+ var CDN_BASE = "https://dev-seatmap.knottech.ai";
602
+ function resolveEngineUrl({
603
+ artifact,
604
+ cdnBase
605
+ }) {
606
+ const base = cdnBase.replace(/\/+$/, "");
607
+ if (base.length === 0 || artifact.length === 0) {
608
+ throw new Error("Engine artifact and CDN base must be configured");
609
+ }
610
+ return `${base}/engine/${artifact}/engine.html`;
611
+ }
612
+ function engineOrigin(engineUrl) {
613
+ const url = new URL(engineUrl);
614
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
615
+ throw new Error("Engine URL must use HTTP or HTTPS");
616
+ }
617
+ return url.origin;
618
+ }
619
+ function getSeatmapEngineOrigin() {
620
+ return engineOrigin(
621
+ resolveEngineUrl({ artifact: ENGINE_ARTIFACT, cdnBase: CDN_BASE })
840
622
  );
841
623
  }
842
- function parentOriginOf(local) {
843
- const origin = local.location?.origin;
844
- if (typeof origin !== "string" || origin.length === 0 || origin === "null") {
845
- return void 0;
846
- }
847
- return origin;
848
- }
849
- function withRuntimeParams(src, channelId, parentOrigin) {
850
- const url = new URL(src);
851
- if (parentOrigin !== void 0) {
852
- url.searchParams.set("parentOrigin", parentOrigin);
853
- }
854
- const params = new URLSearchParams(url.hash.slice(1));
855
- params.set("channel", channelId);
856
- url.hash = params.toString();
857
- return url.toString();
858
- }
859
- function engineGateUrl(apiBaseUrl) {
860
- return `${apiBaseUrl.replace(/\/+$/, "")}/v1/engine-gate`;
861
- }
862
- function bestAvailableUrl(apiBaseUrl, session, opts) {
863
- const params = new URLSearchParams({
864
- count: String(opts.quantity),
865
- limit: "1"
866
- });
867
- if (opts.category !== void 0) params.set("categoryIds", opts.category);
868
- return `${apiBaseUrl.replace(/\/+$/, "")}/v4/sessions/${encodeURIComponent(
869
- session
870
- )}/best-available?${params.toString()}`;
624
+
625
+ // src/mountSeatmap.ts
626
+ var HANDSHAKE_TIMEOUT_MS = 5e3;
627
+ function isRecord2(value) {
628
+ return typeof value === "object" && value !== null && !Array.isArray(value);
871
629
  }
872
- async function preflightEngineGate(apiBaseUrl, token, fetchImpl) {
873
- let response;
874
- try {
875
- response = await fetchImpl(engineGateUrl(apiBaseUrl), {
876
- method: "GET",
877
- headers: { Authorization: `Bearer ${token}` }
878
- });
879
- } catch (error) {
880
- const message = error instanceof Error ? error.message : String(error);
881
- throw {
882
- code: "ENGINE_GATE_FAILED",
883
- message: `@knot-technologies/seatmap: engine gate request failed: ${message}`
884
- };
885
- }
886
- if (!response.ok) {
887
- throw {
888
- code: "ENGINE_GATE_REJECTED",
889
- message: `@knot-technologies/seatmap: engine gate rejected with ${response.status}`
890
- };
630
+ function isHandshakeAcknowledgement(value) {
631
+ if (typeof value !== "object" || value === null) {
632
+ return false;
891
633
  }
634
+ const result = value;
635
+ return result.protocolVersion === PROTOCOL_VERSION;
892
636
  }
893
- function isStringArray(value) {
894
- return Array.isArray(value) && value.every((item) => typeof item === "string");
895
- }
896
- function firstBestAvailableSeatIds(value) {
897
- if (!isRecord3(value)) {
898
- throw new Error("best-available response must be an object");
899
- }
900
- const options = value.options;
901
- if (!Array.isArray(options)) {
902
- throw new Error("best-available response options must be an array");
903
- }
904
- if (options.length === 0) return [];
905
- const first = options[0];
906
- if (!isRecord3(first) || !isStringArray(first.seatIds)) {
907
- throw new Error("best-available option seatIds must be a string array");
908
- }
909
- return first.seatIds;
637
+ function unreachableError(artifact) {
638
+ return new RpcError(
639
+ "ENGINE_UNREACHABLE",
640
+ `Unable to load engine artifact ${artifact}`
641
+ );
910
642
  }
911
- async function holdBestAvailable(config, token, apiBaseUrl, fetchImpl, getChart, opts) {
912
- if (!Number.isInteger(opts.quantity) || opts.quantity < 1) {
913
- throw {
914
- code: "BEST_AVAILABLE_INVALID_ARGS",
915
- message: "@knot-technologies/seatmap: quantity must be a positive integer"
916
- };
643
+ function configureIframe(iframe, src) {
644
+ iframe.title = "KNOT Seatmap";
645
+ iframe.src = src;
646
+ iframe.style.display = "block";
647
+ iframe.style.width = "100%";
648
+ iframe.style.height = "100%";
649
+ iframe.style.border = "0";
650
+ }
651
+ function classicHelloParams(config) {
652
+ const params = {
653
+ sessionId: config.sessionId,
654
+ clientToken: config.clientToken
655
+ };
656
+ if (config.channelKeys !== void 0) {
657
+ params.channelKeys = config.channelKeys;
917
658
  }
918
- let response;
919
- try {
920
- response = await fetchImpl(
921
- bestAvailableUrl(apiBaseUrl, config.session, opts),
922
- {
923
- method: "GET",
924
- headers: { Authorization: `Bearer ${token}` }
925
- }
926
- );
927
- } catch (error) {
928
- const message = error instanceof Error ? error.message : String(error);
929
- throw {
930
- code: "BEST_AVAILABLE_FAILED",
931
- message: `@knot-technologies/seatmap: best-available request failed: ${message}`
932
- };
659
+ if (config.includePublic !== void 0) {
660
+ params.includePublic = config.includePublic;
933
661
  }
934
- if (!response.ok) {
935
- throw {
936
- code: "BEST_AVAILABLE_FAILED",
937
- message: `@knot-technologies/seatmap: best-available rejected with ${response.status}`
938
- };
939
- }
940
- const seatIds = firstBestAvailableSeatIds(await response.json());
941
- if (seatIds.length === 0) return [];
942
- const chart = getChart();
943
- await chart.selectObjects(seatIds);
944
- return chart.listSelectedObjects();
662
+ return params;
945
663
  }
946
- function mountSeatmapInternal(container, config, deps = {}) {
947
- const sensitiveTokens = /* @__PURE__ */ new Set();
948
- sensitiveTokens.add(config.token);
949
- let failureNotified = false;
950
- const notifyFailure = (error) => {
951
- if (failureNotified) return;
952
- failureNotified = true;
953
- config.onChartRenderingFailed?.(toSdkError2(error, sensitiveTokens));
664
+ function seasonHelloParams(config) {
665
+ const params = {
666
+ mode: "season",
667
+ seasonKey: config.seasonKey
954
668
  };
955
- try {
956
- const domFactory = deps.domFactory ?? defaultDomFactory;
957
- const local = deps.localWindow ?? defaultLocalWindow();
958
- const fetchImpl = deps.fetchImpl ?? defaultFetch;
959
- const channelId = deps.channelId ?? createChannelId(local);
960
- const environment = (0, import_seatmap_types5.resolveSeatmapEnvironment)(config.environment);
961
- const src = withRuntimeParams(
962
- engineSrc(deps, environment),
963
- channelId,
964
- parentOriginOf(local)
965
- );
966
- const engineOrigin = originOf(src);
967
- const endpoints = resolveSdkEndpoints(environment);
968
- let holdState = null;
969
- let teardownDone = false;
970
- let unwire = () => {
971
- };
972
- let autoHeight = null;
973
- let removeFrameErrorListener = () => {
974
- };
975
- let frame = null;
976
- let endpoint = null;
977
- let renderTimer = null;
978
- const teardown = () => {
979
- if (teardownDone) return;
980
- teardownDone = true;
981
- if (renderTimer !== null) {
982
- clearTimeout(renderTimer);
983
- renderTimer = null;
669
+ if (config.channelKeys !== void 0) {
670
+ params.channelKeys = config.channelKeys;
671
+ }
672
+ if (config.includePublic !== void 0) {
673
+ params.includePublic = config.includePublic;
674
+ }
675
+ return params;
676
+ }
677
+ function mountSeatmap(container, config, signal) {
678
+ return new Promise((resolve, reject) => {
679
+ const artifact = ENGINE_ARTIFACT;
680
+ const engineUrl = resolveEngineUrl({ artifact, cdnBase: CDN_BASE });
681
+ const targetOrigin = engineOrigin(engineUrl);
682
+ const channelId = crypto.randomUUID();
683
+ const iframe = document.createElement("iframe");
684
+ configureIframe(iframe, engineUrl);
685
+ let endpoint;
686
+ let transport;
687
+ let detachHandshake;
688
+ let channelStarted = false;
689
+ let settled = false;
690
+ const timer = window.setTimeout(() => {
691
+ fail(
692
+ new RpcError(
693
+ "HANDSHAKE_TIMEOUT",
694
+ `Engine artifact ${artifact} did not acknowledge the handshake`
695
+ )
696
+ );
697
+ }, HANDSHAKE_TIMEOUT_MS);
698
+ function removeMountListeners() {
699
+ iframe.removeEventListener("load", handleLoad);
700
+ iframe.removeEventListener("error", handleError);
701
+ signal?.removeEventListener("abort", handleAbort);
702
+ }
703
+ function removeHandshakeListener() {
704
+ detachHandshake?.();
705
+ detachHandshake = void 0;
706
+ }
707
+ function closeChannel() {
708
+ removeHandshakeListener();
709
+ if (endpoint) {
710
+ endpoint.close();
711
+ } else {
712
+ transport?.close();
984
713
  }
985
- removeFrameErrorListener();
986
- autoHeight?.dispose();
987
- autoHeight = null;
988
- unwire();
989
- endpoint?.dispose();
990
- frame?.remove();
991
- sensitiveTokens.clear();
992
- };
993
- return new Promise((resolve, reject) => {
994
- let settled = false;
995
- const fail2 = (error) => {
996
- if (settled) return;
997
- settled = true;
998
- notifyFailure(error);
999
- teardown();
1000
- reject(error);
1001
- };
1002
- const succeed = (chart) => {
1003
- if (settled) return;
1004
- settled = true;
1005
- if (renderTimer !== null) {
1006
- clearTimeout(renderTimer);
1007
- renderTimer = null;
714
+ }
715
+ function cleanFailedMount() {
716
+ window.clearTimeout(timer);
717
+ removeMountListeners();
718
+ closeChannel();
719
+ iframe.remove();
720
+ }
721
+ function fail(error) {
722
+ if (settled) {
723
+ return;
724
+ }
725
+ settled = true;
726
+ cleanFailedMount();
727
+ reject(error);
728
+ }
729
+ function handleError() {
730
+ fail(unreachableError(artifact));
731
+ }
732
+ function handleAbort() {
733
+ fail(new RpcError("CHART_DESTROYED", "Seatmap mount was cancelled"));
734
+ }
735
+ function handleLoad() {
736
+ if (settled || channelStarted) {
737
+ return;
738
+ }
739
+ channelStarted = true;
740
+ const target = iframe.contentWindow;
741
+ if (!target) {
742
+ fail(unreachableError(artifact));
743
+ return;
744
+ }
745
+ transport = createWindowTransport({ target, targetOrigin, channelId });
746
+ endpoint = createEndpoint({ transport, channelId });
747
+ const isSeasonMount = config.seasonKey !== void 0;
748
+ if (isSeasonMount && "seasonKey" in config) {
749
+ const { holdId, tokenProvider } = config;
750
+ endpoint.handle("season.getToken", () => tokenProvider());
751
+ endpoint.handle("season.getHoldId", () => holdId);
752
+ }
753
+ const chart = createChartHandle(
754
+ endpoint,
755
+ () => {
756
+ iframe.remove();
757
+ },
758
+ isSeasonMount && "seasonKey" in config ? {
759
+ initialSeasonHold: {
760
+ status: "idle",
761
+ seasonKey: config.seasonKey
762
+ }
763
+ } : void 0
764
+ );
765
+ const receiveHandshake = (event) => {
766
+ if (event.origin !== targetOrigin || event.source !== target || !isRecord2(event.data) || event.data.channelId !== channelId || event.data.type !== "hello" || typeof event.data.protocolVersion !== "number") {
767
+ return;
768
+ }
769
+ if (event.data.protocolVersion !== PROTOCOL_VERSION) {
770
+ fail(
771
+ new RpcError(
772
+ "ENGINE_INCOMPATIBLE",
773
+ `Engine uses unsupported protocol version ${event.data.protocolVersion}`
774
+ )
775
+ );
776
+ return;
777
+ }
778
+ if (isEnvelope(event.data) && event.data.error) {
779
+ fail(
780
+ new RpcError(
781
+ event.data.error.code,
782
+ event.data.error.message || "Engine rejected the handshake",
783
+ event.data.error.method
784
+ )
785
+ );
786
+ return;
787
+ }
788
+ if (!isEnvelope(event.data) || !isHandshakeAcknowledgement(event.data.result)) {
789
+ fail(
790
+ new RpcError(
791
+ "ENGINE_INCOMPATIBLE",
792
+ "Engine acknowledged with an incompatible protocol version"
793
+ )
794
+ );
795
+ return;
1008
796
  }
1009
- config.onChartRendered?.(chart);
797
+ settled = true;
798
+ window.clearTimeout(timer);
799
+ removeMountListeners();
800
+ removeHandshakeListener();
1010
801
  resolve(chart);
1011
802
  };
1012
- const timeoutMs = deps.renderTimeoutMs ?? DEFAULT_SDK_TIMEOUT_MS;
1013
- renderTimer = setTimeout(() => {
1014
- fail2({
1015
- code: "SDK_MOUNT_TIMEOUT",
1016
- message: `@knot-technologies/seatmap: chart did not render within ${timeoutMs}ms`
1017
- });
1018
- }, timeoutMs);
1019
- const start = async () => {
1020
- await preflightEngineGate(
1021
- endpoints.apiBaseUrl,
1022
- config.token,
1023
- fetchImpl
1024
- );
1025
- frame = domFactory.createFrame(container, src);
1026
- const transport = createWindowTransport({
1027
- local,
1028
- target: frame.contentWindow,
1029
- targetOrigin: engineOrigin,
1030
- acceptOrigin: (origin) => origin === engineOrigin
1031
- });
1032
- const activeEndpoint = new RpcEndpoint({
1033
- transport,
1034
- role: "facade",
1035
- build: deps.build ?? "facade",
1036
- channelId,
1037
- timeoutMs: deps.handshakeTimeoutMs ?? DEFAULT_SDK_TIMEOUT_MS
1038
- });
1039
- endpoint = activeEndpoint;
1040
- let chart = null;
1041
- const getChart = () => {
1042
- if (chart === null) {
1043
- throw new Error(
1044
- "@knot-technologies/seatmap: chart is not initialized"
1045
- );
1046
- }
1047
- return chart;
1048
- };
1049
- chart = createChart({
1050
- endpoint: activeEndpoint,
1051
- getHoldState: () => holdState,
1052
- teardown,
1053
- holdBestAvailable: (opts) => holdBestAvailable(
1054
- config,
1055
- config.token,
1056
- endpoints.apiBaseUrl,
1057
- fetchImpl,
1058
- getChart,
1059
- opts
1060
- ),
1061
- changeConfig: async (patch) => {
1062
- await activeEndpoint.request(
1063
- "changeConfig",
1064
- serializeConfigForWire(patch)
1065
- );
1066
- if ("fitTo" in patch) autoHeight?.setFitTo(patch.fitTo);
1067
- }
1068
- });
1069
- const onFrameError = () => {
1070
- fail2({
1071
- code: "IFRAME_LOAD_FAILED",
1072
- message: "@knot-technologies/seatmap: iframe failed to load"
1073
- });
1074
- };
1075
- frame.iframe.addEventListener("error", onFrameError);
1076
- removeFrameErrorListener = () => {
1077
- frame?.iframe.removeEventListener("error", onFrameError);
1078
- };
1079
- unwire = wireEvents({
1080
- endpoint: activeEndpoint,
1081
- config: {
1082
- ...config,
1083
- onChartRendered: () => succeed(chart),
1084
- onChartRenderingFailed: (error) => fail2(error)
1085
- },
1086
- getChart,
1087
- setHoldState: (state) => {
1088
- holdState = state;
1089
- }
1090
- });
1091
- autoHeight = createFacadeAutoHeightController(
1092
- activeEndpoint,
1093
- frame.iframe,
1094
- config.fitTo
1095
- );
1096
- await activeEndpoint.handshake();
1097
- await activeEndpoint.request(
1098
- "init",
1099
- toInitPayload(config, endpoints, environment)
1100
- );
803
+ window.addEventListener("message", receiveHandshake);
804
+ detachHandshake = () => {
805
+ window.removeEventListener("message", receiveHandshake);
1101
806
  };
1102
- void start().catch(fail2);
1103
- });
1104
- } catch (error) {
1105
- notifyFailure(error);
1106
- return Promise.reject(error);
1107
- }
1108
- }
1109
- function mountSeatmap(container, config, deps = {}) {
1110
- return mountSeatmapInternal(container, config, deps);
807
+ transport.send({
808
+ protocolVersion: PROTOCOL_VERSION,
809
+ channelId,
810
+ type: "hello",
811
+ params: config.seasonKey !== void 0 && "seasonKey" in config ? seasonHelloParams(config) : classicHelloParams(config)
812
+ });
813
+ }
814
+ iframe.addEventListener("load", handleLoad);
815
+ iframe.addEventListener("error", handleError);
816
+ signal?.addEventListener("abort", handleAbort, { once: true });
817
+ container.append(iframe);
818
+ if (signal?.aborted) {
819
+ handleAbort();
820
+ }
821
+ });
1111
822
  }
1112
-
1113
- // src/index.ts
1114
- var import_seatmap_types6 = require("@knot-technologies/seatmap-types");
1115
823
  // Annotate the CommonJS export names for ESM import in node:
1116
824
  0 && (module.exports = {
1117
- mountSeatmap,
1118
- resolveSeatmapEnvironment
825
+ getSeatmapEngineOrigin,
826
+ mountSeatmap
1119
827
  });
1120
828
  //# sourceMappingURL=index.cjs.map