@outfitter/contracts 0.1.0-rc.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.
@@ -0,0 +1,56 @@
1
+ // @bun
2
+ import {
3
+ serializeError
4
+ } from "./serialization.js";
5
+ import"./redactor.js";
6
+ import {
7
+ statusCodeMap
8
+ } from "./errors.js";
9
+ import {
10
+ generateRequestId
11
+ } from "./context.js";
12
+
13
+ // packages/contracts/src/envelope.ts
14
+ function buildMeta(overrides) {
15
+ const meta = {
16
+ requestId: overrides?.requestId ?? generateRequestId(),
17
+ timestamp: new Date().toISOString()
18
+ };
19
+ if (overrides?.durationMs !== undefined) {
20
+ meta.durationMs = overrides.durationMs;
21
+ }
22
+ return meta;
23
+ }
24
+ function toEnvelope(result, meta) {
25
+ const envelopeMeta = buildMeta(meta);
26
+ if (result.isOk()) {
27
+ return {
28
+ ok: true,
29
+ data: result.value,
30
+ meta: envelopeMeta
31
+ };
32
+ }
33
+ return {
34
+ ok: false,
35
+ error: serializeError(result.error),
36
+ meta: envelopeMeta
37
+ };
38
+ }
39
+ function toHttpResponse(result) {
40
+ const envelope = toEnvelope(result);
41
+ if (envelope.ok) {
42
+ return {
43
+ status: 200,
44
+ body: envelope
45
+ };
46
+ }
47
+ const status = statusCodeMap[envelope.error.category];
48
+ return {
49
+ status,
50
+ body: envelope
51
+ };
52
+ }
53
+ export {
54
+ toHttpResponse,
55
+ toEnvelope
56
+ };
@@ -0,0 +1,261 @@
1
+ import { TaggedErrorClass } from "better-result";
2
+ /**
3
+ * Error categories for classification, exit codes, and HTTP status mapping.
4
+ *
5
+ * Used for:
6
+ * - CLI exit code determination
7
+ * - HTTP status code mapping
8
+ * - Error grouping in logs and metrics
9
+ * - Client retry decisions (transient vs permanent)
10
+ */
11
+ type ErrorCategory = "validation" | "not_found" | "conflict" | "permission" | "timeout" | "rate_limit" | "network" | "internal" | "auth" | "cancelled";
12
+ /**
13
+ * Maps error category to CLI exit code.
14
+ * Non-zero exit indicates error; specific values for script automation.
15
+ */
16
+ declare const exitCodeMap: Record<ErrorCategory, number>;
17
+ /**
18
+ * Maps error category to HTTP status code.
19
+ * Used by MCP servers and API responses.
20
+ */
21
+ declare const statusCodeMap: Record<ErrorCategory, number>;
22
+ /**
23
+ * Serialized error format for JSON transport.
24
+ */
25
+ interface SerializedError {
26
+ _tag: string;
27
+ category: ErrorCategory;
28
+ message: string;
29
+ context?: Record<string, unknown>;
30
+ }
31
+ /**
32
+ * Base interface for OutfitterError properties.
33
+ * All concrete error classes must include these fields.
34
+ */
35
+ interface KitErrorProps {
36
+ message: string;
37
+ category: ErrorCategory;
38
+ context?: Record<string, unknown>;
39
+ }
40
+ /**
41
+ * Get CLI exit code for an error category.
42
+ */
43
+ declare function getExitCode(category: ErrorCategory): number;
44
+ /**
45
+ * Get HTTP status code for an error category.
46
+ */
47
+ declare function getStatusCode(category: ErrorCategory): number;
48
+ declare const ValidationErrorBase: TaggedErrorClass<"ValidationError", {
49
+ message: string;
50
+ field?: string;
51
+ }>;
52
+ declare const AssertionErrorBase: TaggedErrorClass<"AssertionError", {
53
+ message: string;
54
+ }>;
55
+ declare const NotFoundErrorBase: TaggedErrorClass<"NotFoundError", {
56
+ message: string;
57
+ resourceType: string;
58
+ resourceId: string;
59
+ }>;
60
+ declare const ConflictErrorBase: TaggedErrorClass<"ConflictError", {
61
+ message: string;
62
+ context?: Record<string, unknown>;
63
+ }>;
64
+ declare const PermissionErrorBase: TaggedErrorClass<"PermissionError", {
65
+ message: string;
66
+ context?: Record<string, unknown>;
67
+ }>;
68
+ declare const TimeoutErrorBase: TaggedErrorClass<"TimeoutError", {
69
+ message: string;
70
+ operation: string;
71
+ timeoutMs: number;
72
+ }>;
73
+ declare const RateLimitErrorBase: TaggedErrorClass<"RateLimitError", {
74
+ message: string;
75
+ retryAfterSeconds?: number;
76
+ }>;
77
+ declare const NetworkErrorBase: TaggedErrorClass<"NetworkError", {
78
+ message: string;
79
+ context?: Record<string, unknown>;
80
+ }>;
81
+ declare const InternalErrorBase: TaggedErrorClass<"InternalError", {
82
+ message: string;
83
+ context?: Record<string, unknown>;
84
+ }>;
85
+ declare const AuthErrorBase: TaggedErrorClass<"AuthError", {
86
+ message: string;
87
+ reason?: "missing" | "invalid" | "expired";
88
+ }>;
89
+ declare const CancelledErrorBase: TaggedErrorClass<"CancelledError", {
90
+ message: string;
91
+ }>;
92
+ /**
93
+ * Input validation failed.
94
+ *
95
+ * @example
96
+ * ```typescript
97
+ * new ValidationError({ message: "Email format invalid", field: "email" });
98
+ * ```
99
+ */
100
+ declare class ValidationError extends ValidationErrorBase {
101
+ readonly category: "validation";
102
+ exitCode(): number;
103
+ statusCode(): number;
104
+ }
105
+ /**
106
+ * Assertion failed (invariant violation).
107
+ *
108
+ * Used by assertion utilities that return Result types instead of throwing.
109
+ * AssertionError indicates a programming bug — an invariant that should
110
+ * never be violated was broken. These are internal errors, not user input
111
+ * validation failures.
112
+ *
113
+ * **Category rationale**: Uses `internal` (not `validation`) because:
114
+ * - Assertions check **invariants** (programmer assumptions), not user input
115
+ * - A failed assertion means "this should be impossible if the code is correct"
116
+ * - User-facing validation uses {@link ValidationError} with helpful field info
117
+ * - HTTP 500 is correct: this is a server bug, not a client mistake
118
+ *
119
+ * @example
120
+ * ```typescript
121
+ * // In domain logic after validation has passed
122
+ * const result = assertDefined(cachedValue, "Cache should always have value after init");
123
+ * if (result.isErr()) {
124
+ * return result; // Propagate as internal error
125
+ * }
126
+ * ```
127
+ *
128
+ * @see ValidationError - For user input validation failures (HTTP 400)
129
+ */
130
+ declare class AssertionError extends AssertionErrorBase {
131
+ readonly category: "internal";
132
+ exitCode(): number;
133
+ statusCode(): number;
134
+ }
135
+ /**
136
+ * Requested resource not found.
137
+ *
138
+ * @example
139
+ * ```typescript
140
+ * new NotFoundError({ message: "note not found: abc123", resourceType: "note", resourceId: "abc123" });
141
+ * ```
142
+ */
143
+ declare class NotFoundError extends NotFoundErrorBase {
144
+ readonly category: "not_found";
145
+ exitCode(): number;
146
+ statusCode(): number;
147
+ }
148
+ /**
149
+ * State conflict (optimistic locking, concurrent modification).
150
+ *
151
+ * @example
152
+ * ```typescript
153
+ * new ConflictError({ message: "Resource was modified by another process" });
154
+ * ```
155
+ */
156
+ declare class ConflictError extends ConflictErrorBase {
157
+ readonly category: "conflict";
158
+ exitCode(): number;
159
+ statusCode(): number;
160
+ }
161
+ /**
162
+ * Authorization denied.
163
+ *
164
+ * @example
165
+ * ```typescript
166
+ * new PermissionError({ message: "Cannot delete read-only resource" });
167
+ * ```
168
+ */
169
+ declare class PermissionError extends PermissionErrorBase {
170
+ readonly category: "permission";
171
+ exitCode(): number;
172
+ statusCode(): number;
173
+ }
174
+ /**
175
+ * Operation timed out.
176
+ *
177
+ * @example
178
+ * ```typescript
179
+ * new TimeoutError({ message: "Database query timed out after 5000ms", operation: "Database query", timeoutMs: 5000 });
180
+ * ```
181
+ */
182
+ declare class TimeoutError extends TimeoutErrorBase {
183
+ readonly category: "timeout";
184
+ exitCode(): number;
185
+ statusCode(): number;
186
+ }
187
+ /**
188
+ * Rate limit exceeded.
189
+ *
190
+ * @example
191
+ * ```typescript
192
+ * new RateLimitError({ message: "Rate limit exceeded, retry after 60s", retryAfterSeconds: 60 });
193
+ * ```
194
+ */
195
+ declare class RateLimitError extends RateLimitErrorBase {
196
+ readonly category: "rate_limit";
197
+ exitCode(): number;
198
+ statusCode(): number;
199
+ }
200
+ /**
201
+ * Network/transport failure.
202
+ *
203
+ * @example
204
+ * ```typescript
205
+ * new NetworkError({ message: "Connection refused to api.example.com" });
206
+ * ```
207
+ */
208
+ declare class NetworkError extends NetworkErrorBase {
209
+ readonly category: "network";
210
+ exitCode(): number;
211
+ statusCode(): number;
212
+ }
213
+ /**
214
+ * Unexpected internal error.
215
+ *
216
+ * @example
217
+ * ```typescript
218
+ * new InternalError({ message: "Unexpected state in processor" });
219
+ * ```
220
+ */
221
+ declare class InternalError extends InternalErrorBase {
222
+ readonly category: "internal";
223
+ exitCode(): number;
224
+ statusCode(): number;
225
+ }
226
+ /**
227
+ * Authentication failed (missing or invalid credentials).
228
+ *
229
+ * @example
230
+ * ```typescript
231
+ * new AuthError({ message: "Invalid API key", reason: "invalid" });
232
+ * ```
233
+ */
234
+ declare class AuthError extends AuthErrorBase {
235
+ readonly category: "auth";
236
+ exitCode(): number;
237
+ statusCode(): number;
238
+ }
239
+ /**
240
+ * Operation cancelled by user or signal.
241
+ *
242
+ * @example
243
+ * ```typescript
244
+ * new CancelledError({ message: "Operation cancelled by user" });
245
+ * ```
246
+ */
247
+ declare class CancelledError extends CancelledErrorBase {
248
+ readonly category: "cancelled";
249
+ exitCode(): number;
250
+ statusCode(): number;
251
+ }
252
+ /**
253
+ * Union type of all concrete error class instances.
254
+ */
255
+ type AnyKitError = InstanceType<typeof ValidationError> | InstanceType<typeof AssertionError> | InstanceType<typeof NotFoundError> | InstanceType<typeof ConflictError> | InstanceType<typeof PermissionError> | InstanceType<typeof TimeoutError> | InstanceType<typeof RateLimitError> | InstanceType<typeof NetworkError> | InstanceType<typeof InternalError> | InstanceType<typeof AuthError> | InstanceType<typeof CancelledError>;
256
+ /**
257
+ * Type alias for backwards compatibility with handler signatures.
258
+ * Use AnyKitError for the union type.
259
+ */
260
+ type OutfitterError = AnyKitError;
261
+ export { statusCodeMap, getStatusCode, getExitCode, exitCodeMap, ValidationError, TimeoutError, SerializedError, RateLimitError, PermissionError, OutfitterError, NotFoundError, NetworkError, KitErrorProps, InternalError, ErrorCategory, ConflictError, CancelledError, AuthError, AssertionError, AnyKitError };
package/dist/errors.js ADDED
@@ -0,0 +1,171 @@
1
+ // @bun
2
+ // packages/contracts/src/errors.ts
3
+ import { TaggedError } from "better-result";
4
+ var exitCodeMap = {
5
+ validation: 1,
6
+ not_found: 2,
7
+ conflict: 3,
8
+ permission: 4,
9
+ timeout: 5,
10
+ rate_limit: 6,
11
+ network: 7,
12
+ internal: 8,
13
+ auth: 9,
14
+ cancelled: 130
15
+ };
16
+ var statusCodeMap = {
17
+ validation: 400,
18
+ not_found: 404,
19
+ conflict: 409,
20
+ permission: 403,
21
+ timeout: 504,
22
+ rate_limit: 429,
23
+ network: 502,
24
+ internal: 500,
25
+ auth: 401,
26
+ cancelled: 499
27
+ };
28
+ function getExitCode(category) {
29
+ return exitCodeMap[category];
30
+ }
31
+ function getStatusCode(category) {
32
+ return statusCodeMap[category];
33
+ }
34
+ var ValidationErrorBase = TaggedError("ValidationError")();
35
+ var AssertionErrorBase = TaggedError("AssertionError")();
36
+ var NotFoundErrorBase = TaggedError("NotFoundError")();
37
+ var ConflictErrorBase = TaggedError("ConflictError")();
38
+ var PermissionErrorBase = TaggedError("PermissionError")();
39
+ var TimeoutErrorBase = TaggedError("TimeoutError")();
40
+ var RateLimitErrorBase = TaggedError("RateLimitError")();
41
+ var NetworkErrorBase = TaggedError("NetworkError")();
42
+ var InternalErrorBase = TaggedError("InternalError")();
43
+ var AuthErrorBase = TaggedError("AuthError")();
44
+ var CancelledErrorBase = TaggedError("CancelledError")();
45
+
46
+ class ValidationError extends ValidationErrorBase {
47
+ category = "validation";
48
+ exitCode() {
49
+ return getExitCode(this.category);
50
+ }
51
+ statusCode() {
52
+ return getStatusCode(this.category);
53
+ }
54
+ }
55
+
56
+ class AssertionError extends AssertionErrorBase {
57
+ category = "internal";
58
+ exitCode() {
59
+ return getExitCode(this.category);
60
+ }
61
+ statusCode() {
62
+ return getStatusCode(this.category);
63
+ }
64
+ }
65
+
66
+ class NotFoundError extends NotFoundErrorBase {
67
+ category = "not_found";
68
+ exitCode() {
69
+ return getExitCode(this.category);
70
+ }
71
+ statusCode() {
72
+ return getStatusCode(this.category);
73
+ }
74
+ }
75
+
76
+ class ConflictError extends ConflictErrorBase {
77
+ category = "conflict";
78
+ exitCode() {
79
+ return getExitCode(this.category);
80
+ }
81
+ statusCode() {
82
+ return getStatusCode(this.category);
83
+ }
84
+ }
85
+
86
+ class PermissionError extends PermissionErrorBase {
87
+ category = "permission";
88
+ exitCode() {
89
+ return getExitCode(this.category);
90
+ }
91
+ statusCode() {
92
+ return getStatusCode(this.category);
93
+ }
94
+ }
95
+
96
+ class TimeoutError extends TimeoutErrorBase {
97
+ category = "timeout";
98
+ exitCode() {
99
+ return getExitCode(this.category);
100
+ }
101
+ statusCode() {
102
+ return getStatusCode(this.category);
103
+ }
104
+ }
105
+
106
+ class RateLimitError extends RateLimitErrorBase {
107
+ category = "rate_limit";
108
+ exitCode() {
109
+ return getExitCode(this.category);
110
+ }
111
+ statusCode() {
112
+ return getStatusCode(this.category);
113
+ }
114
+ }
115
+
116
+ class NetworkError extends NetworkErrorBase {
117
+ category = "network";
118
+ exitCode() {
119
+ return getExitCode(this.category);
120
+ }
121
+ statusCode() {
122
+ return getStatusCode(this.category);
123
+ }
124
+ }
125
+
126
+ class InternalError extends InternalErrorBase {
127
+ category = "internal";
128
+ exitCode() {
129
+ return getExitCode(this.category);
130
+ }
131
+ statusCode() {
132
+ return getStatusCode(this.category);
133
+ }
134
+ }
135
+
136
+ class AuthError extends AuthErrorBase {
137
+ category = "auth";
138
+ exitCode() {
139
+ return getExitCode(this.category);
140
+ }
141
+ statusCode() {
142
+ return getStatusCode(this.category);
143
+ }
144
+ }
145
+
146
+ class CancelledError extends CancelledErrorBase {
147
+ category = "cancelled";
148
+ exitCode() {
149
+ return getExitCode(this.category);
150
+ }
151
+ statusCode() {
152
+ return getStatusCode(this.category);
153
+ }
154
+ }
155
+ export {
156
+ statusCodeMap,
157
+ getStatusCode,
158
+ getExitCode,
159
+ exitCodeMap,
160
+ ValidationError,
161
+ TimeoutError,
162
+ RateLimitError,
163
+ PermissionError,
164
+ NotFoundError,
165
+ NetworkError,
166
+ InternalError,
167
+ ConflictError,
168
+ CancelledError,
169
+ AuthError,
170
+ AssertionError
171
+ };