@aniket-lodh/veyra-sdk 0.1.1 → 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.
Files changed (50) hide show
  1. package/README.md +205 -116
  2. package/dist/cjs/client.d.ts +204 -0
  3. package/dist/cjs/client.js +647 -0
  4. package/dist/cjs/errors.d.ts +147 -0
  5. package/dist/cjs/errors.js +262 -0
  6. package/dist/cjs/handlers.d.ts +165 -0
  7. package/dist/cjs/handlers.js +46 -0
  8. package/dist/cjs/index.d.ts +15 -0
  9. package/dist/cjs/index.js +37 -0
  10. package/dist/cjs/package.json +3 -0
  11. package/dist/cjs/standard-schema.d.ts +86 -0
  12. package/dist/cjs/standard-schema.js +49 -0
  13. package/dist/cjs/types.d.ts +430 -0
  14. package/dist/cjs/types.js +6 -0
  15. package/dist/cjs/webhook.d.ts +98 -0
  16. package/dist/cjs/webhook.js +165 -0
  17. package/dist/cjs/worker.d.ts +101 -0
  18. package/dist/cjs/worker.js +497 -0
  19. package/dist/client.d.ts +159 -25
  20. package/dist/client.js +501 -122
  21. package/dist/errors.d.ts +123 -10
  22. package/dist/errors.js +192 -19
  23. package/dist/handlers.d.ts +165 -0
  24. package/dist/handlers.js +42 -0
  25. package/dist/index.d.ts +13 -6
  26. package/dist/index.js +12 -6
  27. package/dist/standard-schema.d.ts +86 -0
  28. package/dist/standard-schema.js +45 -0
  29. package/dist/types.d.ts +281 -36
  30. package/dist/types.js +2 -2
  31. package/dist/webhook.d.ts +98 -0
  32. package/dist/webhook.js +128 -0
  33. package/dist/worker.d.ts +80 -55
  34. package/dist/worker.js +308 -192
  35. package/package.json +21 -12
  36. package/dist/client.d.ts.map +0 -1
  37. package/dist/client.js.map +0 -1
  38. package/dist/errors.d.ts.map +0 -1
  39. package/dist/errors.js.map +0 -1
  40. package/dist/index.d.ts.map +0 -1
  41. package/dist/index.js.map +0 -1
  42. package/dist/types.d.ts.map +0 -1
  43. package/dist/types.js.map +0 -1
  44. package/dist/worker.d.ts.map +0 -1
  45. package/dist/worker.js.map +0 -1
  46. package/src/client.ts +0 -389
  47. package/src/errors.ts +0 -82
  48. package/src/index.ts +0 -8
  49. package/src/types.ts +0 -217
  50. package/src/worker.ts +0 -469
