@terreno/api 0.0.18 → 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 (71) hide show
  1. package/README.md +73 -3
  2. package/dist/api.d.ts +96 -3
  3. package/dist/api.js +159 -11
  4. package/dist/api.test.js +906 -2
  5. package/dist/auth.js +3 -1
  6. package/dist/betterAuth.d.ts +91 -0
  7. package/dist/betterAuth.js +8 -0
  8. package/dist/betterAuth.test.d.ts +1 -0
  9. package/dist/betterAuth.test.js +181 -0
  10. package/dist/betterAuthApp.d.ts +22 -0
  11. package/dist/betterAuthApp.js +38 -0
  12. package/dist/betterAuthApp.test.d.ts +1 -0
  13. package/dist/betterAuthApp.test.js +242 -0
  14. package/dist/betterAuthSetup.d.ts +60 -0
  15. package/dist/betterAuthSetup.js +278 -0
  16. package/dist/betterAuthSetup.test.d.ts +1 -0
  17. package/dist/betterAuthSetup.test.js +684 -0
  18. package/dist/errors.js +14 -11
  19. package/dist/example.js +7 -7
  20. package/dist/expressServer.js +2 -2
  21. package/dist/githubAuth.test.js +3 -3
  22. package/dist/index.d.ts +6 -0
  23. package/dist/index.js +6 -0
  24. package/dist/openApi.test.js +8 -5
  25. package/dist/openApiBuilder.d.ts +69 -1
  26. package/dist/openApiBuilder.js +109 -5
  27. package/dist/openApiValidator.d.ts +296 -0
  28. package/dist/openApiValidator.js +698 -0
  29. package/dist/openApiValidator.test.d.ts +1 -0
  30. package/dist/openApiValidator.test.js +346 -0
  31. package/dist/plugins.test.js +3 -3
  32. package/dist/terrenoApp.d.ts +189 -0
  33. package/dist/terrenoApp.js +352 -0
  34. package/dist/terrenoApp.test.d.ts +1 -0
  35. package/dist/terrenoApp.test.js +264 -0
  36. package/dist/terrenoPlugin.d.ts +38 -0
  37. package/dist/terrenoPlugin.js +2 -0
  38. package/dist/tests.js +34 -24
  39. package/package.json +8 -2
  40. package/src/__snapshots__/openApi.test.ts.snap +399 -0
  41. package/src/__snapshots__/openApiBuilder.test.ts.snap +108 -0
  42. package/src/api.test.ts +743 -2
  43. package/src/api.ts +270 -6
  44. package/src/auth.ts +3 -1
  45. package/src/betterAuth.test.ts +160 -0
  46. package/src/betterAuth.ts +104 -0
  47. package/src/betterAuthApp.test.ts +114 -0
  48. package/src/betterAuthApp.ts +60 -0
  49. package/src/betterAuthSetup.test.ts +485 -0
  50. package/src/betterAuthSetup.ts +251 -0
  51. package/src/errors.ts +14 -11
  52. package/src/example.ts +7 -7
  53. package/src/expressServer.ts +4 -5
  54. package/src/githubAuth.test.ts +3 -3
  55. package/src/index.ts +6 -0
  56. package/src/openApi.test.ts +8 -5
  57. package/src/openApiBuilder.ts +188 -15
  58. package/src/openApiValidator.test.ts +241 -0
  59. package/src/openApiValidator.ts +860 -0
  60. package/src/plugins.test.ts +3 -3
  61. package/src/terrenoApp.test.ts +201 -0
  62. package/src/terrenoApp.ts +347 -0
  63. package/src/terrenoPlugin.ts +39 -0
  64. package/src/tests.ts +34 -24
  65. package/.cursorrules +0 -107
  66. package/.windsurfrules +0 -107
  67. package/AGENTS.md +0 -313
  68. package/dist/response.d.ts +0 -0
  69. package/dist/response.js +0 -1
  70. package/index.ts +0 -1
  71. package/src/response.ts +0 -0
