monorise 1.11.0 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/base/index.d.ts +4 -4
  2. package/dist/base/index.js.map +1 -1
  3. package/dist/cli/cli.js +6 -0
  4. package/dist/cli/cli.js.map +1 -1
  5. package/dist/core/chunk-W6HUNJ6S.js +79 -0
  6. package/dist/core/chunk-W6HUNJ6S.js.map +1 -0
  7. package/dist/core/index.d.ts +99 -6
  8. package/dist/core/index.js +794 -68
  9. package/dist/core/index.js.map +1 -1
  10. package/dist/core/service.config-U77V7WIB.js +13 -0
  11. package/dist/core/service.config-U77V7WIB.js.map +1 -0
  12. package/dist/index.d.ts +15 -0
  13. package/dist/proxy/index.d.ts +35 -0
  14. package/dist/proxy/index.js +78 -0
  15. package/dist/proxy/index.js.map +1 -0
  16. package/dist/react/actions/websocket.action.d.ts +71 -0
  17. package/dist/react/actions/websocket.action.d.ts.map +1 -0
  18. package/dist/react/chunk-CQQYJW4K.js +444 -0
  19. package/dist/react/chunk-CQQYJW4K.js.map +1 -0
  20. package/dist/react/index.d.ts +30 -2
  21. package/dist/react/index.d.ts.map +1 -1
  22. package/dist/react/index.js +602 -34
  23. package/dist/react/index.js.map +1 -1
  24. package/dist/react/websocket/WebSocketManager.d.ts +72 -0
  25. package/dist/react/websocket/WebSocketManager.d.ts.map +1 -0
  26. package/dist/react/websocket/index.d.ts +3 -0
  27. package/dist/react/websocket/index.d.ts.map +1 -0
  28. package/dist/react/websocket/optimistic.d.ts +51 -0
  29. package/dist/react/websocket/optimistic.d.ts.map +1 -0
  30. package/dist/react/websocket-34W2HQLH.js +9 -0
  31. package/dist/react/websocket-34W2HQLH.js.map +1 -0
  32. package/dist/sst/components/monorise-core.d.ts +10 -0
  33. package/dist/sst/components/monorise-core.d.ts.map +1 -1
  34. package/dist/sst/components/single-table.d.ts.map +1 -1
  35. package/dist/sst/index.js +86 -14
  36. package/dist/sst/index.js.map +1 -1
  37. package/package.json +11 -1
@@ -1,60 +1,15 @@
1
- var __defProp = Object.defineProperty;
2
- var __defProps = Object.defineProperties;
3
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
- var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : /* @__PURE__ */ Symbol.for("Symbol." + name);
8
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
- var __spreadValues = (a, b) => {
10
- for (var prop in b || (b = {}))
11
- if (__hasOwnProp.call(b, prop))
12
- __defNormalProp(a, prop, b[prop]);
13
- if (__getOwnPropSymbols)
14
- for (var prop of __getOwnPropSymbols(b)) {
15
- if (__propIsEnum.call(b, prop))
16
- __defNormalProp(a, prop, b[prop]);
17
- }
18
- return a;
19
- };
20
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
21
- var __objRest = (source, exclude) => {
22
- var target = {};
23
- for (var prop in source)
24
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
25
- target[prop] = source[prop];
26
- if (source != null && __getOwnPropSymbols)
27
- for (var prop of __getOwnPropSymbols(source)) {
28
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
29
- target[prop] = source[prop];
30
- }
31
- return target;
32
- };
33
- var __export = (target, all) => {
34
- for (var name in all)
35
- __defProp(target, name, { get: all[name], enumerable: true });
36
- };
37
- var __async = (__this, __arguments, generator) => {
38
- return new Promise((resolve, reject) => {
39
- var fulfilled = (value) => {
40
- try {
41
- step(generator.next(value));
42
- } catch (e) {
43
- reject(e);
44
- }
45
- };
46
- var rejected = (value) => {
47
- try {
48
- step(generator.throw(value));
49
- } catch (e) {
50
- reject(e);
51
- }
52
- };
53
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
54
- step((generator = generator.apply(__this, __arguments)).next());
55
- });
56
- };
57
- var __forAwait = (obj, it, method) => (it = obj[__knownSymbol("asyncIterator")]) ? it.call(obj) : (obj = obj[__knownSymbol("iterator")](), it = {}, method = (key, fn) => (fn = obj[key]) && (it[key] = (arg) => new Promise((yes, no, done) => (arg = fn.call(obj, arg), done = arg.done, Promise.resolve(arg.value).then((value) => yes({ value, done }), no)))), method("next"), method("return"), it);
1
+ import {
2
+ CORE_EVENT_BUS,
3
+ CORE_TABLE,
4
+ ENTITY_REPLICATION_INDEX,
5
+ MUTUAL_REPLICATION_INDEX,
6
+ __async,
7
+ __export,
8
+ __forAwait,
9
+ __objRest,
10
+ __spreadProps,
11
+ __spreadValues
12
+ } from "./chunk-W6HUNJ6S.js";
58
13
 
59
14
  // controllers/setupRoutes.ts
60
15
  import { Hono } from "hono";
@@ -143,6 +98,10 @@ var setupCommonRoutes = (container) => {
143
98
  );
144
99
  app.get("/tag/:entityType/:tagName", container.listTagsController.controller);
145
100
  app.post("/transaction", container.executeTransactionController.controller);
