@tsed/platform-serverless 6.88.1 → 6.92.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 (65) hide show
  1. package/jest.config.js +2 -2
  2. package/lib/{builder → cjs/builder}/PlatformServerless.d.ts +0 -0
  3. package/lib/cjs/builder/PlatformServerless.js +156 -0
  4. package/lib/cjs/builder/PlatformServerless.js.map +1 -0
  5. package/lib/{builder → cjs/builder}/PlatformServerlessHandler.d.ts +0 -0
  6. package/lib/cjs/builder/PlatformServerlessHandler.js +93 -0
  7. package/lib/cjs/builder/PlatformServerlessHandler.js.map +1 -0
  8. package/lib/{domain → cjs/domain}/ServerlessContext.d.ts +0 -0
  9. package/lib/cjs/domain/ServerlessContext.js +26 -0
  10. package/lib/cjs/domain/ServerlessContext.js.map +1 -0
  11. package/lib/{domain → cjs/domain}/ServerlessRequest.d.ts +0 -0
  12. package/lib/cjs/domain/ServerlessRequest.js +80 -0
  13. package/lib/cjs/domain/ServerlessRequest.js.map +1 -0
  14. package/lib/{domain → cjs/domain}/ServerlessResponse.d.ts +0 -0
  15. package/lib/cjs/domain/ServerlessResponse.js +193 -0
  16. package/lib/cjs/domain/ServerlessResponse.js.map +1 -0
  17. package/lib/{index.d.ts → cjs/index.d.ts} +0 -1
  18. package/lib/cjs/index.js +22 -0
  19. package/lib/cjs/index.js.map +1 -0
  20. package/lib/{utils → cjs/utils}/getRequestId.d.ts +0 -0
  21. package/lib/cjs/utils/getRequestId.js +13 -0
  22. package/lib/cjs/utils/getRequestId.js.map +1 -0
  23. package/lib/{utils → cjs/utils}/setResponseHeaders.d.ts +0 -0
  24. package/lib/cjs/utils/setResponseHeaders.js +35 -0
  25. package/lib/cjs/utils/setResponseHeaders.js.map +1 -0
  26. package/lib/esm/builder/PlatformServerless.js +133 -0
  27. package/lib/esm/builder/PlatformServerless.js.map +1 -0
  28. package/lib/esm/builder/PlatformServerlessHandler.js +90 -0
  29. package/lib/esm/builder/PlatformServerlessHandler.js.map +1 -0
  30. package/lib/esm/domain/ServerlessContext.js +22 -0
  31. package/lib/esm/domain/ServerlessContext.js.map +1 -0
  32. package/lib/esm/domain/ServerlessRequest.js +76 -0
  33. package/lib/esm/domain/ServerlessRequest.js.map +1 -0
  34. package/lib/esm/domain/ServerlessResponse.js +189 -0
  35. package/lib/esm/domain/ServerlessResponse.js.map +1 -0
  36. package/lib/esm/index.js +10 -0
  37. package/lib/esm/index.js.map +1 -0
  38. package/lib/esm/utils/getRequestId.js +9 -0
  39. package/lib/esm/utils/getRequestId.js.map +1 -0
  40. package/lib/esm/utils/setResponseHeaders.js +31 -0
  41. package/lib/esm/utils/setResponseHeaders.js.map +1 -0
  42. package/lib/types/builder/PlatformServerless.d.ts +31 -0
  43. package/lib/types/builder/PlatformServerlessHandler.d.ts +19 -0
  44. package/lib/types/domain/ServerlessContext.d.ts +19 -0
  45. package/lib/types/domain/ServerlessRequest.d.ts +55 -0
  46. package/lib/types/domain/ServerlessResponse.d.ts +105 -0
  47. package/lib/types/index.d.ts +8 -0
  48. package/lib/types/utils/getRequestId.d.ts +2 -0
  49. package/lib/types/utils/setResponseHeaders.d.ts +5 -0
  50. package/package.json +18 -13
  51. package/readme.md +184 -20
  52. package/tsconfig.compile.esm.json +23 -0
  53. package/lib/index-a6c91998.js +0 -955
  54. package/lib/index-a6c91998.js.map +0 -1
  55. package/lib/index-a7574150.js +0 -975
  56. package/lib/index-a7574150.js.map +0 -1
  57. package/lib/index-b255dcf0.js +0 -2350
  58. package/lib/index-b255dcf0.js.map +0 -1
  59. package/lib/index-eeb85309.js +0 -2354
  60. package/lib/index-eeb85309.js.map +0 -1
  61. package/lib/index.js +0 -90
  62. package/lib/index.js.map +0 -1
  63. package/lib/index.modern.js +0 -12
  64. package/lib/index.modern.js.map +0 -1
  65. package/lib/services/PlatformServerlessTest.d.ts +0 -46
