@koralabs/kora-labs-common 1.0.0 → 1.0.2

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.
@@ -0,0 +1,21 @@
1
+ export declare enum ComputeEnvironment {
2
+ AWS_LAMBDA = "aws_lambda",
3
+ AWS_FARGATE = "aws_fargate",
4
+ AWS_EC2 = "aws_ec2",
5
+ AWS_OTHER = "aws_other",
6
+ OTHER = "other"
7
+ }
8
+ export declare class Environment {
9
+ static getComputeEnvironment(): Promise<ComputeEnvironment>;
10
+ static getIpAddress(): Promise<{
11
+ private: string | null;
12
+ public: string | null;
13
+ } | null>;
14
+ static getEc2InstanceName(): Promise<string | null>;
15
+ static getEcsTaskMetaData(): Promise<{
16
+ Networks: [{
17
+ IPv4Addresses: [string];
18
+ }];
19
+ } | null>;
20
+ static getPotentialApplicationName(): Promise<string | null>;
21
+ }
@@ -0,0 +1,123 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.Environment = exports.ComputeEnvironment = void 0;
13
+ var ComputeEnvironment;
14
+ (function (ComputeEnvironment) {
15
+ ComputeEnvironment["AWS_LAMBDA"] = "aws_lambda";
16
+ ComputeEnvironment["AWS_FARGATE"] = "aws_fargate";
17
+ ComputeEnvironment["AWS_EC2"] = "aws_ec2";
18
+ ComputeEnvironment["AWS_OTHER"] = "aws_other";
19
+ ComputeEnvironment["OTHER"] = "other";
20
+ })(ComputeEnvironment = exports.ComputeEnvironment || (exports.ComputeEnvironment = {}));
21
+ class Environment {
22
+ static getComputeEnvironment() {
23
+ return __awaiter(this, void 0, void 0, function* () {
24
+ if (process.env.AWS_LAMBDA_FUNCTION_NAME || process.env.AWS_EXECUTION_ENV) {
25
+ return ComputeEnvironment.AWS_LAMBDA;
26
+ }
27
+ if (process.env.ECS_CLUSTER) {
28
+ return ComputeEnvironment.AWS_FARGATE;
29
+ }
30
+ if (yield Environment.getEc2InstanceName()) {
31
+ return ComputeEnvironment.AWS_EC2;
32
+ }
33
+ if (process.env.AWS_DEFAULT_REGION || process.env.AWS_REGION) {
34
+ return ComputeEnvironment.AWS_OTHER;
35
+ }
36
+ return ComputeEnvironment.OTHER;
37
+ });
38
+ }
39
+ static getIpAddress() {
40
+ var _a, _b;
41
+ return __awaiter(this, void 0, void 0, function* () {
42
+ let prv;
43
+ let pub;
44
+ if ((yield Environment.getComputeEnvironment()) == ComputeEnvironment.AWS_EC2) {
45
+ try {
46
+ const response = yield fetch('http://169.254.169.254/latest/meta-data/local-ipv4');
47
+ prv = yield response.text();
48
+ }
49
+ catch (_c) {
50
+ }
51
+ try {
52
+ const response = yield fetch('http://169.254.169.254/latest/meta-data/public-ipv4');
53
+ pub = yield response.text();
54
+ }
55
+ catch (_d) {
56
+ }
57
+ if (prv || pub) {
58
+ return { private: prv !== null && prv !== void 0 ? prv : null, public: pub !== null && pub !== void 0 ? pub : null };
59
+ }
60
+ }
61
+ if ((yield Environment.getComputeEnvironment()) == ComputeEnvironment.AWS_EC2) {
62
+ const metadata = yield Environment.getEcsTaskMetaData();
63
+ return { private: (_b = (_a = metadata === null || metadata === void 0 ? void 0 : metadata.Networks[0]) === null || _a === void 0 ? void 0 : _a.IPv4Addresses[0]) !== null && _b !== void 0 ? _b : null, public: null };
64
+ }
65
+ return null;
66
+ });
67
+ }
68
+ static getEc2InstanceName() {
69
+ return __awaiter(this, void 0, void 0, function* () {
70
+ try {
71
+ const response = yield fetch('http://169.254.169.254/latest/meta-data/tags/instance/Name');
72
+ return response.text();
73
+ }
74
+ catch (err) {
75
+ }
76
+ try {
77
+ const response = yield fetch('http://169.254.169.254/latest/meta-data/instance-id');
78
+ return response.text();
79
+ }
80
+ catch (err) {
81
+ }
82
+ return null;
83
+ });
84
+ }
85
+ static getEcsTaskMetaData() {
86
+ return __awaiter(this, void 0, void 0, function* () {
87
+ try {
88
+ const response = yield fetch('http://169.254.170.2/v2/metadata');
89
+ return yield response.json();
90
+ }
91
+ catch (err) {
92
+ return null;
93
+ }
94
+ });
95
+ }
96
+ static getPotentialApplicationName() {
97
+ var _a, _b;
98
+ return __awaiter(this, void 0, void 0, function* () {
99
+ if (process.env.APPLICATION_NAME) {
100
+ return process.env.APPLICATION_NAME;
101
+ }
102
+ if ((yield Environment.getComputeEnvironment()) == ComputeEnvironment.AWS_LAMBDA) {
103
+ return (_a = process.env.AWS_LAMBDA_FUNCTION_NAME) !== null && _a !== void 0 ? _a : null;
104
+ }
105
+ if ((yield Environment.getComputeEnvironment()) == ComputeEnvironment.AWS_FARGATE) {
106
+ return (_b = process.env.ECS_CLUSTER) !== null && _b !== void 0 ? _b : null;
107
+ }
108
+ if ((yield Environment.getComputeEnvironment()) == ComputeEnvironment.AWS_EC2) {
109
+ const ec2_name = yield Environment.getEc2InstanceName();
110
+ if (ec2_name) {
111
+ return ec2_name;
112
+ }
113
+ }
114
+ try {
115
+ return process.cwd();
116
+ }
117
+ catch (_c) {
118
+ return null;
119
+ }
120
+ });
121
+ }
122
+ }
123
+ exports.Environment = Environment;
package/lib/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { Logger } from "./logger";
2
+ export { Environment } from "./environment";
package/lib/index.js ADDED
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Environment = exports.Logger = void 0;
4
+ var logger_1 = require("./logger");
5
+ Object.defineProperty(exports, "Logger", { enumerable: true, get: function () { return logger_1.Logger; } });
6
+ var environment_1 = require("./environment");
7
+ Object.defineProperty(exports, "Environment", { enumerable: true, get: function () { return environment_1.Environment; } });
@@ -0,0 +1,23 @@
1
+ export declare enum LogCategory {
2
+ DEBUG = "DEBUG",
3
+ INFO = "INFO",
4
+ WARN = "WARN",
5
+ ERROR = "ERROR",
6
+ FATAL = "FATAL",
7
+ NOTIFY = "NOTIFY",
8
+ METRIC = "METRIC"
9
+ }
10
+ export declare class Logger {
11
+ static application: string;
12
+ private static isInitialized;
13
+ static initialize(): Promise<void>;
14
+ static log(args: {
15
+ message: string;
16
+ category?: LogCategory;
17
+ event?: string;
18
+ milliseconds?: number;
19
+ count?: number;
20
+ dimensions?: string[];
21
+ } | string): void;
22
+ private static log_entry;
23
+ }
@@ -0,0 +1,71 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.Logger = exports.LogCategory = void 0;
13
+ const environment_1 = require("../environment");
14
+ // Fix from https://stackoverflow.com/questions/18391212/is-it-not-possible-to-stringify-an-error-using-json-stringify
15
+ if (!('toJSON' in Error.prototype))
16
+ Object.defineProperty(Error.prototype, 'toJSON', {
17
+ value: function () {
18
+ const alt = {};
19
+ Object.getOwnPropertyNames(this).forEach((key) => {
20
+ alt[key] = this[key];
21
+ }, this);
22
+ return alt;
23
+ },
24
+ configurable: true,
25
+ writable: true
26
+ });
27
+ var LogCategory;
28
+ (function (LogCategory) {
29
+ LogCategory["DEBUG"] = "DEBUG";
30
+ LogCategory["INFO"] = "INFO";
31
+ LogCategory["WARN"] = "WARN";
32
+ LogCategory["ERROR"] = "ERROR";
33
+ LogCategory["FATAL"] = "FATAL";
34
+ LogCategory["NOTIFY"] = "NOTIFY";
35
+ LogCategory["METRIC"] = "METRIC";
36
+ })(LogCategory = exports.LogCategory || (exports.LogCategory = {}));
37
+ class Logger {
38
+ static initialize() {
39
+ return __awaiter(this, void 0, void 0, function* () {
40
+ if (!Logger.application) {
41
+ const potentialName = yield environment_1.Environment.getPotentialApplicationName();
42
+ if (!potentialName) {
43
+ throw new Error("Logger.application must be set!");
44
+ }
45
+ Logger.application = potentialName;
46
+ }
47
+ Logger.isInitialized = true;
48
+ });
49
+ }
50
+ static log(args) {
51
+ if (!Logger.isInitialized)
52
+ Logger.initialize();
53
+ if (typeof args === 'string') {
54
+ this.log_entry(LogCategory.INFO, args);
55
+ return;
56
+ }
57
+ const { message, category, event, milliseconds, count, dimensions } = args;
58
+ this.log_entry(category !== null && category !== void 0 ? category : LogCategory.INFO, message, event, milliseconds, count, dimensions);
59
+ }
60
+ static log_entry(category, message, event, milliseconds, count, dimensions) {
61
+ const now = new Date().toISOString();
62
+ message = message.replace(/\\/g, '\\\\').replace(/"/g, '\\"'); // escape double quotes and already escaped escapes
63
+ const log_event = event ? `, "event": "${event}"` : '';
64
+ const log_milliseconds = milliseconds != undefined && milliseconds != null ? `, "milliseconds": ${milliseconds}` : '';
65
+ const log_count = count != undefined && count != null ? `, "count": ${count}` : '';
66
+ const log_dimensions = dimensions && Object.keys(dimensions).length ? `, "dimensions": ${JSON.stringify(dimensions)}` : '';
67
+ console.log(`{ "category": "${category !== null && category !== void 0 ? category : LogCategory.INFO}", "message": "${message}"${log_event}, "timestamp": "${now}"${log_milliseconds}${log_count}${log_dimensions} }`);
68
+ }
69
+ }
70
+ exports.Logger = Logger;
71
+ Logger.isInitialized = false;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const _1 = require(".");
4
+ describe('Logger Tests', () => {
5
+ it('should log', () => {
6
+ const now = Date.now();
7
+ const logSpy = jest.spyOn(console, 'log');
8
+ _1.Logger.log({
9
+ message: 'burritos',
10
+ category: _1.LogCategory.ERROR,
11
+ event: 'test.log',
12
+ milliseconds: now,
13
+ count: 1,
14
+ dimensions: ['taco']
15
+ });
16
+ const call = logSpy.mock.calls[0][0];
17
+ const obj = JSON.parse(call);
18
+ expect(obj).toEqual({
19
+ category: 'ERROR',
20
+ count: 1,
21
+ dimensions: ['taco'],
22
+ event: 'test.log',
23
+ message: 'burritos',
24
+ milliseconds: now,
25
+ timestamp: expect.stringMatching(/[0-9\-]+T[0-9\:\.]+Z/)
26
+ });
27
+ });
28
+ });
package/package.json CHANGED
@@ -1,7 +1,9 @@
1
1
  {
2
2
  "name": "@koralabs/kora-labs-common",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "description": "Kora Labs Common Utilities",
5
+ "main": "lib/index.js",
6
+ "types": "lib/index.d.ts",
5
7
  "homepage": "https://github.com/koralabs/kora-labs-common",
6
8
  "repository": {
7
9
  "type": "git",