101
+ app.post(
102
+ "/ws/ticket/:entityType/:entityId",
103
+ container.createTicketController.controller
104
+ );
146
105
  return app;
147
106
  };
148
107
 
@@ -2061,6 +2020,240 @@ var TagRepository = class extends Repository {
2061
2020
  }
2062
2021
  };
2063
2022
 
2023
+ // data/WebSocket.ts
2024
+ import {
2025
+ DeleteCommand,
2026
+ DynamoDBDocumentClient,
2027
+ PutCommand,
2028
+ QueryCommand
2029
+ } from "@aws-sdk/lib-dynamodb";
2030
+ var SUBSCRIPTION_TTL_SECONDS = 24 * 60 * 60;
2031
+ var WebSocketRepository = class extends Repository {
2032
+ constructor(tableName, dynamodbClient) {
2033
+ super();
2034
+ this.tableName = tableName;
2035
+ this.dynamodbClient = dynamodbClient;
2036
+ this.docClient = DynamoDBDocumentClient.from(dynamodbClient);
2037
+ }
2038
+ createConnection(connectionId, metadata, expiresAt) {
2039
+ return __async(this, null, function* () {
2040
+ yield this.docClient.send(
2041
+ new PutCommand({
2042
+ TableName: this.tableName,
2043
+ Item: __spreadProps(__spreadValues({
2044
+ PK: `CONN#${connectionId}`,
2045
+ SK: "#METADATA#",
2046
+ connectionId
2047
+ }, metadata), {
2048
+ expiresAt
2049
+ })
2050
+ })
2051
+ );
2052
+ });
2053
+ }
2054
+ getConnection(connectionId) {
2055
+ return __async(this, null, function* () {
2056
+ var _a;
2057
+ const result = yield this.docClient.send(
2058
+ new QueryCommand({
2059
+ TableName: this.tableName,
2060
+ KeyConditionExpression: "PK = :pk",
2061
+ ExpressionAttributeValues: {
2062
+ ":pk": `CONN#${connectionId}`
2063
+ }
2064
+ })
2065
+ );
2066
+ return (_a = result.Items) == null ? void 0 : _a[0];
2067
+ });
2068
+ }
2069
+ deleteConnection(connectionId) {
2070
+ return __async(this, null, function* () {
2071
+ yield this.docClient.send(
2072
+ new DeleteCommand({
2073
+ TableName: this.tableName,
2074
+ Key: {
2075
+ PK: `CONN#${connectionId}`,
2076
+ SK: "#METADATA#"
2077
+ }
2078
+ })
2079
+ );
2080
+ });
2081
+ }
2082
+ createSubscription(subKey, connectionId, data) {
2083
+ return __async(this, null, function* () {
2084
+ yield this.docClient.send(
2085
+ new PutCommand({
2086
+ TableName: this.tableName,
2087
+ Item: __spreadValues({
2088
+ PK: subKey,
2089
+ SK: `CONN#${connectionId}`,
2090
+ R1PK: `CONN#${connectionId}`,
2091
+ R1SK: subKey,
2092
+ connectionId,
2093
+ // Backstop only. $disconnect is what normally removes these, but it
2094
+ // is not guaranteed to run or to see every row, and without a TTL a
2095
+ // missed cleanup leaves the subscription forever. Comfortably longer
2096
+ // than API Gateway's own 2h max WebSocket connection lifetime, so it
2097
+ // never expires a live subscription.
2098
+ expiresAt: Math.floor(Date.now() / 1e3) + SUBSCRIPTION_TTL_SECONDS
2099
+ }, data)
2100
+ })
2101
+ );
2102
+ });
2103
+ }
2104
+ deleteSubscription(subKey, connectionId) {
2105
+ return __async(this, null, function* () {
2106
+ yield this.docClient.send(
2107
+ new DeleteCommand({
2108
+ TableName: this.tableName,
2109
+ Key: {
2110
+ PK: subKey,
2111
+ SK: `CONN#${connectionId}`
2112
+ }
2113
+ })
2114
+ );
2115
+ });
2116
+ }
2117
+ /**
2118
+ * Run a query to exhaustion.
2119
+ *
2120
+ * Every caller below fans a broadcast out to the rows it returns, so a
2121
+ * single-page query silently drops recipients past DynamoDB's 1MB limit --
2122
+ * and on `$disconnect`, silently leaves their subscription rows behind. The
2123
+ * `ConsistentRead` on these queries exists to avoid dropping recipients;
2124
+ * stopping at one page drops them the same way, just at a different
2125
+ * threshold.
2126
+ */
2127
+ queryAllPages(input) {
2128
+ return __async(this, null, function* () {
2129
+ const items = [];
2130
+ let lastKey;
2131
+ do {
2132
+ const result = yield this.docClient.send(
2133
+ new QueryCommand(__spreadProps(__spreadValues({}, input), { ExclusiveStartKey: lastKey }))
2134
+ );
2135
+ items.push(...result.Items || []);
2136
+ lastKey = result.LastEvaluatedKey;
2137
+ } while (lastKey);
2138
+ return items;
2139
+ });
2140
+ }
2141
+ querySubscriptionsByKey(subKey) {
2142
+ return __async(this, null, function* () {
2143
+ const items = yield this.queryAllPages({
2144
+ TableName: this.tableName,
2145
+ KeyConditionExpression: "PK = :pk",
2146
+ ExpressionAttributeValues: {
2147
+ ":pk": subKey
2148
+ },
2149
+ ConsistentRead: true
2150
+ });
2151
+ return items;
2152
+ });
2153
+ }
2154
+ querySubscriptionsByConnectionId(connectionId) {
2155
+ return __async(this, null, function* () {
2156
+ const { ENTITY_REPLICATION_INDEX: ENTITY_REPLICATION_INDEX2 } = yield import("./service.config-U77V7WIB.js");
2157
+ const items = yield this.queryAllPages({
2158
+ TableName: this.tableName,
2159
+ IndexName: ENTITY_REPLICATION_INDEX2,
2160
+ KeyConditionExpression: "R1PK = :r1pk",
2161
+ ExpressionAttributeValues: {
2162
+ ":r1pk": `CONN#${connectionId}`
2163
+ }
2164
+ });
2165
+ return items;
2166
+ });
2167
+ }
2168
+ createTicket(ticket, entityType, entityId, feedTypes, expiresAt) {
2169
+ return __async(this, null, function* () {
2170
+ yield this.docClient.send(
2171
+ new PutCommand({
2172
+ TableName: this.tableName,
2173
+ Item: {
2174
+ PK: `TICKET#${ticket}`,
2175
+ SK: "#METADATA#",
2176
+ entityType,
2177
+ entityId,
2178
+ feedTypes,
2179
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2180
+ expiresAt
2181
+ }
2182
+ })
2183
+ );
2184
+ });
2185
+ }
2186
+ consumeTicket(ticket) {
2187
+ return __async(this, null, function* () {
2188
+ try {
2189
+ const result = yield this.docClient.send(
2190
+ new DeleteCommand({
2191
+ TableName: this.tableName,
2192
+ Key: {
2193
+ PK: `TICKET#${ticket}`,
2194
+ SK: "#METADATA#"
2195
+ },
2196
+ ConditionExpression: "attribute_exists(PK)",
2197
+ ReturnValues: "ALL_OLD"
2198
+ })
2199
+ );
2200
+ const item = result.Attributes;
2201
+ if (!item) return null;
2202
+ const expiresAt = item.expiresAt;
2203
+ if (expiresAt && expiresAt < Math.floor(Date.now() / 1e3)) {
2204
+ return null;
2205
+ }
2206
+ return {
2207
+ entityType: item.entityType,
2208
+ entityId: item.entityId,
2209
+ feedTypes: item.feedTypes || []
2210
+ };
2211
+ } catch (error) {
2212
+ if (error instanceof Error && error.name === "ConditionalCheckFailedException") {
2213
+ return null;
2214
+ }
2215
+ throw error;
2216
+ }
2217
+ });
2218
+ }
2219
+ queryMutualConnections(byEntityType, byEntityId) {
2220
+ return __async(this, null, function* () {
2221
+ const items = yield this.queryAllPages({
2222
+ TableName: this.tableName,
2223
+ KeyConditionExpression: "PK = :pk",
2224
+ ExpressionAttributeValues: {
2225
+ ":pk": `${byEntityType}#${byEntityId}`
2226
+ },
2227
+ ProjectionExpression: "SK",
2228
+ ConsistentRead: true
2229
+ });
2230
+ const connections = [];
2231
+ for (const item of items) {
2232
+ const sk = item.SK;
2233
+ if (!sk || sk === "#METADATA#" || sk.startsWith("#")) continue;
2234
+ const parts = sk.split("#");
2235
+ if (parts.length >= 2) {
2236
+ connections.push({ entityType: parts[0], entityId: parts[1] });
2237
+ }
2238
+ }
2239
+ return connections;
2240
+ });
2241
+ }
2242
+ queryFeedSubscriptions(entityType, entityId) {
2243
+ return __async(this, null, function* () {
2244
+ const items = yield this.queryAllPages({
2245
+ TableName: this.tableName,
2246
+ KeyConditionExpression: "PK = :pk",
2247
+ ExpressionAttributeValues: {
2248
+ ":pk": `SUB#FEED#${entityType}#${entityId}`
2249
+ },
2250
+ ConsistentRead: true
2251
+ });
2252
+ return items;
2253
+ });
2254
+ }
2255
+ };
2256
+
2064
2257
  // handles/app.ts