@@ -1,955 +0,0 @@
1
- import { Inject, InjectorService, LazyInject, Injectable, ProviderScope, DIContext, createContainer, setLoggerLevel, DITest } from '@tsed/di';
2
- import { getStatusMessage, getOperationsRoutes, JsonEntityStore } from '@tsed/schema';
3
- import { PlatformParams, DeserializerPipe, ValidationPipe } from '@tsed/platform-params';
4
- import { __decorate, __metadata } from 'tslib';
5
- import { AnyToPromise, isSerializable, getValue, Env } from '@tsed/core';
6
- import { serialize } from '@tsed/json-mapper';
7
- import { $log } from '@tsed/logger';
8
- import encodeUrl from 'encodeurl';
9
- import * as mime from 'mime';
10
- import { v4 } from 'uuid';
11
-
12
- function _extends() {
13
- _extends = Object.assign || function (target) {
14
- for (var i = 1; i < arguments.length; i++) {
15
- var source = arguments[i];
16
-
17
- for (var key in source) {
18
- if (Object.prototype.hasOwnProperty.call(source, key)) {
19
- target[key] = source[key];
20
- }
21
- }
22
- }
23
-
24
- return target;
25
- };
26
-
27
- return _extends.apply(this, arguments);
28
- }
29
-
30
- function _objectWithoutPropertiesLoose(source, excluded) {
31
- if (source == null) return {};
32
- var target = {};
33
- var sourceKeys = Object.keys(source);
34
- var key, i;
35
-
36
- for (i = 0; i < sourceKeys.length; i++) {
37
- key = sourceKeys[i];
38
- if (excluded.indexOf(key) >= 0) continue;
39
- target[key] = source[key];
40
- }
41
-
42
- return target;
43
- }
44
-
45
- var id = 0;
46
-
47
- function _classPrivateFieldLooseKey(name) {
48
- return "__private_" + id++ + "_" + name;
49
- }
50
-
51
- function _classPrivateFieldLooseBase(receiver, privateKey) {
52
- if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) {
53
- throw new TypeError("attempted to use private field on non-instance");
54
- }
55
-
56
- return receiver;
57
- }
58
-
59
- function mergeHeaders(specHeaders, headers) {
60
- return Object.entries(specHeaders).reduce((headers, [key, item]) => {
61
- key = key.toLowerCase();
62
- return _extends({}, headers, {
63
- [key]: headers[key] === undefined ? String(item.example) : headers[key]
64
- });
65
- }, headers);
66
- }
67
- /**
68
- * @ignore
69
- */
70
-
71
-
72
- function setResponseHeaders(ctx) {
73
- const {
74
- response,
75
- endpoint
76
- } = ctx;
77
- const operation = endpoint.operation;
78
-
79
- if (response.isDone()) {
80
- return;
81
- }
82
-
83
- if (!response.hasStatus()) {
84
- // apply status only if the isn't already modified
85
- response.status(operation.getStatus());
86
- }
87
-
88
- const statusCode = response.statusCode;
89
- const headers = operation.getHeadersOf(response.statusCode);
90
- const mergedHeaders = mergeHeaders(headers, response.getHeaders());
91
- response.setHeaders(mergedHeaders);
92
-
93
- if (operation.isRedirection(statusCode)) {
94
- response.redirect(statusCode, String(mergedHeaders["location"]));
95
- }
96
- }
97
-
98
- let PlatformServerlessHandler = class PlatformServerlessHandler {
99
- createHandler(token, propertyKey) {
100
- var _this = this;
101
-
102
- const promisedHandler = this.params.compileHandler({
103
- token,
104
- propertyKey
105
- });
106
- return async function ($ctx) {
107
- await _this.injector.emit("$onRequest", $ctx);
108
- await _this.injector.runInContext($ctx, async function () {
109
- try {
110
- const resolver = new AnyToPromise();
111
- const handler = await promisedHandler;
112
- const result = await resolver.call(() => handler({
113
- $ctx
114
- }));
115
-
116
- _this.processResult(result, $ctx);
117
- } catch (er) {
118
- $ctx.response.status(500).body(er);
119
- const exceptions = await _this.exceptionsManager;
120
- await exceptions.catch(er, $ctx);
121
- }
122
- });
123
- await _this.injector.emit("$onResponse", $ctx);
124
- return _this.flush($ctx);
125
- };
126
- }
127
-
128
- flush($ctx) {
129
- setResponseHeaders($ctx);
130
- let body = $ctx.response.getBody();
131
-
132
- if (isSerializable(body)) {
133
- $ctx.response.set("content-type", "application/json");
134
- body = JSON.stringify(body);
135
- }
136
-
137
- const response = {
138
- statusCode: $ctx.response.getStatus(),
139
- body: body === undefined ? "" : body,
140
- headers: _extends({}, $ctx.response.getHeaders(), {
141
- "x-request-id": $ctx.id
142
- }),
143
- isBase64Encoded: false
144
- };
145
- $ctx.destroy();
146
- return response;
147
- }
148
-
149
- processResult({
150
- status,
151
- headers,
152
- data
153
- }, $ctx) {
154
- if (status) {
155
- $ctx.response.status(status);
156
- }
157
-
158
- if (headers) {
159
- $ctx.response.setHeaders(headers);
160
- }
161
-
162
- if (data !== undefined) {
163
- data = $ctx.response.getStatus() !== 204 ? data : "";
164
-
165
- if (isSerializable(data)) {
166
- data = serialize(data, _extends({}, $ctx.endpoint.getResponseOptions($ctx.response.getStatus()), {
167
- useAlias: true,
168
- endpoint: true
169
- }));
170
- }
171
-
172
- $ctx.response.body(data);
173
- }
174
- }
175
-
176
- };
177
-
178
- __decorate([Inject(), __metadata("design:type", InjectorService)], PlatformServerlessHandler.prototype, "injector", void 0);
179
-
180
- __decorate([Inject(), __metadata("design:type", PlatformParams)], PlatformServerlessHandler.prototype, "params", void 0);
181
-
182
- __decorate([LazyInject("PlatformExceptions", () => import('@tsed/platform-exceptions')), __metadata("design:type", Promise)], PlatformServerlessHandler.prototype, "exceptionsManager", void 0);
183
-
184
- PlatformServerlessHandler = __decorate([Injectable({
185
- scope: ProviderScope.SINGLETON,
186
- imports: [DeserializerPipe, ValidationPipe]
187
- })], PlatformServerlessHandler);
188
-
189
- /**
190
- * @platform
191
- */
192
-
193
- class ServerlessRequest {
194
- constructor({
195
- event
196
- }) {
197
- this.raw = event;
198
- }
199
-
200
- get secure() {
201
- return true;
202
- }
203
-
204
- get host() {
205
- return this.get("host");
206
- }
207
-
208
- get protocol() {
209
- return "https";
210
- }
211
- /**
212
- * Get the url of the request.
213
- *
214
- * Is equivalent of `express.response.originalUrl || express.response.url`.
215
- */
216
-
217
-
218
- get url() {
219
- return this.raw.path;
220
- }
221
-
222
- get headers() {
223
- return this.raw.headers;
224
- }
225
-
226
- get method() {
227
- return this.raw.httpMethod;
228
- }
229
- /**
230
- * Contains key-value pairs of data submitted in the request body. By default, it is `undefined`, and is populated when you use
231
- * `body-parsing` middleware such as `express.json()` or `express.urlencoded()`.
232
- */
233
-
234
-
235
- get body() {
236
- try {
237
- return this.raw.body ? JSON.parse(this.raw.body) : {};
238
- } catch (er) {
239
- return this.raw.body;
240
- }
241
- }
242
-
243
- get rawBody() {
244
- return this.raw.body;
245
- }
246
- /**
247
- * This property is an object containing properties mapped to the named route `parameters`.
248
- * For example, if you have the route `/user/:name`, then the `name` property is available as `req.params.name`.
249
- * This object defaults to `{}`.
250
- */
251
-
252
-
253
- get params() {
254
- return this.raw.pathParameters || {};
255
- }
256
- /**
257
- * This property is an object containing a property for each query string parameter in the route.
258
- * When query parser is set to disabled, it is an empty object `{}`, otherwise it is the result of the configured query parser.
259
- */
260
-
261
-
262
- get query() {
263
- return this.raw.queryStringParameters || {};
264
- }
265
- /**
266
- * Returns the HTTP request header specified by field. The match is case-insensitive.
267
- *
268
- * ```typescript
269
- * request.get('Content-Type') // => "text/plain"
270
- * ```
271
- *
272
- * @param name
273
- */
274
-
275
-
276
- get(name) {
277
- return getValue(this.raw.headers, name);
278
- }
279
-
280
- destroy() {}
281
-
282
- }
283
-
284
- /**
285
- * @platform
286
- */
287
-
288
- var _status = /*#__PURE__*/_classPrivateFieldLooseKey("status");
289
-
290
- var _body = /*#__PURE__*/_classPrivateFieldLooseKey("body");
291
-
292
- var _headers = /*#__PURE__*/_classPrivateFieldLooseKey("headers");
293
-
294
- var _locals = /*#__PURE__*/_classPrivateFieldLooseKey("locals");
295
-
296
- var _isHeadersSent = /*#__PURE__*/_classPrivateFieldLooseKey("isHeadersSent");
297
-
298
- var _endListeners = /*#__PURE__*/_classPrivateFieldLooseKey("endListeners");
299
-
300
- class ServerlessResponse {
301
- constructor({
302
- event,
303
- request
304
- }) {
305
- Object.defineProperty(this, _status, {
306
- writable: true,
307
- value: void 0
308
- });
309
- Object.defineProperty(this, _body, {
310
- writable: true,
311
- value: void 0
312
- });
313
- Object.defineProperty(this, _headers, {
314
- writable: true,
315
- value: void 0
316
- });
317
- Object.defineProperty(this, _locals, {
318
- writable: true,
319
- value: void 0
320
- });
321
- Object.defineProperty(this, _isHeadersSent, {
322
- writable: true,
323
- value: void 0
324
- });
325
- Object.defineProperty(this, _endListeners, {
326
- writable: true,
327
- value: void 0
328
- });
329
- _classPrivateFieldLooseBase(this, _status)[_status] = 200;
330
- _classPrivateFieldLooseBase(this, _body)[_body] = undefined;
331
- _classPrivateFieldLooseBase(this, _headers)[_headers] = {};
332
- _classPrivateFieldLooseBase(this, _locals)[_locals] = {};
333
- _classPrivateFieldLooseBase(this, _isHeadersSent)[_isHeadersSent] = false;
334
- _classPrivateFieldLooseBase(this, _endListeners)[_endListeners] = [];
335
- this.event = event;
336
- this.request = request;
337
- }
338
-
339
- /**
340
- * Get the current statusCode
341
- */
342
- get statusCode() {
343
- return _classPrivateFieldLooseBase(this, _status)[_status];
344
- }
345
-
346
- set statusCode(status) {
347
- _classPrivateFieldLooseBase(this, _status)[_status] = status;
348
- }
349
- /**
350
- * An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.
351
- *
352
- * This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.
353
- */
354
-
355
-
356
- get locals() {
357
- return _classPrivateFieldLooseBase(this, _locals)[_locals];
358
- }
359
-
360
- get isHeadersSent() {
361
- return _classPrivateFieldLooseBase(this, _isHeadersSent)[_isHeadersSent];
362
- }
363
-
364
- getStatus() {
365
- return _classPrivateFieldLooseBase(this, _status)[_status];
366
- }
367
- /**
368
- * Sets the HTTP status for the response.
369
- *
370
- * @param status
371
- */
372
-
373
-
374
- status(status) {
375
- _classPrivateFieldLooseBase(this, _status)[_status] = status;
376
- return this;
377
- }
378
-
379
- set(name, value) {
380
- return this.setHeader(name, value);
381
- }
382
- /**
383
- * Returns the HTTP response header specified by field. The match is case-insensitive.
384
- *
385
- * ```typescript
386
- * response.get('Content-Type') // => "text/plain"
387
- * ```
388
- *
389
- * @param name
390
- */
391
-
392
-
393
- get(name) {
394
- return getValue(_classPrivateFieldLooseBase(this, _headers)[_headers], name.toLowerCase());
395
- }
396
-
397
- getHeaders() {
398
- return _extends({}, _classPrivateFieldLooseBase(this, _headers)[_headers]);
399
- }
400
-
401
- hasStatus() {
402
- return _classPrivateFieldLooseBase(this, _status)[_status] !== 200;
403
- }
404
- /**
405
- * Set header `field` to `val`, or pass
406
- * an object of header fields.
407
- *
408
- * Examples:
409
- * ```typescript
410
- * response.setHeaders({ Accept: 'text/plain', 'X-API-Key': 'tobi' });
411
- * ```
412
- *
413
- * Aliased as `res.header()`.
414
- */
415
-
416
-
417
- setHeaders(headers) {
418
- // apply headers
419
- Object.entries(headers).forEach(([key, item]) => {
420
- this.setHeader(key, item);
421
- });
422
- return this;
423
- }
424
-
425
- setHeader(key, item) {
426
- if (item !== null && item !== undefined) {
427
- key = key.toLowerCase();
428
-
429
- if (key === "location") {
430
- // "back" is an alias for the referrer
431
- if (item === "back") {
432
- item = this.request.get("Referrer") || "/";
433
- }
434
-
435
- item = encodeUrl(String(item));
436
- }
437
-
438
- _classPrivateFieldLooseBase(this, _headers)[_headers] = _extends({}, _classPrivateFieldLooseBase(this, _headers)[_headers], {
439
- [key.toLowerCase()]: item
440
- });
441
- }
442
-
443
- return this;
444
- }
445
- /**
446
- * Set `Content-Type` response header with `type` through `mime.lookup()`
447
- * when it does not contain "/", or set the Content-Type to `type` otherwise.
448
- *
449
- * Examples:
450
- *
451
- * res.type('.html');
452
- * res.type('html');
453
- * res.type('json');
454
- * res.type('application/json');
455
- * res.type('png');
456
- */
457
-
458
-
459
- contentType(contentType) {
460
- this.setHeader("Content-Type", mime.getType(contentType));
461
- return this;
462
- }
463
-
464
- contentLength(length) {
465
- this.setHeader("Content-Length", length);
466
- return this;
467
- }
468
-
469
- getContentLength() {
470
- if (this.get("Content-Length")) {
471
- return parseInt(this.get("Content-Length"), 10) || 0;
472
- }
473
- }
474
-
475
- getContentType() {
476
- return String(this.get("Content-Type") || "").split(";")[0];
477
- }
478
- /**
479
- * Redirects to the URL derived from the specified path, with specified status, a positive integer that corresponds to an [HTTP status code](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html).
480
- * If not specified, status defaults to `302 Found`.
481
- *
482
- * @param status
483
- * @param url
484
- */
485
-
486
-
487
- redirect(status, url) {
488
- // Set location header
489
- const address = this.location(url).get("Location");
490
- const body = `${getStatusMessage(status)}. Redirecting to ${address}`;
491
- this.status(status).set("Content-Length", Buffer.byteLength(body)).body(body);
492
- return this;
493
- }
494
- /**
495
- * Sets the response Location HTTP header to the specified path parameter.
496
- *
497
- * @param url
498
- */
499
-
500
-
501
- location(url) {
502
- return this.set("Location", url);
503
- }
504
- /**
505
- * Send any data to your consumer.
506
- *
507
- * This method accept a ReadableStream, a plain object, boolean, string, number, null and undefined data.
508
- * It choose the better way to send the data.
509
- *
510
- * @param body
511
- */
512
-
513
-
514
- body(body) {
515
- _classPrivateFieldLooseBase(this, _body)[_body] = body;
516
- return this;
517
- }
518
-
519
- getBody() {
520
- return _classPrivateFieldLooseBase(this, _body)[_body];
521
- }
522
-
523
- isDone() {
524
- return _classPrivateFieldLooseBase(this, _isHeadersSent)[_isHeadersSent];
525
- }
526
-
527
- onEnd(cb) {
528
- _classPrivateFieldLooseBase(this, _endListeners)[_endListeners].push(cb);
529
-
530
- return this;
531
- }
532
-
533
- destroy() {
534
- _classPrivateFieldLooseBase(this, _endListeners)[_endListeners].forEach(cb => cb());
535
-
536
- _classPrivateFieldLooseBase(this, _isHeadersSent)[_isHeadersSent] = true;
537
- }
538
-
539
- }
540
-
541
- const _excluded = ["event", "context", "endpoint"];
542
- class ServerlessContext extends DIContext {
543
- constructor(_ref) {
544
- let {
545
- event,
546
- context,
547
- endpoint
548
- } = _ref,
549
- options = _objectWithoutPropertiesLoose(_ref, _excluded);
550
-
551
- super(_extends({}, options, {
552
- maxStackSize: 0
553
- }));
554
- this.context = context;
555
- this.event = event;
556
- this.request = new ServerlessRequest({
557
- event,
558
- context
559
- });
560
- this.response = new ServerlessResponse({
561
- event,
562
- context,
563
- request: this.request
564
- });
565
- this.endpoint = endpoint;
566
- }
567
-
568
- async destroy() {
569
- await super.destroy();
570
- this.request.destroy();
571
- this.response.destroy();
572
- }
573
-
574
- }
575
-
576
- function getRequestId(event, context) {
577
- var _event$requestContext;
578
-
579
- if (event != null && event.headers && event.headers["x-request-id"]) {
580
- return event.headers["x-request-id"];
581
- }
582
-
583
- return (event == null ? void 0 : (_event$requestContext = event.requestContext) == null ? void 0 : _event$requestContext.requestId) || (context == null ? void 0 : context.awsRequestId) || v4().replace(/-/gi, "");
584
- }
585
-
586
- /**
587
- * @platform
588
- */
589
-
590
- class PlatformServerless {
591
- constructor() {
592
- this.name = "PlatformServerless";
593
- }
594
-
595
- get injector() {
596
- return this._injector;
597
- }
598
-
599
- get settings() {
600
- return this.injector.settings;
601
- }
602
-
603
- get promise() {
604
- return this._promise;
605
- }
606
-
607
- static bootstrap(settings = {}) {
608
- const platform = new PlatformServerless();
609
- platform.createInjector(settings);
610
- return platform;
611
- }
612
-
613
- handler() {
614
- var _this = this;
615
-
616
- return async function (event, context) {
617
- const [router] = await Promise.all([_this.initRouter(), _this.init()]);
618
- const result = router.find(event.httpMethod, event.path);
619
-
620
- if (result) {
621
- const {
622
- handler,
623
- params
624
- } = result;
625
- event.pathParameters = _extends({}, event.pathParameters || {}, params);
626
- return handler(event, context);
627
- }
628
-
629
- return {
630
- statusCode: 404,
631
- body: "Not found",
632
- headers: {
633
- "x-request-id": getRequestId(event, context)
634
- },
635
- isBase64Encoded: false
636
- };
637
- };
638
- }
639
-
640
- callbacks(tokens = [], callbacks = {}) {
641
- return this.settings.get("lambda", []).concat(tokens).reduce((callbacks, token) => {
642
- const routes = getOperationsRoutes(token);
643
- return routes.reduce((callbacks, operationRoute) => {
644
- var _this$_router;
645
-
646
- const {
647
- operationId,
648
- token,
649
- propertyName,
650
- method,
651
- url
652
- } = operationRoute; // istanbul ignore next
653
-
654
- if (method === "USE") {
655
- return callbacks;
656
- }
657
-
658
- const callback = this.callback(token, propertyName);
659
- (_this$_router = this._router) == null ? void 0 : _this$_router.on(method, url, callback);
660
- return _extends({}, callbacks, {
661
- [operationId]: callback
662
- });
663
- }, callbacks);
664
- }, callbacks);
665
- }
666
-
667
- async ready() {
668
- await this.injector.emit("$onReady");
669
- }
670
-
671
- async stop() {
672
- await this.injector.emit("$onDestroy");
673
- return this.injector.destroy();
674
- }
675
-
676
- async init() {
677
- if (!this._promise) {
678
- this._promise = this.loadInjector().then(() => this.ready());
679
- }
680
-
681
- return this._promise;
682
- }
683
-
684
- callback(token, propertyKey) {
685
- var _this2 = this;
686
-
687
- const entity = JsonEntityStore.fromMethod(token, propertyKey);
688
- let handler;
689
- return async function (event, context) {
690
- await _this2.init();
691
-
692
- if (!handler) {
693
- const platformHandler = _this2.injector.get(PlatformServerlessHandler);
694
-
695
- handler = await platformHandler.createHandler(token, propertyKey);
696
- }
697
-
698
- const $ctx = new ServerlessContext({
699
- event,
700
- context,
701
- id: getRequestId(event, context),
702
- logger: _this2.injector.logger,
703
- injector: _this2.injector,
704
- endpoint: entity
705
- });
706
- return handler($ctx);
707
- };
708
- }
709
-
710
- async initRouter() {
711
- if (!this._router) {
712
- const {
713
- default: FindMyMay
714
- } = await import('./index-b255dcf0.js').then(function (n) { return n.i; });
715
- this._router = FindMyMay({
716
- caseSensitive: false,
717
- ignoreTrailingSlash: true
718
- });
719
- this.callbacks();
720
- }
721
-
722
- return this._router;
723
- }
724
-
725
- createInjector(settings) {
726
- var _settings$logger;
727
-
728
- this._injector = new InjectorService();
729
- this.injector.logger = $log;
730
- this.injector.settings.set(settings); // istanbul ignore next
731
-
732
- if (this.injector.settings.get("env") === Env.TEST && !(settings != null && (_settings$logger = settings.logger) != null && _settings$logger.level)) {
733
- $log.stop();
734
- }
735
-
736
- return this;
737
- }
738
-
739
- async loadInjector() {
740
- const container = createContainer();
741
- setLoggerLevel(this.injector);
742
- await this.injector.emit("$beforeInit");
743
- await this.injector.load(container);
744
- await this.injector.emit("$afterInit");
745
- }
746
-
747
- }
748
-
749
- class LambdaClientRequest extends Promise {
750
- constructor() {
751
- super(...arguments);
752
- this.event = LambdaClientRequest.createFakeEvent();
753
- this.context = LambdaClientRequest.createFakeContext();
754
- }
755
-
756
- static call(lambdaName) {
757
- const resolvers = {};
758
- const promise = new LambdaClientRequest((resolve, reject) => {
759
- resolvers.resolve = resolve;
760
- resolvers.reject = reject;
761
- });
762
- promise.init(lambdaName, resolvers.resolve, resolvers.reject);
763
- return promise;
764
- }
765
-
766
- static get(path, options = {}) {
767
- return this.call("handler").get(path, options);
768
- }
769
-
770
- static post(path, body, options = {}) {
771
- return this.call("handler").post(path, body, options);
772
- }
773
-
774
- static put(path, body, options = {}) {
775
- return this.call("handler").put(path, body, options);
776
- }
777
-
778
- static patch(path, body, options = {}) {
779
- return this.call("handler").patch(path, body, options);
780
- }
781
-
782
- static delete(path, body, options = {}) {
783
- return this.call("handler").delete(path, body, options);
784
- }
785
-
786
- static createFakeEvent(event = {}) {
787
- return _extends({
788
- body: "",
789
- headers: {},
790
- httpMethod: "",
791
- isBase64Encoded: false,
792
- multiValueHeaders: {},
793
- multiValueQueryStringParameters: {},
794
- path: event.path || "/",
795
- pathParameters: {},
796
- queryStringParameters: {},
797
- resource: "",
798
- stageVariables: {}
799
- }, event, {
800
- requestContext: _extends({}, event == null ? void 0 : event.requestContext, {
801
- accountId: "",
802
- apiId: "",
803
- protocol: "https",
804
- httpMethod: "",
805
- identity: {},
806
- path: event.path || "/",
807
- stage: "",
808
- requestId: "requestId",
809
- requestTimeEpoch: 0,
810
- resourceId: 1,
811
- resourcePath: event.path || "/"
812
- })
813
- });
814
- }
815
-
816
- static createFakeContext(context) {
817
- return _extends({
818
- awsRequestId: "awsRequestId",
819
- callbackWaitsForEmptyEventLoop: false,
820
- functionName: "",
821
- functionVersion: "",
822
- invokedFunctionArn: "",
823
- logGroupName: "",
824
- logStreamName: "",
825
- memoryLimitInMB: ""
826
- }, context || {});
827
- }
828
-
829
- get(path, options = {}) {
830
- Object.assign(this.event, options);
831
- this.event.path = path;
832
- this.event.httpMethod = "GET";
833
- return this;
834
- }
835
-
836
- post(path, body = {}, options = {}) {
837
- Object.assign(this.event, options);
838
- this.event.path = path;
839
- this.event.httpMethod = "POST";
840
- this.body(body);
841
- return this;
842
- }
843
-
844
- patch(path, body = {}, options = {}) {
845
- Object.assign(this.event, options);
846
- this.event.path = path;
847
- this.event.httpMethod = "PATCH";
848
- this.body(body);
849
- return this;
850
- }
851
-
852
- put(path, body = {}, options = {}) {
853
- Object.assign(this.event, options);
854
- this.event.path = path;
855
- this.event.httpMethod = "PUT";
856
- this.body(body);
857
- return this;
858
- }
859
-
860
- delete(path, body = {}, options = {}) {
861
- Object.assign(this.event, options);
862
- this.event.path = path;
863
- this.event.httpMethod = "DELETE";
864
- this.body(body);
865
- return this;
866
- }
867
-
868
- query(query) {
869
- this.event.queryStringParameters = _extends({}, this.event.queryStringParameters, JSON.parse(JSON.stringify(query)));
870
- return this;
871
- }
872
-
873
- params(pathParameters) {
874
- this.event.pathParameters = _extends({}, this.event.pathParameters, JSON.parse(JSON.stringify(pathParameters)));
875
- return this;
876
- }
877
-
878
- headers(headers) {
879
- this.event.headers = _extends({}, this.event.headers, JSON.parse(JSON.stringify(headers)));
880
- return this;
881
- }
882
-
883
- body(body) {
884
- if (body !== undefined) {
885
- this.event.headers["content-type"] = "application/json";
886
- this.event.body = JSON.stringify(body);
887
- }
888
-
889
- return this;
890
- }
891
-
892
- init(lambda, resolve, reject) {
893
- var _this = this;
894
-
895
- setTimeout(async function () {
896
- try {
897
- const result = await PlatformServerlessTest.callbacks[lambda](_this.event, _this.context, resolve);
898
- resolve(result);
899
- } catch (er) {
900
- reject(er);
901
- }
902
- });
903
- }
904
-
905
- }
906
- class PlatformServerlessTest extends DITest {
907
- static bootstrap(settings = {}) {
908
- return async function before() {
909
- // @ts-ignore
910
- const instance = PlatformServerless.bootstrap(DITest.configure(settings));
911
- PlatformServerlessTest.instance = instance;
912
- PlatformServerlessTest.callbacks = instance.callbacks();
913
- PlatformServerlessTest.callbacks.handler = instance.handler(); // used by inject method
914
-
915
- DITest.injector = instance.injector;
916
- return instance.promise;
917
- };
918
- }
919
- /**
920
- * Resets the test injector of the test context, so it won't pollute your next test. Call this in your `tearDown` logic.
921
- */
922
-
923
-
924
- static async reset() {
925
- if (PlatformServerlessTest.instance) {
926
- await PlatformServerlessTest.instance.stop();
927
- }
928
-
929
- if (DITest.hasInjector()) {
930
- await DITest.injector.destroy();
931
- DITest._injector = null;
932
- }
933
- }
934
-
935
- static createServerlessContext({
936
- endpoint
937
- }) {
938
- const context = LambdaClientRequest.createFakeContext();
939
- const event = LambdaClientRequest.createFakeEvent();
940
- return new ServerlessContext({
941
- event,
942
- context,
943
- id: context.awsRequestId,
944
- logger: PlatformServerlessTest.injector.logger,
945
- injector: PlatformServerlessTest.injector,
946
- endpoint
947
- });
948
- }
949
-
950
- }
951
- PlatformServerlessTest.callbacks = {};
952
- PlatformServerlessTest.request = LambdaClientRequest;
953
-
954
- export { LambdaClientRequest as L, PlatformServerlessHandler as P, ServerlessContext as S, _extends as _, PlatformServerless as a, PlatformServerlessTest as b, ServerlessResponse as c };
955
- //# sourceMappingURL=index-a6c91998.js.map