@yopdev/dev-server 1.4.1-alpha.0 → 1.4.4

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 (46) 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 +24 -0
  4. package/dist/src/cloudformation-lambda-http-proxy.d.ts +12 -0
  5. package/dist/src/cloudformation-lambda-http-proxy.js +42 -0
  6. package/dist/src/cloudformation.d.ts +28 -0
  7. package/dist/src/cloudformation.js +47 -0
  8. package/dist/src/config.d.ts +2 -0
  9. package/dist/src/container.d.ts +18 -0
  10. package/dist/src/container.js +33 -0
  11. package/dist/src/deferred.js +28 -93
  12. package/dist/src/dev-server.js +48 -48
  13. package/dist/src/dynamodb.js +25 -75
  14. package/dist/src/event-proxy.d.ts +5 -4
  15. package/dist/src/event-proxy.js +52 -113
  16. package/dist/src/factories.js +11 -64
  17. package/dist/src/http-server.d.ts +1 -1
  18. package/dist/src/http-server.js +23 -26
  19. package/dist/src/index.d.ts +14 -1
  20. package/dist/src/index.js +18 -1
  21. package/dist/src/internal-queue.d.ts +5 -2
  22. package/dist/src/internal-queue.js +44 -101
  23. package/dist/src/lambda-http-proxy.d.ts +9 -3
  24. package/dist/src/lambda-http-proxy.js +33 -79
  25. package/dist/src/localstack.js +37 -79
  26. package/dist/src/mappers.d.ts +1 -1
  27. package/dist/src/mappers.js +14 -26
  28. package/dist/src/pre-traffic-hooks.d.ts +2 -11
  29. package/dist/src/pre-traffic-hooks.js +12 -61
  30. package/dist/src/responses.d.ts +1 -1
  31. package/dist/src/responses.js +4 -1
  32. package/dist/src/s3.d.ts +7 -0
  33. package/dist/src/s3.js +20 -0
  34. package/dist/src/scheduled-tasks.d.ts +2 -13
  35. package/dist/src/scheduled-tasks.js +12 -61
  36. package/dist/src/services.d.ts +4 -2
  37. package/dist/src/services.js +13 -53
  38. package/dist/src/sns-http-proxy.js +41 -59
  39. package/dist/src/sns.js +29 -79
  40. package/dist/src/sqs.d.ts +3 -1
  41. package/dist/src/sqs.js +27 -65
  42. package/dist/src/stoppable.d.ts +1 -1
  43. package/dist/src/stoppable.js +10 -43
  44. package/dist/src/tunnel.d.ts +10 -0
  45. package/dist/src/tunnel.js +29 -0
  46. package/package.json +7 -2