2065
2258
  import { Hono as Hono2 } from "hono";
2066
2259
  import { handle } from "hono/aws-lambda";
@@ -2100,14 +2293,6 @@ import {
2100
2293
  PutEventsCommand
2101
2294
  } from "@aws-sdk/client-eventbridge";
2102
2295
 
2103
- // constants/table.ts
2104
- var ENTITY_REPLICATION_INDEX = "ENTITY_REPLICATION_INDEX";
2105
- var MUTUAL_REPLICATION_INDEX = "MUTUAL_REPLICATION_INDEX";
2106
-
2107
- // configs/service.config.ts
2108
- var CORE_TABLE = process.env.CORE_TABLE || "";
2109
- var CORE_EVENT_BUS = process.env.CORE_EVENT_BUS || "";
2110
-
2111
2296
  // types/event.ts
2112
2297
  var SOURCE = {
2113
2298
  CORE: "core-service",
@@ -8222,6 +8407,462 @@ var handler10 = (container) => (ev) => __async(null, null, function* () {
8222
8407
  return { batchItemFailures };
8223
8408
  });
8224
8409
 
8410
+ // processors/websocket-processor.ts
8411
+ import {
8412
+ ApiGatewayManagementApiClient,
8413
+ PostToConnectionCommand
8414
+ } from "@aws-sdk/client-apigatewaymanagementapi";
8415
+ import { unmarshall as unmarshall6 } from "@aws-sdk/util-dynamodb";
8416
+ import { ulid as ulid5 } from "ulid";
8417
+ var SUB_ENTITY_TYPE = "SUB#ENTITY#";
8418
+ var SUB_MUTUAL_TYPE = "SUB#MUTUAL#";
8419
+ var SUB_EPHEMERAL = "SUB#EPHEMERAL#";
8420
+ var SUB_FEED = "SUB#FEED#";
8421
+ var getWsEndpoint = () => process.env.WEBSOCKET_MANAGEMENT_ENDPOINT || "";
8422
+ var connect = (container) => (event) => __async(null, null, function* () {
8423
+ var _a, _b, _c, _d;
8424
+ const connectionId = event.requestContext.connectionId;
8425
+ if (!connectionId) {
8426
+ return { statusCode: 400, body: "Missing connection ID" };
8427
+ }
8428
+ const expiresAt = Math.floor(Date.now() / 1e3) + 2 * 60 * 60;
8429
+ const ticket = (_a = event.queryStringParameters) == null ? void 0 : _a.ticket;
8430
+ const token = ((_b = event.queryStringParameters) == null ? void 0 : _b.token) || ((_c = event.headers) == null ? void 0 : _c.authorization) || ((_d = event.headers) == null ? void 0 : _d.Authorization);
8431
+ if (!ticket && !token) {
8432
+ return { statusCode: 401, body: "Unauthorized" };
8433
+ }
8434
+ const wsRepo = container.websocketRepository;
8435
+ try {
8436
+ let entityType;
8437
+ let entityId;
8438
+ let feedTypes;
8439
+ if (ticket) {
8440
+ const ticketData = yield wsRepo.consumeTicket(ticket);
8441
+ if (!ticketData) {
8442
+ return { statusCode: 401, body: "Invalid or expired ticket" };
8443
+ }
8444
+ entityType = ticketData.entityType;
8445
+ entityId = ticketData.entityId;
8446
+ feedTypes = ticketData.feedTypes;
8447
+ } else {
8448
+ entityId = token;
8449
+ }
8450
+ yield wsRepo.createConnection(
8451
+ connectionId,
8452
+ __spreadProps(__spreadValues(__spreadValues({}, entityType && { entityType }), entityId && { entityId }), {
8453
+ connectedAt: (/* @__PURE__ */ new Date()).toISOString()
8454
+ }),
8455
+ expiresAt
8456
+ );
8457
+ if (entityType && entityId && feedTypes) {
8458
+ yield wsRepo.createSubscription(
8459
+ `${SUB_FEED}${entityType}#${entityId}`,
8460
+ connectionId,
8461
+ {
8462
+ subscriptionType: "feed",
8463
+ entityType,
8464
+ entityId,
8465
+ feedTypes,
8466
+ subscribedAt: (/* @__PURE__ */ new Date()).toISOString(),
8467
+ expiresAt
8468
+ }
8469
+ );
8470
+ }
8471
+ return { statusCode: 200, body: "Connected" };
8472
+ } catch (error) {
8473
+ console.error("Error in $connect:", error);
8474
+ return { statusCode: 500, body: "Failed to connect" };
8475
+ }
8476
+ });
8477
+ var disconnect = (container) => (event) => __async(null, null, function* () {
8478
+ const connectionId = event.requestContext.connectionId;
8479
+ if (!connectionId) {
8480
+ return { statusCode: 400, body: "Missing connection ID" };
8481
+ }
8482
+ const wsRepo = container.websocketRepository;
8483
+ try {
8484
+ const subscriptions = yield wsRepo.querySubscriptionsByConnectionId(connectionId);
8485
+ const deletePromises = [];
8486
+ for (const item of subscriptions) {
8487
+ if (item.PK && item.SK) {
8488
+ deletePromises.push(
8489
+ wsRepo.deleteSubscription(item.PK, item.connectionId).catch(
8490
+ (e) => console.warn("Failed to delete subscription on disconnect:", e)
8491
+ )
8492
+ );
8493
+ }
8494
+ }
8495
+ deletePromises.push(wsRepo.deleteConnection(connectionId));
8496
+ yield Promise.all(deletePromises);
8497
+ return { statusCode: 200, body: "Disconnected" };
8498
+ } catch (error) {
8499
+ console.error("Error cleaning up connection:", error);
8500
+ return { statusCode: 500, body: "Failed to disconnect" };
8501
+ }
8502
+ });
8503
+ var $default = (container) => (event) => __async(null, null, function* () {
8504
+ const connectionId = event.requestContext.connectionId;
8505
+ if (!connectionId || !event.body) {
8506
+ return { statusCode: 400, body: "Invalid message" };
8507
+ }
8508
+ let message;
8509
+ try {
8510
+ message = JSON.parse(event.body);
8511
+ } catch (e) {
8512
+ return { statusCode: 400, body: "Invalid JSON" };
8513
+ }
8514
+ const wsRepo = container.websocketRepository;
8515
+ const wsEndpoint = getWsEndpoint();
8516
+ const managementApi = new ApiGatewayManagementApiClient({
8517
+ endpoint: wsEndpoint
8518
+ });
8519
+ try {
8520
+ switch (message.action) {
8521
+ case "subscribe": {
8522
+ const {
8523
+ entityType,
8524
+ byEntityType,
8525
+ byEntityId,
8526
+ mutualEntityType,
8527
+ channel
8528
+ } = message.payload;
8529
+ if (entityType && !byEntityType) {
8530
+ yield wsRepo.createSubscription(
8531
+ `${SUB_ENTITY_TYPE}${entityType}`,
8532
+ connectionId,
8533
+ {
8534
+ subscriptionType: "entity-type",
8535
+ entityType,
8536
+ subscribedAt: (/* @__PURE__ */ new Date()).toISOString()
8537
+ }
8538
+ );
8539
+ } else if (byEntityType && byEntityId && mutualEntityType) {
8540
+ yield wsRepo.createSubscription(
8541
+ `${SUB_MUTUAL_TYPE}${byEntityType}#${byEntityId}#${mutualEntityType}`,
8542
+ connectionId,
8543
+ {
8544
+ subscriptionType: "mutual-type",
8545
+ byEntityType,
8546
+ byEntityId,
8547
+ entityType: mutualEntityType,
8548
+ subscribedAt: (/* @__PURE__ */ new Date()).toISOString()
8549
+ }
8550
+ );
8551
+ } else if (channel) {
8552
+ yield wsRepo.createSubscription(
8553
+ `${SUB_EPHEMERAL}${channel}`,
8554
+ connectionId,
8555
+ {
8556
+ subscriptionType: "ephemeral",
8557
+ channel,
8558
+ subscribedAt: (/* @__PURE__ */ new Date()).toISOString()
8559
+ }
8560
+ );
8561
+ } else {
8562
+ return { statusCode: 400, body: "Invalid subscription parameters" };
8563
+ }
8564
+ const ackMessage = {
8565
+ type: "ack",
8566
+ id: message.id,
8567
+ payload: { action: "subscribe", success: true }
8568
+ };
8569
+ yield managementApi.send(
8570
+ new PostToConnectionCommand({
8571
+ ConnectionId: connectionId,
8572
+ Data: JSON.stringify(ackMessage)
8573
+ })
8574
+ );
8575
+ return { statusCode: 200, body: "Subscribed" };
8576
+ }
8577
+ case "unsubscribe": {
8578
+ const {
8579
+ entityType,
8580
+ byEntityType,
8581
+ byEntityId,
8582
+ mutualEntityType,
8583
+ channel
8584
+ } = message.payload;
8585
+ if (entityType && !byEntityType) {
8586
+ yield wsRepo.deleteSubscription(
8587
+ `${SUB_ENTITY_TYPE}${entityType}`,
8588
+ connectionId
8589
+ );
8590
+ } else if (byEntityType && byEntityId && mutualEntityType) {
8591
+ yield wsRepo.deleteSubscription(
8592
+ `${SUB_MUTUAL_TYPE}${byEntityType}#${byEntityId}#${mutualEntityType}`,
8593
+ connectionId
8594
+ );
8595
+ } else if (channel) {
8596
+ yield wsRepo.deleteSubscription(
8597
+ `${SUB_EPHEMERAL}${channel}`,
8598
+ connectionId
8599
+ );
8600
+ }
8601
+ const ackMessage = {
8602
+ type: "ack",
8603
+ id: message.id,
8604
+ payload: { action: "unsubscribe", success: true }
8605
+ };
8606
+ yield managementApi.send(
8607
+ new PostToConnectionCommand({
8608
+ ConnectionId: connectionId,
8609
+ Data: JSON.stringify(ackMessage)
8610
+ })
8611
+ );
8612
+ return { statusCode: 200, body: "Unsubscribed" };
8613
+ }
8614
+ case "ping": {
8615
+ const pongMessage = {
8616
+ type: "pong",
8617
+ id: message.id,
8618
+ payload: { timestamp: Date.now() }
8619
+ };
8620
+ yield managementApi.send(
8621
+ new PostToConnectionCommand({
8622
+ ConnectionId: connectionId,
8623
+ Data: JSON.stringify(pongMessage)
8624
+ })
8625
+ );
8626
+ return { statusCode: 200, body: "Pong" };
8627
+ }
8628
+ case "ephemeral": {
8629
+ const { channel, data } = message.payload;
8630
+ if (!channel) {
8631
+ return { statusCode: 400, body: "Missing channel" };
8632
+ }
8633
+ const conn = yield wsRepo.getConnection(connectionId);
8634
+ const senderId = conn == null ? void 0 : conn.entityId;
8635
+ const subKey = `${SUB_EPHEMERAL}${channel}`;
8636
+ const ephemeralMessage = {
8637
+ type: "ephemeral",
8638
+ id: ulid5(),
8639
+ payload: { channel, data, senderId }
8640
+ };
8641
+ yield broadcastToSubscribers(
8642
+ managementApi,
8643
+ wsRepo,
8644
+ subKey,
8645
+ ephemeralMessage,
8646
+ connectionId
8647
+ // Exclude sender
8648
+ );
8649
+ return { statusCode: 200, body: "Broadcasted" };
8650
+ }
8651
+ default:
8652
+ return { statusCode: 400, body: "Unknown action" };
8653
+ }
8654
+ } catch (error) {
8655
+ console.error("Error handling message:", error);
8656
+ try {
8657
+ const errorMessage = {
8658
+ type: "error",
8659
+ id: message.id,
8660
+ payload: { message: "Internal server error" }
8661
+ };
8662
+ yield managementApi.send(
8663
+ new PostToConnectionCommand({
8664
+ ConnectionId: connectionId,
8665
+ Data: JSON.stringify(errorMessage)
8666
+ })
8667
+ );
8668
+ } catch (e) {
8669
+ }
8670
+ return { statusCode: 500, body: "Internal server error" };
8671
+ }
8672
+ });
8673
+ var broadcast = (container) => (event) => __async(null, null, function* () {
8674
+ var _a, _b, _c, _d;
8675
+ const wsRepo = container.websocketRepository;
8676
+ const wsEndpoint = getWsEndpoint();
8677
+ const managementApi = new ApiGatewayManagementApiClient({
8678
+ endpoint: wsEndpoint
8679
+ });
8680
+ for (const record of event.Records) {
8681
+ const isInsert = record.eventName === "INSERT";
8682
+ const isModify = record.eventName === "MODIFY";
8683
+ const isRemove = record.eventName === "REMOVE";
8684
+ if (!isInsert && !isModify && !isRemove) continue;
8685
+ const newImage = (_a = record.dynamodb) == null ? void 0 : _a.NewImage;
8686
+ const oldImage = (_b = record.dynamodb) == null ? void 0 : _b.OldImage;
8687
+ const image = newImage || oldImage;
8688
+ if (!image) continue;
8689
+ const pk = ((_c = image.PK) == null ? void 0 : _c.S) || "";
8690
+ const sk = ((_d = image.SK) == null ? void 0 : _d.S) || "";
8691
+ const pkParts = pk.split("#");
8692
+ if (pkParts.length < 2) continue;
8693
+ const entityType = pkParts[0];
8694
+ const entityId = pkParts[1];
8695
+ if (!(entityType in container.config.EntityConfig)) continue;
8696
+ const isMutual = !sk.startsWith("#METADATA#") && sk.includes("#");
8697
+ try {
8698
+ if (isMutual) {
8699
+ const skParts = sk.split("#");
8700
+ const mutualEntityType = skParts[0];
8701
+ const byEntityId = entityId;
8702
+ const subKey = `${SUB_MUTUAL_TYPE}${entityType}#${byEntityId}#${mutualEntityType}`;
8703
+ const subscribers = yield wsRepo.querySubscriptionsByKey(subKey);
8704
+ if (subscribers.length) {
8705
+ let eventType;
8706
+ if (isInsert) eventType = "mutual.created";
8707
+ else if (isModify) eventType = "mutual.updated";
8708
+ else eventType = "mutual.deleted";
8709
+ const message = {
8710
+ type: eventType,
8711
+ id: ulid5(),
8712
+ payload: {
8713
+ byEntityType: entityType,
8714
+ byEntityId,
8715
+ mutualEntityType,
8716
+ entityId: skParts[1],
8717
+ data: isRemove ? void 0 : unmarshall6(image)
8718
+ }
8719
+ };
8720
+ yield broadcastToSubscribers(
8721
+ managementApi,
8722
+ wsRepo,
8723
+ subKey,
8724
+ message
8725
+ );
8726
+ }
8727
+ } else {
8728
+ const subKey = `${SUB_ENTITY_TYPE}${entityType}`;
8729
+ const subscribers = yield wsRepo.querySubscriptionsByKey(subKey);
8730
+ if (subscribers.length) {
8731
+ let eventType;
8732
+ if (isInsert) eventType = "entity.created";
8733
+ else if (isModify) eventType = "entity.updated";
8734
+ else eventType = "entity.deleted";
8735
+ const message = {
8736
+ type: eventType,
8737
+ id: ulid5(),
8738
+ payload: {
8739
+ entityType,
8740
+ entityId,
8741
+ data: isRemove ? void 0 : unmarshall6(image)
8742
+ }
8743
+ };
8744
+ yield broadcastToSubscribers(
8745
+ managementApi,
8746
+ wsRepo,
8747
+ subKey,
8748
+ message
8749
+ );
8750
+ }
8751
+ }
8752
+ yield broadcastToFeedSubscribers(
8753
+ managementApi,
8754
+ wsRepo,
8755
+ entityType,
8756
+ entityId,
8757
+ isMutual ? sk.split("#")[0] : entityType,
8758
+ // the changed entity type
8759
+ isMutual ? {
8760
+ type: isInsert ? "mutual.created" : isModify ? "mutual.updated" : "mutual.deleted",
8761
+ id: ulid5(),
8762
+ payload: {
8763
+ byEntityType: entityType,
8764
+ byEntityId: entityId,
8765
+ mutualEntityType: sk.split("#")[0],
8766
+ entityId: sk.split("#")[1],
8767
+ data: isRemove ? void 0 : unmarshall6(image)
8768
+ }
8769
+ } : {
8770
+ type: isInsert ? "entity.created" : isModify ? "entity.updated" : "entity.deleted",
8771
+ id: ulid5(),
8772
+ payload: {
8773
+ entityType,
8774
+ entityId,
8775
+ data: isRemove ? void 0 : unmarshall6(image)
8776
+ }
8777
+ }
8778
+ );
8779
+ } catch (error) {
8780
+ console.error("Error broadcasting:", error);
8781
+ }
8782
+ }
8783
+ });
8784
+ function broadcastToSubscribers(managementApi, wsRepo, subKey, message, excludeConnectionId) {
8785
+ return __async(this, null, function* () {
8786
+ const subscribers = yield wsRepo.querySubscriptionsByKey(subKey);
8787
+ if (!subscribers.length) return;
8788
+ const messageData = JSON.stringify(message);
8789
+ const sends = subscribers.filter((subscriber) => {
8790
+ const id = subscriber.connectionId;
8791
+ return !excludeConnectionId || id !== excludeConnectionId;
8792
+ }).map((subscriber) => __async(null, null, function* () {
8793
+ var _a;
8794
+ try {
8795
+ yield managementApi.send(
8796
+ new PostToConnectionCommand({
8797
+ ConnectionId: subscriber.connectionId,
8798
+ Data: messageData
8799
+ })
8800
+ );
8801
+ } catch (error) {
8802
+ const isGone = (error == null ? void 0 : error.name) === "GoneException" || ((_a = error == null ? void 0 : error.$metadata) == null ? void 0 : _a.httpStatusCode) === 410;
8803
+ if (isGone) {
8804
+ yield wsRepo.deleteSubscription(subKey, subscriber.connectionId).catch(
8805
+ (e) => console.warn("Failed to clean up stale subscription:", e)
8806
+ );
8807
+ }
8808
+ }
8809
+ }));
8810
+ yield Promise.allSettled(sends);
8811
+ });
8812
+ }
8813
+ function broadcastToFeedSubscribers(managementApi, wsRepo, byEntityType, byEntityId, changedEntityType, message) {
8814
+ return __async(this, null, function* () {
8815
+ var _a;
8816
+ const connections = yield wsRepo.queryMutualConnections(
8817
+ byEntityType,
8818
+ byEntityId
8819
+ );
8820
+ const connectedEntities = new Set(
8821
+ connections.map((c) => `${c.entityType}:${c.entityId}`)
8822
+ );
8823
+ connectedEntities.add(`${byEntityType}:${byEntityId}`);
8824
+ const sentConnections = /* @__PURE__ */ new Set();
8825
+ const resolved = yield Promise.all(
8826
+ Array.from(connectedEntities).map((connEntity) => __async(null, null, function* () {
8827
+ const [entityType, entityId] = connEntity.split(":");
8828
+ return {
8829
+ entityType,
8830
+ entityId,
8831
+ feedSubs: yield wsRepo.queryFeedSubscriptions(entityType, entityId)
8832
+ };
8833
+ }))
8834
+ );
8835
+ for (const { entityType, entityId, feedSubs } of resolved) {
8836
+ if (!feedSubs.length) continue;
8837
+ for (const feedSub of feedSubs) {
8838
+ const feedTypes = feedSub.feedTypes;
8839
+ const connectionId = feedSub.connectionId;
8840
+ if (feedTypes && !feedTypes.includes(changedEntityType)) continue;
8841
+ if (sentConnections.has(connectionId)) continue;
8842
+ sentConnections.add(connectionId);
8843
+ try {
8844
+ yield managementApi.send(
8845
+ new PostToConnectionCommand({
8846
+ ConnectionId: connectionId,
8847
+ Data: JSON.stringify(message)
8848
+ })
8849
+ );
8850
+ } catch (error) {
8851
+ const isGone = (error == null ? void 0 : error.name) === "GoneException" || ((_a = error == null ? void 0 : error.$metadata) == null ? void 0 : _a.httpStatusCode) === 410;
8852
+ if (isGone) {
8853
+ yield wsRepo.deleteSubscription(
8854
+ `SUB#FEED#${entityType}#${entityId}`,
8855
+ connectionId
8856
+ ).catch(
8857
+ (e) => console.warn("Failed to clean up stale feed subscription:", e)
8858
+ );
8859
+ }
8860
+ }
8861
+ }
8862
+ }
8863
+ });
8864
+ }
8865
+
8225
8866
  // services/DependencyContainer.ts
8226
8867
  import { DynamoDB } from "@aws-sdk/client-dynamodb";
8227
8868
 
@@ -9473,6 +10114,72 @@ var ExecuteTransactionController = class {
9473
10114
  }
9474
10115
  };
