@emmett-community/emmett-expressjs-with-openapi 0.1.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.
- package/LICENSE +21 -0
- package/README.md +100 -0
- package/dist/chunk-5TC7YUZR.js +38 -0
- package/dist/chunk-5TC7YUZR.js.map +1 -0
- package/dist/chunk-GS7T56RP.cjs +8 -0
- package/dist/chunk-GS7T56RP.cjs.map +1 -0
- package/dist/chunk-MRSGTROW.cjs +42 -0
- package/dist/chunk-MRSGTROW.cjs.map +1 -0
- package/dist/esm-resolver-I5MW2PIQ.cjs +10 -0
- package/dist/esm-resolver-I5MW2PIQ.cjs.map +1 -0
- package/dist/esm-resolver-ZL5JTVDP.js +9 -0
- package/dist/esm-resolver-ZL5JTVDP.js.map +1 -0
- package/dist/handler-importer-4BVBIZX3.cjs +27 -0
- package/dist/handler-importer-4BVBIZX3.cjs.map +1 -0
- package/dist/handler-importer-OJGFQON5.js +26 -0
- package/dist/handler-importer-OJGFQON5.js.map +1 -0
- package/dist/index.cjs +428 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +440 -0
- package/dist/index.d.ts +440 -0
- package/dist/index.js +425 -0
- package/dist/index.js.map +1 -0
- package/dist/openapi-parser-6EGURSGG.js +73 -0
- package/dist/openapi-parser-6EGURSGG.js.map +1 -0
- package/dist/openapi-parser-KI7BS3DC.cjs +75 -0
- package/dist/openapi-parser-KI7BS3DC.cjs.map +1 -0
- package/package.json +81 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
|
|
2
|
+
|
|
3
|
+
var _chunkMRSGTROWcjs = require('./chunk-MRSGTROW.cjs');
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
var _chunkGS7T56RPcjs = require('./chunk-GS7T56RP.cjs');
|
|
7
|
+
|
|
8
|
+
// src/index.ts
|
|
9
|
+
require('express-async-errors');
|
|
10
|
+
|
|
11
|
+
// src/application.ts
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
var _express = require('express'); var _express2 = _interopRequireDefault(_express);
|
|
15
|
+
|
|
16
|
+
var _http = require('http'); var _http2 = _interopRequireDefault(_http);
|
|
17
|
+
var _module = require('module');
|
|
18
|
+
|
|
19
|
+
// src/middlewares/problemDetailsMiddleware.ts
|
|
20
|
+
var _httpproblemdetails = require('http-problem-details');
|
|
21
|
+
var problemDetailsMiddleware = (mapError) => (error, request, response, _next) => {
|
|
22
|
+
let problemDetails;
|
|
23
|
+
if (mapError) problemDetails = mapError(error, request);
|
|
24
|
+
problemDetails = _nullishCoalesce(problemDetails, () => ( defaultErrorToProblemDetailsMapping(error)));
|
|
25
|
+
sendProblem(response, problemDetails.status, { problem: problemDetails });
|
|
26
|
+
};
|
|
27
|
+
var defaultErrorToProblemDetailsMapping = (error) => {
|
|
28
|
+
let statusCode = 500;
|
|
29
|
+
const errObj = error;
|
|
30
|
+
const maybeStatus = errObj["status"];
|
|
31
|
+
if (typeof maybeStatus === "number" && maybeStatus >= 100 && maybeStatus < 600) {
|
|
32
|
+
statusCode = maybeStatus;
|
|
33
|
+
}
|
|
34
|
+
const maybeErrorCode = errObj["errorCode"];
|
|
35
|
+
if (typeof maybeErrorCode === "number" && maybeErrorCode >= 100 && maybeErrorCode < 600) {
|
|
36
|
+
statusCode = maybeErrorCode;
|
|
37
|
+
}
|
|
38
|
+
return new (0, _httpproblemdetails.ProblemDocument)({
|
|
39
|
+
detail: error.message,
|
|
40
|
+
status: statusCode
|
|
41
|
+
});
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
// src/application.ts
|
|
45
|
+
var getApplication = async (options) => {
|
|
46
|
+
const app = _express2.default.call(void 0, );
|
|
47
|
+
const {
|
|
48
|
+
apis,
|
|
49
|
+
mapError,
|
|
50
|
+
enableDefaultExpressEtag,
|
|
51
|
+
disableJsonMiddleware,
|
|
52
|
+
disableUrlEncodingMiddleware,
|
|
53
|
+
disableProblemDetailsMiddleware,
|
|
54
|
+
openApiValidator
|
|
55
|
+
} = options;
|
|
56
|
+
const router = _express.Router.call(void 0, );
|
|
57
|
+
app.set("etag", _nullishCoalesce(enableDefaultExpressEtag, () => ( false)));
|
|
58
|
+
if (!disableJsonMiddleware) app.use(_express2.default.json());
|
|
59
|
+
if (!disableUrlEncodingMiddleware)
|
|
60
|
+
app.use(
|
|
61
|
+
_express2.default.urlencoded({
|
|
62
|
+
extended: true
|
|
63
|
+
})
|
|
64
|
+
);
|
|
65
|
+
if (openApiValidator) {
|
|
66
|
+
if (openApiValidator.operationHandlers) {
|
|
67
|
+
const { activateESMResolver } = await Promise.resolve().then(() => _interopRequireWildcard(require("./esm-resolver-I5MW2PIQ.cjs")));
|
|
68
|
+
activateESMResolver();
|
|
69
|
+
const handlersBasePath = typeof openApiValidator.operationHandlers === "string" ? openApiValidator.operationHandlers : openApiValidator.operationHandlers.basePath;
|
|
70
|
+
if (handlersBasePath) {
|
|
71
|
+
const { extractHandlerModules } = await Promise.resolve().then(() => _interopRequireWildcard(require("./openapi-parser-KI7BS3DC.cjs")));
|
|
72
|
+
const { importAndRegisterHandlers } = await Promise.resolve().then(() => _interopRequireWildcard(require("./handler-importer-4BVBIZX3.cjs")));
|
|
73
|
+
try {
|
|
74
|
+
const modules = await extractHandlerModules(
|
|
75
|
+
openApiValidator.apiSpec,
|
|
76
|
+
handlersBasePath
|
|
77
|
+
);
|
|
78
|
+
const importedHandlers = await importAndRegisterHandlers(modules);
|
|
79
|
+
if (openApiValidator.initializeHandlers) {
|
|
80
|
+
await openApiValidator.initializeHandlers(importedHandlers);
|
|
81
|
+
}
|
|
82
|
+
} catch (error) {
|
|
83
|
+
console.error("Failed to auto-import handler modules:", error);
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
} else {
|
|
88
|
+
if (openApiValidator.initializeHandlers) {
|
|
89
|
+
await openApiValidator.initializeHandlers();
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
try {
|
|
93
|
+
const require2 = _module.createRequire.call(void 0, _chunkGS7T56RPcjs.importMetaUrl);
|
|
94
|
+
const mod = require2("express-openapi-validator");
|
|
95
|
+
const provider = _nullishCoalesce(mod.default, () => ( mod));
|
|
96
|
+
if (typeof provider.middleware !== "function") {
|
|
97
|
+
throw new Error(
|
|
98
|
+
"Invalid express-openapi-validator module: missing middleware export"
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
if (openApiValidator.serveSpec) {
|
|
102
|
+
if (typeof openApiValidator.apiSpec === "string") {
|
|
103
|
+
app.use(
|
|
104
|
+
openApiValidator.serveSpec,
|
|
105
|
+
_express2.default.static(openApiValidator.apiSpec)
|
|
106
|
+
);
|
|
107
|
+
} else {
|
|
108
|
+
app.get(openApiValidator.serveSpec, (_req, res) => {
|
|
109
|
+
res.json(openApiValidator.apiSpec);
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
const factory = provider.middleware;
|
|
114
|
+
const middleware = factory(openApiValidator);
|
|
115
|
+
if (Array.isArray(middleware)) {
|
|
116
|
+
for (const m of middleware) app.use(m);
|
|
117
|
+
} else {
|
|
118
|
+
app.use(middleware);
|
|
119
|
+
}
|
|
120
|
+
} catch (e) {
|
|
121
|
+
console.warn(
|
|
122
|
+
"OpenAPI validator configuration provided but express-openapi-validator package is not installed. Install it with: npm install express-openapi-validator"
|
|
123
|
+
);
|
|
124
|
+
throw new Error(
|
|
125
|
+
"express-openapi-validator package is required when openApiValidator option is used"
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
if (apis) {
|
|
130
|
+
for (const api of apis) {
|
|
131
|
+
api(router);
|
|
132
|
+
}
|
|
133
|
+
app.use(router);
|
|
134
|
+
}
|
|
135
|
+
if (!disableProblemDetailsMiddleware)
|
|
136
|
+
app.use(problemDetailsMiddleware(mapError));
|
|
137
|
+
return app;
|
|
138
|
+
};
|
|
139
|
+
var startAPI = (app, options = { port: 3e3 }) => {
|
|
140
|
+
const { port } = options;
|
|
141
|
+
const server = _http2.default.createServer(app);
|
|
142
|
+
server.on("listening", () => {
|
|
143
|
+
console.info("server up listening");
|
|
144
|
+
});
|
|
145
|
+
return server.listen(port);
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
// src/etag.ts
|
|
149
|
+
var HeaderNames = {
|
|
150
|
+
IF_MATCH: "if-match",
|
|
151
|
+
IF_NOT_MATCH: "if-not-match",
|
|
152
|
+
ETag: "etag"
|
|
153
|
+
};
|
|
154
|
+
var WeakETagRegex = /W\/"(-?\d+.*)"/;
|
|
155
|
+
var ETagErrors = /* @__PURE__ */ ((ETagErrors2) => {
|
|
156
|
+
ETagErrors2["WRONG_WEAK_ETAG_FORMAT"] = "WRONG_WEAK_ETAG_FORMAT";
|
|
157
|
+
ETagErrors2["MISSING_IF_MATCH_HEADER"] = "MISSING_IF_MATCH_HEADER";
|
|
158
|
+
ETagErrors2["MISSING_IF_NOT_MATCH_HEADER"] = "MISSING_IF_NOT_MATCH_HEADER";
|
|
159
|
+
return ETagErrors2;
|
|
160
|
+
})(ETagErrors || {});
|
|
161
|
+
var isWeakETag = (etag) => {
|
|
162
|
+
return WeakETagRegex.test(etag);
|
|
163
|
+
};
|
|
164
|
+
var getWeakETagValue = (etag) => {
|
|
165
|
+
const result = WeakETagRegex.exec(etag);
|
|
166
|
+
if (result === null || result.length === 0) {
|
|
167
|
+
throw new Error("WRONG_WEAK_ETAG_FORMAT" /* WRONG_WEAK_ETAG_FORMAT */);
|
|
168
|
+
}
|
|
169
|
+
return result[1];
|
|
170
|
+
};
|
|
171
|
+
var toWeakETag = (value) => {
|
|
172
|
+
return `W/"${value}"`;
|
|
173
|
+
};
|
|
174
|
+
var getETagFromIfMatch = (request) => {
|
|
175
|
+
const etag = request.headers[HeaderNames.IF_MATCH];
|
|
176
|
+
if (etag === void 0) {
|
|
177
|
+
throw new Error("MISSING_IF_MATCH_HEADER" /* MISSING_IF_MATCH_HEADER */);
|
|
178
|
+
}
|
|
179
|
+
return etag;
|
|
180
|
+
};
|
|
181
|
+
var getETagFromIfNotMatch = (request) => {
|
|
182
|
+
const etag = request.headers[HeaderNames.IF_NOT_MATCH];
|
|
183
|
+
if (etag === void 0) {
|
|
184
|
+
throw new Error("MISSING_IF_MATCH_HEADER" /* MISSING_IF_MATCH_HEADER */);
|
|
185
|
+
}
|
|
186
|
+
return Array.isArray(etag) ? etag[0] : etag;
|
|
187
|
+
};
|
|
188
|
+
var setETag = (response, etag) => {
|
|
189
|
+
response.setHeader(HeaderNames.ETag, etag);
|
|
190
|
+
};
|
|
191
|
+
var getETagValueFromIfMatch = (request) => {
|
|
192
|
+
const eTagValue = getETagFromIfMatch(request);
|
|
193
|
+
return isWeakETag(eTagValue) ? getWeakETagValue(eTagValue) : eTagValue;
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
// src/handler.ts
|
|
197
|
+
var on = (handle) => async (request, response, _next) => {
|
|
198
|
+
const setResponse = await Promise.resolve(handle(request));
|
|
199
|
+
return setResponse(response);
|
|
200
|
+
};
|
|
201
|
+
var OK = (options) => (response) => {
|
|
202
|
+
send(response, 200, options);
|
|
203
|
+
};
|
|
204
|
+
var Created = (options) => (response) => {
|
|
205
|
+
sendCreated(response, options);
|
|
206
|
+
};
|
|
207
|
+
var Accepted = (options) => (response) => {
|
|
208
|
+
sendAccepted(response, options);
|
|
209
|
+
};
|
|
210
|
+
var NoContent = (options) => HttpResponse(204, options);
|
|
211
|
+
var HttpResponse = (statusCode, options) => (response) => {
|
|
212
|
+
send(response, statusCode, options);
|
|
213
|
+
};
|
|
214
|
+
var BadRequest = (options) => HttpProblem(400, options);
|
|
215
|
+
var Forbidden = (options) => HttpProblem(403, options);
|
|
216
|
+
var NotFound = (options) => HttpProblem(404, options);
|
|
217
|
+
var Conflict = (options) => HttpProblem(409, options);
|
|
218
|
+
var PreconditionFailed = (options) => HttpProblem(412, options);
|
|
219
|
+
var HttpProblem = (statusCode, options) => (response) => {
|
|
220
|
+
sendProblem(response, statusCode, options);
|
|
221
|
+
};
|
|
222
|
+
|
|
223
|
+
// src/openapi/index.ts
|
|
224
|
+
var createOpenApiValidatorOptions = (apiSpec, options) => {
|
|
225
|
+
return {
|
|
226
|
+
apiSpec,
|
|
227
|
+
validateRequests: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _ => _.validateRequests]), () => ( true)),
|
|
228
|
+
validateResponses: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _2 => _2.validateResponses]), () => ( false)),
|
|
229
|
+
validateSecurity: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _3 => _3.validateSecurity]), () => ( true)),
|
|
230
|
+
validateFormats: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _4 => _4.validateFormats]), () => ( true)),
|
|
231
|
+
operationHandlers: _optionalChain([options, 'optionalAccess', _5 => _5.operationHandlers]),
|
|
232
|
+
ignorePaths: _optionalChain([options, 'optionalAccess', _6 => _6.ignorePaths]),
|
|
233
|
+
validateApiSpec: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _7 => _7.validateApiSpec]), () => ( true)),
|
|
234
|
+
$refParser: _optionalChain([options, 'optionalAccess', _8 => _8.$refParser]),
|
|
235
|
+
serveSpec: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _9 => _9.serveSpec]), () => ( false)),
|
|
236
|
+
fileUploader: _optionalChain([options, 'optionalAccess', _10 => _10.fileUploader]),
|
|
237
|
+
initializeHandlers: _optionalChain([options, 'optionalAccess', _11 => _11.initializeHandlers])
|
|
238
|
+
};
|
|
239
|
+
};
|
|
240
|
+
var isOpenApiValidatorAvailable = async () => {
|
|
241
|
+
try {
|
|
242
|
+
await Promise.resolve().then(() => _interopRequireWildcard(require("express-openapi-validator")));
|
|
243
|
+
return true;
|
|
244
|
+
} catch (e2) {
|
|
245
|
+
return false;
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
// src/responses.ts
|
|
250
|
+
|
|
251
|
+
var DefaultHttpResponseOptions = {};
|
|
252
|
+
var DefaultHttpProblemResponseOptions = {
|
|
253
|
+
problemDetails: "Error occured!"
|
|
254
|
+
};
|
|
255
|
+
var sendCreated = (response, { eTag, ...options }) => send(response, 201, {
|
|
256
|
+
location: "url" in options ? options.url : `${response.req.url}/${options.createdId}`,
|
|
257
|
+
body: "createdId" in options ? { id: options.createdId } : void 0,
|
|
258
|
+
eTag
|
|
259
|
+
});
|
|
260
|
+
var sendAccepted = (response, options) => send(response, 202, options);
|
|
261
|
+
var send = (response, statusCode, options) => {
|
|
262
|
+
const { location, body, eTag } = _nullishCoalesce(options, () => ( DefaultHttpResponseOptions));
|
|
263
|
+
if (eTag) setETag(response, eTag);
|
|
264
|
+
if (location) response.setHeader("Location", location);
|
|
265
|
+
if (body) {
|
|
266
|
+
response.statusCode = statusCode;
|
|
267
|
+
response.send(body);
|
|
268
|
+
} else {
|
|
269
|
+
response.sendStatus(statusCode);
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
var sendProblem = (response, statusCode, options) => {
|
|
273
|
+
options = _nullishCoalesce(options, () => ( DefaultHttpProblemResponseOptions));
|
|
274
|
+
const { location, eTag } = options;
|
|
275
|
+
const problemDetails = "problem" in options ? options.problem : new (0, _httpproblemdetails.ProblemDocument)({
|
|
276
|
+
detail: options.problemDetails,
|
|
277
|
+
status: statusCode
|
|
278
|
+
});
|
|
279
|
+
if (eTag) setETag(response, eTag);
|
|
280
|
+
if (location) response.setHeader("Location", location);
|
|
281
|
+
response.setHeader("Content-Type", "application/problem+json");
|
|
282
|
+
response.statusCode = statusCode;
|
|
283
|
+
response.json(problemDetails);
|
|
284
|
+
};
|
|
285
|
+
|
|
286
|
+
// src/testing/apiE2ESpecification.ts
|
|
287
|
+
var _supertest = require('supertest'); var _supertest2 = _interopRequireDefault(_supertest);
|
|
288
|
+
var _assert = require('assert'); var _assert2 = _interopRequireDefault(_assert);
|
|
289
|
+
var ApiE2ESpecification = {
|
|
290
|
+
for: (getEventStore, getApplication2) => {
|
|
291
|
+
{
|
|
292
|
+
return (...givenRequests) => {
|
|
293
|
+
const eventStore = getEventStore();
|
|
294
|
+
return {
|
|
295
|
+
when: (setupRequest) => {
|
|
296
|
+
const handle = async () => {
|
|
297
|
+
const application = await Promise.resolve(getApplication2(eventStore));
|
|
298
|
+
for (const requestFn of givenRequests) {
|
|
299
|
+
await requestFn(_supertest2.default.call(void 0, application));
|
|
300
|
+
}
|
|
301
|
+
return setupRequest(_supertest2.default.call(void 0, application));
|
|
302
|
+
};
|
|
303
|
+
return {
|
|
304
|
+
then: async (verify) => {
|
|
305
|
+
const response = await handle();
|
|
306
|
+
verify.forEach((assertion) => {
|
|
307
|
+
const succeeded = assertion(response);
|
|
308
|
+
if (succeeded === false) _assert2.default.fail();
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
|
|
319
|
+
// src/testing/apiSpecification.ts
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
var _emmett = require('@event-driven-io/emmett');
|
|
326
|
+
|
|
327
|
+
var existingStream = (streamId, events) => {
|
|
328
|
+
return [streamId, events];
|
|
329
|
+
};
|
|
330
|
+
var expect = (streamId, events) => {
|
|
331
|
+
return [streamId, events];
|
|
332
|
+
};
|
|
333
|
+
var expectNewEvents = (streamId, events) => {
|
|
334
|
+
return [streamId, events];
|
|
335
|
+
};
|
|
336
|
+
var expectResponse = (statusCode, options) => (response) => {
|
|
337
|
+
const { body, headers } = _nullishCoalesce(options, () => ( {}));
|
|
338
|
+
_emmett.assertEqual.call(void 0, statusCode, response.statusCode, "Response code doesn't match");
|
|
339
|
+
if (body) _emmett.assertMatches.call(void 0, response.body, body);
|
|
340
|
+
if (headers) _emmett.assertMatches.call(void 0, response.headers, headers);
|
|
341
|
+
};
|
|
342
|
+
var expectError = (errorCode, problemDetails) => expectResponse(
|
|
343
|
+
errorCode,
|
|
344
|
+
problemDetails ? { body: problemDetails } : void 0
|
|
345
|
+
);
|
|
346
|
+
var ApiSpecification = {
|
|
347
|
+
for: (getEventStore, getApplication2) => {
|
|
348
|
+
{
|
|
349
|
+
return (...givenStreams) => {
|
|
350
|
+
const eventStore = _emmett.WrapEventStore.call(void 0, getEventStore());
|
|
351
|
+
return {
|
|
352
|
+
when: (setupRequest) => {
|
|
353
|
+
const handle = async () => {
|
|
354
|
+
const application = await Promise.resolve(getApplication2(eventStore));
|
|
355
|
+
for (const [streamName, events] of givenStreams) {
|
|
356
|
+
await eventStore.setup(streamName, events);
|
|
357
|
+
}
|
|
358
|
+
return setupRequest(_supertest2.default.call(void 0, application));
|
|
359
|
+
};
|
|
360
|
+
return {
|
|
361
|
+
then: async (verify) => {
|
|
362
|
+
const response = await handle();
|
|
363
|
+
if (typeof verify === "function") {
|
|
364
|
+
const succeeded = verify(response);
|
|
365
|
+
if (succeeded === false) _emmett.assertFails.call(void 0, );
|
|
366
|
+
} else if (Array.isArray(verify)) {
|
|
367
|
+
const [first, ...rest] = verify;
|
|
368
|
+
if (typeof first === "function") {
|
|
369
|
+
const succeeded = first(response);
|
|
370
|
+
if (succeeded === false) _emmett.assertFails.call(void 0, );
|
|
371
|
+
}
|
|
372
|
+
const events = typeof first === "function" ? rest : verify;
|
|
373
|
+
_emmett.assertMatches.call(void 0,
|
|
374
|
+
Array.from(eventStore.appendedEvents.values()),
|
|
375
|
+
events
|
|
376
|
+
);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
exports.Accepted = Accepted; exports.ApiE2ESpecification = ApiE2ESpecification; exports.ApiSpecification = ApiSpecification; exports.BadRequest = BadRequest; exports.Conflict = Conflict; exports.Created = Created; exports.DefaultHttpProblemResponseOptions = DefaultHttpProblemResponseOptions; exports.DefaultHttpResponseOptions = DefaultHttpResponseOptions; exports.ETagErrors = ETagErrors; exports.Forbidden = Forbidden; exports.HeaderNames = HeaderNames; exports.HttpProblem = HttpProblem; exports.HttpResponse = HttpResponse; exports.NoContent = NoContent; exports.NotFound = NotFound; exports.OK = OK; exports.PreconditionFailed = PreconditionFailed; exports.WeakETagRegex = WeakETagRegex; exports.createOpenApiValidatorOptions = createOpenApiValidatorOptions; exports.existingStream = existingStream; exports.expect = expect; exports.expectError = expectError; exports.expectNewEvents = expectNewEvents; exports.expectResponse = expectResponse; exports.getApplication = getApplication; exports.getETagFromIfMatch = getETagFromIfMatch; exports.getETagFromIfNotMatch = getETagFromIfNotMatch; exports.getETagValueFromIfMatch = getETagValueFromIfMatch; exports.getWeakETagValue = getWeakETagValue; exports.isOpenApiValidatorAvailable = isOpenApiValidatorAvailable; exports.isWeakETag = isWeakETag; exports.on = on; exports.registerHandlerModule = _chunkMRSGTROWcjs.registerHandlerModule; exports.send = send; exports.sendAccepted = sendAccepted; exports.sendCreated = sendCreated; exports.sendProblem = sendProblem; exports.setETag = setETag; exports.startAPI = startAPI; exports.toWeakETag = toWeakETag;
|
|
428
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/axcosta/Git/pessoal/oss/emmett-community/emmett-expressjs-with-openapi/dist/index.cjs","../src/index.ts","../src/application.ts","../src/middlewares/problemDetailsMiddleware.ts","../src/etag.ts","../src/handler.ts","../src/openapi/index.ts","../src/responses.ts","../src/testing/apiE2ESpecification.ts","../src/testing/apiSpecification.ts"],"names":["require","ETagErrors"],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACPA,gCAAO;ADSP;AACA;AEVA;AACE;AAAA,oFAGK;AACP;AACA,wEAAiB;AACjB,gCAA8B;AFU9B;AACA;AGjBA,0DAAgC;AAGzB,IAAM,yBAAA,EACX,CAAC,QAAA,EAAA,GACD,CACE,KAAA,EACA,OAAA,EACA,QAAA,EACA,KAAA,EAAA,GACS;AACT,EAAA,IAAI,cAAA;AAEJ,EAAA,GAAA,CAAI,QAAA,EAAU,eAAA,EAAiB,QAAA,CAAS,KAAA,EAAO,OAAO,CAAA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ACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/axcosta/Git/pessoal/oss/emmett-community/emmett-expressjs-with-openapi/dist/index.cjs","sourcesContent":[null,"import 'express-async-errors';\n\nexport * from './application';\nexport * from './etag';\nexport * from './handler';\nexport * from './openapi';\nexport * from './responses';\nexport * from './testing';\nexport { registerHandlerModule } from './internal/esm-resolver';\n","import express, {\n Router,\n type Application,\n type RequestHandler,\n} from 'express';\nimport 'express-async-errors';\nimport http from 'http';\nimport { createRequire } from 'node:module';\nimport { problemDetailsMiddleware } from './middlewares/problemDetailsMiddleware';\nimport type { OpenApiValidatorOptions } from './openapi';\nimport type { ErrorToProblemDetailsMapping } from './responses';\n\n// #region web-api-setup\nexport type WebApiSetup = (router: Router) => void;\n// #endregion web-api-setup\n\nexport type ApplicationOptions = {\n apis?: WebApiSetup[];\n mapError?: ErrorToProblemDetailsMapping;\n enableDefaultExpressEtag?: boolean;\n disableJsonMiddleware?: boolean;\n disableUrlEncodingMiddleware?: boolean;\n disableProblemDetailsMiddleware?: boolean;\n /**\n * Optional OpenAPI validator configuration.\n * When provided, enables request/response validation against an OpenAPI specification.\n * Requires the 'express-openapi-validator' package to be installed.\n *\n * @see https://github.com/cdimascio/express-openapi-validator\n * @example\n * ```typescript\n * import { getApplication, createOpenApiValidatorOptions } from '@event-driven-io/emmett-expressjs';\n *\n * type AppDeps = {\n * eventStore: EventStore;\n * messageBus: EventsPublisher;\n * };\n *\n * const app = await getApplication({\n * openApiValidator: createOpenApiValidatorOptions<AppDeps>('./openapi.yaml', {\n * validateResponses: true,\n * operationHandlers: './handlers',\n * initializeHandlers: (deps) => {\n * initializeHandlers(deps.eventStore, deps.messageBus);\n * }\n * })\n * });\n * ```\n */\n openApiValidator?: OpenApiValidatorOptions;\n};\n\nexport const getApplication = async (options: ApplicationOptions) => {\n const app: Application = express();\n\n const {\n apis,\n mapError,\n enableDefaultExpressEtag,\n disableJsonMiddleware,\n disableUrlEncodingMiddleware,\n disableProblemDetailsMiddleware,\n openApiValidator,\n } = options;\n\n const router = Router();\n\n // disabling default etag behaviour\n // to use etags in if-match and if-not-match headers\n app.set('etag', enableDefaultExpressEtag ?? false);\n\n // add json middleware\n if (!disableJsonMiddleware) app.use(express.json());\n\n // enable url encoded urls and bodies\n if (!disableUrlEncodingMiddleware)\n app.use(\n express.urlencoded({\n extended: true,\n }),\n );\n\n // add OpenAPI validator middleware if configured\n if (openApiValidator) {\n // Activate ESM resolver if operationHandlers are configured\n // This ensures handler modules are loaded via ESM import() instead of CJS require(),\n // preventing dual module loading issues when using TypeScript runtimes (tsx, ts-node)\n if (openApiValidator.operationHandlers) {\n const { activateESMResolver } = await import(\n './internal/esm-resolver.js'\n );\n activateESMResolver();\n\n // NEW: Auto-discover and import handler modules from OpenAPI spec\n const handlersBasePath =\n typeof openApiValidator.operationHandlers === 'string'\n ? openApiValidator.operationHandlers\n : openApiValidator.operationHandlers.basePath;\n\n if (handlersBasePath) {\n const { extractHandlerModules } = await import(\n './internal/openapi-parser.js'\n );\n const { importAndRegisterHandlers } = await import(\n './internal/handler-importer.js'\n );\n\n try {\n // Parse OpenAPI spec to find handler modules\n const modules = await extractHandlerModules(\n openApiValidator.apiSpec,\n handlersBasePath,\n );\n\n // Dynamically import and register all handler modules\n const importedHandlers = await importAndRegisterHandlers(modules);\n\n // Call user's initializeHandlers callback with imported modules\n if (openApiValidator.initializeHandlers) {\n await openApiValidator.initializeHandlers(importedHandlers);\n }\n } catch (error) {\n console.error('Failed to auto-import handler modules:', error);\n throw error;\n }\n }\n } else {\n // No operationHandlers, just call initializeHandlers if provided\n if (openApiValidator.initializeHandlers) {\n await openApiValidator.initializeHandlers();\n }\n }\n\n try {\n const require = createRequire(import.meta.url);\n // express-openapi-validator exports a default with .middleware (ESM/CJS compatibility)\n const mod = require('express-openapi-validator') as Record<\n string,\n unknown\n >;\n const provider = (mod.default ?? mod) as Record<string, unknown>;\n\n if (typeof provider.middleware !== 'function') {\n throw new Error(\n 'Invalid express-openapi-validator module: missing middleware export',\n );\n }\n\n // Serve OpenAPI spec if configured\n if (openApiValidator.serveSpec) {\n if (typeof openApiValidator.apiSpec === 'string') {\n // If apiSpec is a file path, serve it as a static file\n app.use(\n openApiValidator.serveSpec,\n express.static(openApiValidator.apiSpec),\n );\n } else {\n // If apiSpec is an object, serve it as JSON\n app.get(openApiValidator.serveSpec, (_req, res) => {\n res.json(openApiValidator.apiSpec);\n });\n }\n }\n\n const factory = provider.middleware as (\n opts: OpenApiValidatorOptions,\n ) => RequestHandler | RequestHandler[];\n const middleware = factory(openApiValidator);\n if (Array.isArray(middleware)) {\n for (const m of middleware) app.use(m);\n } else {\n app.use(middleware);\n }\n } catch {\n console.warn(\n 'OpenAPI validator configuration provided but express-openapi-validator package is not installed. ' +\n 'Install it with: npm install express-openapi-validator',\n );\n throw new Error(\n 'express-openapi-validator package is required when openApiValidator option is used',\n );\n }\n }\n\n // Register API routes if provided\n if (apis) {\n for (const api of apis) {\n api(router);\n }\n app.use(router);\n }\n\n // add problem details middleware\n if (!disableProblemDetailsMiddleware)\n app.use(problemDetailsMiddleware(mapError));\n\n return app;\n};\n\nexport type StartApiOptions = {\n port?: number;\n};\n\nexport const startAPI = (\n app: Application,\n options: StartApiOptions = { port: 3000 },\n) => {\n const { port } = options;\n const server = http.createServer(app);\n\n server.on('listening', () => {\n console.info('server up listening');\n });\n\n return server.listen(port);\n};\n","import type { NextFunction, Request, Response } from 'express';\nimport { ProblemDocument } from 'http-problem-details';\nimport { sendProblem, type ErrorToProblemDetailsMapping } from '..';\n\nexport const problemDetailsMiddleware =\n (mapError?: ErrorToProblemDetailsMapping) =>\n (\n error: Error,\n request: Request,\n response: Response,\n _next: NextFunction,\n ): void => {\n let problemDetails: ProblemDocument | undefined;\n\n if (mapError) problemDetails = mapError(error, request);\n\n problemDetails =\n problemDetails ?? defaultErrorToProblemDetailsMapping(error);\n\n sendProblem(response, problemDetails.status, { problem: problemDetails });\n };\n\nexport const defaultErrorToProblemDetailsMapping = (\n error: Error,\n): ProblemDocument => {\n let statusCode = 500;\n\n // Prefer standard `status` code if present (e.g., express-openapi-validator)\n const errObj = error as unknown as Record<string, unknown>;\n const maybeStatus = errObj['status'];\n if (\n typeof maybeStatus === 'number' &&\n maybeStatus >= 100 &&\n maybeStatus < 600\n ) {\n statusCode = maybeStatus;\n }\n\n const maybeErrorCode = errObj['errorCode'];\n if (\n typeof maybeErrorCode === 'number' &&\n maybeErrorCode >= 100 &&\n maybeErrorCode < 600\n ) {\n statusCode = maybeErrorCode;\n }\n\n return new ProblemDocument({\n detail: error.message,\n status: statusCode,\n });\n};\n","import { type Brand } from '@event-driven-io/emmett';\nimport type { Request, Response } from 'express';\n\n//////////////////////////////////////\n/// ETAG\n//////////////////////////////////////\n\nexport const HeaderNames = {\n IF_MATCH: 'if-match',\n IF_NOT_MATCH: 'if-not-match',\n ETag: 'etag',\n};\n\nexport type WeakETag = Brand<`W/${string}`, 'ETag'>;\nexport type ETag = Brand<string, 'ETag'>;\n\nexport const WeakETagRegex = /W\\/\"(-?\\d+.*)\"/;\n\nexport const enum ETagErrors {\n WRONG_WEAK_ETAG_FORMAT = 'WRONG_WEAK_ETAG_FORMAT',\n MISSING_IF_MATCH_HEADER = 'MISSING_IF_MATCH_HEADER',\n MISSING_IF_NOT_MATCH_HEADER = 'MISSING_IF_NOT_MATCH_HEADER',\n}\n\nexport const isWeakETag = (etag: ETag): etag is WeakETag => {\n return WeakETagRegex.test(etag as string);\n};\n\nexport const getWeakETagValue = (etag: ETag): string => {\n const result = WeakETagRegex.exec(etag as string);\n if (result === null || result.length === 0) {\n throw new Error(ETagErrors.WRONG_WEAK_ETAG_FORMAT);\n }\n return result[1]!;\n};\n\nexport const toWeakETag = (value: number | bigint | string): WeakETag => {\n return `W/\"${value}\"` as WeakETag;\n};\n\nexport const getETagFromIfMatch = (request: Request): ETag => {\n const etag = request.headers[HeaderNames.IF_MATCH];\n\n if (etag === undefined) {\n throw new Error(ETagErrors.MISSING_IF_MATCH_HEADER);\n }\n\n return etag as ETag;\n};\n\nexport const getETagFromIfNotMatch = (request: Request): ETag => {\n const etag = request.headers[HeaderNames.IF_NOT_MATCH];\n\n if (etag === undefined) {\n throw new Error(ETagErrors.MISSING_IF_MATCH_HEADER);\n }\n\n return (Array.isArray(etag) ? etag[0] : etag) as ETag;\n};\n\nexport const setETag = (response: Response, etag: ETag): void => {\n response.setHeader(HeaderNames.ETag, etag as string);\n};\n\nexport const getETagValueFromIfMatch = (request: Request): string => {\n const eTagValue: ETag = getETagFromIfMatch(request);\n\n return isWeakETag(eTagValue)\n ? getWeakETagValue(eTagValue)\n : (eTagValue as string);\n};\n","import { type NextFunction, type Request, type Response } from 'express';\nimport {\n send,\n sendAccepted,\n sendCreated,\n sendProblem,\n type AcceptedHttpResponseOptions,\n type CreatedHttpResponseOptions,\n type HttpProblemResponseOptions,\n type HttpResponseOptions,\n type NoContentHttpResponseOptions,\n} from '.';\n\n// #region httpresponse-on\nexport type HttpResponse = (response: Response) => void;\n\nexport type HttpHandler<RequestType extends Request> = (\n request: RequestType,\n) => Promise<HttpResponse> | HttpResponse;\n\nexport const on =\n <RequestType extends Request>(handle: HttpHandler<RequestType>) =>\n async (\n request: RequestType,\n response: Response,\n _next: NextFunction,\n ): Promise<void> => {\n const setResponse = await Promise.resolve(handle(request));\n\n return setResponse(response);\n };\n// #endregion httpresponse-on\n\nexport const OK =\n (options?: HttpResponseOptions): HttpResponse =>\n (response: Response) => {\n send(response, 200, options);\n };\n\nexport const Created =\n (options: CreatedHttpResponseOptions): HttpResponse =>\n (response: Response) => {\n sendCreated(response, options);\n };\n\nexport const Accepted =\n (options: AcceptedHttpResponseOptions): HttpResponse =>\n (response: Response) => {\n sendAccepted(response, options);\n };\n\nexport const NoContent = (\n options?: NoContentHttpResponseOptions,\n): HttpResponse => HttpResponse(204, options);\n\nexport const HttpResponse =\n (statusCode: number, options?: HttpResponseOptions): HttpResponse =>\n (response: Response) => {\n send(response, statusCode, options);\n };\n\n/////////////////////\n// ERRORS\n/////////////////////\n\nexport const BadRequest = (\n options?: HttpProblemResponseOptions,\n): HttpResponse => HttpProblem(400, options);\n\nexport const Forbidden = (options?: HttpProblemResponseOptions): HttpResponse =>\n HttpProblem(403, options);\n\nexport const NotFound = (options?: HttpProblemResponseOptions): HttpResponse =>\n HttpProblem(404, options);\n\nexport const Conflict = (options?: HttpProblemResponseOptions): HttpResponse =>\n HttpProblem(409, options);\n\nexport const PreconditionFailed = (\n options: HttpProblemResponseOptions,\n): HttpResponse => HttpProblem(412, options);\n\nexport const HttpProblem =\n (statusCode: number, options?: HttpProblemResponseOptions): HttpResponse =>\n (response: Response) => {\n sendProblem(response, statusCode, options);\n };\n","/**\n * OpenAPI v3 Document type (to avoid requiring express-openapi-validator types directly)\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type OpenAPIV3Document = any;\n\n/**\n * Imported handler modules, keyed by module name.\n * Automatically populated by the framework when operationHandlers is configured.\n */\nexport type ImportedHandlerModules = Record<string, any>;\n\n/**\n * Security handlers for custom authentication/authorization logic.\n * Maps security scheme names to handler functions.\n *\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-validate-security/\n */\n\nexport type SecurityHandlers = Record<\n string,\n (req: any, scopes: string[], schema: any) => boolean | Promise<boolean>\n>;\n\n/**\n * Configuration options for express-openapi-validator middleware.\n * This allows optional validation of API requests and responses against an OpenAPI specification.\n *\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/\n */\nexport type OpenApiValidatorOptions = {\n /**\n * Path to the OpenAPI specification file (JSON or YAML)\n * or an OpenAPI specification object.\n */\n apiSpec: string | OpenAPIV3Document;\n\n /**\n * Determines whether the validator should validate requests.\n * Can be a boolean or an object with detailed request validation options.\n * @default true\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-validate-requests/\n */\n validateRequests?:\n | boolean\n | {\n /**\n * Allow unknown query parameters (not defined in the spec).\n * @default false\n */\n allowUnknownQueryParameters?: boolean;\n /**\n * Coerce types in request parameters.\n * @default true\n */\n coerceTypes?: boolean | 'array';\n /**\n * Remove additional properties not defined in the spec.\n * @default false\n */\n removeAdditional?: boolean | 'all' | 'failing';\n };\n\n /**\n * Determines whether the validator should validate responses.\n * Can be a boolean or an object with detailed response validation options.\n * @default false\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-validate-responses/\n */\n validateResponses?:\n | boolean\n | {\n /**\n * Remove additional properties from responses not defined in the spec.\n * @default false\n */\n removeAdditional?: boolean | 'all' | 'failing';\n /**\n * Coerce types in responses.\n * @default true\n */\n coerceTypes?: boolean;\n /**\n * Callback to handle response validation errors.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n onError?: (error: any, body: any, req: any) => void;\n };\n\n /**\n * Determines whether the validator should validate security.\n * Can be a boolean or an object with security handlers.\n * @default true\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-validate-security/\n */\n validateSecurity?:\n | boolean\n | {\n /**\n * Custom security handlers for authentication/authorization.\n */\n handlers?: SecurityHandlers;\n };\n\n /**\n * Defines how the validator should validate formats.\n * When true, uses ajv-formats for format validation.\n * When false, format validation is disabled.\n * Can also be 'fast' or 'full' for different validation modes.\n * @default true\n */\n validateFormats?: boolean | 'fast' | 'full';\n\n /**\n * The base path to the operation handlers directory.\n * When set to a path, automatically wires OpenAPI operations to handler functions\n * based on operationId or x-eov-operation-id.\n * When false, operation handlers are disabled (manual routing required).\n * @default false\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/guide-operation-handlers/\n */\n operationHandlers?:\n | string\n | false\n | {\n /**\n * Base path to operation handlers directory.\n */\n basePath?: string;\n /**\n * Resolver function to map operationId to handler module path.\n */\n resolver?: (\n handlersPath: string,\n route: string,\n apiDoc: OpenAPIV3Document,\n ) => string;\n };\n\n /**\n * Paths or pattern to ignore during validation.\n * @default undefined\n */\n ignorePaths?: RegExp | ((path: string) => boolean);\n\n /**\n * Validate the OpenAPI specification itself.\n * @default true\n */\n validateApiSpec?: boolean;\n\n /**\n * $ref parser configuration for handling OpenAPI references.\n * @default undefined\n */\n $refParser?: {\n mode: 'bundle' | 'dereference';\n };\n\n /**\n * Serve the OpenAPI specification at a specific path.\n * When set to a string, the spec will be served at that path.\n * When false, the spec will not be served.\n * @default false\n * @example '/api-docs/openapi.json'\n */\n serveSpec?: string | false;\n\n /**\n * File upload configuration options.\n * @see https://cdimascio.github.io/express-openapi-validator-documentation/usage-file-uploads/\n */\n fileUploader?:\n | boolean\n | {\n /**\n * Destination directory for uploaded files.\n */\n dest?: string;\n /**\n * File size limit in bytes.\n */\n limits?: {\n fileSize?: number;\n files?: number;\n };\n };\n\n /**\n * Optional callback to initialize operation handlers with dependencies.\n * Called before the OpenAPI validator middleware is configured.\n *\n * The framework automatically imports handler modules referenced in your\n * OpenAPI spec (via x-eov-operation-handler) and passes them as the first parameter.\n *\n * @param handlers - Auto-imported handler modules, keyed by module name\n * @returns void or a Promise that resolves when initialization is complete\n *\n * @example\n * ```typescript\n * // With automatic import (recommended)\n * initializeHandlers: async (handlers) => {\n * handlers.shoppingCarts.initializeHandlers(eventStore, messageBus, getUnitPrice, getCurrentTime);\n * }\n *\n * // Manual import (still supported for backward compatibility)\n * import * as handlersModule from './handlers/shoppingCarts';\n * import { registerHandlerModule } from '@emmett-community/emmett-expressjs-with-openapi';\n * initializeHandlers: () => {\n * const handlersPath = path.join(__dirname, './handlers/shoppingCarts');\n * registerHandlerModule(handlersPath, handlersModule);\n * handlersModule.initializeHandlers(eventStore, messageBus, getUnitPrice, getCurrentTime);\n * }\n * ```\n */\n initializeHandlers?: (\n handlers?: ImportedHandlerModules,\n ) => void | Promise<void>;\n};\n\n/**\n * Helper function to create OpenAPI validator configuration with sensible defaults.\n *\n * @param apiSpec - Path to OpenAPI spec file or OpenAPI document object\n * @param options - Additional validator options\n * @returns Complete OpenApiValidatorOptions configuration\n *\n * @example\n * ```typescript\n * // Basic usage with default options\n * const validatorOptions = createOpenApiValidatorOptions('./openapi.yaml');\n *\n * // With response validation enabled\n * const validatorOptions = createOpenApiValidatorOptions('./openapi.yaml', {\n * validateResponses: true\n * });\n *\n * // With custom security handlers\n * const validatorOptions = createOpenApiValidatorOptions('./openapi.yaml', {\n * validateSecurity: {\n * handlers: {\n * bearerAuth: async (req, scopes) => {\n * // Custom authentication logic\n * return true;\n * }\n * }\n * }\n * });\n *\n * // Serving the spec at /api-docs\n * const validatorOptions = createOpenApiValidatorOptions('./openapi.yaml', {\n * serveSpec: '/api-docs/openapi.json'\n * });\n *\n * // With dependency injection for operation handlers\n * type ShoppingCartDeps = {\n * eventStore: EventStore;\n * messageBus: EventsPublisher;\n * getUnitPrice: (productId: string) => Promise<number>;\n * getCurrentTime: () => Date;\n * };\n *\n * const validatorOptions = createOpenApiValidatorOptions<ShoppingCartDeps>(\n * './openapi.yaml',\n * {\n * operationHandlers: './handlers',\n * initializeHandlers: (deps) => {\n * initializeHandlers(\n * deps.eventStore,\n * deps.messageBus,\n * deps.getUnitPrice,\n * deps.getCurrentTime\n * );\n * }\n * }\n * );\n *\n * const app = getApplication({\n * apis: [myApi],\n * openApiValidator: validatorOptions\n * });\n * ```\n */\nexport const createOpenApiValidatorOptions = (\n apiSpec: string | OpenAPIV3Document,\n options?: Partial<Omit<OpenApiValidatorOptions, 'apiSpec'>>,\n): OpenApiValidatorOptions => {\n return {\n apiSpec,\n validateRequests: options?.validateRequests ?? true,\n validateResponses: options?.validateResponses ?? false,\n validateSecurity: options?.validateSecurity ?? true,\n validateFormats: options?.validateFormats ?? true,\n operationHandlers: options?.operationHandlers,\n ignorePaths: options?.ignorePaths,\n validateApiSpec: options?.validateApiSpec ?? true,\n $refParser: options?.$refParser,\n serveSpec: options?.serveSpec ?? false,\n fileUploader: options?.fileUploader,\n initializeHandlers: options?.initializeHandlers,\n };\n};\n\n/**\n * Type guard to check if express-openapi-validator is available\n */\nexport const isOpenApiValidatorAvailable = async (): Promise<boolean> => {\n try {\n await import('express-openapi-validator');\n return true;\n } catch {\n return false;\n }\n};\n","import { type Request, type Response } from 'express';\nimport { ProblemDocument } from 'http-problem-details';\nimport { setETag, type ETag } from './etag';\n\nexport type ErrorToProblemDetailsMapping = (\n error: Error,\n request: Request,\n) => ProblemDocument | undefined;\n\nexport type HttpResponseOptions = {\n body?: unknown;\n location?: string;\n eTag?: ETag;\n};\nexport const DefaultHttpResponseOptions: HttpResponseOptions = {};\n\nexport type HttpProblemResponseOptions = {\n location?: string;\n eTag?: ETag;\n} & Omit<HttpResponseOptions, 'body'> &\n (\n | {\n problem: ProblemDocument;\n }\n | { problemDetails: string }\n );\nexport const DefaultHttpProblemResponseOptions: HttpProblemResponseOptions = {\n problemDetails: 'Error occured!',\n};\n\nexport type CreatedHttpResponseOptions = (\n | {\n createdId: string;\n }\n | {\n createdId?: string;\n url: string;\n }\n) &\n HttpResponseOptions;\n\nexport const sendCreated = (\n response: Response,\n { eTag, ...options }: CreatedHttpResponseOptions,\n): void =>\n send(response, 201, {\n location:\n 'url' in options\n ? options.url\n : `${response.req.url}/${options.createdId}`,\n body: 'createdId' in options ? { id: options.createdId } : undefined,\n eTag,\n });\n\nexport type AcceptedHttpResponseOptions = {\n location: string;\n} & HttpResponseOptions;\n\nexport const sendAccepted = (\n response: Response,\n options: AcceptedHttpResponseOptions,\n): void => send(response, 202, options);\n\nexport type NoContentHttpResponseOptions = Omit<HttpResponseOptions, 'body'>;\n\nexport const send = (\n response: Response,\n statusCode: number,\n options?: HttpResponseOptions,\n): void => {\n const { location, body, eTag } = options ?? DefaultHttpResponseOptions;\n // HEADERS\n if (eTag) setETag(response, eTag);\n if (location) response.setHeader('Location', location);\n\n if (body) {\n response.statusCode = statusCode;\n response.send(body);\n } else {\n response.sendStatus(statusCode);\n }\n};\n\nexport const sendProblem = (\n response: Response,\n statusCode: number,\n options?: HttpProblemResponseOptions,\n): void => {\n options = options ?? DefaultHttpProblemResponseOptions;\n\n const { location, eTag } = options;\n\n const problemDetails =\n 'problem' in options\n ? options.problem\n : new ProblemDocument({\n detail: options.problemDetails,\n status: statusCode,\n });\n\n // HEADERS\n if (eTag) setETag(response, eTag);\n if (location) response.setHeader('Location', location);\n\n response.setHeader('Content-Type', 'application/problem+json');\n\n response.statusCode = statusCode;\n response.json(problemDetails);\n};\n","import supertest, { type Response } from 'supertest';\n\nimport type { EventStore } from '@event-driven-io/emmett';\nimport assert from 'assert';\nimport type { Application } from 'express';\nimport type { TestRequest } from './apiSpecification';\n\nexport type E2EResponseAssert = (response: Response) => boolean | void;\n\nexport type ApiE2ESpecificationAssert = [E2EResponseAssert];\n\nexport type ApiE2ESpecification = (...givenRequests: TestRequest[]) => {\n when: (setupRequest: TestRequest) => {\n then: (verify: ApiE2ESpecificationAssert) => Promise<void>;\n };\n};\n\nexport const ApiE2ESpecification = {\n for: <Store extends EventStore = EventStore>(\n getEventStore: () => Store,\n getApplication: (eventStore: Store) => Application | Promise<Application>,\n ): ApiE2ESpecification => {\n {\n return (...givenRequests: TestRequest[]) => {\n const eventStore = getEventStore();\n\n return {\n when: (setupRequest: TestRequest) => {\n const handle = async () => {\n const application = await Promise.resolve(getApplication(eventStore));\n\n for (const requestFn of givenRequests) {\n await requestFn(supertest(application));\n }\n\n return setupRequest(supertest(application));\n };\n\n return {\n then: async (\n verify: ApiE2ESpecificationAssert,\n ): Promise<void> => {\n const response = await handle();\n\n verify.forEach((assertion) => {\n const succeeded = assertion(response);\n\n if (succeeded === false) assert.fail();\n });\n },\n };\n },\n };\n };\n }\n },\n};\n","import {\n WrapEventStore,\n assertEqual,\n assertFails,\n assertMatches,\n type Event,\n type EventStore,\n type TestEventStream,\n} from '@event-driven-io/emmett';\nimport { type Application } from 'express';\nimport type { ProblemDocument } from 'http-problem-details';\nimport type { Response, Test } from 'supertest';\nimport supertest from 'supertest';\nimport type TestAgent from 'supertest/lib/agent';\n\n////////////////////////////////\n/////////// Setup\n////////////////////////////////\n\nexport type TestRequest = (request: TestAgent<supertest.Test>) => Test;\n\nexport const existingStream = <EventType extends Event = Event>(\n streamId: string,\n events: EventType[],\n): TestEventStream<EventType> => {\n return [streamId, events];\n};\n\n////////////////////////////////\n/////////// Asserts\n////////////////////////////////\n\nexport type ResponseAssert = (response: Response) => boolean | void;\n\nexport type ApiSpecificationAssert<EventType extends Event = Event> =\n | TestEventStream<EventType>[]\n | ResponseAssert\n | [ResponseAssert, ...TestEventStream<EventType>[]];\n\nexport const expect = <EventType extends Event = Event>(\n streamId: string,\n events: EventType[],\n): TestEventStream<EventType> => {\n return [streamId, events];\n};\n\nexport const expectNewEvents = <EventType extends Event = Event>(\n streamId: string,\n events: EventType[],\n): TestEventStream<EventType> => {\n return [streamId, events];\n};\n\nexport const expectResponse =\n <Body = unknown>(\n statusCode: number,\n options?: { body?: Body; headers?: { [index: string]: string } },\n ) =>\n (response: Response): void => {\n const { body, headers } = options ?? {};\n assertEqual(statusCode, response.statusCode, \"Response code doesn't match\");\n if (body) assertMatches(response.body, body);\n if (headers) assertMatches(response.headers, headers);\n };\n\nexport const expectError = (\n errorCode: number,\n problemDetails?: Partial<ProblemDocument>,\n) =>\n expectResponse(\n errorCode,\n problemDetails ? { body: problemDetails } : undefined,\n );\n\n////////////////////////////////\n/////////// Api Specification\n////////////////////////////////\n\nexport type ApiSpecification<EventType extends Event = Event> = (\n ...givenStreams: TestEventStream<EventType>[]\n) => {\n when: (setupRequest: TestRequest) => {\n then: (verify: ApiSpecificationAssert<EventType>) => Promise<void>;\n };\n};\n\nexport const ApiSpecification = {\n for: <\n EventType extends Event = Event,\n Store extends EventStore<import('@event-driven-io/emmett').ReadEventMetadataWithGlobalPosition> = EventStore<import('@event-driven-io/emmett').ReadEventMetadataWithGlobalPosition>\n >(\n getEventStore: () => Store,\n getApplication: (eventStore: Store) => Application | Promise<Application>,\n ): ApiSpecification<EventType> => {\n {\n return (...givenStreams: TestEventStream<EventType>[]) => {\n const eventStore = WrapEventStore(getEventStore());\n\n return {\n when: (setupRequest: TestRequest) => {\n const handle = async () => {\n const application = await Promise.resolve(getApplication(eventStore));\n\n for (const [streamName, events] of givenStreams) {\n await eventStore.setup(streamName, events);\n }\n\n return setupRequest(supertest(application));\n };\n\n return {\n then: async (\n verify: ApiSpecificationAssert<EventType>,\n ): Promise<void> => {\n const response = await handle();\n\n if (typeof verify === 'function') {\n const succeeded = verify(response);\n\n if (succeeded === false) assertFails();\n } else if (Array.isArray(verify)) {\n const [first, ...rest] = verify;\n\n if (typeof first === 'function') {\n const succeeded = first(response);\n\n if (succeeded === false) assertFails();\n }\n\n const events = typeof first === 'function' ? rest : verify;\n\n assertMatches(\n Array.from(eventStore.appendedEvents.values()),\n events,\n );\n }\n },\n };\n },\n };\n };\n }\n },\n};\n"]}
|