@@ -1,87 +1,41 @@
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))), 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) {
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
- .then(function () { return _this.LOGGER.info('stopped'); }); };
55
- this.handler = function (lambdaHandler) {
56
- return function (request, body, response) {
57
- return lambdaHandler((0, mappers_1.mapToLambdaEvent)(request, body))
58
- .then(function (lambda) {
59
- var _a, _b, _c, _d, _e, _f;
60
- 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);
61
- })
62
- .catch(function (e) {
63
- _this.LOGGER.error(e, 'request failed to execute');
64
- (0, responses_1.internalServerError)(response, e.body);
65
- });
66
- };
67
- };
68
- this.fallback = function (request, _, response) { return __awaiter(_this, void 0, void 0, function () {
69
- return __generator(this, function (_a) {
70
- return [2 /*return*/, Promise.resolve(this.LOGGER.warn('FALLBACK')).then(function () {
71
- return (0, responses_1.writeResponse)(response, 404, "no route found to handle ".concat(request.method, " to ").concat(request.url));
72
- })];
16
+ this.mapper = mapper;
17
+ this.defaultAuthorizer = defaultAuthorizer;
18
+ this.start = () => this.server.start();
19
+ this.stop = () => this.server.stop();
20
+ this.handler = (authorizer, lambdaHandler) => (request, body, response) => this.mapper(request, body)
21
+ .then(async (proxyEvent) => authorizer(proxyEvent.headers['authorization'])
22
+ .then(async (context) => {
23
+ proxyEvent.requestContext.authorizer = context;
24
+ return lambdaHandler(proxyEvent)
25
+ .then((lambda) => (0, responses_1.writeResponse)(response, lambda.statusCode, lambda.body, lambda.headers?.['content-type']?.toString() ?? undefined, lambda.headers?.['location']?.toString() ?? undefined))
26
+ .catch((e) => {
27
+ this.LOGGER.error(e, 'request failed to execute');
28
+ (0, responses_1.internalServerError)(response, e.body);
73
29
  });
74
- }); };
75
- this.resolveRoute = function (request, body, response) {
76
- var _a;
77
- return ((_a = _this.routes.filter(function (r) { return request.method.match(r.method); })
78
- .filter(function (r) { return request.url.match(r.path); })
79
- .sort(function (r1, r2) { return r2.path.source.length - r1.path.source.length; })
80
- .map(function (r) { return _this.handler(r.handler); })
81
- .find(function () { return true; })) !== null && _a !== void 0 ? _a : _this.fallback)(request, body, response);
82
- };
30
+ }, (e) => e === exports.UNAUTHORIZED ? (0, responses_1.writeResponse)(response, 401, '') : (0, responses_1.internalServerError)(response, e)));
31
+ 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}`));
32
+ this.resolveRoute = (request, body, response) => (this.routes.filter((r) => request.method.match(r.method))
33
+ .filter((r) => request.url.match(r.path))
34
+ .sort((r1, r2) => r2.weight - r1.weight)
35
+ .map((r) => this.handler(r.authorizer ?? this.defaultAuthorizer, r.handler))
36
+ .find(() => true) ?? this.fallback)(request, body, response);
83
37
  this.server = new http_server_1.HttpServer(name, settings, this.resolveRoute);
84
- this.LOGGER = logging_1.LoggerFactory.create("HTTP->LAMBDA[".concat(this.name, "]"));
38
+ this.LOGGER = logging_1.LoggerFactory.create(`HTTP->LAMBDA[${this.name}]`);
39
+ this.LOGGER.info('registered %i routes', routes.length);
85
40
  }
86
- return LambdaHttpProxy;
87
- }());
41
+ }
@@ -1,72 +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
- });
62
- }); };
63
- this.stop = function () { return Promise.resolve(_this.started)
64
- .then(function (container) { return container ? container.stop().then(function () { return 'stopped'; }) : 'not started'; })
65
- .then(function (status) { return LOGGER.info(status); }); };
66
- var concreteConfig = this.configOrDefaults(config);
67
- var container = new testcontainers_1.GenericContainer(concreteConfig.localStackDockerImage);
68
- var localStatePath = concreteConfig.localStateBindMount;
69
- 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 ?
70
30
  container
71
31
  .withEnvironment({ PERSISTENCE: '1' })
72
32
  .withBindMounts([{
@@ -75,27 +35,25 @@ var LocalStack = /** @class */ (function () {
75
35
  mode: 'rw',
76
36
  }])
77
37
  : container;
78
- var ready = withLocalState
38
+ const ready = withLocalState
79
39
  .withExposedPorts(concreteConfig.exposedPort)
80
40
  .withNetwork(network)
81
41
  .withNetworkAliases(NETWORK_ALIAS);
82
- this._start = function () { return ready
42
+ this._start = () => ready
83
43
  .start()
84
- .then(function (container) { return _this.started = container; })
85
- .then(function (container) { return "".concat(PROTOCOL, "://").concat(container.getHost(), ":").concat(container.getMappedPort(SERVICES_PORT)); }); };
86
- LOGGER.debug('initialized');
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;
@@ -3,4 +3,4 @@ import { Message } from "@aws-sdk/client-sqs";
3
3
  import { APIGatewayProxyEvent, SQSRecord } from "aws-lambda";
4
4
  import { IncomingMessage } from "http";
5
5
  export declare const mapToLambdaSqsRecord: (message: Message) => SQSRecord;
6
- export declare function mapToLambdaEvent(req: IncomingMessage, requestBody: string): APIGatewayProxyEvent;
6
+ export declare function mapToLambdaEvent(req: IncomingMessage, requestBody: string): Promise<APIGatewayProxyEvent>;
@@ -1,12 +1,10 @@
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
- throw new Error("message Body must be present: ".concat(message.Body));
7
+ throw new Error('message Body must be present');
10
8
  return {
11
9
  messageId: 'N/A',
12
10
  receiptHandle: 'N/A',
@@ -28,16 +26,17 @@ 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'];
40
- return {
36
+ headers['accept'] = req.headers['accept'];
37
+ if (req.headers['authorization'])
38
+ headers['authorization'] = req.headers['authorization'];
39
+ return Promise.resolve({
41
40
  httpMethod: req.method,
42
41
  body: requestBody,
43
42
  headers: headers,
@@ -52,7 +51,7 @@ function mapToLambdaEvent(req, requestBody) {
52
51
  requestContext: {
53
52
  accountId: '',
54
53
  apiId: '',
55
- authorizer: { claims: claims },
54
+ authorizer: undefined,
56
55
  httpMethod: '',
57
56
  identity: {
58
57
  accessKey: '',
@@ -85,17 +84,6 @@ function mapToLambdaEvent(req, requestBody) {
85
84
  resourcePath: '',
86
85
  stage: '',
87
86
  },
88
- };
87
+ });
89
88
  }
90
89
  exports.mapToLambdaEvent = mapToLambdaEvent;
91
- function extractClaims(req) {
92
- var _a;
93
- var jwt = (_a = req.headers['authorization']) === null || _a === void 0 ? void 0 : _a.replace('Bearer ', '');
94
- try {
95
- return jwt ? JSON.parse(atob(jwt.split('.')[1])) : null;
96
- }
97
- catch (e) {
98
- LOGGER.warn('Invalid token, claims could not be extracted: %O', jwt);
99
- return undefined;
100
- }
101
- }
@@ -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>;
@@ -1,68 +1,19 @@
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.newPreTrafficHooks = void 0;
40
- var logging_1 = require("@yopdev/logging");
41
- var services_1 = require("./services");
42
- var newPreTrafficHooks = function (name, hooks, callback) { return new services_1.Service(new PreTrafficHooks(name, hooks), callback); };
4
+ const logging_1 = require("@yopdev/logging");
5
+ const services_1 = require("./services");
6
+ const newPreTrafficHooks = (name, hooks) => new services_1.Service(new PreTrafficHooks(name, hooks));
43
7
  exports.newPreTrafficHooks = newPreTrafficHooks;
44
- var PreTrafficHooks = /** @class */ (function () {
45
- function PreTrafficHooks(name, hooks) {
46
- var _this = this;
8
+ class PreTrafficHooks {
9
+ constructor(name, hooks) {
47
10
  this.name = name;
48
11
  this.hooks = hooks;
49
- this.start = function () { return __awaiter(_this, void 0, void 0, function () {
50
- var _this = this;
51
- return __generator(this, function (_a) {
52
- return [2 /*return*/, Promise
53
- .all(this.hooks())
54
- .then(function () { return _this.LOGGER.info('started'); })
55
- .then(function () { return _this; })];
56
- });
57
- }); };
58
- this.stop = function () { return __awaiter(_this, void 0, void 0, function () {
59
- var _this = this;
60
- return __generator(this, function (_a) {
61
- return [2 /*return*/, Promise.resolve()
62
- .then(function () { return _this.LOGGER.info('stopped'); })];
63
- });
64
- }); };
65
- this.LOGGER = logging_1.LoggerFactory.create("PRETRAFFIC[".concat(name, "]"));
12
+ this.start = async () => Promise
13
+ .all(this.hooks())
14
+ .then(() => undefined);
15
+ this.stop = async () => Promise.resolve();
16
+ this.LOGGER = logging_1.LoggerFactory.create(`PRETRAFFIC[${name}]`);
17
+ this.LOGGER.info('%i hooks registered', hooks.length);
66
18
  }
67
- return PreTrafficHooks;
68
- }());
19
+ }
@@ -1,4 +1,4 @@
1
1
  /// <reference types="node" />
2
2
  import { ServerResponse } from 'http';
3
- export declare function internalServerError(res: ServerResponse, body: string): void;
3
+ export declare function internalServerError(res: ServerResponse, body: any): void;
4
4
  export declare function writeResponse(res: ServerResponse, statusCode: number, body: string, contentType?: string, location?: string): void;
@@ -1,8 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.writeResponse = exports.internalServerError = void 0;
4
+ const logging_1 = require("@yopdev/logging");
5
+ const LOG = logging_1.LoggerFactory.create('RESPONSES');
4
6
  function internalServerError(res, body) {
5
- return writeResponse(res, 500, body);
7
+ LOG.error(body, 'internal server error handled');
8
+ return writeResponse(res, 500, 'internal server error. check system logs');
6
9
  }
7
10
  exports.internalServerError = internalServerError;
8
11
  function writeResponse(res, statusCode, body, contentType, location) {
@@ -0,0 +1,7 @@
1
+ import { CORSConfiguration, S3Client } from '@aws-sdk/client-s3';
2
+ import { AwsConfig } from './config';
3
+ export declare class S3 {
4
+ readonly client: S3Client;
5
+ constructor(aws: AwsConfig);
6
+ createBucket: (name: string, cors?: CORSConfiguration) => Promise<import("@aws-sdk/client-s3").PutBucketCorsCommandOutput>;
7
+ }
package/dist/src/s3.js ADDED
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.S3 = void 0;
4
+ const client_s3_1 = require("@aws-sdk/client-s3");
5
+ const logging_1 = require("@yopdev/logging");
6
+ const LOGGER = logging_1.LoggerFactory.create('S3');
7
+ class S3 {
8
+ constructor(aws) {
9
+ this.createBucket = async (name, cors) => this.client.send(new client_s3_1.CreateBucketCommand({
10
+ Bucket: name,
11
+ }))
12
+ .then(() => cors && this.client.send(new client_s3_1.PutBucketCorsCommand({
13
+ Bucket: name,
14
+ CORSConfiguration: cors
15
+ })))
16
+ .tap(() => LOGGER.debug('bucket %s created', name));
17
+ this.client = new client_s3_1.S3Client({ forcePathStyle: true, ...aws });
18
+ }
19
+ }
20
+ exports.S3 = S3;
@@ -1,17 +1,6 @@
1
- /// <reference types="node" />
2
- import { Lifecycle, Service, Callback } from './services';
3
- export declare const newScheduledTasks: (name: string, schedules: Rate[], callback?: Callback<ScheduledTasks>) => Service<ScheduledTasks>;
4
- declare class ScheduledTasks implements Lifecycle<ScheduledTasks> {
5
- readonly name: string;
6
- private readonly schedules;
7
- private LOGGER;
8
- constructor(name: string, schedules: Rate[]);
9
- intervals: NodeJS.Timeout[];
10
- start: () => Promise<this>;
11
- stop: () => Promise<void>;
12
- }
1
+ import { Service } from './services';
2
+ export declare const newScheduledTasks: (name: string, schedules: Rate[]) => Service<any>;
13
3
  export type Rate = {
14
4
  frequency: number;
15
5
  task: () => Promise<unknown>;
16
6
  };
17
- export {};
@@ -1,69 +1,20 @@
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.newScheduledTasks = void 0;
40
- var logging_1 = require("@yopdev/logging");
41
- var timers_1 = require("timers");
42
- var services_1 = require("./services");
43
- var newScheduledTasks = function (name, schedules, callback) { return new services_1.Service(new ScheduledTasks(name, schedules), callback); };
4
+ const logging_1 = require("@yopdev/logging");
5
+ const timers_1 = require("timers");
6
+ const services_1 = require("./services");
7
+ const newScheduledTasks = (name, schedules) => new services_1.Service(new ScheduledTasks(name, schedules));
44
8
  exports.newScheduledTasks = newScheduledTasks;
45
- var ScheduledTasks = /** @class */ (function () {
46
- function ScheduledTasks(name, schedules) {
47
- var _this = this;
9
+ class ScheduledTasks {
10
+ constructor(name, schedules) {
48
11
  this.name = name;
49
12
  this.schedules = schedules;
50
13
  this.intervals = [];
51
- this.start = function () { return __awaiter(_this, void 0, void 0, function () {
52
- var _this = this;
53
- return __generator(this, function (_a) {
54
- return [2 /*return*/, Promise.resolve(this.schedules.forEach(function (schedule) { return _this.intervals.push(setInterval(schedule.task, schedule.frequency * 1000)); }))
55
- .then(function () { return _this.LOGGER.info('started'); })
56
- .then(function () { return _this; })];
57
- });
58
- }); };
59
- this.stop = function () { return __awaiter(_this, void 0, void 0, function () {
60
- var _this = this;
61
- return __generator(this, function (_a) {
62
- return [2 /*return*/, Promise.resolve(this.intervals.forEach(function (interval) { return (0, timers_1.clearInterval)(interval); }))
63
- .then(function () { return _this.LOGGER.info('stopped'); })];
64
- });
65
- }); };
66
- this.LOGGER = logging_1.LoggerFactory.create("SCHEDULER[".concat(name, "]"));
14
+ this.start = async () => Promise.resolve(this.schedules.forEach((schedule) => this.intervals.push(setInterval(schedule.task, schedule.frequency * 1000))))
15
+ .then(() => undefined);
16
+ this.stop = async () => Promise.resolve(this.intervals.forEach((interval) => (0, timers_1.clearInterval)(interval)));
17
+ this.LOGGER = logging_1.LoggerFactory.create(`SCHEDULER[${name}]`);
18
+ this.LOGGER.info('registered %i scheduled tasks', schedules.length);
67
19
  }
68
- return ScheduledTasks;
69
- }());
20
+ }
@@ -1,7 +1,9 @@
1
1
  import { DevServerConfig } from "./config";
2
- export interface Lifecycle<I> extends Stoppable {
2
+ export interface Lifecycle<I> extends Startable<I>, Stoppable {
3
3
  name: string;
4
- start: (config: DevServerConfig) => Promise<I>;
4
+ }
5
+ export interface Startable<T> {
6
+ start(config: DevServerConfig): Promise<T>;
5
7
  }
6
8
  export interface Stoppable {
7
9
  stop(): Promise<void>;