9475
10116
 
10117
+ // controllers/ws/create-ticket.controller.ts
10118
+ import { createMiddleware as createMiddleware18 } from "hono/factory";
10119
+ import { ulid as ulid6 } from "ulid";
10120
+ var TICKET_TTL_SECONDS = 30 * 60;
10121
+ var CreateTicketController = class {
10122
+ constructor(container) {
10123
+ this.container = container;
10124
+ this.controller = createMiddleware18((c) => __async(this, null, function* () {
10125
+ var _a, _b;
10126
+ const { entityType, entityId } = c.req.param();
10127
+ let feedTypes;
10128
+ try {
10129
+ const body = yield c.req.json();
10130
+ feedTypes = body.feedTypes;
10131
+ } catch (e) {
10132
+ }
10133
+ if (!feedTypes || feedTypes.length === 0) {
10134
+ const allConfigs = this.container.config.EntityConfig;
10135
+ const adjacency = /* @__PURE__ */ new Map();
10136
+ const link = (from, to) => {
10137
+ var _a2;
10138
+ if (!adjacency.has(from)) adjacency.set(from, /* @__PURE__ */ new Set());
10139
+ (_a2 = adjacency.get(from)) == null ? void 0 : _a2.add(to);
10140
+ };
10141
+ for (const [type, config] of Object.entries(allConfigs)) {
10142
+ const fields = (_a = config == null ? void 0 : config.mutual) == null ? void 0 : _a.mutualFields;
10143
+ if (!fields) continue;
10144
+ for (const field of Object.values(fields)) {
10145
+ link(type, field.entityType);
10146
+ link(field.entityType, type);
10147
+ }
10148
+ }
10149
+ const visited = /* @__PURE__ */ new Set();
10150
+ const queue = [entityType];
10151
+ while (queue.length > 0) {
10152
+ const current = queue.shift();
10153
+ if (!current) continue;
10154
+ if (visited.has(current)) continue;
10155
+ visited.add(current);
10156
+ for (const neighbour of (_b = adjacency.get(current)) != null ? _b : []) {
10157
+ if (!visited.has(neighbour)) queue.push(neighbour);
10158
+ }
10159
+ }
10160
+ visited.delete(entityType);
10161
+ feedTypes = Array.from(visited);
10162
+ }
10163
+ const ticket = ulid6();
10164
+ const now = Math.floor(Date.now() / 1e3);
10165
+ const expiresAt = now + TICKET_TTL_SECONDS;
10166
+ yield this.container.websocketRepository.createTicket(
10167
+ ticket,
10168
+ entityType,
10169
+ entityId,
10170
+ feedTypes,
10171
+ expiresAt
10172
+ );
10173
+ const wsEndpoint = process.env.WEBSOCKET_URL || "";
10174
+ return c.json({
10175
+ ticket,
10176
+ wsUrl: wsEndpoint,
10177
+ expiresIn: TICKET_TTL_SECONDS
10178
+ });
10179
+ }));
10180
+ }
10181
+ };
10182
+
9476
10183
  // services/entity-service-lifecycle.ts
