@aniket-lodh/veyra-sdk 0.1.0 → 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 +209 -120
  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 -195
  35. package/package.json +27 -13
  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 -472
package/dist/errors.d.ts CHANGED
@@ -1,34 +1,147 @@
1
1
  /**
2
- * Veyra Error Classes
2
+ * Error types thrown by the Veyra SDK.
3
+ */
4
+ import type { StandardSchemaV1 } from './standard-schema.js';
5
+ /**
6
+ * Base error for every SDK failure.
3
7
  */
4
8
  export declare class VeyraError extends Error {
5
- constructor(message: string);
9
+ /** Error code identifying the failure class. */
10
+ readonly code: string;
11
+ /** Underlying cause if available. */
12
+ readonly cause?: unknown;
13
+ constructor(message: string, options?: {
14
+ code?: string;
15
+ cause?: unknown;
16
+ });
6
17
  }
18
+ /**
19
+ * A payload, result, or configuration argument did not satisfy validation rules.
20
+ * Permanent by design: retrying without fixing input cannot succeed.
21
+ */
22
+ export declare class VeyraValidationError extends VeyraError {
23
+ /** Context label, e.g. `handler 'send_email' payload`. */
24
+ readonly label: string;
25
+ /** Structured issues describing the validation failures. */
26
+ readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
27
+ /** Signals permanent failure to the Veyra worker runtime. */
28
+ readonly permanent = true;
29
+ constructor(label: string, issues: ReadonlyArray<StandardSchemaV1.Issue>, options?: {
30
+ cause?: unknown;
31
+ });
32
+ }
33
+ /** Parameters object accepted by {@link VeyraApiError}. */
34
+ export interface VeyraApiErrorParams {
35
+ status: number;
36
+ statusText: string;
37
+ message: string;
38
+ body: unknown;
39
+ requestId?: string;
40
+ retryable?: boolean;
41
+ code?: string;
42
+ cause?: unknown;
43
+ }
44
+ /**
45
+ * Non-2xx HTTP response from the Veyra API.
46
+ */
7
47
  export declare class VeyraApiError extends VeyraError {
48
+ /** HTTP status code. */
8
49
  readonly status: number;
50
+ /** HTTP status text. */
9
51
  readonly statusText: string;
52
+ /** Unique request ID assigned by Veyra API (`X-Request-Id`), if present. */
53
+ readonly requestId?: string;
54
+ /** Whether this failure is safe to retry automatically. */
55
+ readonly retryable: boolean;
56
+ /** Parsed response body or error excerpt. */
10
57
  readonly body: unknown;
11
- constructor(status: number, statusText: string, message: string, body: unknown);
58
+ constructor(statusOrParams: number | VeyraApiErrorParams, statusText?: string, message?: string, body?: unknown, options?: {
59
+ requestId?: string;
60
+ retryable?: boolean;
61
+ code?: string;
62
+ cause?: unknown;
63
+ });
12
64
  }
65
+ /** `401` or `403`: missing, invalid, or insufficiently scoped API key. */
13
66
  export declare class VeyraAuthError extends VeyraApiError {
14
- constructor(status: number, statusText: string, message: string, body: unknown);
67
+ constructor(statusOrParams: number | VeyraApiErrorParams, statusText?: string, message?: string, body?: unknown, options?: {
68
+ requestId?: string;
69
+ cause?: unknown;
70
+ });
15
71
  }
72
+ /** `404`: the requested job, worker, or resource was not found. */
16
73
  export declare class VeyraNotFoundError extends VeyraApiError {
17
- constructor(status: number, statusText: string, message: string, body: unknown);
74
+ constructor(statusOrParams: number | VeyraApiErrorParams, statusText?: string, message?: string, body?: unknown, options?: {
75
+ requestId?: string;
76
+ cause?: unknown;
77
+ });
18
78
  }
79
+ /** `409`: the request conflicts with current queue or worker state. */
19
80
  export declare class VeyraConflictError extends VeyraApiError {
20
- constructor(status: number, statusText: string, message: string, body: unknown);
81
+ constructor(statusOrParams: number | VeyraApiErrorParams, statusText?: string, message?: string, body?: unknown, options?: {
82
+ requestId?: string;
83
+ cause?: unknown;
84
+ code?: string;
85
+ });
21
86
  }
