@undefineds.co/xpod 0.3.67 → 0.3.68

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/config/components-ignore.json +1 -0
  2. package/dist/api/ApiServer.d.ts +9 -1
  3. package/dist/api/ApiServer.js +22 -1
  4. package/dist/api/ApiServer.js.map +1 -1
  5. package/dist/api/container/routes.js +13 -0
  6. package/dist/api/container/routes.js.map +1 -1
  7. package/dist/api/handlers/DeviceNotificationRuntime.d.ts +26 -0
  8. package/dist/api/handlers/DeviceNotificationRuntime.js +77 -0
  9. package/dist/api/handlers/DeviceNotificationRuntime.js.map +1 -0
  10. package/dist/api/handlers/DeviceNotificationTicketHandler.d.ts +50 -0
  11. package/dist/api/handlers/DeviceNotificationTicketHandler.js +130 -0
  12. package/dist/api/handlers/DeviceNotificationTicketHandler.js.map +1 -0
  13. package/dist/api/handlers/DeviceNotificationTicketHandler.jsonld +117 -0
  14. package/dist/api/runs/InngestRunExecutionBackend.d.ts +2 -2
  15. package/dist/api/tasks/InngestTaskScheduler.d.ts +4 -4
  16. package/dist/components/components.jsonld +6 -1
  17. package/dist/components/context.jsonld +122 -0
  18. package/dist/http/DeviceNotificationWebSocketServer.d.ts +29 -0
  19. package/dist/http/DeviceNotificationWebSocketServer.js +138 -0
  20. package/dist/http/DeviceNotificationWebSocketServer.js.map +1 -0
  21. package/dist/http/DeviceNotificationWebSocketServer.jsonld +148 -0
  22. package/dist/index.d.ts +7 -1
  23. package/dist/index.js +13 -2
  24. package/dist/index.js.map +1 -1
  25. package/dist/notifications/DeviceNotificationHub.d.ts +74 -0
  26. package/dist/notifications/DeviceNotificationHub.js +313 -0
  27. package/dist/notifications/DeviceNotificationHub.js.map +1 -0
  28. package/dist/notifications/DeviceNotificationHub.jsonld +258 -0
  29. package/dist/notifications/DeviceNotificationResourceListener.d.ts +21 -0
  30. package/dist/notifications/DeviceNotificationResourceListener.js +38 -0
  31. package/dist/notifications/DeviceNotificationResourceListener.js.map +1 -0
  32. package/dist/notifications/DeviceNotificationResourceListener.jsonld +98 -0
  33. package/dist/notifications/device-notification-protocol.d.ts +56 -0
  34. package/dist/notifications/device-notification-protocol.js +127 -0
  35. package/dist/notifications/device-notification-protocol.js.map +1 -0
  36. package/dist/notifications/device-notification-protocol.jsonld +29 -0
  37. package/dist/notifications/index.d.ts +3 -0
  38. package/dist/notifications/index.js +20 -0
  39. package/dist/notifications/index.js.map +1 -0
  40. package/dist/storage/ObservableResourceStore.d.ts +3 -0
  41. package/dist/storage/ObservableResourceStore.js +17 -1
  42. package/dist/storage/ObservableResourceStore.js.map +1 -1
  43. package/package.json +1 -1