9477
10184
  var EntityServiceLifeCycle = class {
9478
10185
  constructor(EntityConfig, publishEvent2, eventUtils) {
@@ -9508,7 +10215,7 @@ var EntityServiceLifeCycle = class {
9508
10215
 
9509
10216
  // services/transaction.service.ts
9510
10217
  import { TransactionCanceledException as TransactionCanceledException5 } from "@aws-sdk/client-dynamodb";
9511
- import { ulid as ulid5 } from "ulid";
10218
+ import { ulid as ulid7 } from "ulid";
9512
10219
  var MAX_TRANSACTION_ITEMS = 100;
9513
10220
  var TransactionService = class {
9514
10221
  constructor(EntityConfig, EmailAuthEnabledEntities, entityRepository, dynamodbClient, publishEvent2, entityServiceLifeCycle, eventUtils) {
@@ -9711,7 +10418,7 @@ var TransactionService = class {
9711
10418
  const currentDatetime = /* @__PURE__ */ new Date();
9712
10419
  const entity = new Entity(
9713
10420
  op.entityType,
9714
- op.entityId || ulid5(),
10421
+ op.entityId || ulid7(),
9715
10422
  parsedPayload,
9716
10423
  currentDatetime,
9717
10424
  currentDatetime
@@ -10063,6 +10770,13 @@ var DependencyContainer = class {
10063
10770
  this.dynamodbClient
10064
10771
  );
10065
10772
  }
10773
+ get websocketRepository() {
10774
+ return this.createCachedInstance(
10775
+ WebSocketRepository,
10776
+ this.coreTable,
10777
+ this.dynamodbClient
10778
+ );
10779
+ }
10066
10780
  get getEntityController() {
10067
10781
  return this.createCachedInstance(
10068
10782
  GetEntityController,
@@ -10164,6 +10878,9 @@ var DependencyContainer = class {
10164
10878
  this.transactionService
10165
10879
  );
10166
10880
  }
10881
+ get createTicketController() {
10882
+ return this.createCachedInstance(CreateTicketController, this);
10883
+ }
10167
10884
  };
10168
10885
 
10169
10886
  // helpers/transactional.ts
@@ -10216,6 +10933,10 @@ var CoreFactory = class {
10216
10933
  this.prejoinProcessor = handler8(dependencyContainer);
10217
10934
  this.tagProcessor = handler10(dependencyContainer);
10218
10935
  this.appHandler = appHandler(dependencyContainer);
10936
+ this.wsConnect = connect(dependencyContainer);
10937
+ this.wsDisconnect = disconnect(dependencyContainer);
10938
+ this.wsDefault = $default(dependencyContainer);
10939
+ this.wsBroadcast = broadcast(dependencyContainer);
10219
10940
  }
10220
10941
  };
10221
10942
  var index_default = CoreFactory;
@@ -10232,6 +10953,7 @@ export {
10232
10953
  StandardErrorCode,
10233
10954
  TagRepository,
10234
10955
  TransactionService,
10956
+ WebSocketRepository,
10235
10957
  handler3 as analyticsBackfillProcessor,
10236
10958
  handler4 as analyticsMaterializationProcessor,
10237
10959
  handler5 as analyticsModelProcessor,
@@ -10247,6 +10969,10 @@ export {
10247
10969
  setupCommonRoutes,
10248
10970
  startBackfill as startAnalyticsBackfill,
10249
10971
  handler10 as tagProcessor,
10250
- transactional
10972
+ transactional,
10973
+ broadcast as wsBroadcast,
10974
+ connect as wsConnect,
10975
+ $default as wsDefault,
10976
+ disconnect as wsDisconnect
10251
10977
  };
10252
10978
  //# sourceMappingURL=index.js.map