@geekmidas/events 10.0.0-alpha.15 → 10.0.0-alpha.151

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 (84) hide show
  1. package/README.md +46 -1
  2. package/dist/{SQSSubscriber-BXLE_1L3.mjs → SQSSubscriber-BEJBfNTe.mjs} +94 -10
  3. package/dist/SQSSubscriber-BEJBfNTe.mjs.map +1 -0
  4. package/dist/{SQSSubscriber-DtRUaZB3.cjs → SQSSubscriber-COTqWvOk.cjs} +101 -10
  5. package/dist/SQSSubscriber-COTqWvOk.cjs.map +1 -0
  6. package/dist/basic/index.cjs +35 -4
  7. package/dist/basic/index.cjs.map +1 -1
  8. package/dist/basic/index.d.cts +8 -1
  9. package/dist/basic/index.d.cts.map +1 -1
  10. package/dist/basic/index.d.mts +8 -1
  11. package/dist/basic/index.d.mts.map +1 -1
  12. package/dist/basic/index.mjs +35 -5
  13. package/dist/basic/index.mjs.map +1 -1
  14. package/dist/index.cjs +45 -142
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.d.cts +80 -20
  17. package/dist/index.d.cts.map +1 -1
  18. package/dist/index.d.mts +80 -20
  19. package/dist/index.d.mts.map +1 -1
  20. package/dist/index.mjs +33 -141
  21. package/dist/index.mjs.map +1 -1
  22. package/dist/pgboss/index.cjs +121 -34
  23. package/dist/pgboss/index.cjs.map +1 -1
  24. package/dist/pgboss/index.d.cts +45 -4
  25. package/dist/pgboss/index.d.cts.map +1 -1
  26. package/dist/pgboss/index.d.mts +45 -4
  27. package/dist/pgboss/index.d.mts.map +1 -1
  28. package/dist/pgboss/index.mjs +119 -34
  29. package/dist/pgboss/index.mjs.map +1 -1
  30. package/dist/rabbitmq/index.cjs +60 -27
  31. package/dist/rabbitmq/index.cjs.map +1 -1
  32. package/dist/rabbitmq/index.d.cts +9 -1
  33. package/dist/rabbitmq/index.d.cts.map +1 -1
  34. package/dist/rabbitmq/index.d.mts +9 -1
  35. package/dist/rabbitmq/index.d.mts.map +1 -1
  36. package/dist/rabbitmq/index.mjs +61 -27
  37. package/dist/rabbitmq/index.mjs.map +1 -1
  38. package/dist/{types-gGaoT8qc.d.cts → registry-DIx25Q5s.d.cts} +108 -2
  39. package/dist/registry-DIx25Q5s.d.cts.map +1 -0
  40. package/dist/{types-gGaoT8qc.d.mts → registry-DIx25Q5s.d.mts} +108 -2
  41. package/dist/registry-DIx25Q5s.d.mts.map +1 -0
  42. package/dist/registry-DXLY1Xf6.mjs +99 -0
  43. package/dist/registry-DXLY1Xf6.mjs.map +1 -0
  44. package/dist/registry-DlT36229.cjs +122 -0
  45. package/dist/registry-DlT36229.cjs.map +1 -0
  46. package/dist/sns/index.cjs +425 -11
  47. package/dist/sns/index.cjs.map +1 -1
  48. package/dist/sns/index.d.cts +255 -8
  49. package/dist/sns/index.d.cts.map +1 -1
  50. package/dist/sns/index.d.mts +255 -8
  51. package/dist/sns/index.d.mts.map +1 -1
  52. package/dist/sns/index.mjs +410 -12
  53. package/dist/sns/index.mjs.map +1 -1
  54. package/dist/sns/snsUrl.d.cts.map +1 -1
  55. package/dist/sns/snsUrl.d.mts.map +1 -1
  56. package/dist/sqs/index.cjs +22 -66
  57. package/dist/sqs/index.cjs.map +1 -1
  58. package/dist/sqs/index.d.cts +10 -1
  59. package/dist/sqs/index.d.cts.map +1 -1
  60. package/dist/sqs/index.d.mts +10 -1
  61. package/dist/sqs/index.d.mts.map +1 -1
  62. package/dist/sqs/index.mjs +20 -63
  63. package/dist/sqs/index.mjs.map +1 -1
  64. package/dist/sqs/sqsUrl.d.cts.map +1 -1
  65. package/dist/sqs/sqsUrl.d.mts.map +1 -1
  66. package/dist/telemetry-DG3l807O.cjs +309 -0
  67. package/dist/telemetry-DG3l807O.cjs.map +1 -0
  68. package/dist/telemetry-DjjgJMul.mjs +244 -0
  69. package/dist/telemetry-DjjgJMul.mjs.map +1 -0
  70. package/package.json +8 -3
  71. package/dist/PgBossConnection-CywKoAZU.cjs +0 -2
  72. package/dist/PgBossConnection-DjoqT84r.mjs +0 -2
  73. package/dist/RabbitMQConnection-C9eccBL8.cjs +0 -2
  74. package/dist/RabbitMQConnection-CAp7VqyT.mjs +0 -2
  75. package/dist/SNSConnection-BWDC1wAF.cjs +0 -2
  76. package/dist/SNSConnection-ezQvVrDv.mjs +0 -2
  77. package/dist/SQSSubscriber-BXLE_1L3.mjs.map +0 -1
  78. package/dist/SQSSubscriber-DtRUaZB3.cjs.map +0 -1
  79. package/dist/types-BcZjLxVV.cjs +0 -51
  80. package/dist/types-BcZjLxVV.cjs.map +0 -1
  81. package/dist/types-Bk5JM6MP.mjs +0 -40
  82. package/dist/types-Bk5JM6MP.mjs.map +0 -1
  83. package/dist/types-gGaoT8qc.d.cts.map +0 -1
  84. package/dist/types-gGaoT8qc.d.mts.map +0 -1
