@hookieai/node 0.0.0-stage → 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/CHANGELOG.md +7 -0
- package/README.md +161 -2
- package/admin.d.ts +159 -0
- package/admin.mjs +179 -0
- package/errors.d.ts +50 -0
- package/errors.mjs +113 -0
- package/express.d.ts +8 -0
- package/express.mjs +17 -0
- package/hono.d.ts +6 -0
- package/hono.mjs +6 -0
- package/http.mjs +103 -0
- package/index.d.ts +26 -0
- package/index.mjs +41 -0
- package/ingest.d.ts +58 -0
- package/ingest.mjs +112 -0
- package/next.d.ts +6 -0
- package/next.mjs +1 -0
- package/package.json +85 -4
- package/receiver.d.ts +10 -0
- package/receiver.mjs +66 -0
- package/verify.d.ts +57 -0
- package/verify.mjs +309 -0
package/errors.mjs
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// @hookieai/node: the error model (#471).
|
|
2
|
+
//
|
|
3
|
+
// Every failure the SDK raises is a HookieError carrying what Hookie answered
|
|
4
|
+
// (status, the machine `reason` where there is one, `retryAfter`, the parsed
|
|
5
|
+
// body), so a caller branches on a class or a code, never on message text.
|
|
6
|
+
// Web-standard only: nothing here touches a Node API.
|
|
7
|
+
|
|
8
|
+
export class HookieError extends Error {
|
|
9
|
+
/**
|
|
10
|
+
* @param {string} message
|
|
11
|
+
* @param {{ status?: number, reason?: string, retryAfter?: number, body?: unknown, cause?: unknown, idempotencyKey?: string }} [info]
|
|
12
|
+
*/
|
|
13
|
+
constructor(message, info = {}) {
|
|
14
|
+
super(message, info.cause !== undefined ? { cause: info.cause } : undefined);
|
|
15
|
+
this.name = "HookieError";
|
|
16
|
+
/** HTTP status; 0 when no answer arrived (network error, timeout, abort). */
|
|
17
|
+
this.status = info.status ?? 0;
|
|
18
|
+
/** Hookie's machine reason (`quota_exceeded`, `form_invalid`, `workspace_suspended`, ...), when it sent one. */
|
|
19
|
+
this.reason = info.reason;
|
|
20
|
+
/** Seconds to wait, from a 429. */
|
|
21
|
+
this.retryAfter = info.retryAfter;
|
|
22
|
+
/** The parsed JSON body (or null). */
|
|
23
|
+
this.body = info.body ?? null;
|
|
24
|
+
/** The idempotency key the request carried, so a caller can retry it by hand. */
|
|
25
|
+
this.idempotencyKey = info.idempotencyKey;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** No answer: DNS, TLS, a reset connection, a timeout or an abort. `reason` is `timeout` or `aborted` for the last two. */
|
|
30
|
+
export class HookieNetworkError extends HookieError {
|
|
31
|
+
constructor(message, info) {
|
|
32
|
+
super(message, info);
|
|
33
|
+
this.name = "HookieNetworkError";
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/** 401 or 403: a missing, wrong, revoked or under-scoped credential, a refused origin, a suspended workspace. */
|
|
37
|
+
export class HookieAuthError extends HookieError {
|
|
38
|
+
constructor(message, info) {
|
|
39
|
+
super(message, info);
|
|
40
|
+
this.name = "HookieAuthError";
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** 400 or 422 (or 413, 415): the request itself is wrong. `fieldErrors` is set for a form endpoint's 422. */
|
|
44
|
+
export class HookieValidationError extends HookieError {
|
|
45
|
+
constructor(message, info = {}) {
|
|
46
|
+
super(message, info);
|
|
47
|
+
this.name = "HookieValidationError";
|
|
48
|
+
this.fieldErrors = info.fieldErrors;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/** 404. */
|
|
52
|
+
export class HookieNotFoundError extends HookieError {
|
|
53
|
+
constructor(message, info) {
|
|
54
|
+
super(message, info);
|
|
55
|
+
this.name = "HookieNotFoundError";
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/** 409: a conflict, or an idempotent request that is still running. */
|
|
59
|
+
export class HookieConflictError extends HookieError {
|
|
60
|
+
constructor(message, info) {
|
|
61
|
+
super(message, info);
|
|
62
|
+
this.name = "HookieConflictError";
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/** 429. `reason === "quota_exceeded"` is the monthly plan quota (retrying will not help); otherwise a burst limit. */
|
|
66
|
+
export class HookieRateLimitError extends HookieError {
|
|
67
|
+
constructor(message, info) {
|
|
68
|
+
super(message, info);
|
|
69
|
+
this.name = "HookieRateLimitError";
|
|
70
|
+
}
|
|
71
|
+
get isQuota() {
|
|
72
|
+
return this.reason === "quota_exceeded";
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/** 5xx. */
|
|
76
|
+
export class HookieServerError extends HookieError {
|
|
77
|
+
constructor(message, info) {
|
|
78
|
+
super(message, info);
|
|
79
|
+
this.name = "HookieServerError";
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Why a received webhook was refused. One of:
|
|
85
|
+
* missing_headers, malformed_signature, bad_timestamp, timestamp_too_old,
|
|
86
|
+
* timestamp_too_new, no_valid_signature, replayed, bad_secret.
|
|
87
|
+
*/
|
|
88
|
+
export class HookieSignatureError extends Error {
|
|
89
|
+
/** @param {string} reason @param {string} message */
|
|
90
|
+
constructor(reason, message) {
|
|
91
|
+
super(message);
|
|
92
|
+
this.name = "HookieSignatureError";
|
|
93
|
+
this.reason = reason;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** The right HookieError subclass for a non-2xx answer. */
|
|
98
|
+
export function errorFromResponse(status, body, headers, idempotencyKey) {
|
|
99
|
+
const retryHeader = Number(headers?.get?.("Retry-After"));
|
|
100
|
+
const retryAfter = Number.isFinite(retryHeader) && retryHeader > 0 ? retryHeader : typeof body?.retry_after === "number" ? body.retry_after : undefined;
|
|
101
|
+
const message = typeof body?.error === "string" && body.error ? body.error : `Hookie answered ${status}.`;
|
|
102
|
+
/** @type {any} */
|
|
103
|
+
const info = { status, reason: typeof body?.reason === "string" ? body.reason : undefined, retryAfter, body, idempotencyKey };
|
|
104
|
+
if (Array.isArray(body?.fields)) {
|
|
105
|
+
info.fieldErrors = Object.fromEntries(body.fields.filter((f) => f && typeof f.name === "string").map((f) => [f.name, String(f.error)]));
|
|
106
|
+
}
|
|
107
|
+
if (status === 401 || status === 403) return new HookieAuthError(message, info);
|
|
108
|
+
if (status === 404) return new HookieNotFoundError(message, info);
|
|
109
|
+
if (status === 409) return new HookieConflictError(message, info);
|
|
110
|
+
if (status === 429) return new HookieRateLimitError(message, info);
|
|
111
|
+
if (status >= 500) return new HookieServerError(message, info);
|
|
112
|
+
return new HookieValidationError(message, info);
|
|
113
|
+
}
|
package/express.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Headerish } from "./verify.js";
|
|
2
|
+
import type { EventHandler, ReceiverOptions } from "./receiver.js";
|
|
3
|
+
|
|
4
|
+
export type { EventHandler, ReceiverOptions } from "./receiver.js";
|
|
5
|
+
|
|
6
|
+
/** Mount after express.raw(). A valid JSON event returns 204 after onEvent resolves. */
|
|
7
|
+
export function createWebhookHandler(secret: string | readonly string[], onEvent: EventHandler, options?: ReceiverOptions):
|
|
8
|
+
(req: { body?: unknown; headers: Headerish }, res: { sendStatus(status: number): unknown }, next: (error: unknown) => void) => Promise<void>;
|
package/express.mjs
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { createReceiver } from "./receiver.mjs";
|
|
2
|
+
|
|
3
|
+
export function createWebhookHandler(secret, onEvent, options) {
|
|
4
|
+
const { receive } = createReceiver(secret, onEvent, options);
|
|
5
|
+
return async (req, res, next) => {
|
|
6
|
+
try {
|
|
7
|
+
// express.raw() leaves body undefined for an empty request.
|
|
8
|
+
const bytes = req.body === undefined ? new Uint8Array() : req.body;
|
|
9
|
+
if (!(bytes instanceof Uint8Array)) {
|
|
10
|
+
throw new TypeError("Mount express.raw() before the webhook handler and before express.json().");
|
|
11
|
+
}
|
|
12
|
+
res.sendStatus(await receive(bytes, req.headers));
|
|
13
|
+
} catch (error) {
|
|
14
|
+
next(error);
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
}
|
package/hono.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { EventHandler, ReceiverOptions } from "./receiver.js";
|
|
2
|
+
export type { EventHandler, ReceiverOptions } from "./receiver.js";
|
|
3
|
+
|
|
4
|
+
/** Register with app.post(). Expects the original unread c.req.raw Request. */
|
|
5
|
+
export function createWebhookHandler(secret: string | readonly string[], onEvent: EventHandler, options?: ReceiverOptions):
|
|
6
|
+
(context: { req: { raw: Request } }) => Promise<Response>;
|
package/hono.mjs
ADDED
package/http.mjs
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// @hookieai/node: the one request loop (#471).
|
|
2
|
+
//
|
|
3
|
+
// fetch + AbortController + setTimeout + crypto.randomUUID: all present in
|
|
4
|
+
// Node 22+, Workers, Deno and Bun. Retries are bounded and only for requests
|
|
5
|
+
// that are safe to repeat: a GET, or a POST carrying an Idempotency-Key (the
|
|
6
|
+
// same key is sent on every attempt, so Hookie stores or runs it once).
|
|
7
|
+
|
|
8
|
+
import { HookieError, HookieNetworkError, errorFromResponse } from "./errors.mjs";
|
|
9
|
+
|
|
10
|
+
export const DEFAULT_BASE_URL = "https://app.hookie.ai";
|
|
11
|
+
const DEFAULT_RETRIES = 2;
|
|
12
|
+
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
13
|
+
const MAX_RETRY_WAIT_MS = 10_000;
|
|
14
|
+
|
|
15
|
+
export const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
16
|
+
|
|
17
|
+
export function newIdempotencyKey(prefix = "sdk") {
|
|
18
|
+
const c = globalThis.crypto;
|
|
19
|
+
if (c && typeof c.randomUUID === "function") return `${prefix}-${c.randomUUID()}`;
|
|
20
|
+
const bytes = new Uint8Array(16);
|
|
21
|
+
c.getRandomValues(bytes);
|
|
22
|
+
return `${prefix}-${[...bytes].map((b) => b.toString(16).padStart(2, "0")).join("")}`;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function normalizeBaseUrl(url) {
|
|
26
|
+
const u = new URL(url ?? DEFAULT_BASE_URL);
|
|
27
|
+
if (u.protocol !== "https:" && !(u.protocol === "http:" && /^(localhost|127\.0\.0\.1|\[::1\])$/.test(u.hostname))) {
|
|
28
|
+
throw new HookieError(`baseUrl must be https (or http on localhost), got ${u.protocol}//${u.host}`);
|
|
29
|
+
}
|
|
30
|
+
return u.origin;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* @param {{ fetch?: typeof fetch, retries?: number, timeoutMs?: number, userAgent?: string }} config
|
|
35
|
+
* @param {{ method: string, url: string, headers?: Record<string,string>, body?: BodyInit | null, signal?: AbortSignal,
|
|
36
|
+
* idempotencyKey?: string, retries?: number, timeoutMs?: number, onRetry?: (info: { attempt: number, status: number, waitMs: number }) => void }} req
|
|
37
|
+
* @returns {Promise<{ status: number, headers: Headers, body: any }>}
|
|
38
|
+
*/
|
|
39
|
+
export async function send(config, req) {
|
|
40
|
+
const fetcher = req.fetch ?? config.fetch ?? globalThis.fetch;
|
|
41
|
+
if (typeof fetcher !== "function") throw new HookieError("No fetch available: pass { fetch } in the client options.");
|
|
42
|
+
const retries = req.retries ?? config.retries ?? DEFAULT_RETRIES;
|
|
43
|
+
const timeoutMs = req.timeoutMs ?? config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
44
|
+
const repeatable = req.method === "GET" || req.method === "HEAD" || Boolean(req.idempotencyKey);
|
|
45
|
+
const headers = { Accept: "application/json", ...req.headers };
|
|
46
|
+
if (req.idempotencyKey) headers["Idempotency-Key"] = req.idempotencyKey;
|
|
47
|
+
if (config.userAgent) headers["User-Agent"] = config.userAgent;
|
|
48
|
+
|
|
49
|
+
for (let attempt = 0; ; attempt++) {
|
|
50
|
+
const timeout = new AbortController();
|
|
51
|
+
const timer = setTimeout(() => timeout.abort(), timeoutMs);
|
|
52
|
+
const onAbort = () => timeout.abort();
|
|
53
|
+
req.signal?.addEventListener("abort", onAbort, { once: true });
|
|
54
|
+
if (req.signal?.aborted) timeout.abort();
|
|
55
|
+
let res;
|
|
56
|
+
let text;
|
|
57
|
+
try {
|
|
58
|
+
res = await fetcher(req.url, { method: req.method, headers, body: req.body ?? undefined, signal: timeout.signal });
|
|
59
|
+
// Keep timeout and caller cancellation active until the body completes.
|
|
60
|
+
// A broken body is a transport failure even when its headers said 201.
|
|
61
|
+
text = await res.text();
|
|
62
|
+
} catch (err) {
|
|
63
|
+
clearTimeout(timer);
|
|
64
|
+
req.signal?.removeEventListener("abort", onAbort);
|
|
65
|
+
if (req.signal?.aborted) throw new HookieNetworkError("The request was aborted.", { reason: "aborted", cause: err, idempotencyKey: req.idempotencyKey });
|
|
66
|
+
const timedOut = timeout.signal.aborted;
|
|
67
|
+
if (repeatable && attempt < retries) {
|
|
68
|
+
await backoff(req, attempt, 0, null);
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
throw new HookieNetworkError(timedOut ? `No answer from Hookie within ${timeoutMs} ms.` : "Could not reach Hookie.", {
|
|
72
|
+
reason: timedOut ? "timeout" : "network",
|
|
73
|
+
cause: err,
|
|
74
|
+
idempotencyKey: req.idempotencyKey,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
clearTimeout(timer);
|
|
78
|
+
req.signal?.removeEventListener("abort", onAbort);
|
|
79
|
+
let body = null;
|
|
80
|
+
if (text) {
|
|
81
|
+
try {
|
|
82
|
+
body = JSON.parse(text);
|
|
83
|
+
} catch {
|
|
84
|
+
body = { raw: text };
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
if (res.ok) return { status: res.status, headers: res.headers, body };
|
|
88
|
+
// 5xx and a BURST 429 are worth another try; the monthly quota 429 is not.
|
|
89
|
+
const retryable = res.status >= 500 || (res.status === 429 && body?.reason !== "quota_exceeded" && !body?.upgrade_url);
|
|
90
|
+
if (repeatable && retryable && attempt < retries) {
|
|
91
|
+
await backoff(req, attempt, res.status, res.headers);
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
throw errorFromResponse(res.status, body, res.headers, req.idempotencyKey);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function backoff(req, attempt, status, headers) {
|
|
99
|
+
const retryAfter = Number(headers?.get?.("Retry-After"));
|
|
100
|
+
const waitMs = Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter * 1000, MAX_RETRY_WAIT_MS) : Math.min(400 * 2 ** attempt, MAX_RETRY_WAIT_MS);
|
|
101
|
+
req.onRetry?.({ attempt: attempt + 1, status, waitMs });
|
|
102
|
+
await sleep(waitMs);
|
|
103
|
+
}
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { HookieAdmin } from "./admin.js";
|
|
2
|
+
import type { HookieIngest, ClientOptions } from "./ingest.js";
|
|
3
|
+
|
|
4
|
+
export * from "./errors.js";
|
|
5
|
+
export * from "./verify.js";
|
|
6
|
+
export * from "./ingest.js";
|
|
7
|
+
export * from "./admin.js";
|
|
8
|
+
|
|
9
|
+
export const VERSION: string;
|
|
10
|
+
|
|
11
|
+
export interface HookieOptions extends ClientOptions {
|
|
12
|
+
/** `ik_live_...`: enables `hookie.ingest`. */
|
|
13
|
+
ingestKey?: string;
|
|
14
|
+
/** The ingest key's signing secret, if it requires signed requests. */
|
|
15
|
+
signingSecret?: string;
|
|
16
|
+
/** `hk_...`: enables `hookie.admin`. */
|
|
17
|
+
apiKey?: string;
|
|
18
|
+
projectId?: string;
|
|
19
|
+
hookieVersion?: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export class Hookie {
|
|
23
|
+
constructor(options?: HookieOptions);
|
|
24
|
+
readonly ingest: HookieIngest;
|
|
25
|
+
readonly admin: HookieAdmin;
|
|
26
|
+
}
|
package/index.mjs
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// @hookieai/node (#471): ingest, verify and manage Hookie from a server, a
|
|
2
|
+
// Worker, Deno or Bun. Zero dependencies, no Node-only API anywhere in the core
|
|
3
|
+
// (fetch, WebCrypto, URL, AbortController, TextEncoder).
|
|
4
|
+
//
|
|
5
|
+
// import { Hookie, verifyWebhook } from "@hookieai/node";
|
|
6
|
+
//
|
|
7
|
+
// Receivers that only verify can import "@hookieai/node/verify" and load
|
|
8
|
+
// nothing else.
|
|
9
|
+
|
|
10
|
+
import { HookieAdmin } from "./admin.mjs";
|
|
11
|
+
import { HookieIngest } from "./ingest.mjs";
|
|
12
|
+
import { HookieError } from "./errors.mjs";
|
|
13
|
+
|
|
14
|
+
export * from "./errors.mjs";
|
|
15
|
+
export { HookieIngest, sendToEndpoint } from "./ingest.mjs";
|
|
16
|
+
export { HookieAdmin, OPERATIONS } from "./admin.mjs";
|
|
17
|
+
export { verifyWebhook, safeVerifyWebhook, createMemoryReplayStore, signHookieBody, standardWebhooksKey, DEFAULT_TOLERANCE_SECONDS } from "./verify.mjs";
|
|
18
|
+
|
|
19
|
+
export const VERSION = "0.1.0";
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* One handle for both planes: `new Hookie({ ingestKey, apiKey })`.
|
|
23
|
+
* `hookie.ingest` needs an `ik_live_...` key; `hookie.admin` needs an `hk_...` API key.
|
|
24
|
+
* Either may be omitted; using the missing one throws a clear HookieError.
|
|
25
|
+
*/
|
|
26
|
+
export class Hookie {
|
|
27
|
+
/** @param {import("./index.d.ts").HookieOptions} [options] */
|
|
28
|
+
constructor(options = {}) {
|
|
29
|
+
const shared = { baseUrl: options.baseUrl, fetch: options.fetch, retries: options.retries, timeoutMs: options.timeoutMs, userAgent: options.userAgent };
|
|
30
|
+
this._ingest = options.ingestKey ? new HookieIngest({ ...shared, ingestKey: options.ingestKey, signingSecret: options.signingSecret }) : null;
|
|
31
|
+
this._admin = options.apiKey ? new HookieAdmin({ ...shared, apiKey: options.apiKey, projectId: options.projectId, hookieVersion: options.hookieVersion }) : null;
|
|
32
|
+
}
|
|
33
|
+
get ingest() {
|
|
34
|
+
if (!this._ingest) throw new HookieError("No ingestKey: new Hookie({ ingestKey: 'ik_live_...' }) to send events.");
|
|
35
|
+
return this._ingest;
|
|
36
|
+
}
|
|
37
|
+
get admin() {
|
|
38
|
+
if (!this._admin) throw new HookieError("No apiKey: new Hookie({ apiKey: 'hk_...' }) to manage a workspace.");
|
|
39
|
+
return this._admin;
|
|
40
|
+
}
|
|
41
|
+
}
|
package/ingest.d.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
export interface ClientOptions {
|
|
2
|
+
/** Default https://app.hookie.ai. https only (http on localhost). */
|
|
3
|
+
baseUrl?: string;
|
|
4
|
+
/** For tests and runtimes without a global fetch. */
|
|
5
|
+
fetch?: typeof fetch;
|
|
6
|
+
/** Retries on a network error, a 5xx or a burst 429, with the same Idempotency-Key. Default 2. */
|
|
7
|
+
retries?: number;
|
|
8
|
+
/** Per attempt. Default 30000. */
|
|
9
|
+
timeoutMs?: number;
|
|
10
|
+
userAgent?: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface IngestClientOptions extends ClientOptions {
|
|
14
|
+
/** An `ik_live_...` ingest key. */
|
|
15
|
+
ingestKey?: string;
|
|
16
|
+
/** The key's signing secret, when it requires signed requests: adds X-Hookie-Signature. */
|
|
17
|
+
signingSecret?: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface SendOptions {
|
|
21
|
+
/** Reuse to make your own retry of the same event idempotent. Default: a new one per call, reused on the SDK's retries. */
|
|
22
|
+
idempotencyKey?: string;
|
|
23
|
+
/** Default application/json for objects, text/plain for strings. */
|
|
24
|
+
contentType?: string;
|
|
25
|
+
headers?: Record<string, string>;
|
|
26
|
+
signal?: AbortSignal;
|
|
27
|
+
retries?: number;
|
|
28
|
+
timeoutMs?: number;
|
|
29
|
+
signingSecret?: string;
|
|
30
|
+
onRetry?: (info: { attempt: number; status: number; waitMs: number }) => void;
|
|
31
|
+
/** Overrides the client's fetch / baseUrl-independent settings for this call only (endpoint sends). */
|
|
32
|
+
fetch?: typeof fetch;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface IngestResult {
|
|
36
|
+
status: number;
|
|
37
|
+
submissionId: string | null;
|
|
38
|
+
/** Hookie had already stored this idempotency key. */
|
|
39
|
+
duplicate: boolean;
|
|
40
|
+
/** Names of the rules/datasets the event was routed to. */
|
|
41
|
+
routed: string[];
|
|
42
|
+
records?: number;
|
|
43
|
+
idempotencyKey: string;
|
|
44
|
+
/** The response body as Hookie sent it. */
|
|
45
|
+
raw: Record<string, unknown>;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function sendToEndpoint(url: string, payload: unknown, opts?: SendOptions & ClientOptions): Promise<IngestResult>;
|
|
49
|
+
|
|
50
|
+
export class HookieIngest {
|
|
51
|
+
constructor(options?: IngestClientOptions);
|
|
52
|
+
send(payload: unknown, opts?: SendOptions & { dataset?: string; ingestKey?: string }): Promise<IngestResult>;
|
|
53
|
+
sendToEndpoint(url: string, payload: unknown, opts?: SendOptions): Promise<IngestResult>;
|
|
54
|
+
sendMany(
|
|
55
|
+
payloads: readonly unknown[],
|
|
56
|
+
opts?: Omit<SendOptions, "idempotencyKey"> & { dataset?: string; concurrency?: number }
|
|
57
|
+
): Promise<Array<{ ok: true; result: IngestResult } | { ok: false; error: unknown }>>;
|
|
58
|
+
}
|
package/ingest.mjs
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// @hookieai/node: the ingest client (#471).
|
|
2
|
+
//
|
|
3
|
+
// POST /v1/ingest/{ingest_key}[/{dataset}] an `ik_live_...` ingest key
|
|
4
|
+
// POST {workspace}/{project}/{slug} an endpoint's public URL, which is its own credential
|
|
5
|
+
//
|
|
6
|
+
// One Idempotency-Key per call, reused on every retry, so a flaky network or a
|
|
7
|
+
// retried job stores ONE event. A 200 (instead of 201) means Hookie had already
|
|
8
|
+
// stored that key and answered with the first submission's id.
|
|
9
|
+
|
|
10
|
+
import { HookieError } from "./errors.mjs";
|
|
11
|
+
import { DEFAULT_BASE_URL, newIdempotencyKey, normalizeBaseUrl, send } from "./http.mjs";
|
|
12
|
+
import { signHookieBody } from "./verify.mjs";
|
|
13
|
+
|
|
14
|
+
const enc = new TextEncoder();
|
|
15
|
+
|
|
16
|
+
/** @returns {{ body: string | Uint8Array, contentType: string }} */
|
|
17
|
+
function encodePayload(payload, contentType) {
|
|
18
|
+
if (typeof payload === "string") return { body: payload, contentType: contentType ?? "text/plain; charset=utf-8" };
|
|
19
|
+
if (payload instanceof Uint8Array) return { body: payload, contentType: contentType ?? "application/octet-stream" };
|
|
20
|
+
if (payload === undefined) throw new TypeError("payload is required (use null for an explicit JSON null).");
|
|
21
|
+
return { body: JSON.stringify(payload), contentType: contentType ?? "application/json" };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function toResult(res, key) {
|
|
25
|
+
const b = res.body ?? {};
|
|
26
|
+
return {
|
|
27
|
+
status: res.status,
|
|
28
|
+
submissionId: b.submission_id ?? null,
|
|
29
|
+
/** True when Hookie had already stored this idempotency key (nothing was stored or counted again). */
|
|
30
|
+
duplicate: res.status === 200 || b.idempotent === true,
|
|
31
|
+
routed: Array.isArray(b.routed) ? b.routed : [],
|
|
32
|
+
records: typeof b.records === "number" ? b.records : undefined,
|
|
33
|
+
idempotencyKey: key,
|
|
34
|
+
raw: b,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function post(config, url, payload, opts = {}, extraHeaders = {}) {
|
|
39
|
+
const key = opts.idempotencyKey ?? newIdempotencyKey();
|
|
40
|
+
const { body, contentType } = encodePayload(payload, opts.contentType);
|
|
41
|
+
const headers = { "Content-Type": contentType, ...extraHeaders, ...opts.headers };
|
|
42
|
+
if (opts.signingSecret ?? config.signingSecret) {
|
|
43
|
+
headers["X-Hookie-Signature"] = await signHookieBody(opts.signingSecret ?? config.signingSecret, body);
|
|
44
|
+
}
|
|
45
|
+
const res = await send(config, { method: "POST", url, headers, body, signal: opts.signal, idempotencyKey: key, retries: opts.retries, timeoutMs: opts.timeoutMs, onRetry: opts.onRetry });
|
|
46
|
+
return toResult(res, key);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Send one event to an endpoint's public URL (the high-entropy slug is the credential).
|
|
51
|
+
* @param {string} url
|
|
52
|
+
* @param {unknown} payload an object (sent as JSON), a string, or bytes
|
|
53
|
+
* @param {import("./ingest.d.ts").SendOptions} [opts]
|
|
54
|
+
*/
|
|
55
|
+
export async function sendToEndpoint(url, payload, opts = {}) {
|
|
56
|
+
const u = new URL(url);
|
|
57
|
+
if (u.protocol !== "https:" && u.hostname !== "localhost" && u.hostname !== "127.0.0.1") throw new HookieError("An endpoint URL must be https.");
|
|
58
|
+
return post(opts, u.href, payload, opts);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export class HookieIngest {
|
|
62
|
+
/** @param {import("./ingest.d.ts").IngestClientOptions} [options] */
|
|
63
|
+
constructor(options = {}) {
|
|
64
|
+
this.config = { ...options, baseUrl: normalizeBaseUrl(options.baseUrl ?? DEFAULT_BASE_URL) };
|
|
65
|
+
this.ingestKey = options.ingestKey;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* POST /v1/ingest/{key}[/{dataset}]. Without a dataset the project's mapping rules route it.
|
|
70
|
+
* @param {unknown} payload
|
|
71
|
+
* @param {import("./ingest.d.ts").SendOptions & { dataset?: string }} [opts]
|
|
72
|
+
*/
|
|
73
|
+
async send(payload, opts = {}) {
|
|
74
|
+
const key = opts.ingestKey ?? this.ingestKey;
|
|
75
|
+
if (!key) throw new HookieError("An ingest key is required: new HookieIngest({ ingestKey: 'ik_live_...' }).");
|
|
76
|
+
if (opts.dataset !== undefined && !/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(opts.dataset)) throw new HookieError(`Not a valid dataset name: ${opts.dataset}`);
|
|
77
|
+
const path = `/v1/ingest/${encodeURIComponent(key)}${opts.dataset ? `/${opts.dataset}` : ""}`;
|
|
78
|
+
return post(this.config, this.config.baseUrl + path, payload, opts);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Send to an endpoint URL with this client's retry, timeout and fetch settings. */
|
|
82
|
+
async sendToEndpoint(url, payload, opts = {}) {
|
|
83
|
+
return sendToEndpoint(url, payload, { ...this.config, ...opts });
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Send several events, up to `concurrency` at a time. Resolves one `{ ok, result | error }` per payload, in order. */
|
|
87
|
+
async sendMany(payloads, opts = {}) {
|
|
88
|
+
// One key per payload: a shared key would store only the first.
|
|
89
|
+
const { concurrency: c, idempotencyKey: _ignored, ...perSend } = opts;
|
|
90
|
+
opts = perSend;
|
|
91
|
+
const concurrency = Math.max(1, c ?? 5);
|
|
92
|
+
const out = new Array(payloads.length);
|
|
93
|
+
let next = 0;
|
|
94
|
+
const worker = async () => {
|
|
95
|
+
while (next < payloads.length) {
|
|
96
|
+
const i = next++;
|
|
97
|
+
try {
|
|
98
|
+
out[i] = { ok: true, result: await this.send(payloads[i], opts) };
|
|
99
|
+
} catch (error) {
|
|
100
|
+
out[i] = { ok: false, error };
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, payloads.length) }, worker));
|
|
105
|
+
return out;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// EXTENSION POINT (#468 delivery controls, #469 transforms): ingest-side
|
|
110
|
+
// options for those features are added to SendOptions / IngestClientOptions in
|
|
111
|
+
// ingest.d.ts once their API shapes are decided in their own issues. Nothing is
|
|
112
|
+
// reserved here on their behalf.
|
package/next.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { EventHandler, ReceiverOptions } from "./receiver.js";
|
|
2
|
+
export type { EventHandler, ReceiverOptions } from "./receiver.js";
|
|
3
|
+
|
|
4
|
+
/** Export as POST in a Next.js App Router route. Expects an unread Request. */
|
|
5
|
+
export function createWebhookHandler(secret: string | readonly string[], onEvent: EventHandler, options?: ReceiverOptions):
|
|
6
|
+
(request: Request) => Promise<Response>;
|
package/next.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { createFetchHandler as createWebhookHandler } from "./receiver.mjs";
|
package/package.json
CHANGED
|
@@ -1,6 +1,87 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hookieai/node",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Send events to Hookie, verify the webhooks it delivers (Hookie-Signature and Standard Webhooks) and manage your workspace. Zero dependencies; Node 22+, Cloudflare Workers, Deno and Bun.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "index.mjs",
|
|
8
|
+
"types": "index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./index.d.ts",
|
|
12
|
+
"default": "./index.mjs"
|
|
13
|
+
},
|
|
14
|
+
"./verify": {
|
|
15
|
+
"types": "./verify.d.ts",
|
|
16
|
+
"default": "./verify.mjs"
|
|
17
|
+
},
|
|
18
|
+
"./package.json": "./package.json",
|
|
19
|
+
"./express": {
|
|
20
|
+
"types": "./express.d.ts",
|
|
21
|
+
"default": "./express.mjs"
|
|
22
|
+
},
|
|
23
|
+
"./hono": {
|
|
24
|
+
"types": "./hono.d.ts",
|
|
25
|
+
"default": "./hono.mjs"
|
|
26
|
+
},
|
|
27
|
+
"./next": {
|
|
28
|
+
"types": "./next.d.ts",
|
|
29
|
+
"default": "./next.mjs"
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
"files": [
|
|
33
|
+
"index.mjs",
|
|
34
|
+
"index.d.ts",
|
|
35
|
+
"errors.mjs",
|
|
36
|
+
"errors.d.ts",
|
|
37
|
+
"http.mjs",
|
|
38
|
+
"ingest.mjs",
|
|
39
|
+
"ingest.d.ts",
|
|
40
|
+
"verify.mjs",
|
|
41
|
+
"verify.d.ts",
|
|
42
|
+
"admin.mjs",
|
|
43
|
+
"admin.d.ts",
|
|
44
|
+
"README.md",
|
|
45
|
+
"CHANGELOG.md",
|
|
46
|
+
"receiver.mjs",
|
|
47
|
+
"receiver.d.ts",
|
|
48
|
+
"express.mjs",
|
|
49
|
+
"express.d.ts",
|
|
50
|
+
"hono.mjs",
|
|
51
|
+
"hono.d.ts",
|
|
52
|
+
"next.mjs",
|
|
53
|
+
"next.d.ts"
|
|
54
|
+
],
|
|
55
|
+
"sideEffects": false,
|
|
56
|
+
"engines": {
|
|
57
|
+
"node": ">=22"
|
|
58
|
+
},
|
|
59
|
+
"publishConfig": {
|
|
60
|
+
"access": "public"
|
|
61
|
+
},
|
|
62
|
+
"homepage": "https://docs.hookie.ai/sdk",
|
|
63
|
+
"keywords": [
|
|
64
|
+
"webhooks",
|
|
65
|
+
"webhook-verification",
|
|
66
|
+
"standard-webhooks",
|
|
67
|
+
"signature",
|
|
68
|
+
"ingest",
|
|
69
|
+
"hookie",
|
|
70
|
+
"edge",
|
|
71
|
+
"cloudflare-workers",
|
|
72
|
+
"deno",
|
|
73
|
+
"bun",
|
|
74
|
+
"mcp",
|
|
75
|
+
"ai-agent"
|
|
76
|
+
],
|
|
77
|
+
"repository": {
|
|
78
|
+
"type": "git",
|
|
79
|
+
"url": "git+https://github.com/bcusack1996/Hookie-Docs.git"
|
|
80
|
+
},
|
|
81
|
+
"bugs": "https://hookie.ai/contact",
|
|
82
|
+
"scripts": {
|
|
83
|
+
"test": "node --test",
|
|
84
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
85
|
+
"pack:check": "npm pack --dry-run"
|
|
86
|
+
}
|
|
87
|
+
}
|
package/receiver.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { VerifiedWebhook, VerifyOptions } from "./verify.js";
|
|
2
|
+
|
|
3
|
+
export interface ReceiverOptions extends VerifyOptions {
|
|
4
|
+
/** Default "standard". Select "hookie" explicitly for Hookie-Signature-only senders. */
|
|
5
|
+
scheme?: VerifyOptions["scheme"];
|
|
6
|
+
/** Maximum raw body size, in bytes. Defaults to 1 MiB. */
|
|
7
|
+
maxBodyBytes?: number;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export type EventHandler = (event: unknown, delivery: VerifiedWebhook) => void | Promise<void>;
|