@withone/sdk 0.0.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -4,9 +4,350 @@ import {
4
4
 
5
5
  // src/client.ts
6
6
  import { One as NativeOne } from "../native.js";
7
+
8
+ // src/errors.ts
9
+ var OneError = class extends Error {
10
+ constructor(code, message, status, body, retryable) {
11
+ super(message);
12
+ this.code = code;
13
+ this.status = status;
14
+ this.body = body;
15
+ this.retryable = retryable;
16
+ this.name = "OneError";
17
+ }
18
+ code;
19
+ status;
20
+ body;
21
+ retryable;
22
+ };
23
+ function toOneError(error) {
24
+ const message = error instanceof Error ? error.message : String(error);
25
+ try {
26
+ const envelope = JSON.parse(message);
27
+ return new OneError(envelope.code, envelope.message, envelope.status, envelope.body, envelope.retryable);
28
+ } catch {
29
+ return new OneError("unknown", message, void 0, void 0, false);
30
+ }
31
+ }
32
+
33
+ // src/webhooks.ts
34
+ import { verifyWebhook } from "../native.js";
35
+ var WebhooksBase = class {
36
+ constructor(client, options) {
37
+ this.client = client;
38
+ this.options = options;
39
+ }
40
+ client;
41
+ options;
42
+ handlers = /* @__PURE__ */ new Map();
43
+ anyHandlers = [];
44
+ /** @internal Registers a typed handler; generated methods wrap this. */
45
+ register(event, connection, run) {
46
+ const existing = this.handlers.get(event) ?? [];
47
+ existing.push({ connection, run });
48
+ this.handlers.set(event, existing);
49
+ return this;
50
+ }
51
+ /**
52
+ * Registers handlers scoped to one connection: they fire only for deliveries
53
+ * carrying that connection's key.
54
+ *
55
+ * The block keeps the scope lexical, so a reader never has to scan backwards
56
+ * to work out which connection a handler belongs to, and only the
57
+ * connection-carrying events are offered inside it.
58
+ */
59
+ connection(key, block) {
60
+ const scope = new (this.scopeConstructor())(key);
61
+ block(scope);
62
+ for (const [event, registered] of scope.drain()) {
63
+ const existing = this.handlers.get(event) ?? [];
64
+ existing.push(...registered);
65
+ this.handlers.set(event, existing);
66
+ }
67
+ this.anyHandlers.push(...scope.drainAny());
68
+ return this;
69
+ }
70
+ /** @internal The generated subclass supplies its own scope type. */
71
+ scopeConstructor() {
72
+ return ConnectionWebhooksBase;
73
+ }
74
+ /**
75
+ * Registers a handler fired for every verified delivery, including event
76
+ * types this SDK build does not recognize. Runs after event-specific
77
+ * handlers.
78
+ */
79
+ onAny(handler) {
80
+ this.anyHandlers.push({ connection: null, run: handler });
81
+ return this;
82
+ }
83
+ /**
84
+ * The event types `listen` subscribes to.
85
+ *
86
+ * An unscoped catch-all subscribes to this build's whole catalog; the server
87
+ * matches exact event strings, so events added after this build are not
88
+ * covered. A catch-all scoped to a connection adds only the
89
+ * connection-carrying events, since the server cannot filter by connection
90
+ * and the rest would just be discarded on arrival.
91
+ */
92
+ events() {
93
+ if (this.anyHandlers.some((handler) => handler.connection === null)) return [...this.catalog()];
94
+ const events = new Set(this.handlers.keys());
95
+ if (this.anyHandlers.length > 0) {
96
+ for (const event of this.connectionCatalog()) events.add(event);
97
+ }
98
+ return [...events].sort();
99
+ }
100
+ /** @internal The generated subclass supplies the full event catalog. */
101
+ catalog() {
102
+ return [];
103
+ }
104
+ /** @internal The generated subclass supplies the connection-carrying subset. */
105
+ connectionCatalog() {
106
+ return [];
107
+ }
108
+ /**
109
+ * Verifies the signature and freshness of a delivery without dispatching.
110
+ * Use it when you want to route deliveries yourself.
111
+ *
112
+ * `rawBody` must be the exact bytes One sent. A JSON body parser that has
113
+ * already re-serialized the request will fail verification.
114
+ */
115
+ verify(rawBody, signature) {
116
+ try {
117
+ const verified = verifyWebhook(rawBody, signature, this.options.secret, this.options.toleranceMs);
118
+ return {
119
+ event: verified.event,
120
+ id: verified.eventId,
121
+ timestamp: new Date(verified.timestamp),
122
+ payload: verified.payload,
123
+ metadata: verified.metadata ?? null,
124
+ connection: verified.connection ?? null,
125
+ isTest: verified.isTest
126
+ };
127
+ } catch (error) {
128
+ throw toOneError(error);
129
+ }
130
+ }
131
+ /**
132
+ * Verifies, parses, and dispatches a delivery to every handler registered for
133
+ * its event type, then to the catch-all handlers. Handlers run sequentially
134
+ * and are awaited.
135
+ */
136
+ async handle(rawBody, signature) {
137
+ const delivery = this.verify(rawBody, signature);
138
+ const accepts = (registered) => registered.connection === null || registered.connection === delivery.connection;
139
+ let failure;
140
+ const run = async (registered) => {
141
+ try {
142
+ await registered.run(delivery);
143
+ } catch (error) {
144
+ failure ??= { error };
145
+ }
146
+ };
147
+ if (!delivery.isTest) {
148
+ for (const registered of (this.handlers.get(delivery.event) ?? []).filter(accepts)) {
149
+ await run(registered);
150
+ }
151
+ }
152
+ for (const registered of this.anyHandlers.filter(accepts)) {
153
+ await run(registered);
154
+ }
155
+ if (failure) throw failure.error;
156
+ return delivery;
157
+ }
158
+ /**
159
+ * Registers this listener with One under the stable name `key`, pointing at
160
+ * `url` and subscribing to exactly the events handlers were attached for.
161
+ *
162
+ * Idempotent: calling it on every boot reconciles the one listener named
163
+ * `key` rather than accumulating duplicates.
164
+ */
165
+ async listen(key, url) {
166
+ return this.client.registerWebhook(key, url, this.events(), this.options.secret);
167
+ }
168
+ };
169
+ var ConnectionWebhooksBase = class {
170
+ constructor(key) {
171
+ this.key = key;
172
+ }
173
+ key;
174
+ handlers = /* @__PURE__ */ new Map();
175
+ anyHandlers = [];
176
+ /** @internal Registers a typed handler; generated methods wrap this. */
177
+ register(event, run) {
178
+ const existing = this.handlers.get(event) ?? [];
179
+ existing.push({ connection: this.key, run });
180
+ this.handlers.set(event, existing);
181
+ return this;
182
+ }
183
+ /** Registers a handler for every event concerning this connection. */
184
+ onAny(handler) {
185
+ this.anyHandlers.push({ connection: this.key, run: handler });
186
+ return this;
187
+ }
188
+ /** @internal Hands the collected handlers to the parent registry. */
189
+ drain() {
190
+ return this.handlers;
191
+ }
192
+ /** @internal Hands the collected catch-all handlers to the parent registry. */
193
+ drainAny() {
194
+ return this.anyHandlers;
195
+ }
196
+ };
197
+
198
+ // src/webhooks.generated.ts
199
+ var ALL_WEBHOOK_EVENTS = [
200
+ "connection.created",
201
+ "connection.deleted",
202
+ "connection.oauth.created",
203
+ "member.added",
204
+ "member.removed",
205
+ "member.role_updated",
206
+ "oauth.failed",
207
+ "oauth.refreshed",
208
+ "organization.created",
209
+ "organization.deleted",
210
+ "organization.updated",
211
+ "passthrough.executed",
212
+ "project.created",
213
+ "project.deleted",
214
+ "project.updated"
215
+ ];
216
+ var CONNECTION_SCOPED_EVENTS = [
217
+ "connection.created",
218
+ "connection.deleted",
219
+ "connection.oauth.created",
220
+ "oauth.failed",
221
+ "oauth.refreshed",
222
+ "passthrough.executed"
223
+ ];
224
+ var Webhooks = class extends WebhooksBase {
225
+ /** Scopes to the generated connection registry, so a `connection(..)` block
226
+ * offers the typed per-event methods rather than the bare base. */
227
+ scopeConstructor() {
228
+ return ConnectionWebhooks;
229
+ }
230
+ /** The full catalog, so an unscoped catch-all subscribes to everything. */
231
+ catalog() {
232
+ return ALL_WEBHOOK_EVENTS;
233
+ }
234
+ /** The connection-carrying subset, for a catch-all scoped to a connection. */
235
+ connectionCatalog() {
236
+ return CONNECTION_SCOPED_EVENTS;
237
+ }
238
+ /** Narrows the block's scope to the typed registry. */
239
+ connection(key, block) {
240
+ return super.connection(key, block);
241
+ }
242
+ /** Registers a handler for `connection.created`. */
243
+ connectionCreated(handler) {
244
+ return this.register("connection.created", null, handler);
245
+ }
246
+ /** Registers a handler for `connection.deleted`. */
247
+ connectionDeleted(handler) {
248
+ return this.register("connection.deleted", null, handler);
249
+ }
250
+ /** Registers a handler for `connection.oauth.created`. */
251
+ connectionOauthCreated(handler) {
252
+ return this.register("connection.oauth.created", null, handler);
253
+ }
254
+ /** Registers a handler for `member.added`. */
255
+ memberAdded(handler) {
256
+ return this.register("member.added", null, handler);
257
+ }
258
+ /** Registers a handler for `member.removed`. */
259
+ memberRemoved(handler) {
260
+ return this.register("member.removed", null, handler);
261
+ }
262
+ /** Registers a handler for `member.role_updated`. */
263
+ memberRoleUpdated(handler) {
264
+ return this.register("member.role_updated", null, handler);
265
+ }
266
+ /** Registers a handler for `oauth.failed`. */
267
+ oauthFailed(handler) {
268
+ return this.register("oauth.failed", null, handler);
269
+ }
270
+ /** Registers a handler for `oauth.refreshed`. */
271
+ oauthRefreshed(handler) {
272
+ return this.register("oauth.refreshed", null, handler);
273
+ }
274
+ /** Registers a handler for `organization.created`. */
275
+ organizationCreated(handler) {
276
+ return this.register("organization.created", null, handler);
277
+ }
278
+ /** Registers a handler for `organization.deleted`. */
279
+ organizationDeleted(handler) {
280
+ return this.register("organization.deleted", null, handler);
281
+ }
282
+ /** Registers a handler for `organization.updated`. */
283
+ organizationUpdated(handler) {
284
+ return this.register("organization.updated", null, handler);
285
+ }
286
+ /** Registers a handler for `passthrough.executed`. */
287
+ passthroughExecuted(handler) {
288
+ return this.register("passthrough.executed", null, handler);
289
+ }
290
+ /** Registers a handler for `project.created`. */
291
+ projectCreated(handler) {
292
+ return this.register("project.created", null, handler);
293
+ }
294
+ /** Registers a handler for `project.deleted`. */
295
+ projectDeleted(handler) {
296
+ return this.register("project.deleted", null, handler);
297
+ }
298
+ /** Registers a handler for `project.updated`. */
299
+ projectUpdated(handler) {
300
+ return this.register("project.updated", null, handler);
301
+ }
302
+ };
303
+ var ConnectionWebhooks = class extends ConnectionWebhooksBase {
304
+ /** Registers a handler for `connection.created` on this connection. */
305
+ connectionCreated(handler) {
306
+ return this.register("connection.created", handler);
307
+ }
308
+ /** Registers a handler for `connection.deleted` on this connection. */
309
+ connectionDeleted(handler) {
310
+ return this.register("connection.deleted", handler);
311
+ }
312
+ /** Registers a handler for `connection.oauth.created` on this connection. */
313
+ connectionOauthCreated(handler) {
314
+ return this.register("connection.oauth.created", handler);
315
+ }
316
+ /** Registers a handler for `oauth.failed` on this connection. */
317
+ oauthFailed(handler) {
318
+ return this.register("oauth.failed", handler);
319
+ }
320
+ /** Registers a handler for `oauth.refreshed` on this connection. */
321
+ oauthRefreshed(handler) {
322
+ return this.register("oauth.refreshed", handler);
323
+ }
324
+ /** Registers a handler for `passthrough.executed` on this connection. */
325
+ passthroughExecuted(handler) {
326
+ return this.register("passthrough.executed", handler);
327
+ }
328
+ };
329
+
330
+ // src/client.ts
331
+ var CallLifecycle = class {
332
+ constructor(hooks) {
333
+ this.hooks = hooks;
334
+ }
335
+ hooks;
336
+ async execute(call, complete) {
337
+ try {
338
+ const completed = complete(await call());
339
+ this.hooks.onSuccess?.(completed.result);
340
+ return completed.output;
341
+ } catch (error) {
342
+ const err = toOneError(error);
343
+ this.hooks.onError?.(err);
344
+ throw err;
345
+ }
346
+ }
347
+ };
7
348
  var One = class _One {
8
349
  native;
9
- hooks;
350
+ lifecycle;
10
351
  constructor(secret, options) {
11
352
  const { onSuccess, onError, ...native } = options ?? {};
12
353
  try {
@@ -14,7 +355,7 @@ var One = class _One {
14
355
  } catch (error) {
15
356
  throw toOneError(error);
16
357
  }
17
- this.hooks = { onSuccess, onError };
358
+ this.lifecycle = new CallLifecycle({ onSuccess, onError });
18
359
  }
19
360
  /** Creates a client from the environment (`ONE_SECRET`, `ONE_BASE_URL`). */
20
361
  static fromEnv() {
@@ -25,23 +366,40 @@ var One = class _One {
25
366
  } catch (error) {
26
367
  throw toOneError(error);
27
368
  }
28
- fields.hooks = {};
369
+ fields.lifecycle = new CallLifecycle({});
29
370
  return client;
30
371
  }
31
372
  /** Scopes subsequent calls to a connection by its key. */
32
373
  connection(key) {
33
- return new ConnectionScope(this.native, key, this.hooks);
374
+ return new ConnectionScope(this.native, key, this.lifecycle);
375
+ }
376
+ /**
377
+ * Starts building a webhook listener, verified with the subscription's
378
+ * signing secret.
379
+ */
380
+ webhooks(options) {
381
+ return new Webhooks(this, options);
382
+ }
383
+ /** @internal Registers a webhook listener; the route and request shape live in Rust. */
384
+ async registerWebhook(key, url, events, secret) {
385
+ return this.lifecycle.execute(
386
+ () => this.native.registerWebhook(key, url, events, secret),
387
+ (result) => {
388
+ const out = new CallResult(result.status, result.headers, result.data);
389
+ return { output: result.data, result: out };
390
+ }
391
+ );
34
392
  }
35
393
  };
36
394
  var ConnectionScope = class {
37
- constructor(native, key, hooks) {
395
+ constructor(native, key, lifecycle) {
38
396
  this.native = native;
39
397
  this.key = key;
40
- this.hooks = hooks;
398
+ this.lifecycle = lifecycle;
41
399
  }
42
400
  native;
43
401
  key;
44
- hooks;
402
+ lifecycle;
45
403
  /** Runs a typed action and resolves with the response, typed as the action's
46
404
  * default output. `options` sets per-call retry and timeout. */
47
405
  async run(action, options) {
@@ -56,16 +414,13 @@ var ConnectionScope = class {
56
414
  return this.execute({ connectionKey: this.key, ...request }, options);
57
415
  }
58
416
  async execute(request, options) {
59
- try {
60
- const result = await this.native.run({ ...request, ...options ?? {} });
61
- const out = new CallResult(result.status, result.headers, result.data);
62
- this.hooks.onSuccess?.(out);
63
- return out;
64
- } catch (error) {
65
- const err = toOneError(error);
66
- this.hooks.onError?.(err);
67
- throw err;
68
- }
417
+ return this.lifecycle.execute(
418
+ () => this.native.run({ ...request, ...options ?? {} }),
419
+ (result) => {
420
+ const out = new CallResult(result.status, result.headers, result.data);
421
+ return { output: out, result: out };
422
+ }
423
+ );
69
424
  }
70
425
  };
71
426
  var CallResult = class {
@@ -82,33 +437,12 @@ var CallResult = class {
82
437
  return this.data;
83
438
  }
84
439
  };
85
- var OneError = class extends Error {
86
- constructor(code, message, status, body, retryable) {
87
- super(message);
88
- this.code = code;
89
- this.status = status;
90
- this.body = body;
91
- this.retryable = retryable;
92
- this.name = "OneError";
93
- }
94
- code;
95
- status;
96
- body;
97
- retryable;
98
- };
99
- function toOneError(error) {
100
- const message = error instanceof Error ? error.message : String(error);
101
- try {
102
- const envelope = JSON.parse(message);
103
- return new OneError(envelope.code, envelope.message, envelope.status, envelope.body, envelope.retryable);
104
- } catch {
105
- return new OneError("unknown", message, void 0, void 0, false);
106
- }
107
- }
108
440
  export {
109
441
  Action,
110
442
  CallResult,
111
443
  ConnectionScope,
444
+ ConnectionWebhooks,
112
445
  One,
113
- OneError
446
+ OneError,
447
+ Webhooks
114
448
  };
package/native.d.ts CHANGED
@@ -10,6 +10,12 @@ export declare class One {
10
10
  static fromEnv(): One
11
11
  /** Runs an action against a connection and resolves with the response. */
12
12
  run(request: ActionRequest): Promise<CallResult>
13
+ /**
14
+ * Registers (or reconciles) a webhook listener under a stable name.
15
+ *
16
+ * The route and request shape live in the Rust client; this only marshals.
17
+ */
18
+ registerWebhook(key: string, url: string, events: Array<string>, secret: string): Promise<CallResult>
13
19
  }
14
20
 
15
21
  /**
@@ -59,9 +65,9 @@ export interface ActionRequest {
59
65
  timeoutMs?: number
60
66
  }
61
67
 
62
- /** The result of a successful (2xx) action call. */
68
+ /** The result of a successful (2xx) SDK call. */
63
69
  export interface CallResult {
64
- /** HTTP status code returned by the upstream platform. */
70
+ /** HTTP status code returned by the request. */
65
71
  status: number
66
72
  /** Response headers (rate-limit, request-id, `ETag`, `Link`, …). */
67
73
  headers: Record<string, string>
@@ -88,3 +94,34 @@ export interface RetryConfig {
88
94
  /** Maximum backoff delay in milliseconds (default 1000). */
89
95
  maxDelayMs?: number
90
96
  }
97
+
98
+ /** A verified webhook delivery handed back to the TS registry for dispatch. */
99
+ export interface VerifiedDelivery {
100
+ /** On-the-wire event string (`connection.created`, ...). */
101
+ event: string
102
+ /** Stable delivery id, identical on every retry. Deduplicate on it. */
103
+ eventId: string
104
+ /** RFC 3339 timestamp of when One emitted the event. */
105
+ timestamp: string
106
+ /** The event-specific payload. */
107
+ payload: JsonValue
108
+ /** Subscription metadata echoed back on delivery, if any was configured. */
109
+ metadata?: JsonValue | null
110
+ /** The connection this delivery concerns, for events that carry one. */
111
+ connection?: string
112
+ /**
113
+ * Whether this is a test delivery, decided by the native client so both
114
+ * SDKs share one definition of the marker.
115
+ */
116
+ isTest: boolean
117
+ }
118
+
119
+ /**
120
+ * Verifies a webhook delivery's signature and freshness, returning the parsed
121
+ * delivery or throwing an `ErrorEnvelope`.
122
+ *
123
+ * Signature checking, the tolerance window, and envelope parsing live in Rust
124
+ * so the two SDKs cannot drift on them; only handler dispatch is TS, because
125
+ * handlers are closures and those should not cross the boundary.
126
+ */
127
+ export declare function verifyWebhook(body: Buffer, signature: string, secret: string, toleranceMs?: number | undefined | null): VerifiedDelivery
package/native.js CHANGED
@@ -587,3 +587,4 @@ if (!nativeBinding) {
587
587
 
588
588
  module.exports = nativeBinding
589
589
  module.exports.One = nativeBinding.One
590
+ module.exports.verifyWebhook = nativeBinding.verifyWebhook
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@withone/sdk",
3
- "version": "0.0.4",
3
+ "version": "0.2.0",
4
4
  "description": "The One SDK for Node — typed client over the One API.",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -206,17 +206,17 @@
206
206
  "native.d.ts"
207
207
  ],
208
208
  "optionalDependencies": {
209
- "@withone/sdk-linux-x64-gnu": "0.0.4",
210
- "@withone/sdk-linux-arm64-gnu": "0.0.4",
211
- "@withone/sdk-linux-x64-musl": "0.0.4",
212
- "@withone/sdk-darwin-x64": "0.0.4",
213
- "@withone/sdk-darwin-arm64": "0.0.4",
214
- "@withone/sdk-win32-x64-msvc": "0.0.4"
209
+ "@withone/sdk-linux-x64-gnu": "0.2.0",
210
+ "@withone/sdk-linux-arm64-gnu": "0.2.0",
211
+ "@withone/sdk-linux-x64-musl": "0.2.0",
212
+ "@withone/sdk-darwin-x64": "0.2.0",
213
+ "@withone/sdk-darwin-arm64": "0.2.0",
214
+ "@withone/sdk-win32-x64-msvc": "0.2.0"
215
215
  },
216
216
  "scripts": {
217
217
  "build:native": "napi build --platform --release --js native.js --dts native.d.ts --dts-header \"export type JsonValue = string | number | boolean | null | { [key: string]: JsonValue } | JsonValue[];\n\"",
218
218
  "manifest": "cargo run -p one-codegen --bin one-codegen-manifest -- ../../actions actions.manifest.json",
219
- "gen": "pnpm run manifest && tsx scripts/gen-actions.ts",
219
+ "gen": "pnpm run manifest && tsx scripts/gen-actions.ts && tsx scripts/gen-webhooks.ts",
220
220
  "build:ts": "tsup",
221
221
  "build": "pnpm run build:native && pnpm run gen && pnpm run build:ts",
222
222
  "pretest": "pnpm run build:native && pnpm run gen",