@yopdev/dev-server 1.8.0-alpha.1 → 2.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/src/assert.js +1 -2
  2. package/dist/src/cloudformation-event-proxy.d.ts +13 -0
  3. package/dist/src/cloudformation-event-proxy.js +25 -0
  4. package/dist/src/cloudformation-lambda-http-proxy.d.ts +16 -0
  5. package/dist/src/cloudformation-lambda-http-proxy.js +45 -0
  6. package/dist/src/cloudformation.d.ts +28 -0
  7. package/dist/src/cloudformation.js +46 -0
  8. package/dist/src/container.js +23 -70
  9. package/dist/src/deferred.js +28 -89
  10. package/dist/src/dev-server.js +47 -51
  11. package/dist/src/dynamodb.js +25 -74
  12. package/dist/src/event-proxy.d.ts +3 -1
  13. package/dist/src/event-proxy.js +52 -108
  14. package/dist/src/factories.js +11 -64
  15. package/dist/src/http-server.js +23 -25
  16. package/dist/src/index.d.ts +5 -4
  17. package/dist/src/index.js +8 -46
  18. package/dist/src/internal-queue.d.ts +5 -2
  19. package/dist/src/internal-queue.js +44 -99
  20. package/dist/src/lambda-http-proxy.d.ts +13 -5
  21. package/dist/src/lambda-http-proxy.js +33 -78
  22. package/dist/src/localstack.js +37 -79
  23. package/dist/src/mappers.d.ts +3 -2
  24. package/dist/src/mappers.js +29 -26
  25. package/dist/src/pre-traffic-hooks.d.ts +2 -11
  26. package/dist/src/pre-traffic-hooks.js +11 -56
  27. package/dist/src/responses.d.ts +3 -2
  28. package/dist/src/responses.js +4 -1
  29. package/dist/src/s3.d.ts +2 -2
  30. package/dist/src/s3.js +15 -64
  31. package/dist/src/scheduled-tasks.js +11 -56
  32. package/dist/src/services.d.ts +4 -2
  33. package/dist/src/services.js +13 -53
  34. package/dist/src/sns-http-proxy.js +41 -59
  35. package/dist/src/sns.js +29 -79
  36. package/dist/src/sqs.d.ts +3 -1
  37. package/dist/src/sqs.js +27 -65
  38. package/dist/src/stoppable.js +11 -50
  39. package/dist/src/tunnel.js +41 -68
  40. package/package.json +5 -1
@@ -1,110 +1,55 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
2
  Object.defineProperty(exports, "__esModule", { value: true });
39
3
  exports.newInternalQueue = void 0;
40
- var logging_1 = require("@yopdev/logging");
41
- var sqs_consumer_1 = require("sqs-consumer");
42
- var stoppable_1 = require("./stoppable");
43
- var mappers_1 = require("./mappers");
44
- var services_1 = require("./services");
45
- var newInternalQueue = function (name, config, callback) { return new services_1.Service(new InternalQueue(name, config.visibility, config.handler, config.index), callback); };
4
+ const logging_1 = require("@yopdev/logging");
5
+ const sqs_consumer_1 = require("sqs-consumer");
6
+ const stoppable_1 = require("./stoppable");
7
+ const mappers_1 = require("./mappers");
8
+ const services_1 = require("./services");
9
+ const newInternalQueue = (name, config, callback) => new services_1.Service(new InternalQueue(name, config.visibility, config.handler, (sqs) => config.fifo ? sqs.createFifoQueue : sqs.createStandardQueue, config.mapper ?? mappers_1.mapToLambdaSqsRecord), callback);
46
10
  exports.newInternalQueue = newInternalQueue;