@@ -0,0 +1,122 @@
1
+ const require_telemetry = require("./telemetry-DG3l807O.cjs");
2
+ //#region src/registry.ts
3
+ /**
4
+ * Where each built-in driver lives, so a missing one can be named exactly —
5
+ * the subpath to import and the export to register.
6
+ */
7
+ const BUILT_IN = {
8
+ ["basic"]: {
9
+ subpath: "@geekmidas/events/basic",
10
+ driver: "basicEventsDriver"
11
+ },
12
+ ["pgboss"]: {
13
+ subpath: "@geekmidas/events/pgboss",
14
+ driver: "pgbossEventsDriver"
15
+ },
16
+ ["sns"]: {
17
+ subpath: "@geekmidas/events/sns",
18
+ driver: "snsEventsDriver"
19
+ },
20
+ ["sqs"]: {
21
+ subpath: "@geekmidas/events/sqs",
22
+ driver: "sqsEventsDriver"
23
+ },
24
+ ["rabbitmq"]: {
25
+ subpath: "@geekmidas/events/rabbitmq",
26
+ driver: "rabbitmqEventsDriver"
27
+ }
28
+ };
29
+ /**
30
+ * The registry lives on `globalThis`, so one registration is seen by every
31
+ * copy of this module — the ESM and the CJS build of one install, which a
32
+ * process can load side by side, as `Credentials` already has to allow for.
33
+ */
34
+ const REGISTRY = Symbol.for("@geekmidas/events/drivers");
35
+ function drivers() {
36
+ const global = globalThis;
37
+ global[REGISTRY] ??= /* @__PURE__ */ new Map();
38
+ return global[REGISTRY];
39
+ }
40
+ /** Make a driver available to `Publisher`, `Subscriber` and friends. Idempotent. */
41
+ function registerEventsDriver(driver) {
42
+ drivers().set(driver.scheme, driver);
43
+ }
44
+ /** Which schemes are currently registered — the useful half of a failure. */
45
+ function registeredEventsSchemes() {
46
+ return [...drivers().keys()].sort();
47
+ }
48
+ /**
49
+ * The driver for a scheme — `'pgboss'`, `'pgboss:'`, or a whole connection
50
+ * string, whichever the caller has.
51
+ *
52
+ * @throws {UnregisteredEventsScheme} when the scheme is a broker this package
53
+ * implements but nothing registered its driver.
54
+ * @throws {UnsupportedEventTransport} when no broker here has that scheme.
55
+ */
56
+ function eventsDriverFor(scheme, role = "connection") {
57
+ const name = schemeOf(scheme);
58
+ const driver = drivers().get(name);
59
+ if (driver) return driver;
60
+ if (BUILT_IN[name]) throw new UnregisteredEventsScheme(name, registeredEventsSchemes());
61
+ throw new require_telemetry.UnsupportedEventTransport(name, role);
62
+ }
63
+ /** `pgboss` from `pgboss`, `pgboss:` or `pgboss://…`. */
64
+ function schemeOf(value) {
65
+ const separator = value.indexOf(":");
66
+ return separator === -1 ? value : value.slice(0, separator);
67
+ }
68
+ /**
69
+ * A connection string for a broker whose driver nothing registered.
70
+ *
71
+ * The broker exists — this is not a typo'd scheme — but the process was never
72
+ * told about it. Usually a script building its own publisher, or a build that
73
+ * registered the drivers for a different target than the one that composed
74
+ * the connection string.
75
+ */
76
+ var UnregisteredEventsScheme = class extends Error {
77
+ scheme;
78
+ registered;
79
+ /** The subpath that exports the missing driver. */
80
+ subpath;
81
+ /** The driver's export name. */
82
+ driver;
83
+ constructor(scheme, registered) {
84
+ const { subpath, driver } = BUILT_IN[scheme] ?? {
85
+ subpath: `@geekmidas/events/${scheme}`,
86
+ driver: `${scheme}EventsDriver`
87
+ };
88
+ super(`No events driver is registered for '${scheme}://'. ` + (registered.length ? `Registered: ${registered.join(", ")}. ` : "Nothing is registered. ") + `Register it once where the process starts: import { registerEventsDriver } from '@geekmidas/events'; import { ${driver} } from '${subpath}'; registerEventsDriver(${driver});`);
89
+ this.scheme = scheme;
90
+ this.registered = registered;
91
+ this.name = "UnregisteredEventsScheme";
92
+ this.subpath = subpath;
93
+ this.driver = driver;
94
+ }
95
+ };
96
+ //#endregion
97
+ Object.defineProperty(exports, "UnregisteredEventsScheme", {
98
+ enumerable: true,
99
+ get: function() {
100
+ return UnregisteredEventsScheme;
101
+ }
102
+ });
103
+ Object.defineProperty(exports, "eventsDriverFor", {
104
+ enumerable: true,
105
+ get: function() {
106
+ return eventsDriverFor;
107
+ }
108
+ });
109
+ Object.defineProperty(exports, "registerEventsDriver", {
110
+ enumerable: true,
111
+ get: function() {
112
+ return registerEventsDriver;
113
+ }
114
+ });
115
+ Object.defineProperty(exports, "registeredEventsSchemes", {
116
+ enumerable: true,
117
+ get: function() {
118
+ return registeredEventsSchemes;
119
+ }
120
+ });
121
+
122
+ //# sourceMappingURL=registry-DlT36229.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry-DlT36229.cjs","names":["UnsupportedEventTransport"],"sources":["../src/registry.ts"],"sourcesContent":["/**\n * Events drivers, keyed by connection-string scheme.\n *\n * The same shape `@geekmidas/storage` and `@geekmidas/cache` use, for the same\n * reason: a topic or a queue is handed one connection string, and the scheme in\n * it (`pgboss://`, `sns://`, …) picks the broker. Which brokers exist is the\n * entry point's decision — a generated server registering pg-boss, a Lambda\n * registering SNS and SQS — so a bundle only ever contains the broker its\n * target uses, and never resolves the others' optional peer dependencies.\n *\n * Registration is explicit rather than an import side effect, because a\n * side-effecting module is exactly what a bundler is entitled to drop.\n */\n\nimport type { PublisherOptions } from './Publisher';\nimport type {\n\tEventConnection,\n\tEventPublisher,\n\tEventSubscriber,\n\tPublishableMessage,\n} from './types';\nimport { EventPublisherType, UnsupportedEventTransport } from './types';\n\ntype AnyMessage = PublishableMessage<string, any>;\n\n/** How a subscriber built from a connection is used, beyond its address. */\nexport interface SubscriberOptions {\n\t/**\n\t * The topic subscribed to. pg-boss needs it, with {@link subscription}, to\n\t * give each subscriber a queue of its own; the other brokers carry the topic\n\t * in their address and ignore it.\n\t */\n\ttopic?: string;\n\t/** The subscriber's name — its own queue on pg-boss. */\n\tsubscription?: string;\n}\n\n/**\n * One broker: the connections, publishers and subscribers for its scheme.\n *\n * A driver owns parsing — the shape of an `sns://` string is SNS's business —\n * and is the only module that imports its broker's client library.\n */\nexport interface EventsDriver {\n\t/**\n\t * The scheme this driver handles, without the colon — `'pgboss'`, `'sns'`.\n\t * It is also the `type` of every connection the driver builds, which is how\n\t * a connection finds its way back here.\n\t */\n\treadonly scheme: `${EventPublisherType}`;\n\t/** A connection, connected, for a connection string. */\n\tconnect(connectionString: string): Promise<EventConnection>;\n\t/** A publisher, with a connection of its own, for a connection string. */\n\tpublisher<TMessage extends AnyMessage>(\n\t\tconnectionString: string,\n\t\toptions: PublisherOptions,\n\t): Promise<EventPublisher<TMessage>>;\n\t/** A publisher on a connection this driver built. */\n\tpublisherFor<TMessage extends AnyMessage>(\n\t\tconnection: EventConnection,\n\t\toptions: PublisherOptions,\n\t): EventPublisher<TMessage>;\n\t/** A subscriber, with a connection of its own, for a connection string. */\n\tsubscriber<TMessage extends AnyMessage>(\n\t\tconnectionString: string,\n\t): Promise<EventSubscriber<TMessage>>;\n\t/** A subscriber on a connection this driver built. */\n\tsubscriberFor<TMessage extends AnyMessage>(\n\t\tconnection: EventConnection,\n\t\toptions: SubscriberOptions,\n\t): EventSubscriber<TMessage>;\n}\n\n/**\n * Where each built-in driver lives, so a missing one can be named exactly —\n * the subpath to import and the export to register.\n */\nconst BUILT_IN: Readonly<Record<string, { subpath: string; driver: string }>> =\n\t{\n\t\t[EventPublisherType.Basic]: {\n\t\t\tsubpath: '@geekmidas/events/basic',\n\t\t\tdriver: 'basicEventsDriver',\n\t\t},\n\t\t[EventPublisherType.PgBoss]: {\n\t\t\tsubpath: '@geekmidas/events/pgboss',\n\t\t\tdriver: 'pgbossEventsDriver',\n\t\t},\n\t\t[EventPublisherType.SNS]: {\n\t\t\tsubpath: '@geekmidas/events/sns',\n\t\t\tdriver: 'snsEventsDriver',\n\t\t},\n\t\t[EventPublisherType.SQS]: {\n\t\t\tsubpath: '@geekmidas/events/sqs',\n\t\t\tdriver: 'sqsEventsDriver',\n\t\t},\n\t\t[EventPublisherType.RabbitMQ]: {\n\t\t\tsubpath: '@geekmidas/events/rabbitmq',\n\t\t\tdriver: 'rabbitmqEventsDriver',\n\t\t},\n\t};\n\n/**\n * The registry lives on `globalThis`, so one registration is seen by every\n * copy of this module — the ESM and the CJS build of one install, which a\n * process can load side by side, as `Credentials` already has to allow for.\n */\nconst REGISTRY = Symbol.for('@geekmidas/events/drivers');\n\nfunction drivers(): Map<string, EventsDriver> {\n\tconst global = globalThis as { [REGISTRY]?: Map<string, EventsDriver> };\n\tglobal[REGISTRY] ??= new Map();\n\treturn global[REGISTRY];\n}\n\n/** Make a driver available to `Publisher`, `Subscriber` and friends. Idempotent. */\nexport function registerEventsDriver(driver: EventsDriver): void {\n\tdrivers().set(driver.scheme, driver);\n}\n\n/** Which schemes are currently registered — the useful half of a failure. */\nexport function registeredEventsSchemes(): string[] {\n\treturn [...drivers().keys()].sort();\n}\n\n/**\n * The driver for a scheme — `'pgboss'`, `'pgboss:'`, or a whole connection\n * string, whichever the caller has.\n *\n * @throws {UnregisteredEventsScheme} when the scheme is a broker this package\n * implements but nothing registered its driver.\n * @throws {UnsupportedEventTransport} when no broker here has that scheme.\n */\nexport function eventsDriverFor(\n\tscheme: string,\n\trole: 'publisher' | 'subscriber' | 'connection' = 'connection',\n): EventsDriver {\n\tconst name = schemeOf(scheme);\n\tconst driver = drivers().get(name);\n\tif (driver) return driver;\n\n\tif (BUILT_IN[name]) {\n\t\tthrow new UnregisteredEventsScheme(name, registeredEventsSchemes());\n\t}\n\tthrow new UnsupportedEventTransport(name, role);\n}\n\n/** `pgboss` from `pgboss`, `pgboss:` or `pgboss://…`. */\nfunction schemeOf(value: string): string {\n\tconst separator = value.indexOf(':');\n\treturn separator === -1 ? value : value.slice(0, separator);\n}\n\n/**\n * A connection string for a broker whose driver nothing registered.\n *\n * The broker exists — this is not a typo'd scheme — but the process was never\n * told about it. Usually a script building its own publisher, or a build that\n * registered the drivers for a different target than the one that composed\n * the connection string.\n */\nexport class UnregisteredEventsScheme extends Error {\n\t/** The subpath that exports the missing driver. */\n\treadonly subpath: string;\n\t/** The driver's export name. */\n\treadonly driver: string;\n\n\tconstructor(\n\t\t/** The scheme with no driver, without the colon — `'pgboss'`. */\n\t\treadonly scheme: string,\n\t\t/** What is registered, so the caller can see what was chosen instead. */\n\t\treadonly registered: readonly string[],\n\t) {\n\t\tconst { subpath, driver } = BUILT_IN[scheme] ?? {\n\t\t\tsubpath: `@geekmidas/events/${scheme}`,\n\t\t\tdriver: `${scheme}EventsDriver`,\n\t\t};\n\t\tsuper(\n\t\t\t`No events driver is registered for '${scheme}://'. ` +\n\t\t\t\t(registered.length\n\t\t\t\t\t? `Registered: ${registered.join(', ')}. `\n\t\t\t\t\t: 'Nothing is registered. ') +\n\t\t\t\t`Register it once where the process starts: ` +\n\t\t\t\t`import { registerEventsDriver } from '@geekmidas/events'; ` +\n\t\t\t\t`import { ${driver} } from '${subpath}'; ` +\n\t\t\t\t`registerEventsDriver(${driver});`,\n\t\t);\n\t\tthis.name = 'UnregisteredEventsScheme';\n\t\tthis.subpath = subpath;\n\t\tthis.driver = driver;\n\t}\n}\n"],"mappings":";;;;;;AA6EA,MAAM,WACL;EAC6B,UAAA;EAC3B,SAAS;EACT,QAAQ;CACT;EAC6B,WAAA;EAC5B,SAAS;EACT,QAAQ;CACT;EAC0B,QAAA;EACzB,SAAS;EACT,QAAQ;CACT;EAC0B,QAAA;EACzB,SAAS;EACT,QAAQ;CACT;EAC+B,aAAA;EAC9B,SAAS;EACT,QAAQ;CACT;AACD;;;;;;AAOD,MAAM,WAAW,OAAO,IAAI,2BAA2B;AAEvD,SAAS,UAAqC;CAC7C,MAAM,SAAS;CACf,OAAO,8BAAc,IAAI,IAAI;CAC7B,OAAO,OAAO;AACf;;AAGA,SAAgB,qBAAqB,QAA4B;CAChE,QAAQ,CAAC,CAAC,IAAI,OAAO,QAAQ,MAAM;AACpC;;AAGA,SAAgB,0BAAoC;CACnD,OAAO,CAAC,GAAG,QAAQ,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK;AACnC;;;;;;;;;AAUA,SAAgB,gBACf,QACA,OAAkD,cACnC;CACf,MAAM,OAAO,SAAS,MAAM;CAC5B,MAAM,SAAS,QAAQ,CAAC,CAAC,IAAI,IAAI;CACjC,IAAI,QAAQ,OAAO;CAEnB,IAAI,SAAS,OACZ,MAAM,IAAI,yBAAyB,MAAM,wBAAwB,CAAC;CAEnE,MAAM,IAAIA,kBAAAA,0BAA0B,MAAM,IAAI;AAC/C;;AAGA,SAAS,SAAS,OAAuB;CACxC,MAAM,YAAY,MAAM,QAAQ,GAAG;CACnC,OAAO,cAAc,KAAK,QAAQ,MAAM,MAAM,GAAG,SAAS;AAC3D;;;;;;;;;AAUA,IAAa,2BAAb,cAA8C,MAAM;CAQzC;CAEA;;CARV;;CAEA;CAEA,YAEC,QAEA,YACC;EACD,MAAM,EAAE,SAAS,WAAW,SAAS,WAAW;GAC/C,SAAS,qBAAqB;GAC9B,QAAQ,GAAG,OAAO;EACnB;EACA,MACC,uCAAuC,OAAO,WAC5C,WAAW,SACT,eAAe,WAAW,KAAK,IAAI,EAAE,MACrC,6BACH,iHAEY,OAAO,WAAW,QAAQ,0BACd,OAAO,GACjC;EAjBS,KAAA,SAAA;EAEA,KAAA,aAAA;EAgBT,KAAK,OAAO;EACZ,KAAK,UAAU;EACf,KAAK,SAAS;CACf;AACD"}
@@ -1,10 +1,13 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- require("../types-BcZjLxVV.cjs");
3
- const require_SQSSubscriber = require("../SQSSubscriber-DtRUaZB3.cjs");
2
+ const require_rolldown_runtime = require("../rolldown-runtime-C0BPl7ul.cjs");
3
+ const require_telemetry = require("../telemetry-DG3l807O.cjs");
4
+ const require_SQSSubscriber = require("../SQSSubscriber-COTqWvOk.cjs");
4
5
  const require_sns_snsUrl = require("./snsUrl.cjs");
