@gathertown/webhook-object-sdk 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE-APACHE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Gather Presence, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,92 @@
1
+ # @gathertown/webhook-object-sdk
2
+
3
+ Typed client for emitting events to Gather webhook objects (Smart Objects). Handles the
4
+ fiddly parts of the wire protocol (Standard Webhooks v1 signing, retries, rate limits, and
5
+ error decoding) behind a fully type-safe `send`.
6
+
7
+ Event types and payload shapes come from
8
+ [`@gathertown/webhook-object-types`](https://www.npmjs.com/package/@gathertown/webhook-object-types),
9
+ generated from the same definitions the Gather server enforces. When new capabilities ship,
10
+ this SDK picks them up via a types-package bump, no SDK release needed.
11
+
12
+ ## Usage
13
+
14
+ Each Smart Object is one `(url, secret)` pair, copied from the object's ⋮ menu in Gather.
15
+ Secrets are per-object: a key for one object never authenticates another.
16
+
17
+ ```ts
18
+ import { createWebhookObjectClient, secretFromEnv } from "@gathertown/webhook-object-sdk"
19
+
20
+ const counter = createWebhookObjectClient({
21
+ url: process.env.GATHER_COUNTER_URL!,
22
+ secret: secretFromEnv("GATHER_COUNTER_SECRET"), // whsec_…, read from the environment
23
+ })
24
+
25
+ await counter.send("counter.increment", { by: 2 }) // data type inferred from the event type
26
+ await counter.send("counter.reset") // empty-payload events take no data argument
27
+ await counter.ping() // verify url + secret; returns the object's declared capabilities
28
+ ```
29
+
30
+ `secret` accepts the raw `whsec_…` string, so it plugs straight into whatever secret
31
+ management you already have. The opaque handles are the recommended hardening on top:
32
+ `secretFromEnv(name)` reads the variable itself, and a handle redacts itself if it ever
33
+ reaches a log or `JSON.stringify`, a bare string can't. For values from elsewhere (a
34
+ secret manager, a non-Node runtime), `unsafeSecretLiteral(value)` wraps them; the name
35
+ makes hardcoded secrets easy to catch in review.
36
+
37
+ Every event is also available as capability-namespaced sugar with the same typing; snake_case
38
+ wire names become camelCase methods:
39
+
40
+ ```ts
41
+ await counter.counter.increment({ by: 2 })
42
+ await counter.counter.reset()
43
+ await lamp.switch.setState({ on: true }) // → switch.set_state
44
+ ```
45
+
46
+ The fluent surface is derived from the generated event union and backed by a `Proxy`, so new
47
+ capabilities appear via a types-package bump with zero SDK changes.
48
+
49
+ ### Object catalog
50
+
51
+ To keep several objects at hand (inboxes, lamps, counters, …), build a named catalog. An
52
+ entry's optional `preset` narrows its `send` at compile time to the events that preset
53
+ declares, so wiring the lamp's events to the inbox is a type error, not a runtime 404.
54
+
55
+ ```ts
56
+ import { createWebhookObjectCatalog } from "@gathertown/webhook-object-sdk"
57
+
58
+ const office = createWebhookObjectCatalog({
59
+ supportInbox: { url: INBOX_URL, secret: secretFromEnv("GATHER_INBOX_SECRET"), preset: "inbox" },
60
+ buildLamp: { url: LAMP_URL, secret: secretFromEnv("GATHER_LAMP_SECRET"), preset: "switch" },
61
+ })
62
+
63
+ await office.supportInbox.send("activity.add", { id: "pr-142", text: "PR #142 merged" })
64
+ await office.buildLamp.send("switch.toggle")
65
+ ```
66
+
67
+ ## Wire behavior
68
+
69
+ - Signs with the `standardwebhooks` reference library: HMAC-SHA256 over
70
+ `${webhook-id}.${webhook-timestamp}.${body}`, sent as the `webhook-id` /
71
+ `webhook-timestamp` / `webhook-signature` headers. The exact serialized body is signed and
72
+ sent unchanged.
73
+ - One `webhook-id` (UUID) per event, reused across retries; the server dedups the last 10
74
+ ids per object, so retries are idempotent. Each retry is re-signed with a fresh timestamp.
75
+ - Retries transient failures only (429, 5xx, network errors), honoring `RateLimit-Reset` /
76
+ `Retry-After`, with exponential backoff + jitter otherwise. 4xx failures never retry.
77
+ - Cancelable via a `signal` (`AbortSignal`) in config: aborting cancels the in-flight request
78
+ and any pending backoff, rejecting with an `aborted` error.
79
+ - Rejects payloads over the server's 4 KB body cap client-side, with a clear error instead of
80
+ the receiver's uniform `404`.
81
+ - Refuses non-`https` URLs at construction (signing authenticates but does not encrypt), with
82
+ an `http` carve-out for `localhost` so local development keeps working.
83
+ - Never exposes the secret: error messages never contain it, and the opaque-handle form
84
+ additionally redacts itself when logged or serialized.
85
+ - Failures throw `WebhookObjectError` with a `code` mirroring the server's error bodies
86
+ (`not_found`, `capability_not_declared`, `token_revoked`, …) plus client-side codes
87
+ (`payload_too_large`, `invalid_secret`, `invalid_url`, `network_error`, `aborted`,
88
+ `unexpected_response`).
89
+
90
+ Uses global `fetch` and `crypto.randomUUID` by default (Node 19+, modern browsers, Deno,
91
+ workers). Both are overridable via config. Inject `fetch` and/or `newWebhookId` for other
92
+ runtimes, proxies, or deterministic tests.
@@ -0,0 +1,39 @@
1
+ import type { WebhookObjectPreset } from "@gathertown/webhook-object-types";
2
+ import { WebhookObjectClient, WebhookObjectClientConfig } from "./client";
3
+ /** Runtime options that apply to every client in the catalog rather than a single object. */
4
+ type SharedClientOption = "maxAttempts" | "fetch" | "newWebhookId";
5
+ /** Per-object entry: the (url, secret) pair plus optional compile-time preset scoping. */
6
+ export type WebhookObjectCatalogEntry = Omit<WebhookObjectClientConfig, SharedClientOption>;
7
+ /** Options shared by every client in the catalog. */
8
+ export type WebhookObjectCatalogOptions = Pick<WebhookObjectClientConfig, SharedClientOption>;
9
+ /** The preset literal declared on an entry, or `undefined` when the entry has none. */
10
+ type PresetOf<Entry extends WebhookObjectCatalogEntry> = Entry extends {
11
+ preset: infer Preset extends WebhookObjectPreset;
12
+ } ? Preset : undefined;
13
+ /**
14
+ * The value returned by `createWebhookObjectCatalog`: each entry name maps to a client whose
15
+ * `send` is narrowed to that entry's declared preset (or unconstrained when it has none).
16
+ */
17
+ export type WebhookObjectCatalog<Entries extends Record<string, WebhookObjectCatalogEntry>> = {
18
+ [Name in keyof Entries]: WebhookObjectClient<PresetOf<Entries[Name]>>;
19
+ };
20
+ /**
21
+ * Build a named catalog of webhook-object clients so multiple Smart Objects (inboxes,
22
+ * lamps, counters, …) stay at hand behind one value. Each entry is just its (url, secret)
23
+ * pair, each secret authenticates only its own object.
24
+ *
25
+ * Entries with a `preset` get a compile-time-narrowed `send`: an `inbox` client only
26
+ * accepts inbox event types, so wiring the lamp's events to the inbox is a type error.
27
+ *
28
+ * ```ts
29
+ * const office = createWebhookObjectCatalog({
30
+ * supportInbox: { url: INBOX_URL, secret: secretFromEnv("GATHER_INBOX_SECRET"), preset: "inbox" },
31
+ * buildLamp: { url: LAMP_URL, secret: secretFromEnv("GATHER_LAMP_SECRET"), preset: "switch" },
32
+ * })
33
+ * await office.supportInbox.send("activity.add", { id: "pr-142", text: "PR #142 merged" })
34
+ * await office.buildLamp.send("switch.toggle")
35
+ * ```
36
+ */
37
+ export declare const createWebhookObjectCatalog: <const Entries extends Record<string, WebhookObjectCatalogEntry>>(entries: Entries, options?: WebhookObjectCatalogOptions) => WebhookObjectCatalog<Entries>;
38
+ export {};
39
+ //# sourceMappingURL=catalog.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"catalog.d.ts","sourceRoot":"","sources":["../../src/catalog.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAA;AAC3E,OAAO,EAA6B,mBAAmB,EAAE,yBAAyB,EAAE,MAAM,UAAU,CAAA;AAEpG,6FAA6F;AAC7F,KAAK,kBAAkB,GAAG,aAAa,GAAG,OAAO,GAAG,cAAc,CAAA;AAElE,0FAA0F;AAC1F,MAAM,MAAM,yBAAyB,GAAG,IAAI,CAAC,yBAAyB,EAAE,kBAAkB,CAAC,CAAA;AAE3F,qDAAqD;AACrD,MAAM,MAAM,2BAA2B,GAAG,IAAI,CAAC,yBAAyB,EAAE,kBAAkB,CAAC,CAAA;AAE7F,uFAAuF;AACvF,KAAK,QAAQ,CAAC,KAAK,SAAS,yBAAyB,IAAI,KAAK,SAAS;IACrE,MAAM,EAAE,MAAM,MAAM,SAAS,mBAAmB,CAAA;CACjD,GACG,MAAM,GACN,SAAS,CAAA;AAEb;;;GAGG;AACH,MAAM,MAAM,oBAAoB,CAAC,OAAO,SAAS,MAAM,CAAC,MAAM,EAAE,yBAAyB,CAAC,IAAI;KAC3F,IAAI,IAAI,MAAM,OAAO,GAAG,mBAAmB,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;CACtE,CAAA;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,0BAA0B,GACrC,KAAK,CAAC,OAAO,SAAS,MAAM,CAAC,MAAM,EAAE,yBAAyB,CAAC,EAE/D,SAAS,OAAO,EAChB,UAAS,2BAAgC,KACxC,oBAAoB,CAAC,OAAO,CASgB,CAAA"}
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createWebhookObjectCatalog = void 0;
4
+ const client_1 = require("./client");
5
+ /**
6
+ * Build a named catalog of webhook-object clients so multiple Smart Objects (inboxes,
7
+ * lamps, counters, …) stay at hand behind one value. Each entry is just its (url, secret)
8
+ * pair, each secret authenticates only its own object.
9
+ *
10
+ * Entries with a `preset` get a compile-time-narrowed `send`: an `inbox` client only
11
+ * accepts inbox event types, so wiring the lamp's events to the inbox is a type error.
12
+ *
13
+ * ```ts
14
+ * const office = createWebhookObjectCatalog({
15
+ * supportInbox: { url: INBOX_URL, secret: secretFromEnv("GATHER_INBOX_SECRET"), preset: "inbox" },
16
+ * buildLamp: { url: LAMP_URL, secret: secretFromEnv("GATHER_LAMP_SECRET"), preset: "switch" },
17
+ * })
18
+ * await office.supportInbox.send("activity.add", { id: "pr-142", text: "PR #142 merged" })
19
+ * await office.buildLamp.send("switch.toggle")
20
+ * ```
21
+ */
22
+ const createWebhookObjectCatalog = (entries, options = {}) =>
23
+ // fromEntries can't see the per-entry preset literals, so it needs the double assertion to
24
+ // reach the mapped catalog type; per-name correctness is covered by compile-time tests.
25
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
26
+ Object.fromEntries(Object.entries(entries).map(([name, entry]) => [
27
+ name,
28
+ (0, client_1.createWebhookObjectClient)({ ...entry, ...options }),
29
+ ]));
30
+ exports.createWebhookObjectCatalog = createWebhookObjectCatalog;
31
+ //# sourceMappingURL=catalog.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"catalog.js","sourceRoot":"","sources":["../../src/catalog.ts"],"names":[],"mappings":";;;AACA,qCAAoG;AA0BpG;;;;;;;;;;;;;;;;GAgBG;AACI,MAAM,0BAA0B,GAAG,CAGxC,OAAgB,EAChB,UAAuC,EAAE,EACV,EAAE;AACjC,2FAA2F;AAC3F,wFAAwF;AACxF,yEAAyE;AACzE,MAAM,CAAC,WAAW,CAChB,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC;IAC7C,IAAI;IACJ,IAAA,kCAAyB,EAAC,EAAE,GAAG,KAAK,EAAE,GAAG,OAAO,EAAE,CAAC;CACpD,CAAC,CACyC,CAAA;AAdlC,QAAA,0BAA0B,8BAcQ"}
@@ -0,0 +1,91 @@
1
+ import type { DataFor, EventTypeForPreset, ReservedEventType, WebhookEventType, WebhookObjectPreset } from "@gathertown/webhook-object-types";
2
+ import { WebhookObjectSecret } from "./secret";
3
+ export type WebhookObjectClientConfig = {
4
+ /** The object's full webhook URL (copied from the object's ⋮ menu in Gather). */
5
+ url: string;
6
+ /**
7
+ * The object's signing secret (per-object; never shared between objects). Either the raw
8
+ * `whsec_…` string, or (recommended) an opaque handle from `secretFromEnv()` /
9
+ * `unsafeSecretLiteral()`, which redacts itself if the config is ever logged or serialized.
10
+ */
11
+ secret: WebhookObjectSecret | string;
12
+ /**
13
+ * Compile-time narrowing only: when set, `send` accepts only event types this preset
14
+ * declares (plus reserved `webhook.*`). The server enforces the same thing at runtime.
15
+ */
16
+ preset?: WebhookObjectPreset;
17
+ /** Total delivery attempts per event (initial + retries on 429/5xx/network). Default 3. */
18
+ maxAttempts?: number;
19
+ /** Custom fetch implementation (tests, proxies). Defaults to the global fetch (Node 18+). */
20
+ fetch?: typeof fetch;
21
+ /**
22
+ * Override the per-event `webhook-id` generator. Defaults to the global `crypto.randomUUID`;
23
+ * inject your own for runtimes without global `crypto`, or for deterministic tests. Must return
24
+ * a unique value per event (the server dedups by id, so reused ids would drop distinct events).
25
+ */
26
+ newWebhookId?: () => string;
27
+ /**
28
+ * Cancels an in-flight `send`/`ping`, including any pending retry backoff, when aborted.
29
+ * The call rejects with a `WebhookObjectError` whose `code` is `aborted`.
30
+ */
31
+ signal?: AbortSignal;
32
+ };
33
+ /**
34
+ * Event types a client scoped to preset `P` may send. Intersected with `WebhookEventType`
35
+ * so `DataFor<T>` stays applicable while `P` is still generic.
36
+ */
37
+ export type AllowedEventType<P extends WebhookObjectPreset | undefined> = (P extends WebhookObjectPreset ? EventTypeForPreset<P> : WebhookEventType) & WebhookEventType;
38
+ /** Empty-payload events take no `data` argument; everything else requires one. */
39
+ type DataArgs<T extends WebhookEventType> = DataFor<T> extends Record<string, never> ? [] : [data: DataFor<T>];
40
+ /** Both statuses mean "accepted": `space_idle` means the space wasn't live, and the event was persisted for it. */
41
+ export type SendResult = {
42
+ status: "dispatched" | "space_idle";
43
+ };
44
+ /** The `webhook.ping` snapshot: what this object is and what it currently accepts. */
45
+ export type PingResult = {
46
+ status: "pong";
47
+ objectId: string;
48
+ spaceId: string;
49
+ preset: WebhookObjectPreset | null;
50
+ capabilities: Record<string, unknown>;
51
+ };
52
+ /** `set_state` → `setState`: fluent method names are idiomatic camelCase versions of wire names. */
53
+ type SnakeToCamel<S extends string> = S extends `${infer Head}_${infer Tail}` ? `${Head}${Capitalize<SnakeToCamel<Tail>>}` : S;
54
+ /** The capability segment of an event type: `"counter.reset"` → `"counter"`. */
55
+ type CapabilityNameOf<E extends string> = E extends `${infer Capability}.${string}` ? Capability : never;
56
+ /**
57
+ * Capability-namespaced sugar over `send`: `client.counter.reset()`,
58
+ * `client.switch.setState({ on: true })`. Derived entirely from the generated event union, so
59
+ * new capabilities appear via a types-package bump; reserved `webhook.*` events are excluded
60
+ * (`ping()` is first-class). Backed by a `Proxy` at runtime: no codegen, no runtime catalog.
61
+ */
62
+ export type CapabilityNamespaces<Events extends WebhookEventType> = {
63
+ [Capability in CapabilityNameOf<Exclude<Events, ReservedEventType>>]: {
64
+ [Event in Extract<Events, `${Capability}.${string}`> as Event extends `${Capability}.${infer Method}` ? SnakeToCamel<Method> : never]: (...args: DataArgs<Event>) => Promise<SendResult>;
65
+ };
66
+ };
67
+ /**
68
+ * A client bound to one webhook object. Exposes `send`/`ping` plus the capability-namespaced
69
+ * fluent sugar (`client.counter.increment(...)`). The optional preset `P` narrows every surface
70
+ * to the event types that preset declares.
71
+ */
72
+ export type WebhookObjectClient<P extends WebhookObjectPreset | undefined = undefined> = {
73
+ /**
74
+ * Sign and POST one event. `data` is inferred from the event type and omitted entirely
75
+ * for empty-payload events (e.g. `send("counter.reset")`).
76
+ */
77
+ send<T extends AllowedEventType<P>>(type: T, ...args: DataArgs<T>): Promise<SendResult>;
78
+ /** Verify the URL + secret and fetch the object's declared capability state. */
79
+ ping(): Promise<PingResult>;
80
+ } & CapabilityNamespaces<AllowedEventType<P>>;
81
+ /**
82
+ * Create a client for one webhook object. Signing follows Standard Webhooks v1: HMAC over
83
+ * `${id}.${timestamp}.${body}` via the `standardwebhooks` reference library, sent as the
84
+ * `webhook-id` / `webhook-timestamp` / `webhook-signature` headers. The exact serialized
85
+ * body is signed and sent unchanged, so the two can never drift.
86
+ */
87
+ export declare const createWebhookObjectClient: <P extends WebhookObjectPreset | undefined = undefined>(config: WebhookObjectClientConfig & {
88
+ preset?: P;
89
+ }) => WebhookObjectClient<P>;
90
+ export {};
91
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/client.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,OAAO,EACP,kBAAkB,EAClB,iBAAiB,EACjB,gBAAgB,EAChB,mBAAmB,EACpB,MAAM,kCAAkC,CAAA;AAGzC,OAAO,EAAgB,mBAAmB,EAAE,MAAM,UAAU,CAAA;AAE5D,MAAM,MAAM,yBAAyB,GAAG;IACtC,iFAAiF;IACjF,GAAG,EAAE,MAAM,CAAA;IACX;;;;OAIG;IACH,MAAM,EAAE,mBAAmB,GAAG,MAAM,CAAA;IACpC;;;OAGG;IACH,MAAM,CAAC,EAAE,mBAAmB,CAAA;IAC5B,2FAA2F;IAC3F,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,6FAA6F;IAC7F,KAAK,CAAC,EAAE,OAAO,KAAK,CAAA;IACpB;;;;OAIG;IACH,YAAY,CAAC,EAAE,MAAM,MAAM,CAAA;IA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AU,IAAI,gBAAgB,CAAC,OAAO,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAC,GAAG;SACnE,KAAK,IAAI,OAAO,CACf,MAAM,EACN,GAAG,UAAU,IAAI,MAAM,EAAE,CAC1B,IAAI,KAAK,SAAS,GAAG,UAAU,IAAI,MAAM,MAAM,EAAE,GAAG,YAAY,CAAC,MAAM,CAAC,GAAG,KAAK,GAAG,CAClF,GAAG,IAAI,EAAE,QAAQ,CAAC,KAAK,CAAC,KACrB,OAAO,CAAC,UAAU,CAAC;KACzB;CACF,CAAA;AAED;;;;GAIG;AACH,MAAM,MAAM,mBAAmB,CAAC,CAAC,SAAS,mBAAmB,GAAG,SAAS,GAAG,SAAS,IAAI;IACvF;;;OAGG;IACH,IAAI,CAAC,CAAC,SAAS,gBAAgB,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,GAAG,IAAI,EAAE,QAAQ,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC,CAAA;IACvF,gFAAgF;IAChF,IAAI,IAAI,OAAO,CAAC,UAAU,CAAC,CAAA;CAC5B,GAAG,oBAAoB,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,CAAA;AA4D7C;;;;;GAKG;AACH,eAAO,MAAM,yBAAyB,GAAI,CAAC,SAAS,mBAAmB,GAAG,SAAS,GAAG,SAAS,EAC7F,QAAQ,yBAAyB,GAAG;IAAE,MAAM,CAAC,EAAE,CAAC,CAAA;CAAE,KACjD,mBAAmB,CAAC,CAAC,CAyEvB,CAAA"}
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createWebhookObjectClient = void 0;
4
+ const standardwebhooks_1 = require("standardwebhooks");
5
+ const deliver_1 = require("./deliver");
6
+ const errors_1 = require("./errors");
7
+ const secret_1 = require("./secret");
8
+ /** Hosts allowed to receive cleartext http, so local development keeps working. */
9
+ const LOCAL_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]"]);
10
+ /**
11
+ * Signing authenticates but does not encrypt: over plain http the payload, headers, and
12
+ * signature travel in cleartext. Refuse everything but https, except toward localhost.
13
+ */
14
+ const assertValidUrl = (url) => {
15
+ let parsed;
16
+ try {
17
+ parsed = new URL(url);
18
+ }
19
+ catch (cause) {
20
+ throw new errors_1.WebhookObjectError("invalid_url", `webhook object URL is not a valid URL: ${url}`, {
21
+ cause,
22
+ });
23
+ }
24
+ if (parsed.protocol === "https:")
25
+ return;
26
+ if (parsed.protocol === "http:" && LOCAL_HOSTNAMES.has(parsed.hostname))
27
+ return;
28
+ throw new errors_1.WebhookObjectError("invalid_url", `webhook object URL must use https (got ${parsed.protocol}//); http is allowed only for localhost`);
29
+ };
30
+ /** Fluent method → wire method segment: `setState` → `set_state`. */
31
+ const wireMethodName = (method) => method.replace(/[A-Z]/g, (char) => `_${char.toLowerCase()}`);
32
+ /**
33
+ * Properties runtimes probe on arbitrary objects (`await` checks `then`, serializers check
34
+ * `toJSON`). The capability proxy must not answer these, or `await client.counter` would hang.
35
+ */
36
+ const PROBED_PROPS = new Set(["then", "toJSON"]);
37
+ /** Both "accepted" statuses; extra body fields (if the receiver ever adds any) pass through. */
38
+ const isSendResult = (body) => body.status === "dispatched" || body.status === "space_idle";
39
+ /** The pong snapshot, checked field by field: the wire is untrusted, so the shape is proven. */
40
+ const isPingResult = (body) => body.status === "pong" &&
41
+ typeof body.objectId === "string" &&
42
+ typeof body.spaceId === "string" &&
43
+ (body.preset === null || typeof body.preset === "string") &&
44
+ typeof body.capabilities === "object" &&
45
+ body.capabilities !== null;
46
+ const serializeEnvelope = (type, data) => {
47
+ const body = JSON.stringify({ type, timestamp: new Date().toISOString(), data });
48
+ const byteLength = new TextEncoder().encode(body).length;
49
+ if (byteLength > deliver_1.MAX_BODY_BYTES)
50
+ throw new errors_1.WebhookObjectError("payload_too_large", `webhook object payload is ${byteLength} bytes; the server caps bodies at ${deliver_1.MAX_BODY_BYTES} bytes`);
51
+ return body;
52
+ };
53
+ /**
54
+ * Create a client for one webhook object. Signing follows Standard Webhooks v1: HMAC over
55
+ * `${id}.${timestamp}.${body}` via the `standardwebhooks` reference library, sent as the
56
+ * `webhook-id` / `webhook-timestamp` / `webhook-signature` headers. The exact serialized
57
+ * body is signed and sent unchanged, so the two can never drift.
58
+ */
59
+ const createWebhookObjectClient = (config) => {
60
+ assertValidUrl(config.url);
61
+ // Revealed once here and captured only by the standardwebhooks signer; the returned
62
+ // client never holds the raw value on an enumerable property.
63
+ const webhook = new standardwebhooks_1.Webhook((0, secret_1.revealSecret)(config.secret));
64
+ const fetchImpl = config.fetch ?? fetch;
65
+ const newWebhookId = config.newWebhookId ?? (() => crypto.randomUUID());
66
+ const maxAttempts = config.maxAttempts ?? deliver_1.DEFAULT_MAX_ATTEMPTS;
67
+ /**
68
+ * Sign, deliver, and narrow the response to the caller's expected shape. The caller controls
69
+ * the result type, but through a runtime guard rather than a cast: the wire is untrusted, so
70
+ * an off-contract 200 body throws `unexpected_response` instead of lying about its shape.
71
+ */
72
+ const dispatch = async (type, data, isExpectedBody) => {
73
+ const body = serializeEnvelope(type, data);
74
+ // One id per event, reused across retries: the server dedups the last 10 ids per
75
+ // object, so a retry can never double-apply.
76
+ const webhookId = newWebhookId();
77
+ const responseBody = await (0, deliver_1.deliver)({
78
+ url: config.url,
79
+ body,
80
+ webhookId,
81
+ sign: (timestampSeconds) => webhook.sign(webhookId, new Date(timestampSeconds * 1000), body),
82
+ fetchImpl,
83
+ maxAttempts,
84
+ signal: config.signal,
85
+ });
86
+ if (!isExpectedBody(responseBody))
87
+ throw new errors_1.WebhookObjectError("unexpected_response", `webhook object ${type} succeeded but returned an unrecognized body (status: ${String(responseBody.status)})`);
88
+ return responseBody;
89
+ };
90
+ const sendEvent = (type, data) => dispatch(type, data, isSendResult);
91
+ const base = {
92
+ send: (type, ...args) => sendEvent(type, args[0] ?? {}),
93
+ ping: () => dispatch("webhook.ping", {}, isPingResult),
94
+ };
95
+ /** `client.counter` → namespace whose method calls become `sendEvent("counter.<method>")`. */
96
+ const capabilityNamespace = (capability) => new Proxy({}, {
97
+ get: (_target, method) => {
98
+ if (typeof method !== "string" || PROBED_PROPS.has(method))
99
+ return undefined;
100
+ return (data) => sendEvent(`${capability}.${wireMethodName(method)}`, data ?? {});
101
+ },
102
+ });
103
+ // The fluent surface is type-driven (CapabilityNamespaces); the proxy only assembles wire
104
+ // names, so new capabilities work via a types-package bump with zero SDK changes.
105
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
106
+ return new Proxy(base, {
107
+ get: (target, prop, receiver) => {
108
+ // Real members (send/ping) win over capability namespaces, as do symbol lookups.
109
+ if (prop in target || typeof prop !== "string")
110
+ return Reflect.get(target, prop, receiver);
111
+ if (PROBED_PROPS.has(prop))
112
+ return undefined;
113
+ return capabilityNamespace(prop);
114
+ },
115
+ });
116
+ };
117
+ exports.createWebhookObjectClient = createWebhookObjectClient;
118
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/client.ts"],"names":[],"mappings":";;;AAAA,uDAA0C;AAS1C,uCAAyE;AACzE,qCAA6C;AAC7C,qCAA4D;AAkG5D,mFAAmF;AACnF,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,WAAW,EAAE,OAAO,CAAC,CAAC,CAAA;AAEpE;;;GAGG;AACH,MAAM,cAAc,GAAG,CAAC,GAAW,EAAQ,EAAE;IAC3C,IAAI,MAAW,CAAA;IACf,IAAI,CAAC;QACH,MAAM,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAA;IACvB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,IAAI,2BAAkB,CAAC,aAAa,EAAE,0CAA0C,GAAG,EAAE,EAAE;YAC3F,KAAK;SACN,CAAC,CAAA;IACJ,CAAC;IACD,IAAI,MAAM,CAAC,QAAQ,KAAK,QAAQ;QAAE,OAAM;IAC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E;YAC9B,iFAAiF;YACjF,IAAI,IAAI,IAAI,MAAM,IAAI,OAAO,IAAI,KAAK,QAAQ;gBAAE,OAAO,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAA;YAC1F,IAAI,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC;gBAAE,OAAO,SAAS,CAAA;YAC5C,OAAO,mBAAmB,CAAC,IAAI,CAAC,CAAA;QAClC,CAAC;KACF,CAA2B,CAAA;AAC9B,CAAC,CAAA;AA3EY,QAAA,yBAAyB,6BA2ErC"}
@@ -0,0 +1,31 @@
1
+ /** The receiver caps request bodies at 4 KB; oversized bodies get the uniform 404. */
2
+ export declare const MAX_BODY_BYTES: number;
3
+ export declare const DEFAULT_MAX_ATTEMPTS = 3;
4
+ /**
5
+ * Runtime mirror of the generated `WebhookWireErrorCode` union (the types package is
6
+ * deliberately zero-runtime, so the value list lives here). `satisfies` rejects unknown
7
+ * codes; a compile-time exhaustiveness test catches missing ones. Either way, receiver
8
+ * drift fails the build instead of shipping.
9
+ */
10
+ export declare const WIRE_ERROR_CODES: readonly ["invalid_request", "invalid_args", "not_found", "capability_not_found", "capability_not_declared", "method_not_found", "token_revoked", "unsupported_media_type", "internal_error", "service_unavailable"];
11
+ export type DeliverArgs = {
12
+ url: string;
13
+ /** The exact serialized body, signed per attempt and sent unchanged. */
14
+ body: string;
15
+ /** Stable across retries: the server dedups the last 10 ids per object, making retries idempotent. */
16
+ webhookId: string;
17
+ /** Signs `webhookId`/timestamp/body; called per attempt so retries carry a fresh timestamp. */
18
+ sign: (timestampSeconds: number) => string;
19
+ fetchImpl: typeof fetch;
20
+ maxAttempts: number;
21
+ /** Aborts the in-flight fetch and any pending backoff sleep; surfaces as an `aborted` error. */
22
+ signal?: AbortSignal;
23
+ };
24
+ /**
25
+ * POST the signed event, retrying transient failures (429 honoring `RateLimit-Reset`,
26
+ * 5xx honoring `Retry-After`, network errors) with exponential backoff + jitter.
27
+ * Resolves with the parsed 200 body; throws `WebhookObjectError` otherwise. An aborted
28
+ * `signal` cancels the in-flight fetch and any pending backoff, throwing `aborted` at once.
29
+ */
30
+ export declare const deliver: (args: DeliverArgs) => Promise<Record<string, unknown>>;
31
+ //# sourceMappingURL=deliver.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deliver.d.ts","sourceRoot":"","sources":["../../src/deliver.ts"],"names":[],"mappings":"AAGA,sFAAsF;AACtF,eAAO,MAAM,cAAc,QAAW,CAAA;AAEtC,eAAO,MAAM,oBAAoB,IAAI,CAAA;AAOrC;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,sNAWuB,CAAA;AAsFpD,MAAM,MAAM,WAAW,GAAG;IACxB,GAAG,EAAE,MAAM,CAAA;IACX,wEAAwE;IACxE,IAAI,EAAE,MAAM,CAAA;IACZ,sGAAsG;IACtG,SAAS,EAAE,MAAM,CAAA;IACjB,+FAA+F;IAC/F,IAAI,EAAE,CAAC,gBAAgB,EAAE,MAAM,KAAK,MAAM,CAAA;IAC1C,SAAS,EAAE,OAAO,KAAK,CAAA;IACvB,WAAW,EAAE,MAAM,CAAA;IACnB,gGAAgG;IAChG,MAAM,CAAC,EAAE,WAAW,CAAA;CACrB,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,OAAO,GAAU,MAAM,WAAW,KAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAMhF,CAAA"}
@@ -0,0 +1,150 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.deliver = exports.WIRE_ERROR_CODES = exports.DEFAULT_MAX_ATTEMPTS = exports.MAX_BODY_BYTES = void 0;
4
+ const errors_1 = require("./errors");
5
+ /** The receiver caps request bodies at 4 KB; oversized bodies get the uniform 404. */
6
+ exports.MAX_BODY_BYTES = 4 * 1024;
7
+ exports.DEFAULT_MAX_ATTEMPTS = 3;
8
+ const BACKOFF_BASE_MS = 500;
9
+ const BACKOFF_CAP_MS = 30_000;
10
+ /** Small buffer past `RateLimit-Reset` so the retry lands after the window actually rolls. */
11
+ const RATE_LIMIT_GRACE_MS = 250;
12
+ /**
13
+ * Runtime mirror of the generated `WebhookWireErrorCode` union (the types package is
14
+ * deliberately zero-runtime, so the value list lives here). `satisfies` rejects unknown
15
+ * codes; a compile-time exhaustiveness test catches missing ones. Either way, receiver
16
+ * drift fails the build instead of shipping.
17
+ */
18
+ exports.WIRE_ERROR_CODES = [
19
+ "invalid_request",
20
+ "invalid_args",
21
+ "not_found",
22
+ "capability_not_found",
23
+ "capability_not_declared",
24
+ "method_not_found",
25
+ "token_revoked",
26
+ "unsupported_media_type",
27
+ "internal_error",
28
+ "service_unavailable",
29
+ ];
30
+ const SERVER_ERROR_CODES = new Set(exports.WIRE_ERROR_CODES);
31
+ const ERROR_HINTS = {
32
+ not_found: "uniform pre-auth failure: check the URL, the secret, clock skew (±5 min), and that the body was not re-serialized after signing",
33
+ capability_not_declared: "this object's preset doesn't accept that event type, run ping() to see what it accepts",
34
+ token_revoked: "the API key was regenerated, copy the new one from the object's ⋮ menu",
35
+ rate_limited: "rate limited (per space or per IP) and retries were exhausted",
36
+ };
37
+ const abortError = (signal) => new errors_1.WebhookObjectError("aborted", "webhook object delivery aborted", { cause: signal.reason });
38
+ /** Sleep `ms`, but reject early (and clean up its listener) if `signal` aborts mid-wait. */
39
+ const sleep = (ms, signal) => new Promise((resolve, reject) => {
40
+ if (signal?.aborted) {
41
+ reject(abortError(signal));
42
+ return;
43
+ }
44
+ if (!signal) {
45
+ setTimeout(resolve, ms);
46
+ return;
47
+ }
48
+ const onAbort = () => {
49
+ clearTimeout(timer);
50
+ reject(abortError(signal));
51
+ };
52
+ const timer = setTimeout(() => {
53
+ signal.removeEventListener("abort", onAbort);
54
+ resolve();
55
+ }, ms);
56
+ signal.addEventListener("abort", onAbort, { once: true });
57
+ });
58
+ const backoffDelayMs = (attempt) => Math.min(BACKOFF_BASE_MS * 2 ** attempt, BACKOFF_CAP_MS) * (0.5 + Math.random() * 0.5);
59
+ const retryDelayMs = (response, attempt) => {
60
+ if (response.status === 429) {
61
+ // The receiver uses `express-rate-limit` with `standardHeaders: true` (IETF draft-6), which
62
+ // sets `RateLimit-Reset` to the number of SECONDS remaining until the window resets.
63
+ const resetHeader = response.headers.get("RateLimit-Reset");
64
+ const resetSeconds = resetHeader === null ? NaN : Number(resetHeader);
65
+ if (Number.isFinite(resetSeconds) && resetSeconds >= 0)
66
+ return resetSeconds * 1000 + RATE_LIMIT_GRACE_MS;
67
+ }
68
+ const retryAfterSeconds = Number(response.headers.get("Retry-After"));
69
+ if (Number.isFinite(retryAfterSeconds) && retryAfterSeconds > 0)
70
+ return retryAfterSeconds * 1000;
71
+ return backoffDelayMs(attempt);
72
+ };
73
+ /** Retry only what the receiver documents as transient: 429 and 5xx. 4xx means "fix the request". */
74
+ const isRetryableStatus = (status) => status === 429 || status >= 500;
75
+ const parseBody = async (response) => {
76
+ try {
77
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
78
+ return (await response.json());
79
+ }
80
+ catch {
81
+ return undefined;
82
+ }
83
+ };
84
+ const isWireErrorCode = (code) => SERVER_ERROR_CODES.has(code);
85
+ const errorFromResponse = (status, body) => {
86
+ const code = (() => {
87
+ if (status === 429)
88
+ return "rate_limited";
89
+ const bodyCode = body?.error;
90
+ if (typeof bodyCode === "string" && isWireErrorCode(bodyCode))
91
+ return bodyCode;
92
+ return "unexpected_response";
93
+ })();
94
+ const hint = ERROR_HINTS[code];
95
+ return new errors_1.WebhookObjectError(code, `webhook object delivery failed (${status}): ${code}${hint ? ` (${hint})` : ""}`, { status, body });
96
+ };
97
+ /**
98
+ * POST the signed event, retrying transient failures (429 honoring `RateLimit-Reset`,
99
+ * 5xx honoring `Retry-After`, network errors) with exponential backoff + jitter.
100
+ * Resolves with the parsed 200 body; throws `WebhookObjectError` otherwise. An aborted
101
+ * `signal` cancels the in-flight fetch and any pending backoff, throwing `aborted` at once.
102
+ */
103
+ const deliver = async (args) => {
104
+ // Terminates because `attemptOnce` always throws on the last attempt.
105
+ for (let attempt = 0;; attempt++) {
106
+ const response = await attemptOnce(args, attempt);
107
+ if (response !== undefined)
108
+ return response;
109
+ }
110
+ };
111
+ exports.deliver = deliver;
112
+ /** One attempt: returns the parsed success body, or undefined after sleeping off a transient failure. */
113
+ const attemptOnce = async (args, attempt) => {
114
+ const isLastAttempt = attempt >= args.maxAttempts - 1;
115
+ const timestampSeconds = Math.floor(Date.now() / 1000);
116
+ if (args.signal?.aborted)
117
+ throw abortError(args.signal);
118
+ let response;
119
+ try {
120
+ response = await args.fetchImpl(args.url, {
121
+ method: "POST",
122
+ headers: {
123
+ "content-type": "application/json",
124
+ "webhook-id": args.webhookId,
125
+ "webhook-timestamp": String(timestampSeconds),
126
+ "webhook-signature": args.sign(timestampSeconds),
127
+ },
128
+ body: args.body,
129
+ signal: args.signal,
130
+ });
131
+ }
132
+ catch (cause) {
133
+ // An abort surfaces here as a fetch rejection; report it as `aborted` and never retry it.
134
+ if (args.signal?.aborted)
135
+ throw abortError(args.signal);
136
+ const error = new errors_1.WebhookObjectError("network_error", "webhook object delivery failed: network error", { cause });
137
+ if (isLastAttempt)
138
+ throw error;
139
+ await sleep(backoffDelayMs(attempt), args.signal);
140
+ return undefined;
141
+ }
142
+ if (response.ok)
143
+ return (await parseBody(response)) ?? {};
144
+ const error = errorFromResponse(response.status, await parseBody(response));
145
+ if (!isRetryableStatus(response.status) || isLastAttempt)
146
+ throw error;
147
+ await sleep(retryDelayMs(response, attempt), args.signal);
148
+ return undefined;
149
+ };
150
+ //# sourceMappingURL=deliver.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deliver.js","sourceRoot":"","sources":["../../src/deliver.ts"],"names":[],"mappings":";;;AACA,qCAAqE;AAErE,sFAAsF;AACzE,QAAA,cAAc,GAAG,CAAC,GAAG,IAAI,CAAA;AAEzB,QAAA,oBAAoB,GAAG,CAAC,CAAA;AAErC,MAAM,eAAe,GAAG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9B,MAAM,KAAK,CAAC,cAAc,CAAC,OAAO,CAAC,EAAE,IAAI,CAAC,MAAM,CAAC,CAAA;QACjD,OAAO,SAAS,CAAA;IAClB,CAAC;IAED,IAAI,QAAQ,CAAC,EAAE;QAAE,OAAO,CAAC,MAAM,SAAS,CAAC,QAAQ,CAAC,CAAC,IAAI,EAAE,CAAA;IAEzD,MAAM,KAAK,GAAG,iBAAiB,CAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAA;IAC3E,IAAI,CAAC,iBAAiB,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,aAAa;QAAE,MAAM,KAAK,CAAA;IACrE,MAAM,KAAK,CAAC,YAAY,CAAC,QAAQ,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,MAAM,CAAC,CAAA;IACzD,OAAO,SAAS,CAAA;AAClB,CAAC,CAAA"}
@@ -0,0 +1,32 @@
1
+ import type { WebhookWireErrorCode } from "@gathertown/webhook-object-types";
2
+ /**
3
+ * Error codes surfaced by `WebhookObjectError.code`.
4
+ *
5
+ * Wire codes come verbatim from the generated `WebhookWireErrorCode` (the receiver's error
6
+ * bodies); the rest are client-side conditions the SDK detects before/around the HTTP exchange.
7
+ */
8
+ export type WebhookObjectErrorCode = WebhookWireErrorCode | "rate_limited" | "payload_too_large" | "invalid_secret" | "invalid_url" | "network_error" | "aborted" | "unexpected_response";
9
+ /**
10
+ * The single error type the SDK throws. `code` classifies the failure (see
11
+ * {@link WebhookObjectErrorCode}) and `status` carries the HTTP status when the error
12
+ * originated from a response.
13
+ */
14
+ export declare class WebhookObjectError extends Error {
15
+ readonly code: WebhookObjectErrorCode;
16
+ readonly name = "WebhookObjectError";
17
+ constructor(code: WebhookObjectErrorCode, message: string, options?: {
18
+ /** HTTP status of the response, when the error came from one. */
19
+ status?: number;
20
+ /** Parsed response body, when the error came from one, for reading server-provided fields. */
21
+ body?: unknown;
22
+ cause?: unknown;
23
+ });
24
+ readonly status: number | undefined;
25
+ /**
26
+ * The parsed response body for errors that came from an HTTP response (e.g. `{ error: "…" }`),
27
+ * or `undefined` for client-side errors and unparseable bodies. Lets integrators read any
28
+ * extra fields the receiver returns beyond `code`/`status`.
29
+ */
30
+ readonly body: unknown;
31
+ }
32
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAA;AAE5E;;;;;GAKG;AACH,MAAM,MAAM,sBAAsB,GAC9B,oBAAoB,GAGpB,cAAc,GAEd,mBAAmB,GAEnB,gBAAgB,GAEhB,aAAa,GAEb,eAAe,GAEf,SAAS,GAET,qBAAqB,CAAA;AAEzB;;;;GAIG;AACH,qBAAa,kBAAmB,SAAQ,KAAK;IAIzC,QAAQ,CAAC,IAAI,EAAE,sBAAsB;IAHvC,SAAkB,IAAI,wBAAuB;gBAGlC,IAAI,EAAE,sBAAsB,EACrC,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE;QACR,iEAAiE;QACjE,MAAM,CAAC,EAAE,MAAM,CAAA;QACf,8FAA8F;QAC9F,IAAI,CAAC,EAAE,OAAO,CAAA;QACd,KAAK,CAAC,EAAE,OAAO,CAAA;KAChB;IAOH,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAA;IAEnC;;;;OAIG;IACH,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAA;CACvB"}
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WebhookObjectError = void 0;
4
+ /**
5
+ * The single error type the SDK throws. `code` classifies the failure (see
6
+ * {@link WebhookObjectErrorCode}) and `status` carries the HTTP status when the error
7
+ * originated from a response.
8
+ */
9
+ class WebhookObjectError extends Error {
10
+ code;
11
+ name = "WebhookObjectError";
12
+ constructor(code, message, options) {
13
+ super(message, options?.cause === undefined ? undefined : { cause: options.cause });
14
+ this.code = code;
15
+ this.status = options?.status;
16
+ this.body = options?.body;
17
+ }
18
+ status;
19
+ /**
20
+ * The parsed response body for errors that came from an HTTP response (e.g. `{ error: "…" }`),
21
+ * or `undefined` for client-side errors and unparseable bodies. Lets integrators read any
22
+ * extra fields the receiver returns beyond `code`/`status`.
23
+ */
24
+ body;
25
+ }
26
+ exports.WebhookObjectError = WebhookObjectError;
27
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":";;;AA0BA;;;;GAIG;AACH,MAAa,kBAAmB,SAAQ,KAAK;IAIhC;IAHO,IAAI,GAAG,oBAAoB,CAAA;IAE7C,YACW,IAA4B,EACrC,OAAe,EACf,OAMC;QAED,KAAK,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC,CAAA;QAV1E,SAAI,GAAJ,IAAI,CAAwB;QAWrC,IAAI,CAAC,MAAM,GAAG,OAAO,EAAE,MAAM,CAAA;QAC7B,IAAI,CAAC,IAAI,GAAG,OAAO,EAAE,IAAI,CAAA;IAC3B,CAAC;IAEQ,MAAM,CAAoB;IAEnC;;;;OAIG;IACM,IAAI,CAAS;CACvB;AA3BD,gDA2BC"}
@@ -0,0 +1,5 @@
1
+ export { createWebhookObjectCatalog, type WebhookObjectCatalog, type WebhookObjectCatalogEntry, type WebhookObjectCatalogOptions, } from "./catalog";
2
+ export { type AllowedEventType, type CapabilityNamespaces, createWebhookObjectClient, type PingResult, type SendResult, type WebhookObjectClient, type WebhookObjectClientConfig, } from "./client";
3
+ export { WebhookObjectError, type WebhookObjectErrorCode } from "./errors";
4
+ export { secretFromEnv, unsafeSecretLiteral, type WebhookObjectSecret } from "./secret";
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,0BAA0B,EAC1B,KAAK,oBAAoB,EACzB,KAAK,yBAAyB,EAC9B,KAAK,2BAA2B,GACjC,MAAM,WAAW,CAAA;AAClB,OAAO,EACL,KAAK,gBAAgB,EACrB,KAAK,oBAAoB,EACzB,yBAAyB,EACzB,KAAK,UAAU,EACf,KAAK,UAAU,EACf,KAAK,mBAAmB,EACxB,KAAK,yBAAyB,GAC/B,MAAM,UAAU,CAAA;AACjB,OAAO,EAAE,kBAAkB,EAAE,KAAK,sBAAsB,EAAE,MAAM,UAAU,CAAA;AAC1E,OAAO,EAAE,aAAa,EAAE,mBAAmB,EAAE,KAAK,mBAAmB,EAAE,MAAM,UAAU,CAAA"}
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.unsafeSecretLiteral = exports.secretFromEnv = exports.WebhookObjectError = exports.createWebhookObjectClient = exports.createWebhookObjectCatalog = void 0;
4
+ var catalog_1 = require("./catalog");
5
+ Object.defineProperty(exports, "createWebhookObjectCatalog", { enumerable: true, get: function () { return catalog_1.createWebhookObjectCatalog; } });
6
+ var client_1 = require("./client");
7
+ Object.defineProperty(exports, "createWebhookObjectClient", { enumerable: true, get: function () { return client_1.createWebhookObjectClient; } });
8
+ var errors_1 = require("./errors");
9
+ Object.defineProperty(exports, "WebhookObjectError", { enumerable: true, get: function () { return errors_1.WebhookObjectError; } });
10
+ var secret_1 = require("./secret");
11
+ Object.defineProperty(exports, "secretFromEnv", { enumerable: true, get: function () { return secret_1.secretFromEnv; } });
12
+ Object.defineProperty(exports, "unsafeSecretLiteral", { enumerable: true, get: function () { return secret_1.unsafeSecretLiteral; } });
13
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,qCAKkB;AAJhB,qHAAA,0BAA0B,OAAA;AAK5B,mCAQiB;AALf,mHAAA,yBAAyB,OAAA;AAM3B,mCAA0E;AAAjE,4GAAA,kBAAkB,OAAA;AAC3B,mCAAuF;AAA9E,uGAAA,aAAa,OAAA;AAAE,6GAAA,mBAAmB,OAAA"}
@@ -0,0 +1,30 @@
1
+ declare const webhookObjectSecretBrand: unique symbol;
2
+ /**
3
+ * An opaque handle to a `whsec_…` signing secret, obtained via {@link secretFromEnv} or
4
+ * {@link unsafeSecretLiteral}. Unlike a bare string (which the client also accepts), the
5
+ * handle redacts itself when logged or serialized, so it can't leak through console output,
6
+ * error reporters, or `JSON.stringify` of a config object.
7
+ */
8
+ export type WebhookObjectSecret = {
9
+ readonly [webhookObjectSecretBrand]: true;
10
+ };
11
+ /**
12
+ * Read a `whsec_…` secret from the named environment variable. The recommended way to
13
+ * provide a secret: the value never appears in your source, and a missing or malformed
14
+ * variable fails fast with the variable's name (never its value).
15
+ */
16
+ export declare const secretFromEnv: (name: string) => WebhookObjectSecret;
17
+ /**
18
+ * Wrap a secret you already hold as a string (secret managers, non-Node runtimes without
19
+ * `process.env`). Named `unsafe` so hardcoded `whsec_…` literals are easy to grep for in
20
+ * review; never commit a literal secret to source control.
21
+ */
22
+ export declare const unsafeSecretLiteral: (value: string) => WebhookObjectSecret;
23
+ /**
24
+ * Internal: recover the raw secret for signing. Not re-exported from the package entry
25
+ * point. Bare strings are validated in place; anything else must be a handle minted by
26
+ * this module (an object that isn't one fails the WeakMap lookup and throws).
27
+ */
28
+ export declare const revealSecret: (secret: WebhookObjectSecret | string) => string;
29
+ export {};
30
+ //# sourceMappingURL=secret.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secret.d.ts","sourceRoot":"","sources":["../../src/secret.ts"],"names":[],"mappings":"AAKA,OAAO,CAAC,MAAM,wBAAwB,EAAE,OAAO,MAAM,CAAA;AAErD;;;;;GAKG;AACH,MAAM,MAAM,mBAAmB,GAAG;IAAE,QAAQ,CAAC,CAAC,wBAAwB,CAAC,EAAE,IAAI,CAAA;CAAE,CAAA;AAyB/E;;;;GAIG;AACH,eAAO,MAAM,aAAa,GAAI,MAAM,MAAM,KAAG,mBACY,CAAA;AAEzD;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,GAAI,OAAO,MAAM,KAAG,mBACZ,CAAA;AAExC;;;;GAIG;AACH,eAAO,MAAM,YAAY,GAAI,QAAQ,mBAAmB,GAAG,MAAM,KAAG,MAgBnE,CAAA"}
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.revealSecret = exports.unsafeSecretLiteral = exports.secretFromEnv = void 0;
4
+ const errors_1 = require("./errors");
5
+ /** Fail fast on malformed secrets: `whsec_` + at least 20 chars of key material. */
6
+ const SECRET_PATTERN = /^whsec_.{20,}/;
7
+ /** Secret values live here, keyed by handle identity, so no property on the handle exposes them. */
8
+ const secretValues = new WeakMap();
9
+ const REDACTED = "[redacted webhook object secret]";
10
+ const brandSecret = (value, source) => {
11
+ if (!SECRET_PATTERN.test(value))
12
+ throw new errors_1.WebhookObjectError("invalid_secret", `webhook object secret from ${source} is missing or malformed, expected a whsec_… key`);
13
+ const handle = {
14
+ toString: () => REDACTED,
15
+ toJSON: () => REDACTED,
16
+ [Symbol.for("nodejs.util.inspect.custom")]: () => REDACTED,
17
+ };
18
+ // The brand symbol exists only at the type level; the WeakMap entry is the runtime brand.
19
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
20
+ const secret = handle;
21
+ secretValues.set(secret, value);
22
+ return secret;
23
+ };
24
+ /**
25
+ * Read a `whsec_…` secret from the named environment variable. The recommended way to
26
+ * provide a secret: the value never appears in your source, and a missing or malformed
27
+ * variable fails fast with the variable's name (never its value).
28
+ */
29
+ const secretFromEnv = (name) => brandSecret(process.env[name] ?? "", `env var ${name}`);
30
+ exports.secretFromEnv = secretFromEnv;
31
+ /**
32
+ * Wrap a secret you already hold as a string (secret managers, non-Node runtimes without
33
+ * `process.env`). Named `unsafe` so hardcoded `whsec_…` literals are easy to grep for in
34
+ * review; never commit a literal secret to source control.
35
+ */
36
+ const unsafeSecretLiteral = (value) => brandSecret(value, "a string literal");
37
+ exports.unsafeSecretLiteral = unsafeSecretLiteral;
38
+ /**
39
+ * Internal: recover the raw secret for signing. Not re-exported from the package entry
40
+ * point. Bare strings are validated in place; anything else must be a handle minted by
41
+ * this module (an object that isn't one fails the WeakMap lookup and throws).
42
+ */
43
+ const revealSecret = (secret) => {
44
+ if (typeof secret === "string") {
45
+ if (!SECRET_PATTERN.test(secret))
46
+ throw new errors_1.WebhookObjectError("invalid_secret", "webhook object secret is malformed, expected a whsec_… key");
47
+ return secret;
48
+ }
49
+ const value = secretValues.get(secret);
50
+ if (value === undefined)
51
+ throw new errors_1.WebhookObjectError("invalid_secret", "webhook object secret must be a whsec_… string or created with secretFromEnv() / unsafeSecretLiteral()");
52
+ return value;
53
+ };
54
+ exports.revealSecret = revealSecret;
55
+ //# sourceMappingURL=secret.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secret.js","sourceRoot":"","sources":["../../src/secret.ts"],"names":[],"mappings":";;;AAAA,qCAA6C;AAE7C,oFAAoF;AACpF,MAAM,cAAc,GAAG,eAAe,CAAA;AAYtC,oGAAoG;AACpG,MAAM,YAAY,GAAG,IAAI,OAAO,EAA+B,CAAA;AAE/D,MAAM,QAAQ,GAAG,kCAAkC,CAAA;AAEnD,MAAM,WAAW,GAAG,CAAC,KAAa,EAAE,MAAc,EAAuB,EAAE;IACzE,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC;QAC7B,MAAM,IAAI,2BAAkB,CAC1B,gBAAgB,EAChB,8BAA8B,MAAM,kDAAkD,CACvF,CAAA;IACH,MAAM,MAAM,GAAG;QACb,QAAQ,EAAE,GAAG,EAAE,CAAC,QAAQ;QACxB,MAAM,EAAE,GAAG,EA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typed client for emitting events to Gather webhook objects (Smart Objects): Standard Webhooks signing, retries, and a fully-inferred send API.",
5
+ "main": "dist/src/index.js",
6
+ "types": "dist/src/index.d.ts",
7
+ "sideEffects": false,
8
+ "files": [
9
+ "dist/src/**",
10
+ "!dist/src/__tests__/**",
11
+ "README.md",
12
+ "LICENSE-MIT",
13
+ "LICENSE-APACHE"
14
+ ],
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/gathertown/webhook-objects.git"
18
+ },
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
22
+ "engines": {
23
+ "node": ">=18"
24
+ },
25
+ "author": "Gather Presence, Inc.",
26
+ "license": "MIT OR Apache-2.0",
27
+ "dependencies": {
28
+ "@gathertown/webhook-object-types": "^0.1.1",
29
+ "standardwebhooks": "~1.0.0"
30
+ },
31
+ "devDependencies": {
32
+ "expect-type": "~0.20.0",
33
+ "typescript": "~6.0.3"
34
+ }
35
+ }