@@ -0,0 +1,165 @@
1
+ "use strict";
2
+ /**
3
+ * Typed completion webhooks: signature verification and payload parsing.
4
+ */
5
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ var desc = Object.getOwnPropertyDescriptor(m, k);
8
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
+ desc = { enumerable: true, get: function() { return m[k]; } };
10
+ }
11
+ Object.defineProperty(o, k2, desc);
12
+ }) : (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ o[k2] = m[k];
15
+ }));
16
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
17
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
18
+ }) : function(o, v) {
19
+ o["default"] = v;
20
+ });
21
+ var __importStar = (this && this.__importStar) || (function () {
22
+ var ownKeys = function(o) {
23
+ ownKeys = Object.getOwnPropertyNames || function (o) {
24
+ var ar = [];
25
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
26
+ return ar;
27
+ };
28
+ return ownKeys(o);
29
+ };
30
+ return function (mod) {
31
+ if (mod && mod.__esModule) return mod;
32
+ var result = {};
33
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
34
+ __setModuleDefault(result, mod);
35
+ return result;
36
+ };
37
+ })();
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.verifyWebhookSignature = verifyWebhookSignature;
40
+ exports.parseWebhook = parseWebhook;
41
+ const errors_js_1 = require("./errors.js");
42
+ const handlers_js_1 = require("./handlers.js");
43
+ const standard_schema_js_1 = require("./standard-schema.js");
44
+ function toBytes(body) {
45
+ if (typeof body === 'string') {
46
+ return new TextEncoder().encode(body);
47
+ }
48
+ if (body instanceof Uint8Array) {
49
+ return body;
50
+ }
51
+ if (body instanceof ArrayBuffer) {
52
+ return new Uint8Array(body);
53
+ }
54
+ if (ArrayBuffer.isView(body)) {
55
+ return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
56
+ }
57
+ throw new errors_js_1.VeyraValidationError('rawBody', [
58
+ { message: 'rawBody must be a string, Uint8Array, or ArrayBuffer' },
59
+ ]);
60
+ }
61
+ function hexToBytes(hex) {
62
+ if (hex.length % 2 !== 0 || !/^[0-9a-f]+$/i.test(hex)) {
63
+ return null;
64
+ }
65
+ const bytes = new Uint8Array(hex.length / 2);
66
+ for (let i = 0; i < bytes.length; i++) {
67
+ bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
68
+ }
69
+ return bytes;
70
+ }
71
+ async function hmacSha256(secret, data) {
72
+ const subtle = globalThis.crypto?.subtle ??
73
+ (await Promise.resolve().then(() => __importStar(require('node:crypto'))).catch(() => undefined))?.webcrypto?.subtle;
74
+ if (!subtle) {
75
+ throw new errors_js_1.VeyraWebhookError('Webhook signatures require Web Crypto (globalThis.crypto.subtle) or Node 18+ crypto.');
76
+ }
77
+ const key = await subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
78
+ return new Uint8Array(await subtle.sign('HMAC', key, data));
79
+ }
80
+ /**
81
+ * Constant-time byte comparison using Node's `crypto.timingSafeEqual` where available,
82
+ * falling back to a bitwise constant-time loop. Guards lengths first to prevent RangeError.
83
+ */
84
+ async function timingSafeEqual(a, b) {
85
+ if (a.byteLength !== b.byteLength) {
86
+ return false;
87
+ }
88
+ try {
89
+ const nodeCrypto = await Promise.resolve().then(() => __importStar(require('node:crypto')));
90
+ if (typeof nodeCrypto.timingSafeEqual === 'function') {
91
+ return nodeCrypto.timingSafeEqual(a, b);
92
+ }
93
+ }
94
+ catch {
95
+ // Non-Node environment or module unavailable; use bitwise fallback below
96
+ }
97
+ let diff = 0;
98
+ for (let i = 0; i < a.byteLength; i++) {
99
+ diff |= a[i] ^ b[i];
100
+ }
101
+ return diff === 0;
102
+ }
103
+ /**
104
+ * Verifies the `X-Veyra-Signature` header: `sha256=<hex HMAC-SHA256(rawBody)>`.
105
+ * Comparison is strictly constant-time and lengths are guarded to prevent `RangeError`.
106
+ *
107
+ * @param rawBody - Exact request body bytes (do not re-serialize JSON).
108
+ * @param signature - `X-Veyra-Signature` header value.
109
+ * @param secret - Shared secret configured as `VEYRA_CALLBACK_SECRET` on the API.
110
+ * @returns `true` when the signature matches.
111
+ *
112
+ * @example
113
+ * ```ts
114
+ * const ok = await verifyWebhookSignature(rawBody, req.headers['x-veyra-signature'], secret);
115
+ * ```
116
+ */
117
+ async function verifyWebhookSignature(rawBody, signature, secret) {
118
+ if (!signature || typeof signature !== 'string') {
119
+ return false;
120
+ }
121
+ if (!secret || typeof secret !== 'string') {
122
+ return false;
123
+ }
124
+ const separator = signature.indexOf('=');
125
+ if (separator === -1 || signature.slice(0, separator).toLowerCase() !== 'sha256') {
126
+ return false;
127
+ }
128
+ const providedHex = signature.slice(separator + 1).trim();
129
+ const providedBytes = hexToBytes(providedHex);
130
+ if (!providedBytes) {
131
+ return false;
132
+ }
133
+ const expectedBytes = await hmacSha256(secret, toBytes(rawBody));
134
+ return timingSafeEqual(expectedBytes, providedBytes);
135
+ }
136
+ async function parseWebhook(rawBody, handlerOrOptions, maybeOptions) {
137
+ const handler = (0, handlers_js_1.isHandlerDefinition)(handlerOrOptions)
138
+ ? handlerOrOptions
139
+ : undefined;
140
+ const options = (handler
141
+ ? maybeOptions
142
+ : handlerOrOptions) ?? {};
143
+ if (options.secret) {
144
+ const valid = await verifyWebhookSignature(rawBody, options.signature, options.secret);
145
+ if (!valid) {
146
+ throw new errors_js_1.VeyraWebhookError('parseWebhook: invalid or missing X-Veyra-Signature header');
147
+ }
148
+ }
149
+ const bytes = toBytes(rawBody);
150
+ const text = new TextDecoder().decode(bytes);
151
+ let event;
152
+ try {
153
+ event = JSON.parse(text);
154
+ }
155
+ catch (err) {
156
+ throw new errors_js_1.VeyraWebhookError(`parseWebhook: invalid JSON body: ${err.message}`, { cause: err });
157
+ }
158
+ if (!event || typeof event !== 'object' || event.event !== 'job.completed') {
159
+ throw new errors_js_1.VeyraWebhookError("parseWebhook: unexpected webhook payload structure (expected event='job.completed')");
160
+ }
161
+ if (handler?.result && event.result !== null && event.result !== undefined) {
162
+ event.result = await (0, standard_schema_js_1.validateWithSchema)(handler.result, event.result, `webhook('${handler.name}') result`);
163
+ }
164
+ return event;
165
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Veyra HTTP worker engine.
3
+ */
4
+ import type { VeyraClient } from './client.js';
5
+ import type { BuiltInHandlers, HandlerDefinition, HandlerName, HandlerPayloadFor, HandlerResultFor, ResolvedHandlers } from './handlers.js';
6
+ import type { HandlerFn, JobClaim, JobContext, VeyraWorkerOptions, WorkerRecord } from './types.js';
7
+ /**
8
+ * Long-polling worker that registers with Veyra, claims jobs, renews leases,
9
+ * executes handlers, and reports outcomes.
10
+ *
11
+ * @typeParam THandlers - Extra handler contracts merged over {@link BuiltInHandlers}.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * const worker = client.createWorker({ queues: ['default'] });
16
+ * worker.register(sendEmail, async (job) => ({ messageId: await send(job.payload) }));
17
+ * await worker.start();
18
+ * ```
19
+ */
20
+ export declare class VeyraWorker<THandlers extends object = BuiltInHandlers> {
21
+ #private;
22
+ /**
23
+ * @param client - Client used for API calls.
24
+ * @param options - Queues, concurrency, timings, and lifecycle callbacks.
25
+ * @throws {VeyraValidationError} When options fail validation.
26
+ */
27
+ constructor(client: VeyraClient<THandlers>, options: VeyraWorkerOptions);
28
+ /** Worker id used on every worker-protocol call. */
29
+ get workerId(): string;
30
+ /** Current lifecycle state. */
31
+ get state(): 'stopped' | 'running' | 'draining';
32
+ /** Number of jobs currently executing. */
33
+ get inFlight(): number;
34
+ /** Bound client. */
35
+ get client(): VeyraClient<THandlers>;
36
+ /** Resolved worker options. */
37
+ get options(): VeyraWorkerOptions;
38
+ /** Registered handlers map view. */
39
+ get handlers(): Map<string, HandlerFn<any, any>>;
40
+ /**
41
+ * Safe JSON representation redacting all sensitive credentials.
42
+ */
43
+ toJSON(): Record<string, unknown>;
44
+ /**
45
+ * Registers a typed handler definition.
46
+ *
47
+ * The payload is validated before the callback runs; the returned value is
48
+ * validated before completion is reported to Veyra. Both failures raise
49
+ * {@link VeyraValidationError}, which is permanent.
50
+ *
51
+ * @param definition - Definition created with `defineHandler`.
52
+ * @param handler - Callback receiving a typed payload and returning the result.
53
+ * @throws {VeyraError} When a handler with the same name is already registered.
54
+ *
55
+ * @example
56
+ * ```ts
57
+ * worker.register(sendEmail, async (job) => ({ messageId: await send(job.payload) }));
58
+ * ```
59
+ */
60
+ register<TName extends string, TPayload, TResult, TQueue extends string | undefined>(definition: HandlerDefinition<TName, TPayload, TResult, TQueue>, handler: (job: JobClaim<TPayload>, ctx: JobContext) => TResult | Promise<TResult>): this;
61
+ /**
62
+ * Registers a handler by name.
63
+ *
64
+ * Built-in and `THandlers` names get autocomplete and typed payload/result;
65
+ * arbitrary string names fall back to the supplied generics.
66
+ *
67
+ * @param name - Handler name matched against claimed jobs.
68
+ * @param handler - Callback receiving the claimed job and context.
69
+ * @throws {VeyraError} When a handler with the same name is already registered.
70
+ */
71
+ register<TPayload = unknown, TResult = unknown, const TName extends HandlerName<ResolvedHandlers<THandlers>> | (string & {}) = HandlerName<ResolvedHandlers<THandlers>> | (string & {})>(name: TName, handler: HandlerFn<HandlerPayloadFor<ResolvedHandlers<THandlers>, TName, TPayload>, HandlerResultFor<ResolvedHandlers<THandlers>, TName, TResult>>): this;
72
+ /**
73
+ * Registers a handler by name without a definition. Prefer {@link register}
74
+ * with a `defineHandler` definition for payload/result typing.
75
+ *
76
+ * @param name - Handler name matched against claimed jobs.
77
+ * @param handler - Callback receiving the claimed job and context.
78
+ * @throws {VeyraError} When a handler with the same name is already registered.
79
+ */
80
+ registerHandler<TPayload = unknown, TResult = unknown>(name: string, handler: HandlerFn<TPayload, TResult>): this;
81
+ /**
82
+ * Returns the handler names advertised at registration.
83
+ * Defaults to every registered handler when `options.handlers` is empty.
84
+ */
85
+ getEffectiveHandlers(): string[];
86
+ /**
87
+ * Registers with Veyra, starts heartbeats, and begins claiming jobs.
88
+ *
89
+ * @returns The worker record stored by the API.
90
+ * @throws {VeyraError} When already running or no handlers are registered.
91
+ */
92
+ start(): Promise<WorkerRecord>;
93
+ /**
94
+ * Stops claiming, drains in-flight jobs, cancels timers, and deregisters.
95
+ *
96
+ * @param options.timeoutMs - Maximum drain wait. Defaults to `30000`.
97
+ */
98
+ stop(options?: {
99
+ timeoutMs?: number;
100
+ }): Promise<void>;
101
+ }