@@ -0,0 +1,313 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DeviceNotificationHub = void 0;
4
+ const node_crypto_1 = require("node:crypto");
5
+ const DEFAULT_MAX_TOPICS_PER_CONNECTION = 100;
6
+ const DEFAULT_MAX_QUEUE_MESSAGES = 256;
7
+ const DEFAULT_MAX_REPLAY_EVENTS = 512;
8
+ class DeviceNotificationHub {
9
+ constructor(options) {
10
+ this.connections = new Map();
11
+ this.connectionsByDevice = new Map();
12
+ this.topicMembers = new Map();
13
+ this.replay = [];
14
+ this.sequence = 0;
15
+ this.origin = new URL(options.origin);
16
+ this.maxTopicsPerConnection = options.maxTopicsPerConnection ?? DEFAULT_MAX_TOPICS_PER_CONNECTION;
17
+ this.maxQueueMessages = options.maxQueueMessages ?? DEFAULT_MAX_QUEUE_MESSAGES;
18
+ this.maxReplayEvents = options.maxReplayEvents ?? DEFAULT_MAX_REPLAY_EVENTS;
19
+ this.authorizeTopic = options.authorizeTopic ?? (() => true);
20
+ }
21
+ openConnection(input) {
22
+ const deviceKey = this.deviceConnectionKey(input.identity, input.deviceSessionId);
23
+ const existingConnectionId = this.connectionsByDevice.get(deviceKey);
24
+ if (existingConnectionId) {
25
+ this.closeConnection(existingConnectionId, 4000, 'Replaced by newer device connection');
26
+ }
27
+ const connectionId = (0, node_crypto_1.randomUUID)();
28
+ this.connections.set(connectionId, {
29
+ connectionId,
30
+ identity: input.identity,
31
+ deviceSessionId: input.deviceSessionId,
32
+ topics: new Set(),
33
+ queue: [],
34
+ resyncTopics: new Set(),
35
+ resyncQueued: new Set(),
36
+ seenRequestIds: new Set(),
37
+ lastAck: 0,
38
+ pendingResumeFrom: undefined,
39
+ send: input.send,
40
+ close: input.close,
41
+ });
42
+ this.connectionsByDevice.set(deviceKey, connectionId);
43
+ return { connectionId };
44
+ }
45
+ hello(connectionId, resumeFrom) {
46
+ const connection = this.requireConnection(connectionId);
47
+ const ready = {
48
+ type: 'ready',
49
+ connectionId,
50
+ sequence: this.sequence,
51
+ };
52
+ this.deliver(connection, ready);
53
+ if (resumeFrom !== undefined) {
54
+ connection.pendingResumeFrom = resumeFrom;
55
+ }
56
+ return ready;
57
+ }
58
+ async registerTopics(connectionId, requestId, topics) {
59
+ const connection = this.requireConnection(connectionId);
60
+ this.assertNewRequestId(connection, requestId);
61
+ const normalizedTopics = topics.map((topic) => this.normalizeTopic(topic));
62
+ if ((new Set([...connection.topics, ...normalizedTopics])).size > this.maxTopicsPerConnection) {
63
+ throw new Error('Too many topics for connection');
64
+ }
65
+ for (const topic of normalizedTopics) {
66
+ if (!await this.authorizeTopic({ identity: connection.identity, topic })) {
67
+ throw new Error(`Topic not authorized: ${topic}`);
68
+ }
69
+ connection.topics.add(topic);
70
+ if (!this.topicMembers.has(topic)) {
71
+ this.topicMembers.set(topic, new Set());
72
+ }
73
+ this.topicMembers.get(topic).add(connectionId);
74
+ }
75
+ const frame = {
76
+ type: 'registered',
77
+ requestId,
78
+ topics: normalizedTopics,
79
+ };
80
+ this.deliver(connection, frame);
81
+ this.deliverPendingResume(connection);
82
+ return frame;
83
+ }
84
+ async unregisterTopics(connectionId, requestId, topics) {
85
+ const connection = this.requireConnection(connectionId);
86
+ this.assertNewRequestId(connection, requestId);
87
+ const normalizedTopics = topics.map((topic) => this.normalizeTopic(topic));
88
+ for (const topic of normalizedTopics) {
89
+ connection.topics.delete(topic);
90
+ const members = this.topicMembers.get(topic);
91
+ members?.delete(connectionId);
92
+ if (members?.size === 0) {
93
+ this.topicMembers.delete(topic);
94
+ }
95
+ }
96
+ const frame = {
97
+ type: 'unregistered',
98
+ requestId,
99
+ topics: normalizedTopics,
100
+ };
101
+ this.deliver(connection, frame);
102
+ return frame;
103
+ }
104
+ ack(connectionId, sequence) {
105
+ const connection = this.requireConnection(connectionId);
106
+ connection.lastAck = Math.max(connection.lastAck, sequence);
107
+ connection.queue = connection.queue.filter((frame) => frame.type !== 'event' || frame.sequence > sequence);
108
+ }
109
+ publish(input) {
110
+ const topic = this.normalizeTopic(input.topic);
111
+ const event = {
112
+ type: 'event',
113
+ sequence: ++this.sequence,
114
+ eventId: `urn:uuid:${(0, node_crypto_1.randomUUID)()}`,
115
+ topic,
116
+ ...(input.object ? { object: this.normalizeResource(input.object) } : {}),
117
+ operation: input.operation,
118
+ emittedAt: new Date().toISOString(),
119
+ };
120
+ this.pushReplay(event);
121
+ const memberIds = this.matchingMemberIds(topic, event.object);
122
+ for (const connectionId of memberIds) {
123
+ const connection = this.connections.get(connectionId);
124
+ if (!connection) {
125
+ continue;
126
+ }
127
+ this.deliver(connection, event);
128
+ }
129
+ return event;
130
+ }
131
+ resume(connectionId, resumeFrom) {
132
+ const connection = this.requireConnection(connectionId);
133
+ if (this.replay.length === 0) {
134
+ return [];
135
+ }
136
+ const oldest = this.replay[0].sequence;
137
+ if (resumeFrom < oldest) {
138
+ return {
139
+ type: 'resync-required',
140
+ topics: [...connection.topics].sort(),
141
+ reason: 'expired',
142
+ };
143
+ }
144
+ return this.replay
145
+ .filter((event) => event.sequence > resumeFrom)
146
+ .filter((event) => this.connectionMatches(connection, event.topic, event.object));
147
+ }
148
+ closeConnection(connectionId, code, reason) {
149
+ const connection = this.connections.get(connectionId);
150
+ if (!connection) {
151
+ return;
152
+ }
153
+ if (code !== undefined && reason !== undefined) {
154
+ connection.close?.(code, reason);
155
+ }
156
+ for (const topic of connection.topics) {
157
+ const members = this.topicMembers.get(topic);
158
+ members?.delete(connectionId);
159
+ if (members?.size === 0) {
160
+ this.topicMembers.delete(topic);
161
+ }
162
+ }
163
+ this.connections.delete(connectionId);
164
+ this.connectionsByDevice.delete(this.deviceConnectionKey(connection.identity, connection.deviceSessionId));
165
+ }
166
+ getSeenRequestIds(connectionId) {
167
+ return this.requireConnection(connectionId).seenRequestIds;
168
+ }
169
+ getTopicMemberCount(topic) {
170
+ return this.topicMembers.get(this.normalizeTopic(topic))?.size ?? 0;
171
+ }
172
+ getConnectionSnapshot(connectionId) {
173
+ const connection = this.connections.get(connectionId);
174
+ if (!connection) {
175
+ return undefined;
176
+ }
177
+ return {
178
+ topicCount: connection.topics.size,
179
+ topics: [...connection.topics].sort(),
180
+ queueLength: connection.queue.length,
181
+ resyncTopics: [...connection.resyncTopics].sort(),
182
+ lastAck: connection.lastAck,
183
+ };
184
+ }
185
+ deliver(connection, frame) {
186
+ if (connection.send(frame)) {
187
+ return;
188
+ }
189
+ this.enqueue(connection, frame);
190
+ }
191
+ deliverPendingResume(connection) {
192
+ if (connection.pendingResumeFrom === undefined) {
193
+ return;
194
+ }
195
+ const resumeFrom = connection.pendingResumeFrom;
196
+ connection.pendingResumeFrom = undefined;
197
+ const replay = this.resume(connection.connectionId, resumeFrom);
198
+ if (Array.isArray(replay)) {
199
+ for (const frame of replay) {
200
+ this.deliver(connection, frame);
201
+ }
202
+ }
203
+ else {
204
+ this.deliver(connection, replay);
205
+ }
206
+ }
207
+ enqueue(connection, frame) {
208
+ if (frame.type === 'event') {
209
+ this.coalesceEvent(connection, frame);
210
+ }
211
+ else {
212
+ connection.queue.push(frame);
213
+ }
214
+ if (connection.queue.length > this.maxQueueMessages) {
215
+ this.markOverflow(connection, frame);
216
+ }
217
+ }
218
+ coalesceEvent(connection, frame) {
219
+ const index = connection.queue.findIndex((queued) => queued.type === 'event' && queued.topic === frame.topic && queued.object === frame.object);
220
+ if (index === -1) {
221
+ connection.queue.push(frame);
222
+ return;
223
+ }
224
+ const previous = connection.queue[index];
225
+ connection.queue[index] = {
226
+ ...frame,
227
+ operation: previous.operation === 'delete' ? 'delete' : frame.operation,
228
+ };
229
+ }
230
+ markOverflow(connection, frame) {
231
+ const topics = frame.type === 'event' ? [frame.topic] : [...connection.topics];
232
+ for (const topic of topics) {
233
+ connection.resyncTopics.add(topic);
234
+ if (!connection.resyncQueued.has(topic)) {
235
+ connection.queue.push({
236
+ type: 'resync-required',
237
+ topics: [topic],
238
+ reason: 'overflow',
239
+ });
240
+ connection.resyncQueued.add(topic);
241
+ }
242
+ }
243
+ while (connection.queue.length > this.maxQueueMessages) {
244
+ const dropped = connection.queue.findIndex((queued) => queued.type === 'event');
245
+ connection.queue.splice(dropped === -1 ? 0 : dropped, 1);
246
+ }
247
+ }
248
+ pushReplay(event) {
249
+ this.replay.push(event);
250
+ while (this.replay.length > this.maxReplayEvents) {
251
+ this.replay.shift();
252
+ }
253
+ }
254
+ matchingMemberIds(topic, object) {
255
+ const ids = new Set();
256
+ for (const [registeredTopic, members] of this.topicMembers) {
257
+ if (this.topicMatches(registeredTopic, topic, object)) {
258
+ for (const member of members) {
259
+ ids.add(member);
260
+ }
261
+ }
262
+ }
263
+ return ids;
264
+ }
265
+ connectionMatches(connection, topic, object) {
266
+ for (const registeredTopic of connection.topics) {
267
+ if (this.topicMatches(registeredTopic, topic, object)) {
268
+ return true;
269
+ }
270
+ }
271
+ return false;
272
+ }
273
+ topicMatches(registeredTopic, eventTopic, object) {
274
+ return eventTopic === registeredTopic ||
275
+ object === registeredTopic ||
276
+ Boolean(object && registeredTopic.endsWith('/') && object.startsWith(registeredTopic));
277
+ }
278
+ assertNewRequestId(connection, requestId) {
279
+ if (connection.seenRequestIds.has(requestId)) {
280
+ throw new Error(`Duplicate requestId: ${requestId}`);
281
+ }
282
+ connection.seenRequestIds.add(requestId);
283
+ }
284
+ normalizeTopic(topic) {
285
+ const url = new URL(topic, this.origin);
286
+ if (url.origin !== this.origin.origin) {
287
+ throw new Error('topic must be same-origin');
288
+ }
289
+ url.hash = '';
290
+ url.search = '';
291
+ return url.toString();
292
+ }
293
+ normalizeResource(resource) {
294
+ const url = new URL(resource, this.origin);
295
+ if (url.origin !== this.origin.origin) {
296
+ throw new Error('resource must be same-origin');
297
+ }
298
+ url.hash = '';
299
+ return url.toString();
300
+ }
301
+ requireConnection(connectionId) {
302
+ const connection = this.connections.get(connectionId);
303
+ if (!connection) {
304
+ throw new Error(`Unknown notification connection: ${connectionId}`);
305
+ }
306
+ return connection;
307
+ }
308
+ deviceConnectionKey(identity, deviceSessionId) {
309
+ return `${identity.webId}\u0000${deviceSessionId}`;
310
+ }
311
+ }
312
+ exports.DeviceNotificationHub = DeviceNotificationHub;
313
+ //# sourceMappingURL=DeviceNotificationHub.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DeviceNotificationHub.js","sourceRoot":"","sources":["../../src/notifications/DeviceNotificationHub.ts"],"names":[],"mappings":";;;AAAA,6CAAyC;AAiDzC,MAAM,iCAAiC,GAAG,GAAG,CAAC;AAC9C,MAAM,0BAA0B,GAAG,GAAG,CAAC;AACvC,MAAM,yBAAyB,GAAG,GAAG,CAAC;AAEtC,MAAa,qBAAqB;IAYhC,YAAmB,OAAqC;QANvC,gBAAW,GAAG,IAAI,GAAG,EAA2B,CAAC;QACjD,wBAAmB,GAAG,IAAI,GAAG,EAAkB,CAAC;QAChD,iBAAY,GAAG,IAAI,GAAG,EAAuB,CAAC;QAC9C,WAAM,GAAiB,EAAE,CAAC;QACnC,aAAQ,GAAG,CAAC,CAAC;QAGnB,IAAI,CAAC,MAAM,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QACtC,IAAI,CAAC,sBAAsB,GAAG,OAAO,CAAC,sBAAsB,IAAI,iCAAiC,CAAC;QAClG,IAAI,CAAC,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,IAAI,0B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C,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;QAC3C,IAAI,GAAG,CAAC,MAAM,KAAK,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;QAClD,CAAC;QACD,GAAG,CAAC,IAAI,GAAG,EAAE,CAAC;QACd,OAAO,GAAG,CAAC,QAAQ,EAAE,CAAC;IACxB,CAAC;IAEO,iBAAiB,CAAC,YAAoB;QAC5C,MAAM,UAAU,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;QACtD,IAAI,CAAC,UAAU,EAAE,CAAC;YAChB,MAAM,IAAI,KAAK,CAAC,oCAAoC,YAAY,EAAE,CAAC,CAAC;QACtE,CAAC;QACD,OAAO,UAAU,CAAC;IACpB,CAAC;IAEO,mBAAmB,CAAC,QAAoC,EAAE,eAAuB;QACvF,OAAO,GAAG,QAAQ,CAAC,KAAK,SAAS,eAAe,EAAE,CAAC;IACrD,CAAC;CACF;AAnVD,sDAmVC","sourcesContent":["import { randomUUID } from 'node:crypto';\nimport type {\n DeviceNotificationOperation,\n DeviceNotificationServerFrame,\n} from './device-notification-protocol';\nimport type { DeviceNotificationIdentity } from '../api/handlers/DeviceNotificationTicketHandler';\n\nexport interface DeviceNotificationHubOptions {\n origin: string;\n maxTopicsPerConnection?: number;\n maxQueueMessages?: number;\n maxReplayEvents?: number;\n authorizeTopic?: (input: { identity: DeviceNotificationIdentity; topic: string }) => boolean | Promise<boolean>;\n}\n\nexport interface OpenDeviceNotificationConnectionInput {\n identity: DeviceNotificationIdentity;\n deviceSessionId: string;\n send: (frame: DeviceNotificationServerFrame) => boolean;\n close?: (code: number, reason: string) => void;\n}\n\nexport interface DeviceNotificationConnectionHandle {\n connectionId: string;\n}\n\nexport interface DeviceNotificationPublishInput {\n topic: string;\n object?: string;\n operation: DeviceNotificationOperation;\n}\n\ninterface ConnectionState {\n connectionId: string;\n identity: DeviceNotificationIdentity;\n deviceSessionId: string;\n topics: Set<string>;\n queue: DeviceNotificationServerFrame[];\n resyncTopics: Set<string>;\n resyncQueued: Set<string>;\n seenRequestIds: Set<string>;\n lastAck: number;\n pendingResumeFrom?: number;\n send: (frame: DeviceNotificationServerFrame) => boolean;\n close?: (code: number, reason: string) => void;\n}\n\ntype EventFrame = Extract<DeviceNotificationServerFrame, { type: 'event' }>;\n\nconst DEFAULT_MAX_TOPICS_PER_CONNECTION = 100;\nconst DEFAULT_MAX_QUEUE_MESSAGES = 256;\nconst DEFAULT_MAX_REPLAY_EVENTS = 512;\n\nexport class DeviceNotificationHub {\n private readonly origin: URL;\n private readonly maxTopicsPerConnection: number;\n private readonly maxQueueMessages: number;\n private readonly maxReplayEvents: number;\n private readonly authorizeTopic: (input: { identity: DeviceNotificationIdentity; topic: string }) => boolean | Promise<boolean>;\n private readonly connections = new Map<string, ConnectionState>();\n private readonly connectionsByDevice = new Map<string, string>();\n private readonly topicMembers = new Map<string, Set<string>>();\n private readonly replay: EventFrame[] = [];\n private sequence = 0;\n\n public constructor(options: DeviceNotificationHubOptions) {\n this.origin = new URL(options.origin);\n this.maxTopicsPerConnection = options.maxTopicsPerConnection ?? DEFAULT_MAX_TOPICS_PER_CONNECTION;\n this.maxQueueMessages = options.maxQueueMessages ?? DEFAULT_MAX_QUEUE_MESSAGES;\n this.maxReplayEvents = options.maxReplayEvents ?? DEFAULT_MAX_REPLAY_EVENTS;\n this.authorizeTopic = options.authorizeTopic ?? (() => true);\n }\n\n public openConnection(input: OpenDeviceNotificationConnectionInput): DeviceNotificationConnectionHandle {\n const deviceKey = this.deviceConnectionKey(input.identity, input.deviceSessionId);\n const existingConnectionId = this.connectionsByDevice.get(deviceKey);\n if (existingConnectionId) {\n this.closeConnection(existingConnectionId, 4000, 'Replaced by newer device connection');\n }\n const connectionId = randomUUID();\n this.connections.set(connectionId, {\n connectionId,\n identity: input.identity,\n deviceSessionId: input.deviceSessionId,\n topics: new Set(),\n queue: [],\n resyncTopics: new Set(),\n resyncQueued: new Set(),\n seenRequestIds: new Set(),\n lastAck: 0,\n pendingResumeFrom: undefined,\n send: input.send,\n close: input.close,\n });\n this.connectionsByDevice.set(deviceKey, connectionId);\n return { connectionId };\n }\n\n public hello(connectionId: string, resumeFrom?: number): DeviceNotificationServerFrame {\n const connection = this.requireConnection(connectionId);\n const ready: DeviceNotificationServerFrame = {\n type: 'ready',\n connectionId,\n sequence: this.sequence,\n };\n this.deliver(connection, ready);\n if (resumeFrom !== undefined) {\n connection.pendingResumeFrom = resumeFrom;\n }\n return ready;\n }\n\n public async registerTopics(connectionId: string, requestId: string, topics: string[]): Promise<DeviceNotificationServerFrame> {\n const connection = this.requireConnection(connectionId);\n this.assertNewRequestId(connection, requestId);\n const normalizedTopics = topics.map((topic) => this.normalizeTopic(topic));\n if ((new Set([...connection.topics, ...normalizedTopics])).size > this.maxTopicsPerConnection) {\n throw new Error('Too many topics for connection');\n }\n for (const topic of normalizedTopics) {\n if (!await this.authorizeTopic({ identity: connection.identity, topic })) {\n throw new Error(`Topic not authorized: ${topic}`);\n }\n connection.topics.add(topic);\n if (!this.topicMembers.has(topic)) {\n this.topicMembers.set(topic, new Set());\n }\n this.topicMembers.get(topic)!.add(connectionId);\n }\n const frame: DeviceNotificationServerFrame = {\n type: 'registered',\n requestId,\n topics: normalizedTopics,\n };\n this.deliver(connection, frame);\n this.deliverPendingResume(connection);\n return frame;\n }\n\n public async unregisterTopics(connectionId: string, requestId: string, topics: string[]): Promise<DeviceNotificationServerFrame> {\n const connection = this.requireConnection(connectionId);\n this.assertNewRequestId(connection, requestId);\n const normalizedTopics = topics.map((topic) => this.normalizeTopic(topic));\n for (const topic of normalizedTopics) {\n connection.topics.delete(topic);\n const members = this.topicMembers.get(topic);\n members?.delete(connectionId);\n if (members?.size === 0) {\n this.topicMembers.delete(topic);\n }\n }\n const frame: DeviceNotificationServerFrame = {\n type: 'unregistered',\n requestId,\n topics: normalizedTopics,\n };\n this.deliver(connection, frame);\n return frame;\n }\n\n public ack(connectionId: string, sequence: number): void {\n const connection = this.requireConnection(connectionId);\n connection.lastAck = Math.max(connection.lastAck, sequence);\n connection.queue = connection.queue.filter((frame) => frame.type !== 'event' || frame.sequence > sequence);\n }\n\n public publish(input: DeviceNotificationPublishInput): EventFrame {\n const topic = this.normalizeTopic(input.topic);\n const event: EventFrame = {\n type: 'event',\n sequence: ++this.sequence,\n eventId: `urn:uuid:${randomUUID()}`,\n topic,\n ...(input.object ? { object: this.normalizeResource(input.object) } : {}),\n operation: input.operation,\n emittedAt: new Date().toISOString(),\n };\n this.pushReplay(event);\n const memberIds = this.matchingMemberIds(topic, event.object);\n for (const connectionId of memberIds) {\n const connection = this.connections.get(connectionId);\n if (!connection) {\n continue;\n }\n this.deliver(connection, event);\n }\n return event;\n }\n\n public resume(connectionId: string, resumeFrom: number): EventFrame[] | DeviceNotificationServerFrame {\n const connection = this.requireConnection(connectionId);\n if (this.replay.length === 0) {\n return [];\n }\n const oldest = this.replay[0].sequence;\n if (resumeFrom < oldest) {\n return {\n type: 'resync-required',\n topics: [...connection.topics].sort(),\n reason: 'expired',\n };\n }\n return this.replay\n .filter((event) => event.sequence > resumeFrom)\n .filter((event) => this.connectionMatches(connection, event.topic, event.object));\n }\n\n public closeConnection(connectionId: string, code?: number, reason?: string): void {\n const connection = this.connections.get(connectionId);\n if (!connection) {\n return;\n }\n if (code !== undefined && reason !== undefined) {\n connection.close?.(code, reason);\n }\n for (const topic of connection.topics) {\n const members = this.topicMembers.get(topic);\n members?.delete(connectionId);\n if (members?.size === 0) {\n this.topicMembers.delete(topic);\n }\n }\n this.connections.delete(connectionId);\n this.connectionsByDevice.delete(this.deviceConnectionKey(connection.identity, connection.deviceSessionId));\n }\n\n public getSeenRequestIds(connectionId: string): Set<string> {\n return this.requireConnection(connectionId).seenRequestIds;\n }\n\n public getTopicMemberCount(topic: string): number {\n return this.topicMembers.get(this.normalizeTopic(topic))?.size ?? 0;\n }\n\n public getConnectionSnapshot(connectionId: string): {\n topicCount: number;\n topics: string[];\n queueLength: number;\n resyncTopics: string[];\n lastAck: number;\n } | undefined {\n const connection = this.connections.get(connectionId);\n if (!connection) {\n return undefined;\n }\n return {\n topicCount: connection.topics.size,\n topics: [...connection.topics].sort(),\n queueLength: connection.queue.length,\n resyncTopics: [...connection.resyncTopics].sort(),\n lastAck: connection.lastAck,\n };\n }\n\n private deliver(connection: ConnectionState, frame: DeviceNotificationServerFrame): void {\n if (connection.send(frame)) {\n return;\n }\n this.enqueue(connection, frame);\n }\n\n private deliverPendingResume(connection: ConnectionState): void {\n if (connection.pendingResumeFrom === undefined) {\n return;\n }\n const resumeFrom = connection.pendingResumeFrom;\n connection.pendingResumeFrom = undefined;\n const replay = this.resume(connection.connectionId, resumeFrom);\n if (Array.isArray(replay)) {\n for (const frame of replay) {\n this.deliver(connection, frame);\n }\n } else {\n this.deliver(connection, replay);\n }\n }\n\n private enqueue(connection: ConnectionState, frame: DeviceNotificationServerFrame): void {\n if (frame.type === 'event') {\n this.coalesceEvent(connection, frame);\n } else {\n connection.queue.push(frame);\n }\n if (connection.queue.length > this.maxQueueMessages) {\n this.markOverflow(connection, frame);\n }\n }\n\n private coalesceEvent(connection: ConnectionState, frame: EventFrame): void {\n const index = connection.queue.findIndex((queued) =>\n queued.type === 'event' && queued.topic === frame.topic && queued.object === frame.object);\n if (index === -1) {\n connection.queue.push(frame);\n return;\n }\n const previous = connection.queue[index] as EventFrame;\n connection.queue[index] = {\n ...frame,\n operation: previous.operation === 'delete' ? 'delete' : frame.operation,\n };\n }\n\n private markOverflow(connection: ConnectionState, frame: DeviceNotificationServerFrame): void {\n const topics = frame.type === 'event' ? [frame.topic] : [...connection.topics];\n for (const topic of topics) {\n connection.resyncTopics.add(topic);\n if (!connection.resyncQueued.has(topic)) {\n connection.queue.push({\n type: 'resync-required',\n topics: [topic],\n reason: 'overflow',\n });\n connection.resyncQueued.add(topic);\n }\n }\n while (connection.queue.length > this.maxQueueMessages) {\n const dropped = connection.queue.findIndex((queued) => queued.type === 'event');\n connection.queue.splice(dropped === -1 ? 0 : dropped, 1);\n }\n }\n\n private pushReplay(event: EventFrame): void {\n this.replay.push(event);\n while (this.replay.length > this.maxReplayEvents) {\n this.replay.shift();\n }\n }\n\n private matchingMemberIds(topic: string, object?: string): Set<string> {\n const ids = new Set<string>();\n for (const [registeredTopic, members] of this.topicMembers) {\n if (this.topicMatches(registeredTopic, topic, object)) {\n for (const member of members) {\n ids.add(member);\n }\n }\n }\n return ids;\n }\n\n private connectionMatches(connection: ConnectionState, topic: string, object?: string): boolean {\n for (const registeredTopic of connection.topics) {\n if (this.topicMatches(registeredTopic, topic, object)) {\n return true;\n }\n }\n return false;\n }\n\n private topicMatches(registeredTopic: string, eventTopic: string, object?: string): boolean {\n return eventTopic === registeredTopic ||\n object === registeredTopic ||\n Boolean(object && registeredTopic.endsWith('/') && object.startsWith(registeredTopic));\n }\n\n private assertNewRequestId(connection: ConnectionState, requestId: string): void {\n if (connection.seenRequestIds.has(requestId)) {\n throw new Error(`Duplicate requestId: ${requestId}`);\n }\n connection.seenRequestIds.add(requestId);\n }\n\n private normalizeTopic(topic: string): string {\n const url = new URL(topic, this.origin);\n if (url.origin !== this.origin.origin) {\n throw new Error('topic must be same-origin');\n }\n url.hash = '';\n url.search = '';\n return url.toString();\n }\n\n private normalizeResource(resource: string): string {\n const url = new URL(resource, this.origin);\n if (url.origin !== this.origin.origin) {\n throw new Error('resource must be same-origin');\n }\n url.hash = '';\n return url.toString();\n }\n\n private requireConnection(connectionId: string): ConnectionState {\n const connection = this.connections.get(connectionId);\n if (!connection) {\n throw new Error(`Unknown notification connection: ${connectionId}`);\n }\n return connection;\n }\n\n private deviceConnectionKey(identity: DeviceNotificationIdentity, deviceSessionId: string): string {\n return `${identity.webId}\\u0000${deviceSessionId}`;\n }\n}\n"]}
@@ -0,0 +1,258 @@
1
+ {
2
+ "@context": [
3
+ "https://linkedsoftwaredependencies.org/bundles/npm/@undefineds.co/xpod/^0.0.0/components/context.jsonld"
4
+ ],
5
+ "@id": "npmd:@undefineds.co/xpod",
6
+ "components": [
7
+ {
8
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub",
9
+ "@type": "Class",
10
+ "requireElement": "DeviceNotificationHub",
11
+ "parameters": [
12
+ {
13
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub_options",
14
+ "range": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHubOptions"
15
+ }
16
+ ],
17
+ "memberFields": [
18
+ {
19
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_origin",
20
+ "memberFieldName": "origin"
21
+ },
22
+ {
23
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_maxTopicsPerConnection",
24
+ "memberFieldName": "maxTopicsPerConnection"
25
+ },
26
+ {
27
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_maxQueueMessages",
28
+ "memberFieldName": "maxQueueMessages"
29
+ },
30
+ {
31
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_maxReplayEvents",
32
+ "memberFieldName": "maxReplayEvents"
33
+ },
34
+ {
35
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_authorizeTopic",
36
+ "memberFieldName": "authorizeTopic"
37
+ },
38
+ {
39
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_connections",
40
+ "memberFieldName": "connections"
41
+ },
42
+ {
43
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_connectionsByDevice",
44
+ "memberFieldName": "connectionsByDevice"
45
+ },
46
+ {
47
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_topicMembers",
48
+ "memberFieldName": "topicMembers"
49
+ },
50
+ {
51
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_replay",
52
+ "memberFieldName": "replay"
53
+ },
54
+ {
55
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_sequence",
56
+ "memberFieldName": "sequence"
57
+ },
58
+ {
59
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_constructor",
60
+ "memberFieldName": "constructor"
61
+ },
62
+ {
63
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_openConnection",
64
+ "memberFieldName": "openConnection"
65
+ },
66
+ {
67
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_hello",
68
+ "memberFieldName": "hello"
69
+ },
70
+ {
71
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_registerTopics",
72
+ "memberFieldName": "registerTopics"
73
+ },
74
+ {
75
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_unregisterTopics",
76
+ "memberFieldName": "unregisterTopics"
77
+ },
78
+ {
79
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_ack",
80
+ "memberFieldName": "ack"
81
+ },
82
+ {
83
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_publish",
84
+ "memberFieldName": "publish"
85
+ },
86
+ {
87
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_resume",
88
+ "memberFieldName": "resume"
89
+ },
90
+ {
91
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_closeConnection",
92
+ "memberFieldName": "closeConnection"
93
+ },
94
+ {
95
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_getSeenRequestIds",
96
+ "memberFieldName": "getSeenRequestIds"
97
+ },
98
+ {
99
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_getTopicMemberCount",
100
+ "memberFieldName": "getTopicMemberCount"
101
+ },
102
+ {
103
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_getConnectionSnapshot",
104
+ "memberFieldName": "getConnectionSnapshot"
105
+ },
106
+ {
107
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_deliver",
108
+ "memberFieldName": "deliver"
109
+ },
110
+ {
111
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_deliverPendingResume",
112
+ "memberFieldName": "deliverPendingResume"
113
+ },
114
+ {
115
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_enqueue",
116
+ "memberFieldName": "enqueue"
117
+ },
118
+ {
119
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_coalesceEvent",
120
+ "memberFieldName": "coalesceEvent"
121
+ },
122
+ {
123
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_markOverflow",
124
+ "memberFieldName": "markOverflow"
125
+ },
126
+ {
127
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_pushReplay",
128
+ "memberFieldName": "pushReplay"
129
+ },
130
+ {
131
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_matchingMemberIds",
132
+ "memberFieldName": "matchingMemberIds"
133
+ },
134
+ {
135
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_connectionMatches",
136
+ "memberFieldName": "connectionMatches"
137
+ },
138
+ {
139
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_topicMatches",
140
+ "memberFieldName": "topicMatches"
141
+ },
142
+ {
143
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_assertNewRequestId",
144
+ "memberFieldName": "assertNewRequestId"
145
+ },
146
+ {
147
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_normalizeTopic",
148
+ "memberFieldName": "normalizeTopic"
149
+ },
150
+ {
151
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_normalizeResource",
152
+ "memberFieldName": "normalizeResource"
153
+ },
154
+ {
155
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_requireConnection",
156
+ "memberFieldName": "requireConnection"
157
+ },
158
+ {
159
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub__member_deviceConnectionKey",
160
+ "memberFieldName": "deviceConnectionKey"
161
+ }
162
+ ],
163
+ "constructorArguments": [
164
+ {
165
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHub_options"
166
+ }
167
+ ]
168
+ },
169
+ {
170
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHubOptions",
171
+ "@type": "AbstractClass",
172
+ "requireElement": "DeviceNotificationHubOptions",
173
+ "parameters": [],
174
+ "memberFields": [
175
+ {
176
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHubOptions__member_origin",
177
+ "memberFieldName": "origin"
178
+ },
179
+ {
180
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHubOptions__member_maxTopicsPerConnection",
181
+ "memberFieldName": "maxTopicsPerConnection"
182
+ },
183
+ {
184
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHubOptions__member_maxQueueMessages",
185
+ "memberFieldName": "maxQueueMessages"
186
+ },
187
+ {
188
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHubOptions__member_maxReplayEvents",
189
+ "memberFieldName": "maxReplayEvents"
190
+ },
191
+ {
192
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationHubOptions__member_authorizeTopic",
193
+ "memberFieldName": "authorizeTopic"
194
+ }
195
+ ],
196
+ "constructorArguments": []
197
+ },
198
+ {
199
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#OpenDeviceNotificationConnectionInput",
200
+ "@type": "AbstractClass",
201
+ "requireElement": "OpenDeviceNotificationConnectionInput",
202
+ "parameters": [],
203
+ "memberFields": [
204
+ {
205
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#OpenDeviceNotificationConnectionInput__member_identity",
206
+ "memberFieldName": "identity"
207
+ },
208
+ {
209
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#OpenDeviceNotificationConnectionInput__member_deviceSessionId",
210
+ "memberFieldName": "deviceSessionId"
211
+ },
212
+ {
213
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#OpenDeviceNotificationConnectionInput__member_send",
214
+ "memberFieldName": "send"
215
+ },
216
+ {
217
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#OpenDeviceNotificationConnectionInput__member_close",
218
+ "memberFieldName": "close"
219
+ }
220
+ ],
221
+ "constructorArguments": []
222
+ },
223
+ {
224
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationConnectionHandle",
225
+ "@type": "AbstractClass",
226
+ "requireElement": "DeviceNotificationConnectionHandle",
227
+ "parameters": [],
228
+ "memberFields": [
229
+ {
230
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationConnectionHandle__member_connectionId",
231
+ "memberFieldName": "connectionId"
232
+ }
233
+ ],
234
+ "constructorArguments": []
235
+ },
236
+ {
237
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationPublishInput",
238
+ "@type": "AbstractClass",
239
+ "requireElement": "DeviceNotificationPublishInput",
240
+ "parameters": [],
241
+ "memberFields": [
242
+ {
243
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationPublishInput__member_topic",
244
+ "memberFieldName": "topic"
245
+ },
246
+ {
247
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationPublishInput__member_object",
248
+ "memberFieldName": "object"
249
+ },
250
+ {
251
+ "@id": "undefineds:dist/notifications/DeviceNotificationHub.jsonld#DeviceNotificationPublishInput__member_operation",
252
+ "memberFieldName": "operation"
253
+ }
254
+ ],
255
+ "constructorArguments": []
256
+ }
257
+ ]
258
+ }
@@ -0,0 +1,21 @@
1
+ import type { ResourceChangeEvent } from '../storage/ObservableResourceStore';
2
+ import type { DeviceNotificationOperation } from './device-notification-protocol';
3
+ export interface DeviceNotificationResourcePublisher {
4
+ publish(event: {
5
+ topic: string;
6
+ object?: string;
7
+ operation: DeviceNotificationOperation;
8
+ }): void;
9
+ }
10
+ export interface DeviceNotificationResourceListenerOptions {
11
+ origin: string;
12
+ hub: DeviceNotificationResourcePublisher;
13
+ }
14
+ export declare class DeviceNotificationResourceListener {
15
+ private readonly origin;
16
+ private readonly hub;
17
+ constructor(options: DeviceNotificationResourceListenerOptions);
18
+ onResourceChanged(event: ResourceChangeEvent): Promise<void>;
19
+ private toResourceUrl;
20
+ private toParentTopic;
21
+ }