87
+ /**
88
+ * `409` caused by an expired, reclaimed, or reassigned job lease.
89
+ * The worker aborts the job's execution context signal when this is raised.
90
+ */
22
91
  export declare class LeaseLostError extends VeyraConflictError {
23
- constructor(message?: string);
92
+ constructor(message?: string, options?: {
93
+ requestId?: string;
94
+ cause?: unknown;
95
+ });
96
+ }
97
+ /** `429`: rate limit exceeded. Automatically retried when retries are enabled. */
98
+ export declare class VeyraRateLimitError extends VeyraApiError {
99
+ /** Suggested backoff in milliseconds parsed from `Retry-After` header, if provided. */
100
+ readonly retryAfterMs?: number;
101
+ constructor(statusOrParams: number | (VeyraApiErrorParams & {
102
+ retryAfterMs?: number;
103
+ }), statusText?: string, message?: string, body?: unknown, options?: {
104
+ requestId?: string;
105
+ retryAfterMs?: number;
106
+ cause?: unknown;
107
+ });
108
+ }
109
+ /** Request exceeded its timeout deadline. */
110
+ export declare class VeyraTimeoutError extends VeyraError {
111
+ /** Configured timeout in milliseconds that was exceeded. */
112
+ readonly timeoutMs: number;
113
+ /** Timeouts are safe to retry on idempotent requests. */
114
+ readonly retryable = true;
115
+ constructor(message: string, timeoutMs: number, options?: {
116
+ cause?: unknown;
117
+ });
118
+ }
119
+ /** Network-level transport error (DNS lookup failure, connection refused, connection reset). */
120
+ export declare class VeyraNetworkError extends VeyraError {
121
+ /** Network transport errors are safe to retry on idempotent requests. */
122
+ readonly retryable = true;
123
+ constructor(message: string, options?: {
124
+ cause?: unknown;
125
+ });
126
+ }
127
+ /** Webhook HMAC signature verification failure or malformed webhook payload. */
128
+ export declare class VeyraWebhookError extends VeyraError {
129
+ constructor(message: string, options?: {
130
+ cause?: unknown;
131
+ });
24
132
  }
25
133
  /**
26
- * Throwing a NonRetryableError signals to Veyra that the job should fail
27
- * permanently (dead-lettered immediately) without exhausting max attempts.
134
+ * Throw from a worker handler to fail the job permanently: no further attempts,
135
+ * the job is dead-lettered immediately.
28
136
  */
29
137
  export declare class NonRetryableError extends Error {
138
+ /** Signals permanent failure to the Veyra worker runtime. */
30
139
  readonly permanent = true;
31
140
  constructor(message: string);
32
141
  }
142
+ /**
143
+ * Returns `true` when an error asks the worker to skip retries.
144
+ * Honours {@link NonRetryableError}, {@link VeyraValidationError}, and any
145
+ * error object with `permanent: true`.
146
+ */
33
147
  export declare function isNonRetryable(err: unknown): boolean;
34
- //# sourceMappingURL=errors.d.ts.map
package/dist/errors.js CHANGED
@@ -1,59 +1,228 @@
1
1
  /**
2
- * Veyra Error Classes
2
+ * Error types thrown by the Veyra SDK.
3
+ */
4
+ function formatIssuePath(path) {
5
+ if (!path || path.length === 0) {
6
+ return '';
7
+ }
8
+ return path
9
+ .map((segment) => typeof segment === 'object' && segment !== null && 'key' in segment
10
+ ? String(segment.key)
11
+ : String(segment))
12
+ .join('.');
13
+ }
14
+ /**
15
+ * Base error for every SDK failure.
3
16
  */