47
- var InternalQueue = /** @class */ (function () {
48
- function InternalQueue(name, visibility, handler, index) {
49
- var _this = this;
11
+ class InternalQueue {
12
+ constructor(name, visibility, handler, creator, mapper) {
50
13
  this.name = name;
51
14
  this.visibility = visibility;
52
15
  this.handler = handler;
53
- this.start = function (config) { return _this.create(config.sqs); };
54
- this.create = function (sqs) { return __awaiter(_this, void 0, void 0, function () {
55
- var _this = this;
56
- return __generator(this, function (_a) {
57
- return [2 /*return*/, this.createQueue(sqs, this.queueName)
58
- .then(function (queue) { return _this
59
- .createConsumer(sqs.client, _this.queueName, queue.url, _this.handler(queue), _this.visibility)
60
- .then(function () { return queue.url; }); })];
16
+ this.creator = creator;
17
+ this.mapper = mapper;
18
+ this.start = (config) => this.create(config.sqs);
19
+ this.create = async (sqs) => this.createQueue(sqs, this.name)
20
+ .then((queue) => this
21
+ .createConsumer(sqs.client, this.name, queue.url, this.handler(queue), this.visibility)
22
+ .then(() => queue.url));
23
+ this.createConsumer = async (sqs, name, url, handler, visibility) => Promise.resolve(sqs_consumer_1.Consumer.create({
24
+ queueUrl: url,
25
+ waitTimeSeconds: visibility,
26
+ sqs: sqs,
27
+ handleMessage: async (message) => handler({ Records: [this.mapper(message)] }),
28
+ }))
29
+ .then((consumer) => {
30
+ consumer.on('error', (err) => {
31
+ this.LOGGER.error(err, 'failed to handle message');
61
32
  });
62
- }); };
63
- this.createConsumer = function (sqs, name, url, handler, visibility) { return __awaiter(_this, void 0, void 0, function () {
64
- var _this = this;
65
- return __generator(this, function (_a) {
66
- return [2 /*return*/, Promise.resolve(sqs_consumer_1.Consumer.create({
67
- queueUrl: url,
68
- waitTimeSeconds: visibility,
69
- sqs: sqs,
70
- handleMessage: function (message) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
71
- return [2 /*return*/, handler({ Records: [(0, mappers_1.mapToLambdaSqsRecord)(message)] })];
72
- }); }); },
73
- }))
74
- .then(function (consumer) {
75
- consumer.on('error', function (err) {
76
- _this.LOGGER.error(err, 'failed to handle message');
77
- });
78
- consumer.on('processing_error', function (err) {
79
- _this.LOGGER.error(err, 'failed to process message');
80
- });
81
- consumer.start();
82
- _this.LOGGER.info('consumer for %s initialized', name);
83
- _this.state = {
84
- consumer: consumer,
85
- visibility: visibility,
86
- };
87
- })
88
- .then(function () { return _this.LOGGER.info('started'); })
89
- .then(function () { return _this; })];
33
+ consumer.on('processing_error', (err) => {
34
+ this.LOGGER.error(err, 'failed to process message');
90
35
  });
91
- }); };
92
- this.stop = function () { return (0, stoppable_1.stopConsumer)(_this.state.visibility, _this.state.consumer); };
93
- this.queueName = (index + 1000).toString().padStart(10, '0');
94
- this.LOGGER = logging_1.LoggerFactory.create("INTERNALQUEUE[".concat(name, "]"));
36
+ consumer.start();
37
+ this.LOGGER.info('consumer for %s initialized', name);
38
+ this.state = {
39
+ consumer: consumer,
40
+ visibility: visibility,
41
+ };
42
+ })
43
+ .then(() => this.LOGGER.info('started'))
44
+ .then(() => this);
45
+ this.stop = () => (0, stoppable_1.stopConsumer)(this.state.visibility, this.state.consumer);
46
+ this.LOGGER = logging_1.LoggerFactory.create(`INTERNALQUEUE[${name}]`);
95
47
  }
96
- InternalQueue.prototype.createQueue = function (sqs, name) {
97
- return __awaiter(this, void 0, void 0, function () {
98
- var _this = this;
99
- return __generator(this, function (_a) {
100
- return [2 /*return*/, sqs
101
- .createNamedQueue(name) //
102
- .then(function (queue) {
103
- _this.LOGGER.info('created: %s', queue.url);
104
- return queue;
105
- })];
106
- });
48
+ async createQueue(sqs, name) {
49
+ return this.creator(sqs)(name) //
50
+ .then((queue) => {
51
+ this.LOGGER.info('created: %s', queue.url);
52
+ return queue;
107
53
  });
108
- };
109
- return InternalQueue;
110
- }());
54
+ }
55
+ }
@@ -1,13 +1,21 @@
1
1
  import { HttpSettings } from "./http-server";
2
- import { APIGatewayProxyEvent, APIGatewayProxyResult } from "aws-lambda";
2
+ import { APIGatewayEventRequestContextV2WithAuthorizer, APIGatewayProxyEventV2WithRequestContext, APIGatewayProxyStructuredResultV2 } from "aws-lambda";
3
+ import { IncomingMessage } from "http";
3
4
  import { Service, Callback } from "./services";
4
- export declare const newLambdaHttpProxy: (name: string, config: {
5
+ export declare const UNAUTHORIZED: Error;
6
+ export declare const newLambdaHttpProxy: <C, A>(name: string, config: {
5
7
  settings: HttpSettings;
6
- routes: Route[];
8
+ routes: Route<C, A>[];
9
+ mapper?: (request: IncomingMessage, body: string) => Promise<APIGatewayEventRequestContextV2WithGenericAuthorizer<A>>;
10
+ authorizer?: Authorizer<A>;
11
+ context?: () => C;
7
12
  }, callback?: Callback<string>) => Service<string>;
8
- export type Route = {
13
+ export type APIGatewayEventRequestContextV2WithGenericAuthorizer<A> = APIGatewayProxyEventV2WithRequestContext<APIGatewayEventRequestContextV2WithAuthorizer<A>>;
14
+ export type Route<C, A> = {
9
15
  method: RegExp;
10
16
  path: RegExp;
11
17
  weight: number;
12
- handler: (event: APIGatewayProxyEvent) => Promise<APIGatewayProxyResult>;
18
+ authorizer?: Authorizer<A>;
19
+ handler: (event: APIGatewayEventRequestContextV2WithGenericAuthorizer<A>, context: C) => Promise<APIGatewayProxyStructuredResultV2>;
13
20
  };
21
+ export type Authorizer<A> = (authorization: string) => Promise<A | undefined>;
@@ -1,87 +1,42 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
2
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.newLambdaHttpProxy = void 0;
40
- var logging_1 = require("@yopdev/logging");
41
- var http_server_1 = require("./http-server");
42
- var mappers_1 = require("./mappers");
43
- var responses_1 = require("./responses");
44
- var services_1 = require("./services");
45
- var newLambdaHttpProxy = function (name, config, callback) { return new services_1.Service(new LambdaHttpProxy(name, config.settings, config.routes), callback); };
3
+ exports.newLambdaHttpProxy = exports.UNAUTHORIZED = void 0;
4
+ const logging_1 = require("@yopdev/logging");
5
+ const http_server_1 = require("./http-server");
6
+ const mappers_1 = require("./mappers");
7
+ const responses_1 = require("./responses");
8
+ const services_1 = require("./services");
9
+ exports.UNAUTHORIZED = new Error('UNAUTHORIZED');
10
+ const newLambdaHttpProxy = (name, config, callback) => new services_1.Service(new LambdaHttpProxy(name, config.settings, config.routes, config.mapper ?? mappers_1.mapToLambdaEvent, config.authorizer ?? (() => Promise.resolve(undefined)), config.context), callback);
46
11
  exports.newLambdaHttpProxy = newLambdaHttpProxy;
47
- var LambdaHttpProxy = /** @class */ (function () {
48
- function LambdaHttpProxy(name, settings, routes) {
49
- var _this = this;
12
+ class LambdaHttpProxy {
13
+ constructor(name, settings, routes, mapper, defaultAuthorizer, context = () => undefined) {
50
14
  this.name = name;
51
15
  this.routes = routes;
52
- this.start = function () { return _this.server.start(); };
53
- this.stop = function () { return _this.server.stop(); };
54
- this.handler = function (lambdaHandler) {
55
- return function (request, body, response) {
56
- return lambdaHandler((0, mappers_1.mapToLambdaEvent)(request, body))
57
- .then(function (lambda) {
58
- var _a, _b, _c, _d, _e, _f;
59
- return (0, responses_1.writeResponse)(response, lambda.statusCode, lambda.body, (_c = (_b = (_a = lambda.headers) === null || _a === void 0 ? void 0 : _a['Content-Type']) === null || _b === void 0 ? void 0 : _b.toString()) !== null && _c !== void 0 ? _c : undefined, (_f = (_e = (_d = lambda.headers) === null || _d === void 0 ? void 0 : _d['Location']) === null || _e === void 0 ? void 0 : _e.toString()) !== null && _f !== void 0 ? _f : undefined);
60
- })
61
- .catch(function (e) {
62
- _this.LOGGER.error(e, 'request failed to execute');
63
- (0, responses_1.internalServerError)(response, e.body);
64
- });
65
- };
66
- };
67
- this.fallback = function (request, _, response) { return __awaiter(_this, void 0, void 0, function () {
68
- return __generator(this, function (_a) {
69
- return [2 /*return*/, Promise.resolve(this.LOGGER.warn('FALLBACK')).then(function () {
70
- return (0, responses_1.writeResponse)(response, 404, "no route found to handle ".concat(request.method, " to ").concat(request.url));
71
- })];
16
+ this.mapper = mapper;
17
+ this.defaultAuthorizer = defaultAuthorizer;
18
+ this.context = context;
19
+ this.start = () => this.server.start();
20
+ this.stop = () => this.server.stop();
21
+ this.handler = (authorizer, lambdaHandler) => (request, body, response) => this.mapper(request, body)
22
+ .then(async (proxyEvent) => authorizer(proxyEvent.headers['authorization'])
23
+ .then(async (context) => {
24
+ proxyEvent.requestContext.authorizer = context;
25
+ return lambdaHandler(proxyEvent, this.context())
26
+ .then((lambda) => (0, responses_1.writeResponse)(response, lambda.statusCode, lambda.isBase64Encoded ? Buffer.from(lambda.body, 'base64') : lambda.body, lambda.headers?.['content-type']?.toString() ?? undefined, lambda.headers?.['location']?.toString() ?? undefined))
27
+ .catch((e) => {
28
+ this.LOGGER.error(e, 'request failed to execute');
29
+ (0, responses_1.internalServerError)(response, e.body);
72
30
  });
73
- }); };
74
- this.resolveRoute = function (request, body, response) {
75
- var _a;
76
- return ((_a = _this.routes.filter(function (r) { return request.method.match(r.method); })
77
- .filter(function (r) { return request.url.match(r.path); })
78
- .sort(function (r1, r2) { return r2.weight - r1.weight; })
79
- .map(function (r) { return _this.handler(r.handler); })
80
- .find(function () { return true; })) !== null && _a !== void 0 ? _a : _this.fallback)(request, body, response);
81
- };
31
+ }, (e) => e === exports.UNAUTHORIZED ? (0, responses_1.writeResponse)(response, 401, '') : (0, responses_1.internalServerError)(response, e)));
32
+ this.fallback = async (request, _, response) => Promise.resolve(this.LOGGER.warn('FALLBACK')).then(() => (0, responses_1.writeResponse)(response, 404, `no route found to handle ${request.method} to ${request.url}`));
33
+ this.resolveRoute = (request, body, response) => (this.routes.filter((r) => request.method.match(r.method))
34
+ .filter((r) => request.url.match(r.path))
35
+ .sort((r1, r2) => r2.weight - r1.weight)
36
+ .map((r) => this.handler(r.authorizer ?? this.defaultAuthorizer, r.handler))
37
+ .find(() => true) ?? this.fallback)(request, body, response);
82
38
  this.server = new http_server_1.HttpServer(name, settings, this.resolveRoute);
83
- this.LOGGER = logging_1.LoggerFactory.create("HTTP->LAMBDA[".concat(this.name, "]"));
39
+ this.LOGGER = logging_1.LoggerFactory.create(`HTTP->LAMBDA[${this.name}]`);
84
40
  this.LOGGER.info('registered %i routes', routes.length);
85
41
  }
86
- return LambdaHttpProxy;
87
- }());
42
+ }
@@ -1,73 +1,32 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
2
  Object.defineProperty(exports, "__esModule", { value: true });
39
3
  exports.LocalStack = void 0;
40
- var logging_1 = require("@yopdev/logging");
41
- var testcontainers_1 = require("testcontainers");
42
- var LOGGER = logging_1.LoggerFactory.create('LOCALSTACK');
43
- var SERVICES_PORT = 4566;
44
- var NETWORK_ALIAS = 'localstack';
45
- var PROTOCOL = 'http';
46
- var DEFAULT_DOCKER_IMAGE = 'localstack/localstack:stable';
47
- var LocalStack = /** @class */ (function () {
48
- function LocalStack(network, config) {
49
- var _this = this;
50
- this.start = function () { return __awaiter(_this, void 0, void 0, function () {
51
- return __generator(this, function (_a) {
52
- return [2 /*return*/, this._start()
53
- .then(function (endpoint) { return ({
54
- region: 'us-east-1',
55
- endpoint: endpoint,
56
- credentials: {
57
- accessKeyId: 'dummy',
58
- secretAccessKey: 'dummy'
59
- }
60
- }); })
61
- .tap(function () { return LOGGER.debug('started'); })];
62
- });
63
- }); };
64
- this.stop = function () { return Promise.resolve(_this.started)
65
- .then(function (container) { return container ? container.stop().then(function () { return 'stopped'; }) : 'not started'; })
66
- .then(function (status) { return LOGGER.debug(status); }); };
67
- var concreteConfig = this.configOrDefaults(config);
68
- var container = new testcontainers_1.GenericContainer(concreteConfig.localStackDockerImage);
69
- var localStatePath = concreteConfig.localStateBindMount;
70
- var withLocalState = localStatePath !== undefined ?
4
+ const logging_1 = require("@yopdev/logging");
5
+ const testcontainers_1 = require("testcontainers");
6
+ const LOGGER = logging_1.LoggerFactory.create('LOCALSTACK');
7
+ const SERVICES_PORT = 4566;
8
+ const NETWORK_ALIAS = 'localstack';
9
+ const PROTOCOL = 'http';
10
+ const DEFAULT_DOCKER_IMAGE = 'localstack/localstack:stable';
11
+ class LocalStack {
12
+ constructor(network, config) {
13
+ this.start = async () => this._start()
14
+ .then((endpoint) => ({
15
+ region: 'us-east-1',
16
+ endpoint: endpoint,
17
+ credentials: {
18
+ accessKeyId: 'dummy',
19
+ secretAccessKey: 'dummy'
20
+ }
21
+ }))
22
+ .tap(() => LOGGER.debug('started'));
23
+ this.stop = () => Promise.resolve(this.started)
24
+ .then((container) => container ? container.stop().then(() => 'stopped') : 'not started')
25
+ .then((status) => LOGGER.debug(status));
26
+ const concreteConfig = this.configOrDefaults(config);
27
+ const container = new testcontainers_1.GenericContainer(concreteConfig.localStackDockerImage);
28
+ const localStatePath = concreteConfig.localStateBindMount;
29
+ const withLocalState = localStatePath !== undefined ?
71
30
  container
72
31
  .withEnvironment({ PERSISTENCE: '1' })
73
32
  .withBindMounts([{
@@ -76,26 +35,25 @@ var LocalStack = /** @class */ (function () {
76
35
  mode: 'rw',
77
36
  }])
78
37
  : container;
79
- var ready = withLocalState
38
+ const ready = withLocalState
80
39
  .withExposedPorts(concreteConfig.exposedPort)
81
40
  .withNetwork(network)
82
41
  .withNetworkAliases(NETWORK_ALIAS);
83
- this._start = function () { return ready
42
+ this._start = () => ready
84
43
  .start()
85
- .then(function (container) { return _this.started = container; })
86
- .then(function (container) { return "".concat(PROTOCOL, "://").concat(container.getHost(), ":").concat(container.getMappedPort(SERVICES_PORT)); }); };
44
+ .then((container) => this.started = container)
45
+ .then((container) => `${PROTOCOL}://${container.getHost()}:${container.getMappedPort(SERVICES_PORT)}`);
87
46
  }
88
- LocalStack.prototype.configOrDefaults = function (config) {
89
- var selectedServicesPort = config === null || config === void 0 ? void 0 : config.boundServicesPort;
90
- var exposedPort = selectedServicesPort !== undefined ?
47
+ configOrDefaults(config) {
48
+ const selectedServicesPort = config?.boundServicesPort;
49
+ const exposedPort = selectedServicesPort !== undefined ?
91
50
  { container: SERVICES_PORT, host: selectedServicesPort } :
92
51
  SERVICES_PORT;
93
52
  return {
94
- localStackDockerImage: (config === null || config === void 0 ? void 0 : config.localStackDockerImage) || DEFAULT_DOCKER_IMAGE,
53
+ localStackDockerImage: config?.localStackDockerImage || DEFAULT_DOCKER_IMAGE,
95
54
  exposedPort: exposedPort,
96
- localStateBindMount: config === null || config === void 0 ? void 0 : config.localStateBindMount,
55
+ localStateBindMount: config?.localStateBindMount,
97
56
  };
98
- };
99
- return LocalStack;
100
- }());
57
+ }
58
+ }
101
59
  exports.LocalStack = LocalStack;
@@ -1,6 +1,7 @@
1
1
  /// <reference types="node" />
2
2
  import { Message } from "@aws-sdk/client-sqs";
3
- import { APIGatewayProxyEvent, SQSRecord } from "aws-lambda";
3
+ import { SQSRecord } from "aws-lambda";
4
4
  import { IncomingMessage } from "http";
5
+ import { APIGatewayEventRequestContextV2WithGenericAuthorizer } from "./lambda-http-proxy";
5
6
  export declare const mapToLambdaSqsRecord: (message: Message) => SQSRecord;
6
- export declare function mapToLambdaEvent(req: IncomingMessage, requestBody: string): APIGatewayProxyEvent;
7
+ export declare function mapToLambdaEvent<A>(req: IncomingMessage, requestBody: string): Promise<APIGatewayEventRequestContextV2WithGenericAuthorizer<A>>;
@@ -1,10 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.mapToLambdaEvent = exports.mapToLambdaSqsRecord = void 0;
4
- var logging_1 = require("@yopdev/logging");
5
- var url_1 = require("url");
6
- var LOGGER = logging_1.LoggerFactory.create('MAPPERS');
7
- var mapToLambdaSqsRecord = function (message) {
4
+ const url_1 = require("url");
5
+ const mapToLambdaSqsRecord = (message) => {
8
6
  if (!message.Body)
9
7
  throw new Error('message Body must be present');
10
8
  return {
@@ -28,18 +26,22 @@ exports.mapToLambdaSqsRecord = mapToLambdaSqsRecord;
28
26
  function mapToLambdaEvent(req, requestBody) {
29
27
  if (!req.url || !req.method)
30
28
  throw new Error('url and method are required');
31
- var url = new url_1.URL(decodeURIComponent(req.url), "http://".concat(req.headers.host));
32
- var qsp = {};
33
- url.searchParams.forEach(function (v, k) { return (qsp[k] = v); });
34
- var claims = extractClaims(req);
35
- var headers = {};
29
+ const url = new url_1.URL(req.url, `http://${req.headers.host}`);
30
+ const qsp = {};
31
+ url.searchParams.forEach((v, k) => (qsp[k] = decodeURIComponent(v)));
32
+ const headers = {};
36
33
  if (req.headers['content-type'])
37
- headers['Content-Type'] = req.headers['content-type'];
34
+ headers['content-type'] = req.headers['content-type'];
38
35
  if (req.headers['accept'])
39
- headers['Accept'] = req.headers['accept'];
36
+ headers['accept'] = req.headers['accept'];
40
37
  if (req.headers['authorization'])
41
38
  headers['authorization'] = req.headers['authorization'];
42
- return {
39
+ const time = 1428582896000;
40
+ return Promise.resolve({
41
+ version: '2.0',
42
+ rawPath: url.pathname,
43
+ rawQueryString: url.search,
44
+ routeKey: '',
43
45
  httpMethod: req.method,
44
46
  body: requestBody,
45
47
  headers: headers,
@@ -52,9 +54,21 @@ function mapToLambdaEvent(req, requestBody) {
52
54
  multiValueQueryStringParameters: null,
53
55
  stageVariables: null,
54
56
  requestContext: {
57
+ domainName: req.headers.host,
58
+ domainPrefix: '',
59
+ http: {
60
+ method: req.method,
61
+ path: url.pathname,
62
+ protocol: 'http',
63
+ sourceIp: '127.0.0.1',
64
+ userAgent: req.headers['user-agent'],
65
+ },
66
+ routeKey: '',
67
+ time: new Date(time).toString(),
68
+ timeEpoch: time,
55
69
  accountId: '',
56
70
  apiId: '',
57
- authorizer: { claims: claims },
71
+ authorizer: undefined,
58
72
  httpMethod: '',
59
73
  identity: {
60
74
  accessKey: '',
@@ -82,22 +96,11 @@ function mapToLambdaEvent(req, requestBody) {
82
96
  path: '',
83
97
  protocol: '',
84
98
  requestId: '',
85
- requestTimeEpoch: 1428582896000,
99
+ requestTimeEpoch: time,
86
100
  resourceId: '',
87
101
  resourcePath: '',
88
102
  stage: '',
89
103
  },
90
- };
104
+ });
91
105
  }
92
106
  exports.mapToLambdaEvent = mapToLambdaEvent;
93
- function extractClaims(req) {
94
- var _a;
95
- var jwt = (_a = req.headers['authorization']) === null || _a === void 0 ? void 0 : _a.replace('Bearer ', '');
96
- try {
97
- return jwt ? JSON.parse(atob(jwt.split('.')[1])) : null;
98
- }
99
- catch (e) {
100
- LOGGER.warn('Invalid token, claims could not be extracted: %O', jwt);
101
- return undefined;
102
- }
103
- }
@@ -1,11 +1,2 @@
1
- import { Lifecycle, Service, Callback } from './services';
2
- export declare const newPreTrafficHooks: (name: string, hooks: () => Promise<void>[], callback?: Callback<PreTrafficHooks>) => Service<PreTrafficHooks>;
3
- declare class PreTrafficHooks implements Lifecycle<PreTrafficHooks> {
4
- readonly name: string;
5
- private readonly hooks;
6
- private LOGGER;
7
- constructor(name: string, hooks: () => Promise<void>[]);
8
- start: () => Promise<this>;
9
- stop: () => Promise<void>;
10
- }
11
- export {};
1
+ import { Service } from './services';
2
+ export declare const newPreTrafficHooks: (name: string, hooks: () => Promise<void>[]) => Service<any>;