@@ -0,0 +1,296 @@
1
+ /**
2
+ * OpenAPI Request Validator
3
+ *
4
+ * Provides runtime validation of incoming requests against OpenAPI schemas.
5
+ * Uses AJV for JSON Schema validation with OpenAPI-compatible settings.
6
+ *
7
+ * Validation is always installed as middleware but only activates after
8
+ * `configureOpenApiValidator()` is called. This makes it safe to include
9
+ * in modelRouter by default.
10
+ *
11
+ * @module openApiValidator
12
+ *
13
+ * @packageDocumentation
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * // Enable validation globally at server startup
18
+ * configureOpenApiValidator({
19
+ * removeAdditional: true,
20
+ * onAdditionalPropertiesRemoved: (props, req) => {
21
+ * logger.warn(`Stripped: ${props.join(", ")} on ${req.method} ${req.path}`);
22
+ * },
23
+ * });
24
+ *
25
+ * // modelRouter automatically validates when configured
26
+ * modelRouter(Todo, {
27
+ * permissions: {...},
28
+ * validation: {
29
+ * validateCreate: true,
30
+ * validateUpdate: true,
31
+ * validateQuery: true,
32
+ * },
33
+ * });
34
+ * ```
35
+ */
36
+ import { type ErrorObject } from "ajv";
37
+ import type { NextFunction, Request, Response } from "express";
38
+ import type { Model } from "mongoose";
39
+ import type { OpenApiSchemaProperty } from "./openApiBuilder";
40
+ /**
41
+ * Global configuration for OpenAPI validation.
42
+ * This can be set at server startup to control validation behavior.
43
+ */
44
+ export interface OpenApiValidatorConfig {
45
+ /**
46
+ * Enable or disable request body validation.
47
+ * Default: true (when configureOpenApiValidator is called)
48
+ */
49
+ validateRequests?: boolean;
50
+ /**
51
+ * Enable or disable response validation.
52
+ * Default: false (response validation has performance overhead)
53
+ */
54
+ validateResponses?: boolean;
55
+ /**
56
+ * Whether to coerce types (e.g., string "123" to number 123).
57
+ * Default: true
58
+ */
59
+ coerceTypes?: boolean;
60
+ /**
61
+ * Whether to remove additional properties not in the schema.
62
+ * Default: true
63
+ */
64
+ removeAdditional?: boolean;
65
+ /**
66
+ * Custom error handler for validation failures.
67
+ * If not provided, throws an APIError with status 400.
68
+ */
69
+ onValidationError?: (errors: ErrorObject[], req: Request) => void;
70
+ /**
71
+ * Log validation errors for debugging.
72
+ * Default: true
73
+ */
74
+ logValidationErrors?: boolean;
75
+ /**
76
+ * Callback fired when additional properties are removed from a request body.
77
+ * Only fires when `removeAdditional: true` and extra properties are present.
78
+ * Receives the list of removed property names and the request.
79
+ */
80
+ onAdditionalPropertiesRemoved?: (removedProperties: string[], req: Request) => void;
81
+ }
82
+ /**
83
+ * Check whether `configureOpenApiValidator()` has been called.
84
+ * Validation middleware is a no-op when this returns false.
85
+ */
86
+ export declare function isOpenApiValidatorConfigured(): boolean;
87
+ /**
88
+ * Configure the global OpenAPI validator settings.
89
+ * Calling this function activates validation — middleware that was previously
90
+ * installed as a no-op will begin validating requests.
91
+ *
92
+ * @param config - Configuration options to merge with existing config
93
+ *
94
+ * @example
95
+ * ```typescript
96
+ * configureOpenApiValidator({
97
+ * removeAdditional: true,
98
+ * onAdditionalPropertiesRemoved: (props, req) => {
99
+ * Sentry.captureMessage(`Stripped: ${props.join(", ")} on ${req.method} ${req.path}`);
100
+ * },
101
+ * });
102
+ * ```
103
+ */
104
+ export declare function configureOpenApiValidator(config?: Partial<OpenApiValidatorConfig>): void;
105
+ /**
106
+ * Get the current global validator configuration.
107
+ */
108
+ export declare function getOpenApiValidatorConfig(): OpenApiValidatorConfig;
109
+ /**
110
+ * Reset the global validator configuration to defaults.
111
+ * Also resets `isConfigured` to false.
112
+ * Useful for testing.
113
+ */
114
+ export declare function resetOpenApiValidatorConfig(): void;
115
+ /**
116
+ * Options for the request body validator middleware.
117
+ */
118
+ export interface RequestBodyValidatorOptions {
119
+ /**
120
+ * Override the global validateRequests setting for this specific route.
121
+ */
122
+ enabled?: boolean;
123
+ /**
124
+ * List of required field names.
125
+ */
126
+ required?: string[];
127
+ /**
128
+ * Fields to exclude from validation (e.g. fields set by preCreate hooks).
129
+ * Excluded fields are removed from both the schema properties and the required array.
130
+ */
131
+ excludeFields?: string[];
132
+ /**
133
+ * Custom error handler for this specific route.
134
+ */
135
+ onError?: (errors: ErrorObject[], req: Request) => void;
136
+ /**
137
+ * Callback fired when additional properties are removed.
138
+ * Overrides the global onAdditionalPropertiesRemoved for this route.
139
+ */
140
+ onAdditionalPropertiesRemoved?: (removedProperties: string[], req: Request) => void;
141
+ }
142
+ /**
143
+ * Creates middleware that validates the request body against an OpenAPI schema.
144
+ *
145
+ * The middleware checks `isConfigured` at request time — if `configureOpenApiValidator()`
146
+ * has not been called, the middleware is a no-op.
147
+ *
148
+ * @param schema - The schema to validate against (same format as withRequestBody)
149
+ * @param options - Optional configuration for this validator
150
+ * @returns Express middleware function
151
+ */
152
+ export declare function validateRequestBody(schema: Record<string, OpenApiSchemaProperty>, options?: RequestBodyValidatorOptions): (req: Request, res: Response, next: NextFunction) => void;
153
+ /**
154
+ * Options for the query parameter validator middleware.
155
+ */
156
+ export interface QueryValidatorOptions {
157
+ /**
158
+ * Override the global validateRequests setting for this specific route.
159
+ */
160
+ enabled?: boolean;
161
+ /**
162
+ * Custom error handler for this specific route.
163
+ */
164
+ onError?: (errors: ErrorObject[], req: Request) => void;
165
+ }
166
+ /**
167
+ * Creates middleware that validates query parameters against an OpenAPI schema.
168
+ *
169
+ * @param schema - The schema to validate against
170
+ * @param options - Optional configuration for this validator
171
+ * @returns Express middleware function
172
+ */
173
+ export declare function validateQueryParams(schema: Record<string, OpenApiSchemaProperty>, options?: QueryValidatorOptions): (req: Request, res: Response, next: NextFunction) => void;
174
+ /**
175
+ * Options for creating a combined validation middleware.
176
+ */
177
+ export interface CreateValidatorOptions {
178
+ /**
179
+ * Schema for request body validation.
180
+ */
181
+ body?: Record<string, OpenApiSchemaProperty>;
182
+ /**
183
+ * Schema for query parameter validation.
184
+ */
185
+ query?: Record<string, OpenApiSchemaProperty>;
186
+ /**
187
+ * Override the global validation enabled setting.
188
+ */
189
+ enabled?: boolean;
190
+ }
191
+ /**
192
+ * Creates a combined validation middleware for both body and query parameters.
193
+ *
194
+ * @param options - Configuration for what to validate
195
+ * @returns Express middleware function
196
+ *
197
+ * @example
198
+ * ```typescript
199
+ * router.post("/search", [
200
+ * openApiMiddleware,
201
+ * createValidator({
202
+ * body: {query: {type: "string", required: true}},
203
+ * query: {limit: {type: "number"}},
204
+ * }),
205
+ * ], handler);
206
+ * ```
207
+ */
208
+ export declare function createValidator(options: CreateValidatorOptions): (req: Request, res: Response, next: NextFunction) => void;
209
+ /**
210
+ * Validates response data against a schema.
211
+ * This is primarily for development/testing to ensure responses match documentation.
212
+ *
213
+ * @param data - The response data to validate
214
+ * @param schema - The expected schema
215
+ * @returns Object with valid flag and any errors
216
+ */
217
+ export declare function validateResponseData(data: unknown, schema: Record<string, OpenApiSchemaProperty>): {
218
+ valid: boolean;
219
+ errors?: ErrorObject[];
220
+ };
221
+ /**
222
+ * Extract an OpenAPI-compatible schema from a Mongoose model.
223
+ * This allows you to use the same schema definitions for both documentation
224
+ * and runtime validation.
225
+ *
226
+ * @param model - A Mongoose model
227
+ * @returns Schema properties suitable for validation
228
+ */
229
+ export declare function getSchemaFromModel<T>(model: Model<T>): Record<string, OpenApiSchemaProperty>;
230
+ /**
231
+ * Creates a request body validator middleware from a Mongoose model.
232
+ * This is a convenience function that combines getSchemaFromModel and validateRequestBody.
233
+ *
234
+ * @param model - A Mongoose model to derive the schema from
235
+ * @param options - Optional configuration for the validator
236
+ * @returns Express middleware function
237
+ */
238
+ export declare function validateModelRequestBody<T>(model: Model<T>, options?: RequestBodyValidatorOptions): (req: Request, res: Response, next: NextFunction) => void;
239
+ /**
240
+ * Options for creating validation middleware for a modelRouter.
241
+ */
242
+ export interface ModelRouterValidationOptions {
243
+ /**
244
+ * Enable validation for create (POST) requests.
245
+ * Default: true (when validation is globally enabled)
246
+ */
247
+ validateCreate?: boolean;
248
+ /**
249
+ * Enable validation for update (PATCH) requests.
250
+ * Default: true (when validation is globally enabled)
251
+ */
252
+ validateUpdate?: boolean;
253
+ /**
254
+ * Enable validation for query (GET list) requests.
255
+ * Default: true (when validation is globally enabled)
256
+ */
257
+ validateQuery?: boolean;
258
+ /**
259
+ * Fields to exclude from create validation (e.g. fields injected by preCreate).
260
+ */
261
+ excludeFromCreate?: string[];
262
+ /**
263
+ * Fields to exclude from update validation (e.g. fields injected by preUpdate).
264
+ */
265
+ excludeFromUpdate?: string[];
266
+ /**
267
+ * Custom error handler for validation failures.
268
+ */
269
+ onError?: (errors: ErrorObject[], req: Request) => void;
270
+ /**
271
+ * Callback fired when additional properties are removed from a request body.
272
+ * Overrides the global onAdditionalPropertiesRemoved for this router.
273
+ */
274
+ onAdditionalPropertiesRemoved?: (removedProperties: string[], req: Request) => void;
275
+ }
276
+ /**
277
+ * Creates validation middleware for use with modelRouter.
278
+ * Returns an object with middleware for each operation type.
279
+ *
280
+ * @param model - The Mongoose model
281
+ * @param options - Configuration options
282
+ * @returns Object with create and update validation middleware
283
+ */
284
+ export declare function createModelValidators<T>(model: Model<T>, options?: ModelRouterValidationOptions): {
285
+ create: (req: Request, res: Response, next: NextFunction) => void;
286
+ update: (req: Request, res: Response, next: NextFunction) => void;
287
+ };
288
+ /**
289
+ * Build a query parameter schema from a model's Mongoose schema and queryFields array.
290
+ * Always includes pagination parameters (limit, page, sort).
291
+ *
292
+ * @param model - A Mongoose model
293
+ * @param queryFields - Array of field names allowed for querying
294
+ * @returns Schema properties suitable for query validation
295
+ */
296
+ export declare function buildQuerySchemaFromFields<T>(model: Model<T>, queryFields?: string[]): Record<string, OpenApiSchemaProperty>;