4
17
  export class VeyraError extends Error {
5
- constructor(message) {
18
+ /** Error code identifying the failure class. */
19
+ code;
20
+ /** Underlying cause if available. */
21
+ cause;
22
+ constructor(message, options) {
6
23
  super(message);
7
24
  this.name = 'VeyraError';
25
+ this.code = options?.code ?? 'VEYRA_ERROR';
26
+ this.cause = options?.cause;
8
27
  Object.setPrototypeOf(this, new.target.prototype);
9
28
  }
10
29
  }
30
+ /**
31
+ * A payload, result, or configuration argument did not satisfy validation rules.
32
+ * Permanent by design: retrying without fixing input cannot succeed.
33
+ */
34
+ export class VeyraValidationError extends VeyraError {
35
+ /** Context label, e.g. `handler 'send_email' payload`. */
36
+ label;
37
+ /** Structured issues describing the validation failures. */
38
+ issues;
39
+ /** Signals permanent failure to the Veyra worker runtime. */
40
+ permanent = true;
41
+ constructor(label, issues, options) {
42
+ const detail = issues
43
+ .map((issue) => {
44
+ const path = formatIssuePath(issue.path);
45
+ return path ? `${path}: ${issue.message}` : issue.message;
46
+ })
47
+ .join('; ');
48
+ super(`${label} validation failed${detail ? `: ${detail}` : ''}`, {
49
+ code: 'VALIDATION_ERROR',
50
+ cause: options?.cause,
51
+ });
52
+ this.name = 'VeyraValidationError';
53
+ this.label = label;
54
+ this.issues = issues;
55
+ Object.setPrototypeOf(this, new.target.prototype);
56
+ }
57
+ }
58
+ /**
59
+ * Non-2xx HTTP response from the Veyra API.
60
+ */
11
61
  export class VeyraApiError extends VeyraError {
62
+ /** HTTP status code. */
12
63
  status;
64
+ /** HTTP status text. */
13
65
  statusText;
66
+ /** Unique request ID assigned by Veyra API (`X-Request-Id`), if present. */
67
+ requestId;
68
+ /** Whether this failure is safe to retry automatically. */
69
+ retryable;
70
+ /** Parsed response body or error excerpt. */
14
71
  body;
15
- constructor(status, statusText, message, body) {
16
- super(message);
17
- this.name = 'VeyraApiError';
18
- this.status = status;
19
- this.statusText = statusText;
20
- this.body = body;
72
+ constructor(statusOrParams, statusText, message, body, options) {
73
+ if (typeof statusOrParams === 'object') {
74
+ const p = statusOrParams;
75
+ super(p.message, { code: p.code ?? 'API_ERROR', cause: p.cause });
76
+ this.name = 'VeyraApiError';
77
+ this.status = p.status;
78
+ this.statusText = p.statusText;
79
+ this.body = p.body;
80
+ this.requestId = p.requestId;
81
+ this.retryable = p.retryable ?? (p.status >= 500 && p.status !== 501);
82
+ }
83
+ else {
84
+ super(message ?? `HTTP ${statusOrParams}`, {
85
+ code: options?.code ?? 'API_ERROR',
86
+ cause: options?.cause,
87
+ });
88
+ this.name = 'VeyraApiError';
89
+ this.status = statusOrParams;
90
+ this.statusText = statusText ?? '';
91
+ this.body = body;
92
+ this.requestId = options?.requestId;
93
+ this.retryable = options?.retryable ?? (statusOrParams >= 500 && statusOrParams !== 501);
94
+ }
21
95
  Object.setPrototypeOf(this, new.target.prototype);
22
96
  }
23
97
  }
98
+ /** `401` or `403`: missing, invalid, or insufficiently scoped API key. */
24
99
  export class VeyraAuthError extends VeyraApiError {
25
- constructor(status, statusText, message, body) {
26
- super(status, statusText, message, body);
100
+ constructor(statusOrParams, statusText, message, body, options) {
101
+ if (typeof statusOrParams === 'object') {
102
+ super({ ...statusOrParams, code: 'AUTH_ERROR', retryable: false });
103
+ }
104
+ else {
105
+ super(statusOrParams, statusText, message, body, {
106
+ ...options,
107
+ code: 'AUTH_ERROR',
108
+ retryable: false,
109
+ });
110
+ }
27
111
  this.name = 'VeyraAuthError';
28
112
  Object.setPrototypeOf(this, new.target.prototype);
29
113
  }
30
114
  }
115
+ /** `404`: the requested job, worker, or resource was not found. */
31
116
  export class VeyraNotFoundError extends VeyraApiError {
32
- constructor(status, statusText, message, body) {
33
- super(status, statusText, message, body);
117
+ constructor(statusOrParams, statusText, message, body, options) {
118
+ if (typeof statusOrParams === 'object') {
119
+ super({ ...statusOrParams, code: 'NOT_FOUND', retryable: false });
120
+ }
121
+ else {
122
+ super(statusOrParams, statusText, message, body, {
123
+ ...options,
124
+ code: 'NOT_FOUND',
125
+ retryable: false,
126
+ });
127
+ }
34
128
  this.name = 'VeyraNotFoundError';
35
129
  Object.setPrototypeOf(this, new.target.prototype);
36
130
  }
37
131
  }
132
+ /** `409`: the request conflicts with current queue or worker state. */
38
133
  export class VeyraConflictError extends VeyraApiError {
39
- constructor(status, statusText, message, body) {
40
- super(status, statusText, message, body);
134
+ constructor(statusOrParams, statusText, message, body, options) {
135
+ if (typeof statusOrParams === 'object') {
136
+ super({
137
+ ...statusOrParams,
138
+ code: statusOrParams.code ?? 'CONFLICT',
139
+ retryable: false,
140
+ });
141
+ }
142
+ else {
143
+ super(statusOrParams, statusText, message, body, {
144
+ ...options,
145
+ code: options?.code ?? 'CONFLICT',
146
+ retryable: false,
147
+ });
148
+ }
41
149
  this.name = 'VeyraConflictError';
42
150
  Object.setPrototypeOf(this, new.target.prototype);
43
151
  }
44
152
  }
153
+ /**
154
+ * `409` caused by an expired, reclaimed, or reassigned job lease.
155
+ * The worker aborts the job's execution context signal when this is raised.
156
+ */
45
157
  export class LeaseLostError extends VeyraConflictError {
46
- constructor(message = 'Job lease was lost or expired') {
47
- super(409, 'Conflict', message, { error: message });
158
+ constructor(message = 'Job lease was lost or expired', options) {
159
+ super(409, 'Conflict', message, { error: message }, {
160
+ requestId: options?.requestId,
161
+ cause: options?.cause,
162
+ code: 'LEASE_LOST',
163
+ });
48
164
  this.name = 'LeaseLostError';
49
165
  Object.setPrototypeOf(this, new.target.prototype);
50
166
  }
51
167
  }
168
+ /** `429`: rate limit exceeded. Automatically retried when retries are enabled. */
169
+ export class VeyraRateLimitError extends VeyraApiError {
170
+ /** Suggested backoff in milliseconds parsed from `Retry-After` header, if provided. */
171
+ retryAfterMs;
172
+ constructor(statusOrParams, statusText, message, body, options) {
173
+ if (typeof statusOrParams === 'object') {
174
+ super({ ...statusOrParams, code: 'RATE_LIMIT_EXCEEDED', retryable: true });
175
+ this.retryAfterMs = statusOrParams.retryAfterMs;
176
+ }
177
+ else {
178
+ super(statusOrParams, statusText, message, body, {
179
+ ...options,
180
+ code: 'RATE_LIMIT_EXCEEDED',
181
+ retryable: true,
182
+ });
183
+ this.retryAfterMs = options?.retryAfterMs;
184
+ }
185
+ this.name = 'VeyraRateLimitError';
186
+ Object.setPrototypeOf(this, new.target.prototype);
187
+ }
188
+ }
189
+ /** Request exceeded its timeout deadline. */
190
+ export class VeyraTimeoutError extends VeyraError {
191
+ /** Configured timeout in milliseconds that was exceeded. */
192
+ timeoutMs;
193
+ /** Timeouts are safe to retry on idempotent requests. */
194
+ retryable = true;
195
+ constructor(message, timeoutMs, options) {
196
+ super(message, { code: 'TIMEOUT', cause: options?.cause });
197
+ this.name = 'VeyraTimeoutError';
198
+ this.timeoutMs = timeoutMs;
199
+ Object.setPrototypeOf(this, new.target.prototype);
200
+ }
201
+ }
202
+ /** Network-level transport error (DNS lookup failure, connection refused, connection reset). */
203
+ export class VeyraNetworkError extends VeyraError {
204
+ /** Network transport errors are safe to retry on idempotent requests. */
205
+ retryable = true;
206
+ constructor(message, options) {
207
+ super(message, { code: 'NETWORK_ERROR', cause: options?.cause });
208
+ this.name = 'VeyraNetworkError';
209
+ Object.setPrototypeOf(this, new.target.prototype);
210
+ }
211
+ }
212
+ /** Webhook HMAC signature verification failure or malformed webhook payload. */
213
+ export class VeyraWebhookError extends VeyraError {
214
+ constructor(message, options) {
215
+ super(message, { code: 'WEBHOOK_ERROR', cause: options?.cause });
216
+ this.name = 'VeyraWebhookError';
217
+ Object.setPrototypeOf(this, new.target.prototype);
218
+ }
219
+ }
52
220
  /**
53
- * Throwing a NonRetryableError signals to Veyra that the job should fail
54
- * permanently (dead-lettered immediately) without exhausting max attempts.
221
+ * Throw from a worker handler to fail the job permanently: no further attempts,
222
+ * the job is dead-lettered immediately.
55
223
  */
56
224
  export class NonRetryableError extends Error {
225
+ /** Signals permanent failure to the Veyra worker runtime. */
57
226
  permanent = true;
58
227
  constructor(message) {
59
228
  super(message);
@@ -61,6 +230,11 @@ export class NonRetryableError extends Error {
61
230
  Object.setPrototypeOf(this, new.target.prototype);
62
231
  }
63
232
  }
233
+ /**
234
+ * Returns `true` when an error asks the worker to skip retries.
235
+ * Honours {@link NonRetryableError}, {@link VeyraValidationError}, and any
236
+ * error object with `permanent: true`.
237
+ */
64
238
  export function isNonRetryable(err) {
65
239
  if (err instanceof NonRetryableError) {
66
240
  return true;
@@ -70,4 +244,3 @@ export function isNonRetryable(err) {
70
244
  }
71
245
  return false;
72
246
  }
73
- //# sourceMappingURL=errors.js.map
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Handler contracts: built-in platform handlers, custom handler definitions,
3
+ * and the generic handler map used to type `VeyraClient` and `VeyraWorker`.
4
+ */
5
+ import type { SchemaLike } from './standard-schema.js';
6
+ import type { JsonValue } from './types.js';
7
+ /** Payload accepted by the built-in `http_request` handler. */
8
+ export interface HttpRequestPayload {
9
+ /** Absolute URL to call. Required. */
10
+ url: string;
11
+ /** HTTP method. Defaults to `POST`. */
12
+ method?: string;
13
+ /** Headers applied verbatim to the outbound request. */
14
+ headers?: Record<string, string>;
15
+ /**
16
+ * Request body. Strings are sent as-is; objects, arrays, numbers, and
17
+ * booleans are JSON-encoded by the worker.
18
+ */
19
+ body?: JsonValue;
20
+ /** Per-request timeout in seconds. Defaults to `30`, capped at `300`. */
21
+ timeoutSeconds?: number;
22
+ }
23
+ /** Result recorded for a successful `http_request` job (2xx response). */
24
+ export interface HttpRequestResult {
25
+ /** Upstream HTTP status code. */
26
+ statusCode: number;
27
+ /** Wall-clock request duration in milliseconds. */
28
+ durationMs: number;
29
+ /** Upstream `Content-Type` header, or an empty string. */
30
+ contentType: string;
31
+ /** First 2 KiB of the upstream response body. */
32
+ responseExcerpt: string;
33
+ }
34
+ /** Payload accepted by the built-in `send_email` handler. */
35
+ export interface SendEmailPayload {
36
+ /** One address or a list of addresses. */
37
+ to: string | string[];
38
+ /** Sender address. Falls back to the worker's `VEYRA_SMTP_FROM`. */
39
+ from?: string;
40
+ /** Subject line. Required. */
41
+ subject: string;
42
+ /** Plain-text body. At least one of `text` or `html` is required. */
43
+ text?: string;
44
+ /** HTML body. At least one of `text` or `html` is required. */
45
+ html?: string;
46
+ /** Carbon-copy recipients. */
47
+ cc?: string | string[];
48
+ /** Blind carbon-copy recipients. */
49
+ bcc?: string | string[];
50
+ /** Reply-To address. */
51
+ replyTo?: string;
52
+ /** Extra MIME headers. A caller-supplied `Message-ID` wins. */
53
+ headers?: Record<string, string>;
54
+ }
55
+ /** Result recorded for a successful `send_email` job. */
56
+ export interface SendEmailResult {
57
+ /** Message-ID used for delivery, without angle brackets. */
58
+ messageId: string;
59
+ /** Recipients the message was sent to. */
60
+ to: string[];
61
+ /** SMTP send duration in milliseconds. */
62
+ durationMs: number;
63
+ }
64
+ /** The built-in `noop` handler ignores its payload. */
65
+ export type NoopPayload = unknown;
66
+ /** Result recorded for a successful `noop` job. */
67
+ export interface NoopResult {
68
+ /** Always `true`; marks the result as synthetic. */
69
+ simulated: boolean;
70
+ /** Time spent in the handler, in milliseconds. */
71
+ durationMs: number;
72
+ }
73
+ /**
74
+ * Handlers shipped with the Veyra Go worker. Each entry maps a handler name to
75
+ * its payload and result types.
76
+ */
77
+ export interface BuiltInHandlers {
78
+ http_request: {
79
+ payload: HttpRequestPayload;
80
+ result: HttpRequestResult;
81
+ };
82
+ send_email: {
83
+ payload: SendEmailPayload;
84
+ result: SendEmailResult;
85
+ };
86
+ noop: {
87
+ payload: NoopPayload;
88
+ result: NoopResult;
89
+ };
90
+ }
91
+ /** Shape of one handler entry in a {@link HandlerMap}. */
92
+ export interface HandlerContract<TPayload = unknown, TResult = unknown> {
93
+ payload: TPayload;
94
+ result: TResult;
95
+ }
96
+ /** A map of handler name to payload/result contract. */
97
+ export type HandlerMap = Record<string, HandlerContract<any, any>>;
98
+ /**
99
+ * A reusable handler definition carrying its name, optional default queue,
100
+ * and optional Standard Schemas for payload and result.
101
+ */
102
+ export interface HandlerDefinition<TName extends string = string, TPayload = unknown, TResult = unknown, TQueue extends string | undefined = string | undefined> {
103
+ /** Handler name matched by the Veyra API and worker. */
104
+ readonly name: TName;
105
+ /** Default queue used by `client.enqueue(definition, payload)`. */
106
+ readonly queue?: TQueue;
107
+ /** Optional payload schema: validated on enqueue and before execution. */
108
+ readonly payload?: SchemaLike<TPayload>;
109
+ /** Optional result schema: validated after execution and on retrieval. */
110
+ readonly result?: SchemaLike<TResult>;
111
+ /** @internal Phantom type carrier. Never set at runtime. */
112
+ readonly __types?: {
113
+ readonly payload: TPayload;
114
+ readonly result: TResult;
115
+ };
116
+ }
117
+ /** Configuration accepted by {@link defineHandler}. */
118
+ export interface HandlerConfig<TName extends string, TPayload, TResult, TQueue extends string | undefined> {
119
+ /** Handler name matched by the Veyra API and worker. */
120
+ name: TName;
121
+ /** Default queue used when enqueueing with this definition. */
122
+ queue?: TQueue;
123
+ /** Optional Standard Schema (or {@link staticSchema}) for the payload. */
124
+ payload?: SchemaLike<TPayload>;
125
+ /** Optional Standard Schema (or {@link staticSchema}) for the result. */
126
+ result?: SchemaLike<TResult>;
127
+ }
128
+ /**
129
+ * Defines a typed handler once and reuse it on producers, workers, and
130
+ * webhook consumers.
131
+ *
132
+ * Payload and result types are inferred from the supplied schemas. Use explicit
133
+ * generics when you only need types: `defineHandler<Payload, Result>({ name })`.
134
+ *
135
+ * @example
136
+ * ```ts
137
+ * const sendEmail = defineHandler({
138
+ * name: 'send_email',
139
+ * queue: 'emails',
140
+ * payload: z.object({ to: z.string(), subject: z.string() }),
141
+ * result: z.object({ messageId: z.string() }),
142
+ * });
143
+ * ```
144
+ *
145
+ * @throws {VeyraError} When `name` is empty.
146
+ */
147
+ export declare function defineHandler<TPayload = unknown, TResult = unknown, const TName extends string = string, const TQueue extends string | undefined = undefined>(config: HandlerConfig<TName, TPayload, TResult, TQueue>): HandlerDefinition<TName, TPayload, TResult, TQueue>;
148
+ /** Built-ins plus user handlers, with user definitions winning on collisions. */
149
+ export type ResolvedHandlers<THandlers extends object> = Omit<BuiltInHandlers, keyof THandlers> & THandlers;
150
+ /** String keys of a handler map. */
151
+ export type HandlerName<THandlers extends object> = Extract<keyof THandlers, string>;
152
+ /** Payload type of a named handler. */
153
+ export type HandlerPayload<THandlers extends object, TName extends HandlerName<THandlers>> = THandlers[TName] extends HandlerContract<infer TPayload, any> ? TPayload : unknown;
154
+ /** Result type of a named handler. */
155
+ export type HandlerResult<THandlers extends object, TName extends HandlerName<THandlers>> = THandlers[TName] extends HandlerContract<any, infer TResult> ? TResult : unknown;
156
+ /** Payload type of a known handler, or a fallback for arbitrary names. */
157
+ export type HandlerPayloadFor<THandlers extends object, TName extends string, TFallback = unknown> = TName extends HandlerName<THandlers> ? HandlerPayload<THandlers, TName> : TFallback;
158
+ /** Result type of a known handler, or a fallback for arbitrary names. */
159
+ export type HandlerResultFor<THandlers extends object, TName extends string, TFallback = unknown> = TName extends HandlerName<THandlers> ? HandlerResult<THandlers, TName> : TFallback;
160
+ /** Payload type carried by a {@link HandlerDefinition}. */
161
+ export type DefinitionPayload<TDefinition> = TDefinition extends HandlerDefinition<any, infer TPayload, any, any> ? TPayload : unknown;
162
+ /** Result type carried by a {@link HandlerDefinition}. */
163
+ export type DefinitionResult<TDefinition> = TDefinition extends HandlerDefinition<any, any, infer TResult, any> ? TResult : unknown;
164
+ /** Returns `true` for a {@link HandlerDefinition} (and not an enqueue input). */
165
+ export declare function isHandlerDefinition(value: unknown): value is HandlerDefinition;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Handler contracts: built-in platform handlers, custom handler definitions,
3
+ * and the generic handler map used to type `VeyraClient` and `VeyraWorker`.
4
+ */
5
+ import { VeyraError } from './errors.js';
6
+ /**
7
+ * Defines a typed handler once and reuse it on producers, workers, and
8
+ * webhook consumers.
9
+ *
10
+ * Payload and result types are inferred from the supplied schemas. Use explicit
11
+ * generics when you only need types: `defineHandler<Payload, Result>({ name })`.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * const sendEmail = defineHandler({
16
+ * name: 'send_email',
17
+ * queue: 'emails',
18
+ * payload: z.object({ to: z.string(), subject: z.string() }),
19
+ * result: z.object({ messageId: z.string() }),
20
+ * });
21
+ * ```
22
+ *
23
+ * @throws {VeyraError} When `name` is empty.
24
+ */
25
+ export function defineHandler(config) {
26
+ if (typeof config.name !== 'string' || config.name.trim() === '') {
27
+ throw new VeyraError('defineHandler: name must not be empty');
28
+ }
29
+ return {
30
+ name: config.name.trim(),
31
+ queue: config.queue,
32
+ payload: config.payload,
33
+ result: config.result,
34
+ };
35
+ }
36
+ /** Returns `true` for a {@link HandlerDefinition} (and not an enqueue input). */
37
+ export function isHandlerDefinition(value) {
38
+ return (typeof value === 'object' &&
39
+ value !== null &&
40
+ 'name' in value &&
41
+ !('handler' in value));
42
+ }
package/dist/index.d.ts CHANGED
@@ -1,8 +1,15 @@
1
1
  /**
2
- * @veyra/sdk - Lightweight TypeScript & Node SDK for Veyra Distributed Execution Platform
2
+ * @aniket-lodh/veyra-sdk - Lightweight, zero-dependency TypeScript & Node.js SDK
3
+ * for the Veyra Distributed Execution Platform.
3
4
  */
4
- export * from './client.js';
5
- export * from './errors.js';
6
- export * from './types.js';
7
- export * from './worker.js';
8
- //# sourceMappingURL=index.d.ts.map
5
+ export { VeyraClient } from './client.js';
6
+ export { VeyraWorker } from './worker.js';
7
+ export { defineHandler, isHandlerDefinition } from './handlers.js';
8
+ export { staticSchema } from './standard-schema.js';
9
+ export { parseWebhook, verifyWebhookSignature } from './webhook.js';
10
+ export { VeyraError, VeyraValidationError, VeyraApiError, VeyraAuthError, VeyraNotFoundError, VeyraConflictError, LeaseLostError, VeyraRateLimitError, VeyraTimeoutError, VeyraNetworkError, VeyraWebhookError, NonRetryableError, isNonRetryable, } from './errors.js';
11
+ export type { VeyraClientConfig, VeyraWorkerOptions, VeyraLogger, EnqueueOptions, EnqueueJobInput, DefinitionEnqueueInput, TypedEnqueueInput, TypedEnqueuePayload, TypedEnqueueResult, RequestOptions, Job, JobStatus, StorageJobStatus, JobError, JobAttempt, BackoffStrategy, CallbackStatus, JobClaim, JobContext, HandlerFn, WorkerRecord, WorkerState, WorkerLease, WorkerRegisterParams, ClaimParams, CompleteJobResponse, FailJobParams, FailJobResponse, HeartbeatResponse, RenewLeaseResponse, DeregisterWorkerResponse, JsonValue, } from './types.js';
12
+ export type { BuiltInHandlers, HttpRequestPayload, HttpRequestResult, SendEmailPayload, SendEmailResult, NoopPayload, NoopResult, HandlerDefinition, HandlerConfig, HandlerContract, HandlerMap, DefinitionPayload, DefinitionResult, HandlerName, HandlerPayload, HandlerResult, HandlerPayloadFor, HandlerResultFor, ResolvedHandlers, } from './handlers.js';
13
+ export type { StandardSchemaV1, StaticSchema, SchemaLike, InferSchemaOutput, } from './standard-schema.js';
14
+ export type { WebhookEvent, WebhookJobStatus, WebhookVerificationOptions, } from './webhook.js';
15
+ export type { VeyraApiErrorParams } from './errors.js';
package/dist/index.js CHANGED
@@ -1,8 +1,14 @@
1
1
  /**
2
- * @veyra/sdk - Lightweight TypeScript & Node SDK for Veyra Distributed Execution Platform
2
+ * @aniket-lodh/veyra-sdk - Lightweight, zero-dependency TypeScript & Node.js SDK
3
+ * for the Veyra Distributed Execution Platform.
3
4
  */
4
- export * from './client.js';
5
- export * from './errors.js';
6
- export * from './types.js';
7
- export * from './worker.js';
8
- //# sourceMappingURL=index.js.map
5
+ // Public Classes
6
+ export { VeyraClient } from './client.js';
7
+ export { VeyraWorker } from './worker.js';
8
+ // Handler Definitions & Schema Helpers
9
+ export { defineHandler, isHandlerDefinition } from './handlers.js';
10
+ export { staticSchema } from './standard-schema.js';
11
+ // Webhook Helpers
12
+ export { parseWebhook, verifyWebhookSignature } from './webhook.js';
13
+ // Error Classes & Helpers
14
+ export { VeyraError, VeyraValidationError, VeyraApiError, VeyraAuthError, VeyraNotFoundError, VeyraConflictError, LeaseLostError, VeyraRateLimitError, VeyraTimeoutError, VeyraNetworkError, VeyraWebhookError, NonRetryableError, isNonRetryable, } from './errors.js';