5
6
  let _aws_sdk_client_sqs = require("@aws-sdk/client-sqs");
6
7
  let _aws_sdk_client_sns = require("@aws-sdk/client-sns");
8
+ let node_crypto = require("node:crypto");
7
9
  //#region src/sns/SNSConnection.ts
10
+ var SNSConnection_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({ SNSConnection: () => SNSConnection });
8
11
  var SNSConnection = class SNSConnection {
9
12
  type = "sns";
10
13
  client;
@@ -77,26 +80,35 @@ var SNSPublisher = class SNSPublisher {
77
80
  * Format: sns://?topicArn=arn:aws:sns:region:account:topic&region=us-east-1&endpoint=http://localhost:4566
78
81
  */
79
82
  static async fromConnectionString(connectionString) {
80
- const { SNSConnection } = await Promise.resolve().then(() => require("../SNSConnection-BWDC1wAF.cjs"));
83
+ const { SNSConnection } = await Promise.resolve().then(() => SNSConnection_exports);
81
84
  const connection = await SNSConnection.fromConnectionString(connectionString);
82
85
  return new SNSPublisher(connection);
83
86
  }
84
87
  async publish(messages) {
85
88
  if (messages.length === 0) return;
86
89
  if (!this.connection.isConnected()) await this.connection.connect();
87
- await Promise.all(messages.map((message) => this.publishMessage(message)));
90
+ const topicArn = this.connection.topicArn;
91
+ const destination = topicArn.split(":").pop() ?? topicArn;
92
+ await require_telemetry.publishTraced(messages, (message) => ({
93
+ system: "aws_sns",
94
+ destination,
95
+ type: message.type
96
+ }), (carriers) => Promise.all(messages.map((message, i) => this.publishMessage(message, carriers[i]))));
88
97
  }
89
- async publishMessage(message) {
98
+ async publishMessage(message, carrier) {
90
99
  const command = new _aws_sdk_client_sns.PublishCommand({
91
100
  TopicArn: this.connection.topicArn,
92
101
  Message: JSON.stringify({
93
102
  type: message.type,
94
103
  payload: message.payload
95
104
  }),
96
- MessageAttributes: { type: {
97
- DataType: "String",
98
- StringValue: message.type
99
- } }
105
+ MessageAttributes: {
106
+ type: {
107
+ DataType: "String",
108
+ StringValue: message.type
109
+ },
110
+ ...require_telemetry.carrierAsAttributes(carrier)
111
+ }
100
112
  });
101
113
  await this.connection.snsClient.send(command);
102
114
  }
@@ -150,7 +162,7 @@ var SNSSubscriber = class SNSSubscriber {
150
162
  */
151
163
  static async fromConnectionString(connectionString) {
152
164
  const params = new URL(connectionString).searchParams;
153
- const { SNSConnection } = await Promise.resolve().then(() => require("../SNSConnection-BWDC1wAF.cjs"));
165
+ const { SNSConnection } = await Promise.resolve().then(() => SNSConnection_exports);
154
166
  const connection = await SNSConnection.fromConnectionString(connectionString);
155
167
  const options = {
156
168
  queueName: params.get("queueName") || void 0,
@@ -246,16 +258,418 @@ var SnsQueueMissing = class extends Error {
246
258
  }
247
259
  };
248
260
  //#endregion
261
+ //#region src/sns/driver.ts
262
+ /**
263
+ * `sns://` — an SNS topic, consumed through an SQS queue subscribed to it.
264
+ * Register it with `registerEventsDriver(snsEventsDriver)`; an AWS entry
265
+ * registers `sqsEventsDriver` beside it.
266
+ */
267
+ const snsEventsDriver = {
268
+ scheme: "sns",
269
+ connect: (url) => SNSConnection.fromConnectionString(url),
270
+ publisher: (url) => SNSPublisher.fromConnectionString(url),
271
+ publisherFor: (connection) => new SNSPublisher(connection),
272
+ subscriber: (url) => SNSSubscriber.fromConnectionString(url),
273
+ subscriberFor: (connection) => new SNSSubscriber(connection)
274
+ };
275
+ //#endregion
276
+ //#region src/sns/push.ts
277
+ /** The fields signed, in the order SNS signs them, per message type. */
278
+ const SIGNED_FIELDS = {
279
+ Notification: [
280
+ "Message",
281
+ "MessageId",
282
+ "Subject",
283
+ "Timestamp",
284
+ "TopicArn",
285
+ "Type"
286
+ ],
287
+ SubscriptionConfirmation: [
288
+ "Message",
289
+ "MessageId",
290
+ "SubscribeURL",
291
+ "Timestamp",
292
+ "Token",
293
+ "TopicArn",
294
+ "Type"
295
+ ],
296
+ UnsubscribeConfirmation: [
297
+ "Message",
298
+ "MessageId",
299
+ "SubscribeURL",
300
+ "Timestamp",
301
+ "Token",
302
+ "TopicArn",
303
+ "Type"
304
+ ]
305
+ };
306
+ /**
307
+ * Where SNS serves its signing certificates. Anywhere else is a certificate
308
+ * the sender chose, which would let the sender sign its own forgeries.
309
+ */
310
+ const SNS_CERTIFICATE_HOST = /^sns\.[a-z0-9-]+\.amazonaws\.com(\.cn)?$/;
311
+ const certificates = /* @__PURE__ */ new Map();
312
+ async function defaultFetchCertificate(url) {
313
+ const response = await fetch(url);
314
+ if (!response.ok) throw new SnsCertificateUnavailable(url, response.status);
315
+ return response.text();
316
+ }
317
+ /**
318
+ * A URL, or undefined for a value that is not one at all — what an emulator
319
+ * sends — so it is untrusted rather than a crash. (`URL.parse` is Node 22.1+.)
320
+ */
321
+ function parseUrl(value) {
322
+ try {
323
+ return new URL(String(value));
324
+ } catch {
325
+ return;
326
+ }
327
+ }
328
+ /** The string SNS signed for this message. */
329
+ function snsStringToSign(message) {
330
+ const fields = SIGNED_FIELDS[message.Type];
331
+ if (!fields) throw new SnsMessageTypeUnknown(String(message.Type));
332
+ return fields.filter((field) => message[field] !== void 0).map((field) => `${field}\n${message[field]}\n`).join("");
333
+ }
334
+ /**
335
+ * Check that SNS sent this message: the certificate is SNS's own, and the
336
+ * signature over the message's signed fields verifies against it.
337
+ *
338
+ * Throws rather than returning false, so a caller cannot forget to look.
339
+ */
340
+ async function verifySnsMessage(message, options = {}) {
341
+ const url = parseUrl(message.SigningCertURL);
342
+ if (url?.protocol !== "https:" || !SNS_CERTIFICATE_HOST.test(url.hostname)) throw new SnsCertificateUntrusted(message.SigningCertURL);
343
+ const algorithm = message.SignatureVersion === "1" ? "RSA-SHA1" : message.SignatureVersion === "2" ? "RSA-SHA256" : void 0;
344
+ if (!algorithm) throw new SnsSignatureVersionUnknown(message.SignatureVersion);
345
+ const fetchCertificate = options.fetchCertificate ?? defaultFetchCertificate;
346
+ let certificate = certificates.get(message.SigningCertURL);
347
+ if (!certificate || options.fetchCertificate) {
348
+ certificate = fetchCertificate(message.SigningCertURL);
349
+ if (!options.fetchCertificate) {
350
+ certificates.set(message.SigningCertURL, certificate);
351
+ certificate.catch(() => certificates.delete(message.SigningCertURL));
352
+ }
353
+ }
354
+ const verifier = (0, node_crypto.createVerify)(algorithm);
355
+ verifier.update(snsStringToSign(message), "utf8");
356
+ if (!verifier.verify(await certificate, message.Signature, "base64")) throw new SnsSignatureInvalid(message.MessageId, message.TopicArn);
357
+ }
358
+ /**
359
+ * Confirm a subscription by visiting the URL SNS sent. Until this happens SNS
360
+ * delivers nothing to the endpoint.
361
+ */
362
+ async function confirmSnsSubscription(message, request = fetch) {
363
+ if (message.Type !== "SubscriptionConfirmation" || !message.SubscribeURL) throw new SnsNotAConfirmation(message.Type);
364
+ const response = await request(message.SubscribeURL);
365
+ if (!response.ok) throw new SnsConfirmationFailed(message.TopicArn, response.status);
366
+ }
367
+ /** The subscription attributes a filter asks for, as SNS spells them. */
368
+ function subscriptionAttributes(filter) {
369
+ const attributes = filter.filterPolicy ? {
370
+ FilterPolicyScope: filter.filterPolicyScope ?? "MessageAttributes",
371
+ FilterPolicy: JSON.stringify(filter.filterPolicy)
372
+ } : filter.events ? {
373
+ FilterPolicyScope: "MessageAttributes",
374
+ FilterPolicy: JSON.stringify({ type: [...filter.events] })
375
+ } : {};
376
+ if (filter.deadLetterQueueArn) attributes.RedrivePolicy = JSON.stringify({ deadLetterTargetArn: filter.deadLetterQueueArn });
377
+ return attributes;
378
+ }
379
+ /** The protocol SNS delivers to an endpoint with, from its URL. */
380
+ function protocolOf(endpoint) {
381
+ const protocol = parseUrl(endpoint)?.protocol.replace(":", "");
382
+ if (protocol !== "http" && protocol !== "https") throw new SnsEndpointNotHttp(endpoint);
383
+ return protocol;
384
+ }
385
+ /** Bring an existing subscription's attributes up to what is asked for. */
386
+ async function updateAttributes(connection, subscriptionArn, current, wanted) {
387
+ for (const [name, value] of Object.entries(wanted)) {
388
+ if (current[name] === value) continue;
389
+ await connection.snsClient.send(new _aws_sdk_client_sns.SetSubscriptionAttributesCommand({
390
+ SubscriptionArn: subscriptionArn,
391
+ AttributeName: name,
392
+ AttributeValue: value
393
+ }));
394
+ }
395
+ }
396
+ /**
397
+ * Subscribe an HTTP endpoint to the connection's topic, converging on one
398
+ * confirmed subscription with the filter asked for — so it is safe on every
399
+ * start. What a server does against an emulator, where nothing deploys it;
400
+ * against SNS itself the deploy owns the subscription
401
+ * ({@link reconcileHttpSubscriptions}).
402
+ *
403
+ * - **none yet** — subscribed; SNS sends a confirmation to the endpoint.
404
+ * - **confirmed** — its filter and dead-letter queue are brought up to date.
405
+ * Subscribing again with different attributes is an error on SNS, and the
406
+ * events a subscriber names change.
407
+ * - **stuck pending** — a confirmation that never landed (the endpoint was
408
+ * down, or answered wrong). Subscribing the same endpoint again is a no-op
409
+ * on an emulator, so it is dropped and subscribed afresh, which sends a new
410
+ * confirmation.
411
+ */
412
+ async function subscribeHttpEndpoint(connection, options) {
413
+ const protocol = protocolOf(options.endpoint);
414
+ const attributes = subscriptionAttributes(options);
415
+ const client = connection.snsClient;
416
+ const existing = (await topicSubscriptions(connection)).find((s) => s.endpoint === options.endpoint)?.arn;
417
+ if (existing) {
418
+ const { Attributes = {} } = await client.send(new _aws_sdk_client_sns.GetSubscriptionAttributesCommand({ SubscriptionArn: existing }));
419
+ if (Attributes.PendingConfirmation === "true") await client.send(new _aws_sdk_client_sns.UnsubscribeCommand({ SubscriptionArn: existing }));
420
+ else {
421
+ await updateAttributes(connection, existing, Attributes, attributes);
422
+ return existing;
423
+ }
424
+ }
425
+ const { SubscriptionArn } = await client.send(new _aws_sdk_client_sns.SubscribeCommand({
426
+ TopicArn: connection.topicArn,
427
+ Protocol: protocol,
428
+ Endpoint: options.endpoint,
429
+ Attributes: attributes,
430
+ ReturnSubscriptionArn: true
431
+ }));
432
+ return SubscriptionArn;
433
+ }
434
+ /**
435
+ * Converge a topic's HTTP subscriptions on the endpoints a deploy wants, and
436
+ * answer each one's ARN for the deploy to record and hand to the server.
437
+ *
438
+ * The deploy's half of push delivery against SNS itself: the server never
439
+ * subscribes, so its credentials need no `sns:Subscribe` — and the only
440
+ * subscriptions to the topic are ones the deploy made.
441
+ *
442
+ * Run it twice: once before the server starts, for the ARNs it is configured
443
+ * with — SNS answers one even while the subscription waits to be confirmed —
444
+ * and once the server is up, which subscribes each still-pending endpoint
445
+ * again so SNS resends its confirmation to a server now there to answer it.
446
+ * The ARN does not change between the two.
447
+ *
448
+ * - **absent** — subscribed with its filter.
449
+ * - **present** — its filter and dead-letter queue are brought up to date;
450
+ * pending, it is subscribed again to resend the confirmation.
451
+ * - **stale** — on {@link ReconcileHttpSubscriptionsOptions.ownedHost} and no
452
+ * longer wanted: unsubscribed. (A stale one SNS still lists as pending has
453
+ * no ARN to act on; SNS drops it unconfirmed after three days.)
454
+ */
455
+ async function reconcileHttpSubscriptions(connection, options) {
456
+ const client = connection.snsClient;
457
+ const listed = await topicSubscriptions(connection);
458
+ const result = {
459
+ subscriptions: {},
460
+ pending: [],
461
+ removed: []
462
+ };
463
+ for (const spec of options.endpoints) {
464
+ const protocol = protocolOf(spec.endpoint);
465
+ const attributes = subscriptionAttributes(spec);
466
+ const subscribe = async () => (await client.send(new _aws_sdk_client_sns.SubscribeCommand({
467
+ TopicArn: connection.topicArn,
468
+ Protocol: protocol,
469
+ Endpoint: spec.endpoint,
470
+ Attributes: attributes,
471
+ ReturnSubscriptionArn: true
472
+ }))).SubscriptionArn;
473
+ const existing = listed.find((s) => s.endpoint === spec.endpoint)?.arn;
474
+ let arn;
475
+ let pending;
476
+ if (existing) {
477
+ const { Attributes = {} } = await client.send(new _aws_sdk_client_sns.GetSubscriptionAttributesCommand({ SubscriptionArn: existing }));
478
+ await updateAttributes(connection, existing, Attributes, attributes);
479
+ pending = Attributes.PendingConfirmation === "true";
480
+ arn = pending ? await subscribe() ?? existing : existing;
481
+ } else {
482
+ arn = await subscribe();
483
+ pending = true;
484
+ }
485
+ if (!arn) throw new SnsSubscriptionArnMissing(connection.topicArn, spec.endpoint);
486
+ result.subscriptions[spec.name] = arn;
487
+ if (pending) result.pending.push(spec.name);
488
+ }
489
+ const wanted = new Set(options.endpoints.map((spec) => spec.endpoint));
490
+ for (const { arn, endpoint } of listed) {
491
+ if (!arn || wanted.has(endpoint)) continue;
492
+ if (parseUrl(endpoint)?.host !== options.ownedHost) continue;
493
+ await client.send(new _aws_sdk_client_sns.UnsubscribeCommand({ SubscriptionArn: arn }));
494
+ result.removed.push(arn);
495
+ }
496
+ return result;
497
+ }
498
+ /**
499
+ * Confirm a subscription through the API, as its topic's owner, rather than by
500
+ * visiting the URL SNS sent.
501
+ *
502
+ * `AuthenticateOnUnsubscribe` is the point of it. A subscription confirmed by
503
+ * visiting `SubscribeURL` can be removed by anyone holding the
504
+ * `UnsubscribeURL` every notification carries — one unauthenticated GET, and
505
+ * the endpoint is silently cut off. Confirmed this way, only the topic's owner
506
+ * can unsubscribe it. All it takes of the caller's credentials is
507
+ * `sns:ConfirmSubscription` on this one topic.
508
+ */
509
+ async function confirmSubscription(connection, message) {
510
+ if (message.Type !== "SubscriptionConfirmation" || !message.Token) throw new SnsNotAConfirmation(message.Type);
511
+ const { SubscriptionArn } = await connection.snsClient.send(new _aws_sdk_client_sns.ConfirmSubscriptionCommand({
512
+ TopicArn: message.TopicArn,
513
+ Token: message.Token,
514
+ AuthenticateOnUnsubscribe: "true"
515
+ }));
516
+ return SubscriptionArn;
517
+ }
518
+ /**
519
+ * Every subscription on the connection's topic, with the ARN SNS names for it
520
+ * — none for one real SNS lists as `PendingConfirmation`, which there is no
521
+ * ARN to act on (and which a new Subscribe resends the confirmation of anyway).
522
+ */
523
+ async function topicSubscriptions(connection) {
524
+ const found = [];
525
+ let NextToken;
526
+ do {
527
+ const page = await connection.snsClient.send(new _aws_sdk_client_sns.ListSubscriptionsByTopicCommand({
528
+ TopicArn: connection.topicArn,
529
+ NextToken
530
+ }));
531
+ for (const s of page.Subscriptions ?? []) {
532
+ if (!s.Endpoint) continue;
533
+ found.push({
534
+ endpoint: s.Endpoint,
535
+ ...s.SubscriptionArn?.startsWith("arn:") ? { arn: s.SubscriptionArn } : {}
536
+ });
537
+ }
538
+ NextToken = page.NextToken;
539
+ } while (NextToken);
540
+ return found;
541
+ }
542
+ /**
543
+ * A pushed notification as the Lambda event SNS would have invoked a function
544
+ * with, so it can be handed to the same adaptor.
545
+ */
546
+ function toSnsEvent(message, subscriptionArn = "") {
547
+ return { Records: [{
548
+ EventSource: "aws:sns",
549
+ EventVersion: "1.0",
550
+ EventSubscriptionArn: subscriptionArn,
551
+ Sns: {
552
+ Type: message.Type,
553
+ MessageId: message.MessageId,
554
+ TopicArn: message.TopicArn,
555
+ Subject: message.Subject ?? null,
556
+ Message: message.Message,
557
+ Timestamp: message.Timestamp,
558
+ SignatureVersion: message.SignatureVersion,
559
+ Signature: message.Signature,
560
+ SigningCertUrl: message.SigningCertURL,
561
+ UnsubscribeUrl: message.UnsubscribeURL ?? "",
562
+ MessageAttributes: message.MessageAttributes ?? {}
563
+ }
564
+ }] };
565
+ }
566
+ var SnsCertificateUntrusted = class extends Error {
567
+ url;
568
+ constructor(url) {
569
+ super(`The SNS message names a signing certificate at '${url}', which is not an https URL on sns.<region>.amazonaws.com. Only SNS can send to this endpoint; reject the request.`);
570
+ this.url = url;
571
+ this.name = "SnsCertificateUntrusted";
572
+ }
573
+ };
574
+ var SnsCertificateUnavailable = class extends Error {
575
+ url;
576
+ status;
577
+ constructor(url, status) {
578
+ super(`Fetching the SNS signing certificate at '${url}' answered ${status}. The message cannot be verified, so it is not handled; SNS will retry.`);
579
+ this.url = url;
580
+ this.status = status;
581
+ this.name = "SnsCertificateUnavailable";
582
+ }
583
+ };
584
+ var SnsSignatureVersionUnknown = class extends Error {
585
+ version;
586
+ constructor(version) {
587
+ super(`SNS signature version '${version}' is not one this endpoint verifies (it knows '1' and '2'). Reject the request.`);
588
+ this.version = version;
589
+ this.name = "SnsSignatureVersionUnknown";
590
+ }
591
+ };
592
+ var SnsSignatureInvalid = class extends Error {
593
+ messageId;
594
+ topicArn;
595
+ constructor(messageId, topicArn) {
596
+ super(`SNS message '${messageId}' from '${topicArn}' does not verify against its signing certificate. It was not sent by SNS, or was altered on the way; reject it.`);
597
+ this.messageId = messageId;
598
+ this.topicArn = topicArn;
599
+ this.name = "SnsSignatureInvalid";
600
+ }
601
+ };
602
+ var SnsMessageTypeUnknown = class extends Error {
603
+ type;
604
+ constructor(type) {
605
+ super(`'${type}' is not an SNS message type (Notification, SubscriptionConfirmation, UnsubscribeConfirmation). Reject it.`);
606
+ this.type = type;
607
+ this.name = "SnsMessageTypeUnknown";
608
+ }
609
+ };
610
+ var SnsNotAConfirmation = class extends Error {
611
+ type;
612
+ constructor(type) {
613
+ super(`Only a SubscriptionConfirmation carries a URL to confirm; this is a '${type}'.`);
614
+ this.type = type;
615
+ this.name = "SnsNotAConfirmation";
616
+ }
617
+ };
618
+ var SnsConfirmationFailed = class extends Error {
619
+ topicArn;
620
+ status;
621
+ constructor(topicArn, status) {
622
+ super(`Confirming the subscription to '${topicArn}' answered ${status}. SNS will deliver nothing until it is confirmed; it resends the confirmation, or subscribe the endpoint again.`);
623
+ this.topicArn = topicArn;
624
+ this.status = status;
625
+ this.name = "SnsConfirmationFailed";
626
+ }
627
+ };
628
+ var SnsEndpointNotHttp = class extends Error {
629
+ endpoint;
630
+ constructor(endpoint) {
631
+ super(`'${endpoint}' is not an http(s) URL. SNS pushes to an HTTP endpoint; subscribe a queue for anything else.`);
632
+ this.endpoint = endpoint;
633
+ this.name = "SnsEndpointNotHttp";
634
+ }
635
+ };
636
+ var SnsSubscriptionArnMissing = class extends Error {
637
+ topicArn;
638
+ endpoint;
639
+ constructor(topicArn, endpoint) {
640
+ super(`Subscribing '${endpoint}' to '${topicArn}' answered no subscription ARN, so there is nothing to record for the server to accept. Check the topic exists and the deploy may subscribe to it.`);
641
+ this.topicArn = topicArn;
642
+ this.endpoint = endpoint;
643
+ this.name = "SnsSubscriptionArnMissing";
644
+ }
645
+ };
646
+ //#endregion
249
647
  exports.SNSConnection = SNSConnection;
250
- exports.SNSConnection$1 = SNSConnection;
251
648
  exports.SNSPublisher = SNSPublisher;
252
649
  exports.SNSSubscriber = SNSSubscriber;
650
+ exports.SnsCertificateUnavailable = SnsCertificateUnavailable;
651
+ exports.SnsCertificateUntrusted = SnsCertificateUntrusted;
652
+ exports.SnsConfirmationFailed = SnsConfirmationFailed;
653
+ exports.SnsEndpointNotHttp = SnsEndpointNotHttp;
654
+ exports.SnsMessageTypeUnknown = SnsMessageTypeUnknown;
655
+ exports.SnsNotAConfirmation = SnsNotAConfirmation;
253
656
  exports.SnsQueueMissing = SnsQueueMissing;
657
+ exports.SnsSignatureInvalid = SnsSignatureInvalid;
658
+ exports.SnsSignatureVersionUnknown = SnsSignatureVersionUnknown;
659
+ exports.SnsSubscriptionArnMissing = SnsSubscriptionArnMissing;
660
+ exports.confirmSnsSubscription = confirmSnsSubscription;
661
+ exports.confirmSubscription = confirmSubscription;
662
+ exports.reconcileHttpSubscriptions = reconcileHttpSubscriptions;
663
+ exports.snsEventsDriver = snsEventsDriver;
664
+ exports.snsStringToSign = snsStringToSign;
254
665
  Object.defineProperty(exports, "snsUrl", {
255
666
  enumerable: true,
256
667
  get: function() {
257
668
  return require_sns_snsUrl.snsUrl_exports;
258
669
  }
259
670
  });
671
+ exports.subscribeHttpEndpoint = subscribeHttpEndpoint;
672
+ exports.toSnsEvent = toSnsEvent;
673
+ exports.verifySnsMessage = verifySnsMessage;
260
674
 
261
675
  //# sourceMappingURL=index.cjs.map