@visulima/health-check 1.0.2 → 1.0.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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,19 @@
1
+ ## @visulima/health-check [1.0.4](https://github.com/visulima/visulima/compare/@visulima/health-check@1.0.3...@visulima/health-check@1.0.4) (2023-05-25)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * chore updated the deps and the engine to allow node v20 ([e7e0001](https://github.com/visulima/visulima/commit/e7e00010663be1a57285c6070cb3b9da8f4f3134))
7
+ * fixed all calls to radar with sonarjs, removed radar eslint package ([001aecf](https://github.com/visulima/visulima/commit/001aecf78dde134bade44f382698d52eedbd3bbe))
8
+ * updated package deps ([5f605aa](https://github.com/visulima/visulima/commit/5f605aab74a7c1f4cbdfe4502363e36d57716921))
9
+
10
+ ## @visulima/health-check [1.0.3](https://github.com/visulima/visulima/compare/@visulima/health-check@1.0.2...@visulima/health-check@1.0.3) (2023-01-25)
11
+
12
+
13
+ ### Bug Fixes
14
+
15
+ * updated tsconfig to use module esnext and target es2021 ([#107](https://github.com/visulima/visulima/issues/107)) ([e888fe8](https://github.com/visulima/visulima/commit/e888fe8d15c99453a3c04f2cf9d2f6c69c158648))
16
+
1
17
  ## @visulima/health-check [1.0.2](https://github.com/visulima/visulima/compare/@visulima/health-check@1.0.1...@visulima/health-check@1.0.2) (2023-01-08)
2
18
 
3
19
 
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { IncomingMessage, ServerResponse } from 'node:http';
2
- import { IPFamily, Options } from 'cacheable-lookup';
2
+ import { Options, IPFamily } from 'cacheable-lookup';
3
3
  import { extendedPingOptions } from 'pingman';
4
4
 
5
5
  type Checker = () => Promise<HealthReportEntry>;
@@ -30,9 +30,9 @@ type HealthReport = {
30
30
  */
31
31
  interface HealthCheck {
32
32
  servicesList: string[];
33
- addChecker(service: string, checker: Checker): void;
34
- isLive(): Promise<boolean>;
35
- getReport(): Promise<{ healthy: boolean; report: HealthReport }>;
33
+ addChecker: (service: string, checker: Checker) => void;
34
+ isLive: () => Promise<boolean>;
35
+ getReport: () => Promise<{ healthy: boolean; report: HealthReport }>;
36
36
  }
37
37
 
38
38
  declare const _default$1: (healthCheck: HealthCheck, sendHeader?: boolean | undefined) => <Request_1 extends IncomingMessage, Response_1 extends ServerResponse<IncomingMessage>>(_: Request_1, response: Response_1) => Promise<void>;
@@ -51,10 +51,10 @@ declare class Healthcheck implements HealthCheck {
51
51
  isLive(): Promise<boolean>;
52
52
  }
53
53
 
54
- declare const dnsCheck: (host: string, expectedAddresses?: string[], options?: {
54
+ declare const dnsCheck: (host: string, expectedAddresses?: string[], options?: Options & {
55
55
  family?: IPFamily | "all";
56
56
  hints?: number;
57
- } & Options) => Checker;
57
+ }) => Checker;
58
58
 
59
59
  declare const httpCheck: (host: RequestInfo | URL, options?: {
60
60
  fetchOptions?: RequestInit;
package/dist/index.js CHANGED
@@ -1,2 +1,23 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var _httpstatuscodes = require('http-status-codes');var u=(t,e=!0)=>async(a,r)=>{let{healthy:s,report:h}=await t.getReport(),l={status:s?"ok":"error",message:s?"Health check successful":"Health check failed",appName:_nullishCoalesce(process.env.APP_NAME, () => ("unknown")),appVersion:_nullishCoalesce(process.env.APP_VERSION, () => ("unknown")),timestamp:new Date().toISOString(),reports:h};r.statusCode=s?_httpstatuscodes.StatusCodes.OK:_httpstatuscodes.StatusCodes.SERVICE_UNAVAILABLE,e&&r.setHeader("Content-Type","application/json"),r.end(JSON.stringify(l,null,2))};var g=t=>async(e,a)=>{let{healthy:r}=await t.getReport();a.statusCode=r?_httpstatuscodes.StatusCodes.NO_CONTENT:_httpstatuscodes.StatusCodes.SERVICE_UNAVAILABLE,a.end()};var p=class{constructor(){this.healthCheckers={}}get servicesList(){return Object.keys(this.healthCheckers)}async invokeChecker(e,a){let r=this.healthCheckers[e],s;try{s=await r(),s.displayName=s.displayName||e}catch(h){s={displayName:e,health:{healthy:!1,message:h.message,timestamp:new Date().toISOString()},meta:{fatal:!0}}}return a[e]=s,s.health.healthy}addChecker(e,a){this.healthCheckers[e]=a}async getReport(){let e={};return await Promise.all(Object.keys(this.healthCheckers).map(r=>this.invokeChecker(r,e))),{healthy:!Object.keys(e).find(r=>!e[r].health.healthy),report:e}}async isLive(){let{healthy:e}=await this.getReport();return e}},k= exports.HealthCheck =p;var _cacheablelookup = require('cacheable-lookup'); var _cacheablelookup2 = _interopRequireDefault(_cacheablelookup);var i="DNS check for",S=(t,e,a)=>async()=>{let{hints:r,family:s="all",...h}=a||{},l=new (0, _cacheablelookup2.default)(h);try{let n=await l.lookupAsync(t.replace(/^https?:\/\//,""),{hints:r,...s==="all"?{all:!0}:{family:s}});return Array.isArray(e)&&!(e!=null&&e.includes(n.address))?{displayName:`${i} ${t}`,health:{healthy:!1,message:`${i} ${t} returned address ${n.address} instead of ${e.join(", ")}.`,timestamp:new Date().toISOString()},meta:{host:t,addresses:n}}:{displayName:`${i} ${t}`,health:{healthy:!0,message:`${i} ${t} were resolved.`,timestamp:new Date().toISOString()},meta:{host:t,addresses:n}}}catch(n){return{displayName:`${i} ${t}`,health:{healthy:!1,message:n.message,timestamp:new Date().toISOString()},meta:{host:t}}}},N= exports.dnsCheck =S;var _assert = require('assert');var m="HTTP check for",I=(t,e)=>async()=>{var a,r,s,h,l;try{let n=await fetch(t,(e==null?void 0:e.fetchOptions)||{});if(((a=e==null?void 0:e.expected)==null?void 0:a.status)!==void 0&&((r=e==null?void 0:e.expected)==null?void 0:r.status)!==n.status)throw new Error(`${m} ${t} returned status ${n.status} instead of ${e==null?void 0:e.expected.status}`);if(((s=e==null?void 0:e.expected)==null?void 0:s.body)!==void 0){let o=await n.text();try{_assert.deepStrictEqual.call(void 0, o,e==null?void 0:e.expected.body)}catch (e2){throw new Error(`${m} ${t} returned body ${JSON.stringify(o)} instead of ${JSON.stringify(e==null?void 0:e.expected.body)}`)}}return{displayName:`${m} ${t}`,health:{healthy:!0,message:`${m} ${t} was successful.`,timestamp:new Date().toISOString()},meta:{host:t,method:((h=e==null?void 0:e.fetchOptions)==null?void 0:h.method)||"GET",status:n.status}}}catch(n){return{displayName:`${m} ${t}`,health:{healthy:!1,message:n.message,timestamp:new Date().toISOString()},meta:{host:t,method:((l=e==null?void 0:e.fetchOptions)==null?void 0:l.method)||"GET"}}}},O= exports.httpCheck =I;var f="Node Environment Check",R=t=>async()=>{let e="production",a;return e!==void 0&&t!==void 0&&e!==t?a=`NODE_ENV environment variable is set to "${e}" instead of "${t}".`:e===void 0&&(a=["Missing NODE_ENV environment variable.","It can make some parts of the application misbehave"].join(" ")),a!==void 0?{displayName:f,health:{healthy:!1,message:a,timestamp:new Date().toISOString()}}:{displayName:f,health:{healthy:!0,timestamp:new Date().toISOString()},meta:{env:e}}},w= exports.nodeEnvCheck =R;var _pingman = require('pingman'); var _pingman2 = _interopRequireDefault(_pingman);var c="Ping check for",b=(t,e)=>async()=>{try{let a=await _pingman2.default.call(void 0, t.replace(/^https?:\/\//,""),e);return a.alive?{displayName:`${c} ${t}`,health:{healthy:!0,message:`${c} ${t} was successful.`,timestamp:new Date().toISOString()},meta:a}:{displayName:`${c} ${t}`,health:{healthy:!1,message:`Ping failed for ${t}.`,timestamp:new Date().toISOString()},meta:a}}catch(a){return{displayName:`${c} ${t}`,health:{healthy:!1,message:a.message,timestamp:new Date().toISOString()}}}},v= exports.pingCheck =b;exports.HealthCheck = k; exports.dnsCheck = N; exports.healthCheckHandler = u; exports.healthReadyHandler = g; exports.httpCheck = O; exports.nodeEnvCheck = w; exports.pingCheck = v;
1
+ 'use strict';
2
+
3
+ var httpStatusCodes = require('http-status-codes');
4
+ var N = require('cacheable-lookup');
5
+ var assert = require('assert');
6
+ var v = require('pingman');
7
+
8
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
9
+
10
+ var N__default = /*#__PURE__*/_interopDefault(N);
11
+ var v__default = /*#__PURE__*/_interopDefault(v);
12
+
13
+ var u=Object.defineProperty;var g=(t,e,a)=>e in t?u(t,e,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[e]=a;var m=(t,e,a)=>(g(t,typeof e!="symbol"?e+"":e,a),a);var k=(t,e=!0)=>async(a,r)=>{let{healthy:s,report:o}=await t.getReport(),l={status:s?"ok":"error",message:s?"Health check successful":"Health check failed",appName:process.env.APP_NAME??"unknown",appVersion:process.env.APP_VERSION??"unknown",timestamp:new Date().toISOString(),reports:o};r.statusCode=s?httpStatusCodes.StatusCodes.OK:httpStatusCodes.StatusCodes.SERVICE_UNAVAILABLE,e&&r.setHeader("Content-Type","application/json"),r.end(JSON.stringify(l,null,2));};var C=t=>async(e,a)=>{let{healthy:r}=await t.getReport();a.statusCode=r?httpStatusCodes.StatusCodes.NO_CONTENT:httpStatusCodes.StatusCodes.SERVICE_UNAVAILABLE,a.end();};var c=class{constructor(){m(this,"healthCheckers",{});}get servicesList(){return Object.keys(this.healthCheckers)}async invokeChecker(e,a){let r=this.healthCheckers[e],s;try{s=await r(),s.displayName=s.displayName||e;}catch(o){s={displayName:e,health:{healthy:!1,message:o.message,timestamp:new Date().toISOString()},meta:{fatal:!0}};}return a[e]=s,s.health.healthy}addChecker(e,a){this.healthCheckers[e]=a;}async getReport(){let e={};return await Promise.all(Object.keys(this.healthCheckers).map(r=>this.invokeChecker(r,e))),{healthy:!Object.keys(e).find(r=>!e[r].health.healthy),report:e}}async isLive(){let{healthy:e}=await this.getReport();return e}},S=c;var i="DNS check for",$=(t,e,a)=>async()=>{let{hints:r,family:s="all",...o}=a??{},l=new N__default.default(o);try{let n=await l.lookupAsync(t.replace(/^https?:\/\//,""),{hints:r,...s==="all"?{all:!0}:{family:s}});return Array.isArray(e)&&!e.includes(n.address)?{displayName:`${i} ${t}`,health:{healthy:!1,message:`${i} ${t} returned address ${n.address} instead of ${e.join(", ")}.`,timestamp:new Date().toISOString()},meta:{host:t,addresses:n}}:{displayName:`${i} ${t}`,health:{healthy:!0,message:`${i} ${t} were resolved.`,timestamp:new Date().toISOString()},meta:{host:t,addresses:n}}}catch(n){return {displayName:`${i} ${t}`,health:{healthy:!1,message:n.message,timestamp:new Date().toISOString()},meta:{host:t}}}},O=$;var h="HTTP check for",I=(t,e)=>async()=>{try{let a=await fetch(t,e?.fetchOptions??{});if(e?.expected?.status!==void 0&&e.expected.status!==a.status)throw new Error(`${h} ${t} returned status ${a.status} instead of ${e.expected.status}`);if(e?.expected?.body!==void 0){let r=await a.text();try{assert.deepStrictEqual(r,e.expected.body);}catch{throw new Error(`${h} ${t} returned body ${JSON.stringify(r)} instead of ${JSON.stringify(e.expected.body)}`)}}return {displayName:`${h} ${t}`,health:{healthy:!0,message:`${h} ${t} was successful.`,timestamp:new Date().toISOString()},meta:{host:t,method:e?.fetchOptions?.method??"GET",status:a.status}}}catch(a){return {displayName:`${h} ${t}`,health:{healthy:!1,message:a.message,timestamp:new Date().toISOString()},meta:{host:t,method:e?.fetchOptions?.method??"GET"}}}},R=I;var f="Node Environment Check",w=t=>async()=>{let e="production",a;return t!==void 0&&e!==t?a=`NODE_ENV environment variable is set to "${e}" instead of "${t}".`:e,a!==void 0?{displayName:f,health:{healthy:!1,message:a,timestamp:new Date().toISOString()}}:{displayName:f,health:{healthy:!0,timestamp:new Date().toISOString()},meta:{env:e}}},x=w;var p="Ping check for",b=(t,e)=>async()=>{try{let a=await v__default.default(t.replace(/^https?:\/\//,""),e);return a.alive?{displayName:`${p} ${t}`,health:{healthy:!0,message:`${p} ${t} was successful.`,timestamp:new Date().toISOString()},meta:a}:{displayName:`${p} ${t}`,health:{healthy:!1,message:`Ping failed for ${t}.`,timestamp:new Date().toISOString()},meta:a}}catch(a){return {displayName:`${p} ${t}`,health:{healthy:!1,message:a.message,timestamp:new Date().toISOString()}}}},H=b;
14
+
15
+ exports.HealthCheck = S;
16
+ exports.dnsCheck = O;
17
+ exports.healthCheckHandler = k;
18
+ exports.healthReadyHandler = C;
19
+ exports.httpCheck = R;
20
+ exports.nodeEnvCheck = x;
21
+ exports.pingCheck = H;
22
+ //# sourceMappingURL=out.js.map
2
23
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/handler/healthcheck.ts","../src/handler/readyhandler.ts","../src/healthcheck.ts","../src/checks/dns-check.ts","../src/checks/http-check.ts","../src/checks/node-environment-check.ts","../src/checks/ping-check.ts"],"names":["StatusCodes","healthcheck_default","healthCheck","sendHeader","_","response","healthy","report","payload","readyhandler_default","_request","Healthcheck","service","reportSheet","checker","error","CacheableLookup","DISPLAY_NAME","dnsCheck","host","expectedAddresses","options","hints","family","config","cacheable","meta","dns_check_default","deepStrictEqual","httpCheck","_a","_b","_c","_d","_e","textBody","http_check_default","nodeEnvironmentCheck","expectedEnvironment","environment","errorMessage","node_environment_check_default","ping","pingCheck","ping_check_default"],"mappings":"AAAA,OAAS,eAAAA,MAAmB,oBAM5B,IAAOC,EAAQ,CAACC,EAA0BC,EAAkC,KAAS,MAAyEC,EAAYC,IAAuB,CAC7L,GAAM,CAAE,QAAAC,EAAS,OAAAC,CAAO,EAAI,MAAML,EAAY,UAAU,EAElDM,EAAiC,CACnC,OAAQF,EAAU,KAAO,QACzB,QAASA,EAAU,0BAA4B,sBAC/C,QAAS,QAAQ,IAAI,UAAY,UACjC,WAAY,QAAQ,IAAI,aAAe,UACvC,UAAW,IAAI,KAAK,EAAE,YAAY,EAClC,QAASC,CACb,EAEAF,EAAS,WAAaC,EAAUN,EAAY,GAAKA,EAAY,oBAEzDG,GACAE,EAAS,UAAU,eAAgB,kBAAkB,EAGzDA,EAAS,IAAI,KAAK,UAAUG,EAAS,KAAM,CAAC,CAAC,CACjD,ECzBA,OAAS,eAAAR,MAAmB,oBAM5B,IAAOS,EAA2EP,GAA6B,MAAO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AAK,GAAG,GAGzHA,IAAiB,OACV,CACH,YAAavB,EACb,OAAQ,CACJ,QAAS,GACT,QAASuB,EACT,UAAW,IAAI,KAAK,EAAE,YAAY,CACtC,CACJ,EAGG,CACH,YAAavB,EACb,OAAQ,CACJ,QAAS,GACT,UAAW,IAAI,KAAK,EAAE,YAAY,CACtC,EACA,KAAM,CACF,IAAKsB,CACT,CACJ,CACJ,EAEOE,EAAQJ,ECzCf,OAAOK,MAAU,UAIjB,IAAMzB,EAAe,iBAKf0B,EAAY,CAACxB,EAAcE,IAA2C,SAAY,CACpF,GAAI,CACA,IAAMhB,EAAW,MAAMqC,EAAKvB,EAAK,QAAQ,eAAgB,EAAE,EAAGE,CAAO,EAErE,OAAKhB,EAAS,MAYP,CACH,YAAa,GAAGY,KAAgBE,IAChC,OAAQ,CACJ,QAAS,GACT,QAAS,GAAGF,KAAgBE,oBAC5B,UAAW,IAAI,KAAK,EAAE,YAAY,CACtC,EACA,KAAMd,CACV,EAnBW,CACH,YAAa,GAAGY,KAAgBE,IAChC,OAAQ,CACJ,QAAS,GACT,QAAS,mBAAmBA,KAC5B,UAAW,IAAI,KAAK,EAAE,YAAY,CACtC,EACA,KAAMd,CACV,CAYR,OAASU,EAAP,CACE,MAAO,CACH,YAAa,GAAGE,KAAgBE,IAChC,OAAQ,CACJ,QAAS,GACT,QAASJ,EAAM,QACf,UAAW,IAAI,KAAK,EAAE,YAAY,CACtC,CACJ,CACJ,CACJ,EAEO6B,EAAQD","sourcesContent":["import { StatusCodes } from \"http-status-codes\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { HealthCheck, HealthReport } from \"../types\";\n\n// eslint-disable-next-line max-len\nexport default (healthCheck: HealthCheck, sendHeader: boolean | undefined = true) => async <Request extends IncomingMessage, Response extends ServerResponse>(_: Request, response: Response) => {\n const { healthy, report } = await healthCheck.getReport();\n\n const payload: HealthCheckApiPayload = {\n status: healthy ? \"ok\" : \"error\",\n message: healthy ? \"Health check successful\" : \"Health check failed\",\n appName: process.env.APP_NAME ?? \"unknown\",\n appVersion: process.env.APP_VERSION ?? \"unknown\",\n timestamp: new Date().toISOString(),\n reports: report,\n };\n\n response.statusCode = healthy ? StatusCodes.OK : StatusCodes.SERVICE_UNAVAILABLE;\n\n if (sendHeader) {\n response.setHeader(\"Content-Type\", \"application/json\");\n }\n\n response.end(JSON.stringify(payload, null, 2));\n};\n\nexport type HealthCheckApiPayload = {\n status: \"ok\" | \"error\";\n message: string;\n appName: string;\n appVersion: string;\n timestamp: string;\n reports: HealthReport;\n};\n","import { StatusCodes } from \"http-status-codes\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { HealthCheck } from \"../types\";\n\n// eslint-disable-next-line max-len\nexport default <Request extends IncomingMessage, Response extends ServerResponse>(healthCheck: HealthCheck) => async (_request: Request, response: Response) => {\n const { healthy } = await healthCheck.getReport();\n\n response.statusCode = healthy ? StatusCodes.NO_CONTENT : StatusCodes.SERVICE_UNAVAILABLE;\n response.end();\n};\n","import {\n Checker, HealthCheck as HealthcheckInterface, HealthReport, HealthReportEntry,\n} from \"./types\";\n\nclass Healthcheck implements HealthcheckInterface {\n /**\n * A copy of registered checkers\n */\n private healthCheckers: { [service: string]: Checker } = {};\n\n /**\n * Returns an array of registered services names\n */\n public get servicesList(): string[] {\n return Object.keys(this.healthCheckers);\n }\n\n /**\n * Invokes a given checker to collect the report metrics.\n */\n private async invokeChecker(service: string, reportSheet: HealthReport): Promise<boolean> {\n const checker = this.healthCheckers[service] as Checker;\n\n let report: HealthReportEntry;\n\n try {\n report = await checker();\n\n report.displayName = report.displayName || service;\n } catch (error: any) {\n report = {\n displayName: service,\n health: { healthy: false, message: error.message, timestamp: new Date().toISOString() },\n meta: { fatal: true },\n };\n }\n\n // eslint-disable-next-line no-param-reassign\n reportSheet[service] = report;\n\n return report.health.healthy;\n }\n\n public addChecker(service: string, checker: Checker): void {\n this.healthCheckers[service] = checker;\n }\n\n /**\n * Returns the health check reports. The health checks are performed when\n * this method is invoked.\n */\n public async getReport(): Promise<{ healthy: boolean; report: HealthReport }> {\n const report: HealthReport = {};\n\n // eslint-disable-next-line compat/compat\n await Promise.all(Object.keys(this.healthCheckers).map((service) => this.invokeChecker(service, report)));\n\n /**\n * Finding unhealthy service to know if system is healthy or not\n */\n const unhealthyService = Object.keys(report).find((service) => !(report[service] as HealthReportEntry).health.healthy);\n\n return { healthy: !unhealthyService, report };\n }\n\n public async isLive(): Promise<boolean> {\n const { healthy } = await this.getReport();\n\n return healthy;\n }\n}\n\nexport default Healthcheck;\n","import type { IPFamily, Options } from \"cacheable-lookup\";\nimport CacheableLookup from \"cacheable-lookup\";\n\nimport type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"DNS check for\";\n\n/**\n * Register the `dns` checker to ensure that a domain is reachable.\n */\nconst dnsCheck = (\n host: string,\n expectedAddresses?: string[],\n options?: {\n family?: IPFamily | \"all\";\n hints?: number;\n } & Options,\n): Checker => async () => {\n const { hints, family = \"all\", ...config } = options || {};\n\n const cacheable = new CacheableLookup(config);\n\n try {\n const meta = await cacheable.lookupAsync(host.replace(/^https?:\\/\\//, \"\"), {\n hints,\n ...(family === \"all\" ? { all: true } : { family: family as IPFamily }),\n });\n\n if (Array.isArray(expectedAddresses) && !expectedAddresses?.includes(meta.address)) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: `${DISPLAY_NAME} ${host} returned address ${meta.address} instead of ${expectedAddresses.join(\", \")}.`,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n addresses: meta,\n },\n };\n }\n\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: true,\n message: `${DISPLAY_NAME} ${host} were resolved.`,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n addresses: meta,\n },\n };\n } catch (error: any) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: error.message,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n },\n };\n }\n};\n\nexport default dnsCheck;\n","import { deepStrictEqual } from \"node:assert\";\n\nimport type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"HTTP check for\";\n\n/**\n * Register the `http` checker to ensure http body and status is correct.\n */\nconst httpCheck = (host: RequestInfo | URL, options?: {\n fetchOptions?: RequestInit,\n expected?: { status?: number; body?: string }\n}): Checker => async () => {\n try {\n // eslint-disable-next-line compat/compat\n const response = await fetch(host, options?.fetchOptions || {});\n\n if (options?.expected?.status !== undefined && options?.expected?.status !== response.status) {\n throw new Error(`${DISPLAY_NAME} ${host} returned status ${response.status} instead of ${options?.expected.status}`);\n }\n\n if (options?.expected?.body !== undefined) {\n const textBody = await response.text();\n\n try {\n deepStrictEqual(textBody, options?.expected.body);\n } catch {\n throw new Error(`${DISPLAY_NAME} ${host} returned body ${JSON.stringify(textBody)} instead of ${JSON.stringify(options?.expected.body)}`);\n }\n }\n\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: true,\n message: `${DISPLAY_NAME} ${host} was successful.`,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n method: options?.fetchOptions?.method || \"GET\",\n status: response.status,\n },\n };\n } catch (error: any) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: error.message,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n method: options?.fetchOptions?.method || \"GET\",\n },\n };\n }\n};\n\nexport default httpCheck;\n","import type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"Node Environment Check\";\n\n/**\n * Register the `env` checker to ensure that `NODE_ENV` environment\n * variable is defined.\n */\nconst nodeEnvironmentCheck = (expectedEnvironment?: string): Checker => async () => {\n const environment = process.env.NODE_ENV;\n\n let errorMessage: string | undefined;\n\n if (environment !== undefined && expectedEnvironment !== undefined && environment !== expectedEnvironment) {\n errorMessage = `NODE_ENV environment variable is set to \"${environment}\" instead of \"${expectedEnvironment}\".`;\n } else if (environment === undefined) {\n errorMessage = [\"Missing NODE_ENV environment variable.\", \"It can make some parts of the application misbehave\"].join(\" \");\n }\n\n if (errorMessage !== undefined) {\n return {\n displayName: DISPLAY_NAME,\n health: {\n healthy: false,\n message: errorMessage,\n timestamp: new Date().toISOString(),\n },\n };\n }\n\n return {\n displayName: DISPLAY_NAME,\n health: {\n healthy: true,\n timestamp: new Date().toISOString(),\n },\n meta: {\n env: environment,\n },\n };\n};\n\nexport default nodeEnvironmentCheck;\n","import type { extendedPingOptions } from \"pingman\";\nimport ping from \"pingman\";\n\nimport type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"Ping check for\";\n\n/**\n * Register the `ping` checker to ensure that a domain is reachable.\n */\nconst pingCheck = (host: string, options?: extendedPingOptions): Checker => async () => {\n try {\n const response = await ping(host.replace(/^https?:\\/\\//, \"\"), options);\n\n if (!response.alive) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: `Ping failed for ${host}.`,\n timestamp: new Date().toISOString(),\n },\n meta: response,\n };\n }\n\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: true,\n message: `${DISPLAY_NAME} ${host} was successful.`,\n timestamp: new Date().toISOString(),\n },\n meta: response,\n };\n } catch (error: any) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: error.message,\n timestamp: new Date().toISOString(),\n },\n };\n }\n};\n\nexport default pingCheck;\n"]}
1
+ {"version":3,"sources":["../src/handler/healthcheck.ts","../src/handler/readyhandler.ts","../src/healthcheck.ts","../src/checks/dns-check.ts","../src/checks/http-check.ts","../src/checks/node-environment-check.ts","../src/checks/ping-check.ts"],"names":["StatusCodes","healthcheck_default","healthCheck","sendHeader","_","response","healthy","report","payload","readyhandler_default","_request","Healthcheck","__publicField","service","reportSheet","checker","error","CacheableLookup","DISPLAY_NAME","dnsCheck","host","expectedAddresses","options","hints","family","config","cacheable","meta","dns_check_default","deepStrictEqual","httpCheck","textBody","http_check_default","nodeEnvironmentCheck","expectedEnvironment","environment","errorMessage","node_environment_check_default","ping","pingCheck","ping_check_default"],"mappings":"wKAAA,OAAS,eAAAA,MAAmB,oBAM5B,IAAOC,EAAQ,CAACC,EAA0BC,EAAkC,KAAS,MAAyEC,EAAYC,IAAsC,CAC5M,GAAM,CAAE,QAAAC,EAAS,OAAAC,CAAO,EAAI,MAAML,EAAY,UAAU,EAElDM,EAAiC,CACnC,OAAQF,EAAU,KAAO,QACzB,QAASA,EAAU,0BAA4B,sBAC/C,QAAS,QAAQ,IAAI,UAAe,UACpC,WAAY,QAAQ,IAAI,aAAkB,UAC1C,UAAW,IAAI,KAAK,EAAE,YAAY,EAClC,QAASC,CACb,EAEAF,EAAS,WAAaC,EAAUN,EAAY,GAAKA,EAAY,oBAEzDG,GACAE,EAAS,UAAU,eAAgB,kBAAkB,EAGzDA,EAAS,IAAI,KAAK,UAAUG,EAAS,KAAM,CAAC,CAAC,CACjD,ECzBA,OAAS,eAAAR,MAAmB,oBAM5B,IAAOS,EAA2EP,GAA6B,MAAOQ,EAAmBL,IAAsC,CAC3K,GAAM,CAAE,QAAAC,CAAQ,EAAI,MAAMJ,EAAY,UAAU,EAEhDG,EAAS,WAAaC,EAAUN,EAAY,WAAaA,EAAY,oBACrEK,EAAS,IAAI,CACjB,ECPA,IAAMM,EAAN,KAAkD,CAAlD,cAIIC,EAAA,KAAQ,iBAAiD,CAAC,GAK1D,IAAW,cAAyB,CAChC,OAAO,OAAO,KAAK,KAAK,cAAc,CAC1C,CAKA,MAAc,cAAcC,EAAiBC,EAA6C,CACtF,IAAMC,EAAU,KAAK,eAAeF,CAAO,EAEvCN,EAEJ,GAAI,CACAA,EAAS,MAAMQ,EAAQ,EAEvBR,EAAO,YAAcA,EAAO,aAAeM,CAC/C,OAASG,EAAP,CACET,EAAS,CACL,YAAaM,EACb,OAAQ,CAAE,QAAS,GAAO,QAAUG,EAAgB,QAAS,UAAW,IAAI,KAAK,EAAE,YAAY,CAAE,EACjG,KAAM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AS,GACT,QAAUJ,EAAgB,QAC1B,UAAW,IAAI,KAAK,EAAE,YAAY,CACtC,CACJ,CACJ,CACJ,EAEOwB,EAAQD","sourcesContent":["import { StatusCodes } from \"http-status-codes\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { HealthCheck, HealthReport } from \"../types\";\n\n// eslint-disable-next-line max-len\nexport default (healthCheck: HealthCheck, sendHeader: boolean | undefined = true) => async <Request extends IncomingMessage, Response extends ServerResponse>(_: Request, response: Response): Promise<void> => {\n const { healthy, report } = await healthCheck.getReport();\n\n const payload: HealthCheckApiPayload = {\n status: healthy ? \"ok\" : \"error\",\n message: healthy ? \"Health check successful\" : \"Health check failed\",\n appName: process.env[\"APP_NAME\"] ?? \"unknown\",\n appVersion: process.env[\"APP_VERSION\"] ?? \"unknown\",\n timestamp: new Date().toISOString(),\n reports: report,\n };\n\n response.statusCode = healthy ? StatusCodes.OK : StatusCodes.SERVICE_UNAVAILABLE;\n\n if (sendHeader) {\n response.setHeader(\"Content-Type\", \"application/json\");\n }\n\n response.end(JSON.stringify(payload, null, 2));\n};\n\nexport type HealthCheckApiPayload = {\n status: \"error\" | \"ok\";\n message: string;\n appName: string;\n appVersion: string;\n timestamp: string;\n reports: HealthReport;\n};\n","import { StatusCodes } from \"http-status-codes\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { HealthCheck } from \"../types\";\n\n// eslint-disable-next-line max-len\nexport default <Request extends IncomingMessage, Response extends ServerResponse>(healthCheck: HealthCheck) => async (_request: Request, response: Response): Promise<void> => {\n const { healthy } = await healthCheck.getReport();\n\n response.statusCode = healthy ? StatusCodes.NO_CONTENT : StatusCodes.SERVICE_UNAVAILABLE;\n response.end();\n};\n","import type {\n Checker, HealthCheck as HealthcheckInterface, HealthReport, HealthReportEntry,\n} from \"./types.d\";\n\nclass Healthcheck implements HealthcheckInterface {\n /**\n * A copy of registered checkers\n */\n private healthCheckers: { [service: string]: Checker } = {};\n\n /**\n * Returns an array of registered services names\n */\n public get servicesList(): string[] {\n return Object.keys(this.healthCheckers);\n }\n\n /**\n * Invokes a given checker to collect the report metrics.\n */\n private async invokeChecker(service: string, reportSheet: HealthReport): Promise<boolean> {\n const checker = this.healthCheckers[service] as Checker;\n\n let report: HealthReportEntry;\n\n try {\n report = await checker();\n\n report.displayName = report.displayName || service;\n } catch (error: any) {\n report = {\n displayName: service,\n health: { healthy: false, message: (error as Error).message, timestamp: new Date().toISOString() },\n meta: { fatal: true },\n };\n }\n\n // eslint-disable-next-line no-param-reassign\n reportSheet[service] = report;\n\n return report.health.healthy;\n }\n\n public addChecker(service: string, checker: Checker): void {\n this.healthCheckers[service] = checker;\n }\n\n /**\n * Returns the health check reports. The health checks are performed when\n * this method is invoked.\n */\n public async getReport(): Promise<{ healthy: boolean; report: HealthReport }> {\n const report: HealthReport = {};\n\n // eslint-disable-next-line compat/compat\n await Promise.all(Object.keys(this.healthCheckers).map((service) => this.invokeChecker(service, report)));\n\n /**\n * Finding unhealthy service to know if system is healthy or not\n */\n const unhealthyService = Object.keys(report).find((service) => !(report[service] as HealthReportEntry).health.healthy);\n\n return { healthy: !unhealthyService, report };\n }\n\n public async isLive(): Promise<boolean> {\n const { healthy } = await this.getReport();\n\n return healthy;\n }\n}\n\nexport default Healthcheck;\n","import type { IPFamily, Options } from \"cacheable-lookup\";\nimport CacheableLookup from \"cacheable-lookup\";\n\nimport type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"DNS check for\";\n\n/**\n * Register the `dns` checker to ensure that a domain is reachable.\n */\nconst dnsCheck = (\n host: string,\n expectedAddresses?: string[],\n options?: Options & {\n family?: IPFamily | \"all\";\n hints?: number;\n },\n): Checker => async () => {\n const { hints, family = \"all\", ...config } = options ?? {};\n\n const cacheable = new CacheableLookup(config);\n\n try {\n const meta = await cacheable.lookupAsync(host.replace(/^https?:\\/\\//, \"\"), {\n hints,\n ...(family === \"all\" ? { all: true } : { family }),\n });\n\n if (Array.isArray(expectedAddresses) && !expectedAddresses.includes(meta.address)) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: `${DISPLAY_NAME} ${host} returned address ${meta.address} instead of ${expectedAddresses.join(\", \")}.`,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n addresses: meta,\n },\n };\n }\n\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: true,\n message: `${DISPLAY_NAME} ${host} were resolved.`,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n addresses: meta,\n },\n };\n } catch (error: any) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: (error as Error).message,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n },\n };\n }\n};\n\nexport default dnsCheck;\n","import { deepStrictEqual } from \"node:assert\";\n\nimport type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"HTTP check for\";\n\n/**\n * Register the `http` checker to ensure http body and status is correct.\n */\nconst httpCheck = (host: RequestInfo | URL, options?: {\n fetchOptions?: RequestInit,\n expected?: { status?: number; body?: string }\n}): Checker => async () => {\n try {\n // eslint-disable-next-line compat/compat\n const response = await fetch(host, options?.fetchOptions ?? {});\n\n if (options?.expected?.status !== undefined && options.expected.status !== response.status) {\n throw new Error(`${DISPLAY_NAME} ${host} returned status ${response.status} instead of ${options.expected.status}`);\n }\n\n if (options?.expected?.body !== undefined) {\n const textBody = await response.text();\n\n try {\n deepStrictEqual(textBody, options.expected.body);\n } catch {\n throw new Error(`${DISPLAY_NAME} ${host} returned body ${JSON.stringify(textBody)} instead of ${JSON.stringify(options.expected.body)}`);\n }\n }\n\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: true,\n message: `${DISPLAY_NAME} ${host} was successful.`,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n method: options?.fetchOptions?.method ?? \"GET\",\n status: response.status,\n },\n };\n } catch (error: any) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: (error as Error).message,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n method: options?.fetchOptions?.method ?? \"GET\",\n },\n };\n }\n};\n\nexport default httpCheck;\n","import type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"Node Environment Check\";\n\n/**\n * Register the `env` checker to ensure that `NODE_ENV` environment\n * variable is defined.\n */\nconst nodeEnvironmentCheck = (expectedEnvironment?: string): Checker => async () => {\n // eslint-disable-next-line @typescript-eslint/dot-notation\n const environment: string | undefined = process.env[\"NODE_ENV\"];\n\n let errorMessage: string | undefined;\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (environment !== undefined && expectedEnvironment !== undefined && environment !== expectedEnvironment) {\n errorMessage = `NODE_ENV environment variable is set to \"${environment}\" instead of \"${expectedEnvironment}\".`;\n } else if (!environment) {\n errorMessage = [\"Missing NODE_ENV environment variable.\", \"It can make some parts of the application misbehave\"].join(\" \");\n }\n\n if (errorMessage !== undefined) {\n return {\n displayName: DISPLAY_NAME,\n health: {\n healthy: false,\n message: errorMessage,\n timestamp: new Date().toISOString(),\n },\n };\n }\n\n return {\n displayName: DISPLAY_NAME,\n health: {\n healthy: true,\n timestamp: new Date().toISOString(),\n },\n meta: {\n env: environment,\n },\n };\n};\n\nexport default nodeEnvironmentCheck;\n","import type { extendedPingOptions } from \"pingman\";\nimport ping from \"pingman\";\n\nimport type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"Ping check for\";\n\n/**\n * Register the `ping` checker to ensure that a domain is reachable.\n */\nconst pingCheck = (host: string, options?: extendedPingOptions): Checker => async () => {\n try {\n const response = await ping(host.replace(/^https?:\\/\\//, \"\"), options);\n\n if (!response.alive) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: `Ping failed for ${host}.`,\n timestamp: new Date().toISOString(),\n },\n meta: response,\n };\n }\n\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: true,\n message: `${DISPLAY_NAME} ${host} was successful.`,\n timestamp: new Date().toISOString(),\n },\n meta: response,\n };\n } catch (error: any) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: (error as Error).message,\n timestamp: new Date().toISOString(),\n },\n };\n }\n};\n\nexport default pingCheck;\n"]}
package/dist/index.mjs CHANGED
@@ -1,2 +1,10 @@
1
- import{StatusCodes as y}from"http-status-codes";var u=(t,e=!0)=>async(a,r)=>{let{healthy:s,report:h}=await t.getReport(),l={status:s?"ok":"error",message:s?"Health check successful":"Health check failed",appName:process.env.APP_NAME??"unknown",appVersion:process.env.APP_VERSION??"unknown",timestamp:new Date().toISOString(),reports:h};r.statusCode=s?y.OK:y.SERVICE_UNAVAILABLE,e&&r.setHeader("Content-Type","application/json"),r.end(JSON.stringify(l,null,2))};import{StatusCodes as d}from"http-status-codes";var g=t=>async(e,a)=>{let{healthy:r}=await t.getReport();a.statusCode=r?d.NO_CONTENT:d.SERVICE_UNAVAILABLE,a.end()};var p=class{constructor(){this.healthCheckers={}}get servicesList(){return Object.keys(this.healthCheckers)}async invokeChecker(e,a){let r=this.healthCheckers[e],s;try{s=await r(),s.displayName=s.displayName||e}catch(h){s={displayName:e,health:{healthy:!1,message:h.message,timestamp:new Date().toISOString()},meta:{fatal:!0}}}return a[e]=s,s.health.healthy}addChecker(e,a){this.healthCheckers[e]=a}async getReport(){let e={};return await Promise.all(Object.keys(this.healthCheckers).map(r=>this.invokeChecker(r,e))),{healthy:!Object.keys(e).find(r=>!e[r].health.healthy),report:e}}async isLive(){let{healthy:e}=await this.getReport();return e}},k=p;import C from"cacheable-lookup";var i="DNS check for",S=(t,e,a)=>async()=>{let{hints:r,family:s="all",...h}=a||{},l=new C(h);try{let n=await l.lookupAsync(t.replace(/^https?:\/\//,""),{hints:r,...s==="all"?{all:!0}:{family:s}});return Array.isArray(e)&&!(e!=null&&e.includes(n.address))?{displayName:`${i} ${t}`,health:{healthy:!1,message:`${i} ${t} returned address ${n.address} instead of ${e.join(", ")}.`,timestamp:new Date().toISOString()},meta:{host:t,addresses:n}}:{displayName:`${i} ${t}`,health:{healthy:!0,message:`${i} ${t} were resolved.`,timestamp:new Date().toISOString()},meta:{host:t,addresses:n}}}catch(n){return{displayName:`${i} ${t}`,health:{healthy:!1,message:n.message,timestamp:new Date().toISOString()},meta:{host:t}}}},N=S;import{deepStrictEqual as $}from"assert";var m="HTTP check for",I=(t,e)=>async()=>{var a,r,s,h,l;try{let n=await fetch(t,(e==null?void 0:e.fetchOptions)||{});if(((a=e==null?void 0:e.expected)==null?void 0:a.status)!==void 0&&((r=e==null?void 0:e.expected)==null?void 0:r.status)!==n.status)throw new Error(`${m} ${t} returned status ${n.status} instead of ${e==null?void 0:e.expected.status}`);if(((s=e==null?void 0:e.expected)==null?void 0:s.body)!==void 0){let o=await n.text();try{$(o,e==null?void 0:e.expected.body)}catch{throw new Error(`${m} ${t} returned body ${JSON.stringify(o)} instead of ${JSON.stringify(e==null?void 0:e.expected.body)}`)}}return{displayName:`${m} ${t}`,health:{healthy:!0,message:`${m} ${t} was successful.`,timestamp:new Date().toISOString()},meta:{host:t,method:((h=e==null?void 0:e.fetchOptions)==null?void 0:h.method)||"GET",status:n.status}}}catch(n){return{displayName:`${m} ${t}`,health:{healthy:!1,message:n.message,timestamp:new Date().toISOString()},meta:{host:t,method:((l=e==null?void 0:e.fetchOptions)==null?void 0:l.method)||"GET"}}}},O=I;var f="Node Environment Check",R=t=>async()=>{let e="production",a;return e!==void 0&&t!==void 0&&e!==t?a=`NODE_ENV environment variable is set to "${e}" instead of "${t}".`:e===void 0&&(a=["Missing NODE_ENV environment variable.","It can make some parts of the application misbehave"].join(" ")),a!==void 0?{displayName:f,health:{healthy:!1,message:a,timestamp:new Date().toISOString()}}:{displayName:f,health:{healthy:!0,timestamp:new Date().toISOString()},meta:{env:e}}},w=R;import E from"pingman";var c="Ping check for",b=(t,e)=>async()=>{try{let a=await E(t.replace(/^https?:\/\//,""),e);return a.alive?{displayName:`${c} ${t}`,health:{healthy:!0,message:`${c} ${t} was successful.`,timestamp:new Date().toISOString()},meta:a}:{displayName:`${c} ${t}`,health:{healthy:!1,message:`Ping failed for ${t}.`,timestamp:new Date().toISOString()},meta:a}}catch(a){return{displayName:`${c} ${t}`,health:{healthy:!1,message:a.message,timestamp:new Date().toISOString()}}}},v=b;export{k as HealthCheck,N as dnsCheck,u as healthCheckHandler,g as healthReadyHandler,O as httpCheck,w as nodeEnvCheck,v as pingCheck};
1
+ import { StatusCodes } from 'http-status-codes';
2
+ import N from 'cacheable-lookup';
3
+ import { deepStrictEqual } from 'assert';
4
+ import v from 'pingman';
5
+
6
+ var u=Object.defineProperty;var g=(t,e,a)=>e in t?u(t,e,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[e]=a;var m=(t,e,a)=>(g(t,typeof e!="symbol"?e+"":e,a),a);var k=(t,e=!0)=>async(a,r)=>{let{healthy:s,report:o}=await t.getReport(),l={status:s?"ok":"error",message:s?"Health check successful":"Health check failed",appName:process.env.APP_NAME??"unknown",appVersion:process.env.APP_VERSION??"unknown",timestamp:new Date().toISOString(),reports:o};r.statusCode=s?StatusCodes.OK:StatusCodes.SERVICE_UNAVAILABLE,e&&r.setHeader("Content-Type","application/json"),r.end(JSON.stringify(l,null,2));};var C=t=>async(e,a)=>{let{healthy:r}=await t.getReport();a.statusCode=r?StatusCodes.NO_CONTENT:StatusCodes.SERVICE_UNAVAILABLE,a.end();};var c=class{constructor(){m(this,"healthCheckers",{});}get servicesList(){return Object.keys(this.healthCheckers)}async invokeChecker(e,a){let r=this.healthCheckers[e],s;try{s=await r(),s.displayName=s.displayName||e;}catch(o){s={displayName:e,health:{healthy:!1,message:o.message,timestamp:new Date().toISOString()},meta:{fatal:!0}};}return a[e]=s,s.health.healthy}addChecker(e,a){this.healthCheckers[e]=a;}async getReport(){let e={};return await Promise.all(Object.keys(this.healthCheckers).map(r=>this.invokeChecker(r,e))),{healthy:!Object.keys(e).find(r=>!e[r].health.healthy),report:e}}async isLive(){let{healthy:e}=await this.getReport();return e}},S=c;var i="DNS check for",$=(t,e,a)=>async()=>{let{hints:r,family:s="all",...o}=a??{},l=new N(o);try{let n=await l.lookupAsync(t.replace(/^https?:\/\//,""),{hints:r,...s==="all"?{all:!0}:{family:s}});return Array.isArray(e)&&!e.includes(n.address)?{displayName:`${i} ${t}`,health:{healthy:!1,message:`${i} ${t} returned address ${n.address} instead of ${e.join(", ")}.`,timestamp:new Date().toISOString()},meta:{host:t,addresses:n}}:{displayName:`${i} ${t}`,health:{healthy:!0,message:`${i} ${t} were resolved.`,timestamp:new Date().toISOString()},meta:{host:t,addresses:n}}}catch(n){return {displayName:`${i} ${t}`,health:{healthy:!1,message:n.message,timestamp:new Date().toISOString()},meta:{host:t}}}},O=$;var h="HTTP check for",I=(t,e)=>async()=>{try{let a=await fetch(t,e?.fetchOptions??{});if(e?.expected?.status!==void 0&&e.expected.status!==a.status)throw new Error(`${h} ${t} returned status ${a.status} instead of ${e.expected.status}`);if(e?.expected?.body!==void 0){let r=await a.text();try{deepStrictEqual(r,e.expected.body);}catch{throw new Error(`${h} ${t} returned body ${JSON.stringify(r)} instead of ${JSON.stringify(e.expected.body)}`)}}return {displayName:`${h} ${t}`,health:{healthy:!0,message:`${h} ${t} was successful.`,timestamp:new Date().toISOString()},meta:{host:t,method:e?.fetchOptions?.method??"GET",status:a.status}}}catch(a){return {displayName:`${h} ${t}`,health:{healthy:!1,message:a.message,timestamp:new Date().toISOString()},meta:{host:t,method:e?.fetchOptions?.method??"GET"}}}},R=I;var f="Node Environment Check",w=t=>async()=>{let e="production",a;return t!==void 0&&e!==t?a=`NODE_ENV environment variable is set to "${e}" instead of "${t}".`:e,a!==void 0?{displayName:f,health:{healthy:!1,message:a,timestamp:new Date().toISOString()}}:{displayName:f,health:{healthy:!0,timestamp:new Date().toISOString()},meta:{env:e}}},x=w;var p="Ping check for",b=(t,e)=>async()=>{try{let a=await v(t.replace(/^https?:\/\//,""),e);return a.alive?{displayName:`${p} ${t}`,health:{healthy:!0,message:`${p} ${t} was successful.`,timestamp:new Date().toISOString()},meta:a}:{displayName:`${p} ${t}`,health:{healthy:!1,message:`Ping failed for ${t}.`,timestamp:new Date().toISOString()},meta:a}}catch(a){return {displayName:`${p} ${t}`,health:{healthy:!1,message:a.message,timestamp:new Date().toISOString()}}}},H=b;
7
+
8
+ export { S as HealthCheck, O as dnsCheck, k as healthCheckHandler, C as healthReadyHandler, R as httpCheck, x as nodeEnvCheck, H as pingCheck };
9
+ //# sourceMappingURL=out.js.map
2
10
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/handler/healthcheck.ts","../src/handler/readyhandler.ts","../src/healthcheck.ts","../src/checks/dns-check.ts","../src/checks/http-check.ts","../src/checks/node-environment-check.ts","../src/checks/ping-check.ts"],"sourcesContent":["import { StatusCodes } from \"http-status-codes\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { HealthCheck, HealthReport } from \"../types\";\n\n// eslint-disable-next-line max-len\nexport default (healthCheck: HealthCheck, sendHeader: boolean | undefined = true) => async <Request extends IncomingMessage, Response extends ServerResponse>(_: Request, response: Response) => {\n const { healthy, report } = await healthCheck.getReport();\n\n const payload: HealthCheckApiPayload = {\n status: healthy ? \"ok\" : \"error\",\n message: healthy ? \"Health check successful\" : \"Health check failed\",\n appName: process.env.APP_NAME ?? \"unknown\",\n appVersion: process.env.APP_VERSION ?? \"unknown\",\n timestamp: new Date().toISOString(),\n reports: report,\n };\n\n response.statusCode = healthy ? StatusCodes.OK : StatusCodes.SERVICE_UNAVAILABLE;\n\n if (sendHeader) {\n response.setHeader(\"Content-Type\", \"application/json\");\n }\n\n response.end(JSON.stringify(payload, null, 2));\n};\n\nexport type HealthCheckApiPayload = {\n status: \"ok\" | \"error\";\n message: string;\n appName: string;\n appVersion: string;\n timestamp: string;\n reports: HealthReport;\n};\n","import { StatusCodes } from \"http-status-codes\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { HealthCheck } from \"../types\";\n\n// eslint-disable-next-line max-len\nexport default <Request extends IncomingMessage, Response extends ServerResponse>(healthCheck: HealthCheck) => async (_request: Request, response: Response) => {\n const { healthy } = await healthCheck.getReport();\n\n response.statusCode = healthy ? StatusCodes.NO_CONTENT : StatusCodes.SERVICE_UNAVAILABLE;\n response.end();\n};\n","import {\n Checker, HealthCheck as HealthcheckInterface, HealthReport, HealthReportEntry,\n} from \"./types\";\n\nclass Healthcheck implements HealthcheckInterface {\n /**\n * A copy of registered checkers\n */\n private healthCheckers: { [service: string]: Checker } = {};\n\n /**\n * Returns an array of registered services names\n */\n public get servicesList(): string[] {\n return Object.keys(this.healthCheckers);\n }\n\n /**\n * Invokes a given checker to collect the report metrics.\n */\n private async invokeChecker(service: string, reportSheet: HealthReport): Promise<boolean> {\n const checker = this.healthCheckers[service] as Checker;\n\n let report: HealthReportEntry;\n\n try {\n report = await checker();\n\n report.displayName = report.displayName || service;\n } catch (error: any) {\n report = {\n displayName: service,\n health: { healthy: false, message: error.message, timestamp: new Date().toISOString() },\n meta: { fatal: true },\n };\n }\n\n // eslint-disable-next-line no-param-reassign\n reportSheet[service] = report;\n\n return report.health.healthy;\n }\n\n public addChecker(service: string, checker: Checker): void {\n this.healthCheckers[service] = checker;\n }\n\n /**\n * Returns the health check reports. The health checks are performed when\n * this method is invoked.\n */\n public async getReport(): Promise<{ healthy: boolean; report: HealthReport }> {\n const report: HealthReport = {};\n\n // eslint-disable-next-line compat/compat\n await Promise.all(Object.keys(this.healthCheckers).map((service) => this.invokeChecker(service, report)));\n\n /**\n * Finding unhealthy service to know if system is healthy or not\n */\n const unhealthyService = Object.keys(report).find((service) => !(report[service] as HealthReportEntry).health.healthy);\n\n return { healthy: !unhealthyService, report };\n }\n\n public async isLive(): Promise<boolean> {\n const { healthy } = await this.getReport();\n\n return healthy;\n }\n}\n\nexport default Healthcheck;\n","import type { IPFamily, Options } from \"cacheable-lookup\";\nimport CacheableLookup from \"cacheable-lookup\";\n\nimport type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"DNS check for\";\n\n/**\n * Register the `dns` checker to ensure that a domain is reachable.\n */\nconst dnsCheck = (\n host: string,\n expectedAddresses?: string[],\n options?: {\n family?: IPFamily | \"all\";\n hints?: number;\n } & Options,\n): Checker => async () => {\n const { hints, family = \"all\", ...config } = options || {};\n\n const cacheable = new CacheableLookup(config);\n\n try {\n const meta = await cacheable.lookupAsync(host.replace(/^https?:\\/\\//, \"\"), {\n hints,\n ...(family === \"all\" ? { all: true } : { family: family as IPFamily }),\n });\n\n if (Array.isArray(expectedAddresses) && !expectedAddresses?.includes(meta.address)) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: `${DISPLAY_NAME} ${host} returned address ${meta.address} instead of ${expectedAddresses.join(\", \")}.`,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n addresses: meta,\n },\n };\n }\n\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: true,\n message: `${DISPLAY_NAME} ${host} were resolved.`,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n addresses: meta,\n },\n };\n } catch (error: any) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: error.message,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n },\n };\n }\n};\n\nexport default dnsCheck;\n","import { deepStrictEqual } from \"node:assert\";\n\nimport type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"HTTP check for\";\n\n/**\n * Register the `http` checker to ensure http body and status is correct.\n */\nconst httpCheck = (host: RequestInfo | URL, options?: {\n fetchOptions?: RequestInit,\n expected?: { status?: number; body?: string }\n}): Checker => async () => {\n try {\n // eslint-disable-next-line compat/compat\n const response = await fetch(host, options?.fetchOptions || {});\n\n if (options?.expected?.status !== undefined && options?.expected?.status !== response.status) {\n throw new Error(`${DISPLAY_NAME} ${host} returned status ${response.status} instead of ${options?.expected.status}`);\n }\n\n if (options?.expected?.body !== undefined) {\n const textBody = await response.text();\n\n try {\n deepStrictEqual(textBody, options?.expected.body);\n } catch {\n throw new Error(`${DISPLAY_NAME} ${host} returned body ${JSON.stringify(textBody)} instead of ${JSON.stringify(options?.expected.body)}`);\n }\n }\n\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: true,\n message: `${DISPLAY_NAME} ${host} was successful.`,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n method: options?.fetchOptions?.method || \"GET\",\n status: response.status,\n },\n };\n } catch (error: any) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: error.message,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n method: options?.fetchOptions?.method || \"GET\",\n },\n };\n }\n};\n\nexport default httpCheck;\n","import type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"Node Environment Check\";\n\n/**\n * Register the `env` checker to ensure that `NODE_ENV` environment\n * variable is defined.\n */\nconst nodeEnvironmentCheck = (expectedEnvironment?: string): Checker => async () => {\n const environment = process.env.NODE_ENV;\n\n let errorMessage: string | undefined;\n\n if (environment !== undefined && expectedEnvironment !== undefined && environment !== expectedEnvironment) {\n errorMessage = `NODE_ENV environment variable is set to \"${environment}\" instead of \"${expectedEnvironment}\".`;\n } else if (environment === undefined) {\n errorMessage = [\"Missing NODE_ENV environment variable.\", \"It can make some parts of the application misbehave\"].join(\" \");\n }\n\n if (errorMessage !== undefined) {\n return {\n displayName: DISPLAY_NAME,\n health: {\n healthy: false,\n message: errorMessage,\n timestamp: new Date().toISOString(),\n },\n };\n }\n\n return {\n displayName: DISPLAY_NAME,\n health: {\n healthy: true,\n timestamp: new Date().toISOString(),\n },\n meta: {\n env: environment,\n },\n };\n};\n\nexport default nodeEnvironmentCheck;\n","import type { extendedPingOptions } from \"pingman\";\nimport ping from \"pingman\";\n\nimport type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"Ping check for\";\n\n/**\n * Register the `ping` checker to ensure that a domain is reachable.\n */\nconst pingCheck = (host: string, options?: extendedPingOptions): Checker => async () => {\n try {\n const response = await ping(host.replace(/^https?:\\/\\//, \"\"), options);\n\n if (!response.alive) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: `Ping failed for ${host}.`,\n timestamp: new Date().toISOString(),\n },\n meta: response,\n };\n }\n\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: true,\n message: `${DISPLAY_NAME} ${host} was successful.`,\n timestamp: new Date().toISOString(),\n },\n meta: response,\n };\n } catch (error: any) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: error.message,\n timestamp: new Date().toISOString(),\n },\n };\n }\n};\n\nexport default pingCheck;\n"],"mappings":"AAAA,OAAS,eAAAA,MAAmB,oBAM5B,IAAOC,EAAQ,CAACC,EAA0BC,EAAkC,KAAS,MAAyEC,EAAYC,IAAuB,CAC7L,GAAM,CAAE,QAAAC,EAAS,OAAAC,CAAO,EAAI,MAAML,EAAY,UAAU,EAElDM,EAAiC,CACnC,OAAQF,EAAU,KAAO,QACzB,QAASA,EAAU,0BAA4B,sBAC/C,QAAS,QAAQ,IAAI,UAAY,UACjC,WAAY,QAAQ,IAAI,aAAe,UACvC,UAAW,IAAI,KAAK,EAAE,YAAY,EAClC,QAASC,CACb,EAEAF,EAAS,WAAaC,EAAUN,EAAY,GAAKA,EAAY,oBAEzDG,GACAE,EAAS,UAAU,eAAgB,kBAAkB,EAGzDA,EAAS,IAAI,KAAK,UAAUG,EAAS,KAAM,CAAC,CAAC,CACjD,ECzBA,OAAS,eAAAC,MAAmB,oBAM5B,IAAOC,EAA2EC,GAA6B,MAAOC,EAAmBC,IAAuB,CAC5J,GAAM,CAAE,QAAAC,CAAQ,EAAI,MAAMH,EAAY,UAAU,EAEhDE,EAAS,WAAaC,EAAUL,EAAY,WAAaA,EAAY,oBACrEI,EAAS,IAAI,CACjB,ECPA,IAAME,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IAAI,KAAK,EAAE,YAAY,CACtC,EACA,KAAM,CACF,IAAKG,CACT,CACJ,CACJ,EAEOE,EAAQJ,ECzCf,OAAOK,MAAU,UAIjB,IAAMC,EAAe,iBAKfC,EAAY,CAACC,EAAcC,IAA2C,SAAY,CACpF,GAAI,CACA,IAAMC,EAAW,MAAML,EAAKG,EAAK,QAAQ,eAAgB,EAAE,EAAGC,CAAO,EAErE,OAAKC,EAAS,MAYP,CACH,YAAa,GAAGJ,KAAgBE,IAChC,OAAQ,CACJ,QAAS,GACT,QAAS,GAAGF,KAAgBE,oBAC5B,UAAW,IAAI,KAAK,EAAE,YAAY,CACtC,EACA,KAAME,CACV,EAnBW,CACH,YAAa,GAAGJ,KAAgBE,IAChC,OAAQ,CACJ,QAAS,GACT,QAAS,mBAAmBA,KAC5B,UAAW,IAAI,KAAK,EAAE,YAAY,CACtC,EACA,KAAME,CACV,CAYR,OAASC,EAAP,CACE,MAAO,CACH,YAAa,GAAGL,KAAgBE,IAChC,OAAQ,CACJ,QAAS,GACT,QAASG,EAAM,QACf,UAAW,IAAI,KAAK,EAAE,YAAY,CACtC,CACJ,CACJ,CACJ,EAEOC,EAAQL","names":["StatusCodes","healthcheck_default","healthCheck","sendHeader","_","response","healthy","report","payload","StatusCodes","readyhandler_default","healthCheck","_request","response","healthy","Healthcheck","service","reportSheet","checker","report","error","healthy","healthcheck_default","CacheableLookup","DISPLAY_NAME","dnsCheck","host","expectedAddresses","options","hints","family","config","cacheable","meta","error","dns_check_default","deepStrictEqual","DISPLAY_NAME","httpCheck","host","options","_a","_b","_c","_d","_e","response","textBody","error","http_check_default","DISPLAY_NAME","nodeEnvironmentCheck","expectedEnvironment","environment","errorMessage","node_environment_check_default","ping","DISPLAY_NAME","pingCheck","host","options","response","error","ping_check_default"]}
1
+ {"version":3,"sources":["../src/handler/healthcheck.ts","../src/handler/readyhandler.ts","../src/healthcheck.ts","../src/checks/dns-check.ts","../src/checks/http-check.ts","../src/checks/node-environment-check.ts","../src/checks/ping-check.ts"],"names":["StatusCodes","healthcheck_default","healthCheck","sendHeader","_","response","healthy","report","payload","readyhandler_default","_request","Healthcheck","__publicField","service","reportSheet","checker","error","CacheableLookup","DISPLAY_NAME","dnsCheck","host","expectedAddresses","options","hints","family","config","cacheable","meta","dns_check_default","deepStrictEqual","httpCheck","textBody","http_check_default","nodeEnvironmentCheck","expectedEnvironment","environment","errorMessage","node_environment_check_default","ping","pingCheck","ping_check_default"],"mappings":"wKAAA,OAAS,eAAAA,MAAmB,oBAM5B,IAAOC,EAAQ,CAACC,EAA0BC,EAAkC,KAAS,MAAyEC,EAAYC,IAAsC,CAC5M,GAAM,CAAE,QAAAC,EAAS,OAAAC,CAAO,EAAI,MAAML,EAAY,UAAU,EAElDM,EAAiC,CACnC,OAAQF,EAAU,KAAO,QACzB,QAASA,EAAU,0BAA4B,sBAC/C,QAAS,QAAQ,IAAI,UAAe,UACpC,WAAY,QAAQ,IAAI,aAAkB,UAC1C,UAAW,IAAI,KAAK,EAAE,YAAY,EAClC,QAASC,CACb,EAEAF,EAAS,WAAaC,EAAUN,EAAY,GAAKA,EAAY,oBAEzDG,GACAE,EAAS,UAAU,eAAgB,kBAAkB,EAGzDA,EAAS,IAAI,KAAK,UAAUG,EAAS,KAAM,CAAC,CAAC,CACjD,ECzBA,OAAS,eAAAR,MAAmB,oBAM5B,IAAOS,EAA2EP,GAA6B,MAAOQ,EAAmBL,IAAsC,CAC3K,GAAM,CAAE,QAAAC,CAAQ,EAAI,MAAMJ,EAAY,UAAU,EAEhDG,EAAS,WAAaC,EAAUN,EAAY,WAAaA,EAAY,oBACrEK,EAAS,IAAI,CACjB,ECPA,IAAMM,EAAN,KAAkD,CAAlD,cAIIC,EAAA,KAAQ,iBAAiD,CAAC,GAK1D,IAAW,cAAyB,CAChC,OAAO,OAAO,KAAK,KAAK,cAAc,CAC1C,CAKA,MAAc,cAAcC,EAAiBC,EAA6C,CACtF,IAAMC,EAAU,KAAK,eAAeF,CAAO,EAEvCN,E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nBW,CACH,YAAa,GAAGa,KAAgBE,IAChC,OAAQ,CACJ,QAAS,GACT,QAAS,mBAAmBA,KAC5B,UAAW,IAAI,KAAK,EAAE,YAAY,CACtC,EACA,KAAMf,CACV,CAYR,OAASW,EAAP,CACE,MAAO,CACH,YAAa,GAAGE,KAAgBE,IAChC,OAAQ,CACJ,QAAS,GACT,QAAUJ,EAAgB,QAC1B,UAAW,IAAI,KAAK,EAAE,YAAY,CACtC,CACJ,CACJ,CACJ,EAEOwB,EAAQD","sourcesContent":["import { StatusCodes } from \"http-status-codes\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { HealthCheck, HealthReport } from \"../types\";\n\n// eslint-disable-next-line max-len\nexport default (healthCheck: HealthCheck, sendHeader: boolean | undefined = true) => async <Request extends IncomingMessage, Response extends ServerResponse>(_: Request, response: Response): Promise<void> => {\n const { healthy, report } = await healthCheck.getReport();\n\n const payload: HealthCheckApiPayload = {\n status: healthy ? \"ok\" : \"error\",\n message: healthy ? \"Health check successful\" : \"Health check failed\",\n appName: process.env[\"APP_NAME\"] ?? \"unknown\",\n appVersion: process.env[\"APP_VERSION\"] ?? \"unknown\",\n timestamp: new Date().toISOString(),\n reports: report,\n };\n\n response.statusCode = healthy ? StatusCodes.OK : StatusCodes.SERVICE_UNAVAILABLE;\n\n if (sendHeader) {\n response.setHeader(\"Content-Type\", \"application/json\");\n }\n\n response.end(JSON.stringify(payload, null, 2));\n};\n\nexport type HealthCheckApiPayload = {\n status: \"error\" | \"ok\";\n message: string;\n appName: string;\n appVersion: string;\n timestamp: string;\n reports: HealthReport;\n};\n","import { StatusCodes } from \"http-status-codes\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { HealthCheck } from \"../types\";\n\n// eslint-disable-next-line max-len\nexport default <Request extends IncomingMessage, Response extends ServerResponse>(healthCheck: HealthCheck) => async (_request: Request, response: Response): Promise<void> => {\n const { healthy } = await healthCheck.getReport();\n\n response.statusCode = healthy ? StatusCodes.NO_CONTENT : StatusCodes.SERVICE_UNAVAILABLE;\n response.end();\n};\n","import type {\n Checker, HealthCheck as HealthcheckInterface, HealthReport, HealthReportEntry,\n} from \"./types.d\";\n\nclass Healthcheck implements HealthcheckInterface {\n /**\n * A copy of registered checkers\n */\n private healthCheckers: { [service: string]: Checker } = {};\n\n /**\n * Returns an array of registered services names\n */\n public get servicesList(): string[] {\n return Object.keys(this.healthCheckers);\n }\n\n /**\n * Invokes a given checker to collect the report metrics.\n */\n private async invokeChecker(service: string, reportSheet: HealthReport): Promise<boolean> {\n const checker = this.healthCheckers[service] as Checker;\n\n let report: HealthReportEntry;\n\n try {\n report = await checker();\n\n report.displayName = report.displayName || service;\n } catch (error: any) {\n report = {\n displayName: service,\n health: { healthy: false, message: (error as Error).message, timestamp: new Date().toISOString() },\n meta: { fatal: true },\n };\n }\n\n // eslint-disable-next-line no-param-reassign\n reportSheet[service] = report;\n\n return report.health.healthy;\n }\n\n public addChecker(service: string, checker: Checker): void {\n this.healthCheckers[service] = checker;\n }\n\n /**\n * Returns the health check reports. The health checks are performed when\n * this method is invoked.\n */\n public async getReport(): Promise<{ healthy: boolean; report: HealthReport }> {\n const report: HealthReport = {};\n\n // eslint-disable-next-line compat/compat\n await Promise.all(Object.keys(this.healthCheckers).map((service) => this.invokeChecker(service, report)));\n\n /**\n * Finding unhealthy service to know if system is healthy or not\n */\n const unhealthyService = Object.keys(report).find((service) => !(report[service] as HealthReportEntry).health.healthy);\n\n return { healthy: !unhealthyService, report };\n }\n\n public async isLive(): Promise<boolean> {\n const { healthy } = await this.getReport();\n\n return healthy;\n }\n}\n\nexport default Healthcheck;\n","import type { IPFamily, Options } from \"cacheable-lookup\";\nimport CacheableLookup from \"cacheable-lookup\";\n\nimport type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"DNS check for\";\n\n/**\n * Register the `dns` checker to ensure that a domain is reachable.\n */\nconst dnsCheck = (\n host: string,\n expectedAddresses?: string[],\n options?: Options & {\n family?: IPFamily | \"all\";\n hints?: number;\n },\n): Checker => async () => {\n const { hints, family = \"all\", ...config } = options ?? {};\n\n const cacheable = new CacheableLookup(config);\n\n try {\n const meta = await cacheable.lookupAsync(host.replace(/^https?:\\/\\//, \"\"), {\n hints,\n ...(family === \"all\" ? { all: true } : { family }),\n });\n\n if (Array.isArray(expectedAddresses) && !expectedAddresses.includes(meta.address)) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: `${DISPLAY_NAME} ${host} returned address ${meta.address} instead of ${expectedAddresses.join(\", \")}.`,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n addresses: meta,\n },\n };\n }\n\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: true,\n message: `${DISPLAY_NAME} ${host} were resolved.`,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n addresses: meta,\n },\n };\n } catch (error: any) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: (error as Error).message,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n },\n };\n }\n};\n\nexport default dnsCheck;\n","import { deepStrictEqual } from \"node:assert\";\n\nimport type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"HTTP check for\";\n\n/**\n * Register the `http` checker to ensure http body and status is correct.\n */\nconst httpCheck = (host: RequestInfo | URL, options?: {\n fetchOptions?: RequestInit,\n expected?: { status?: number; body?: string }\n}): Checker => async () => {\n try {\n // eslint-disable-next-line compat/compat\n const response = await fetch(host, options?.fetchOptions ?? {});\n\n if (options?.expected?.status !== undefined && options.expected.status !== response.status) {\n throw new Error(`${DISPLAY_NAME} ${host} returned status ${response.status} instead of ${options.expected.status}`);\n }\n\n if (options?.expected?.body !== undefined) {\n const textBody = await response.text();\n\n try {\n deepStrictEqual(textBody, options.expected.body);\n } catch {\n throw new Error(`${DISPLAY_NAME} ${host} returned body ${JSON.stringify(textBody)} instead of ${JSON.stringify(options.expected.body)}`);\n }\n }\n\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: true,\n message: `${DISPLAY_NAME} ${host} was successful.`,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n method: options?.fetchOptions?.method ?? \"GET\",\n status: response.status,\n },\n };\n } catch (error: any) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: (error as Error).message,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n method: options?.fetchOptions?.method ?? \"GET\",\n },\n };\n }\n};\n\nexport default httpCheck;\n","import type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"Node Environment Check\";\n\n/**\n * Register the `env` checker to ensure that `NODE_ENV` environment\n * variable is defined.\n */\nconst nodeEnvironmentCheck = (expectedEnvironment?: string): Checker => async () => {\n // eslint-disable-next-line @typescript-eslint/dot-notation\n const environment: string | undefined = process.env[\"NODE_ENV\"];\n\n let errorMessage: string | undefined;\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (environment !== undefined && expectedEnvironment !== undefined && environment !== expectedEnvironment) {\n errorMessage = `NODE_ENV environment variable is set to \"${environment}\" instead of \"${expectedEnvironment}\".`;\n } else if (!environment) {\n errorMessage = [\"Missing NODE_ENV environment variable.\", \"It can make some parts of the application misbehave\"].join(\" \");\n }\n\n if (errorMessage !== undefined) {\n return {\n displayName: DISPLAY_NAME,\n health: {\n healthy: false,\n message: errorMessage,\n timestamp: new Date().toISOString(),\n },\n };\n }\n\n return {\n displayName: DISPLAY_NAME,\n health: {\n healthy: true,\n timestamp: new Date().toISOString(),\n },\n meta: {\n env: environment,\n },\n };\n};\n\nexport default nodeEnvironmentCheck;\n","import type { extendedPingOptions } from \"pingman\";\nimport ping from \"pingman\";\n\nimport type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"Ping check for\";\n\n/**\n * Register the `ping` checker to ensure that a domain is reachable.\n */\nconst pingCheck = (host: string, options?: extendedPingOptions): Checker => async () => {\n try {\n const response = await ping(host.replace(/^https?:\\/\\//, \"\"), options);\n\n if (!response.alive) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: `Ping failed for ${host}.`,\n timestamp: new Date().toISOString(),\n },\n meta: response,\n };\n }\n\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: true,\n message: `${DISPLAY_NAME} ${host} was successful.`,\n timestamp: new Date().toISOString(),\n },\n meta: response,\n };\n } catch (error: any) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: (error as Error).message,\n timestamp: new Date().toISOString(),\n },\n };\n }\n};\n\nexport default pingCheck;\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@visulima/health-check",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "description": "A library built to provide support for defining service health for node services. It allows you to register async health checks for your dependencies and the service itself, provides a health endpoint that exposes their status, and health metrics.",
5
5
  "keywords": [
6
6
  "anolilab",
@@ -58,68 +58,69 @@
58
58
  "scripts": {
59
59
  "build": "cross-env NODE_ENV=development tsup",
60
60
  "build:prod": "cross-env NODE_ENV=production tsup",
61
- "clean": "rimraf node_modules dist",
61
+ "clean": "rimraf node_modules dist .eslintcache",
62
62
  "coverage": "vitest run --coverage",
63
63
  "dev": "pnpm predev && pnpm run build --watch",
64
64
  "lint:eslint": "cross-env NO_LOGS=true eslint . --ext js,jsx,ts,tsx --max-warnings=0 --config .eslintrc.cjs --cache --cache-strategy content .",
65
65
  "lint:eslint:fix": "pnpm run lint:eslint --fix",
66
- "test": "vitest"
66
+ "test": "vitest run",
67
+ "test:watch": "vitest"
67
68
  },
68
69
  "dependencies": {
69
70
  "cacheable-lookup": "^7.0.0",
70
71
  "http-status-codes": "^2.2.0",
71
- "pingman": "^1.1.5"
72
+ "pingman": "^2.0.0"
72
73
  },
73
74
  "devDependencies": {
74
- "@anolilab/eslint-config": "^4.0.9",
75
- "@anolilab/semantic-release-preset": "^2.0.7",
76
- "@rushstack/eslint-plugin-security": "^0.5.0",
77
- "@types/node": "^18.8.4",
78
- "@types/react": "^18.0.21",
79
- "@types/react-dom": "^18.0.6",
80
- "@typescript-eslint/eslint-plugin": "^5.40.0",
81
- "@typescript-eslint/parser": "^5.40.0",
75
+ "@anolilab/eslint-config": "^5.0.5",
76
+ "@anolilab/semantic-release-preset": "^2.2.1",
77
+ "@rushstack/eslint-plugin-security": "^0.6.0",
78
+ "@types/node": "18.16.14",
79
+ "@types/react": "^18.2.7",
80
+ "@types/react-dom": "^18.2.4",
81
+ "@typescript-eslint/eslint-plugin": "^5.59.7",
82
+ "@typescript-eslint/parser": "^5.59.7",
83
+ "@vitest/coverage-c8": "^0.31.1",
82
84
  "cross-env": "^7.0.3",
83
- "cross-fetch": "^3.1.5",
84
- "eslint": "^8.25.0",
85
- "eslint-plugin-compat": "^4.0.2",
85
+ "cross-fetch": "^3.1.6",
86
+ "eslint": "^8.41.0",
87
+ "eslint-plugin-compat": "^4.1.4",
86
88
  "eslint-plugin-eslint-comments": "^3.2.0",
87
- "eslint-plugin-import": "^2.26.0",
89
+ "eslint-plugin-import": "^2.27.5",
88
90
  "eslint-plugin-json": "^3.1.0",
89
- "eslint-plugin-jsx-a11y": "^6.6.1",
91
+ "eslint-plugin-jsonc": "^2.8.0",
92
+ "eslint-plugin-jsx-a11y": "^6.7.1",
90
93
  "eslint-plugin-markdown": "^3.0.0",
91
94
  "eslint-plugin-no-loops": "^0.3.0",
92
95
  "eslint-plugin-no-secrets": "^0.8.9",
93
96
  "eslint-plugin-node": "^11.1.0",
94
97
  "eslint-plugin-optimize-regex": "^1.2.1",
95
- "eslint-plugin-promise": "^6.0.1",
96
- "eslint-plugin-radar": "^0.2.1",
97
- "eslint-plugin-react": "7.31.11",
98
+ "eslint-plugin-promise": "^6.1.1",
99
+ "eslint-plugin-react": "7.32.2",
98
100
  "eslint-plugin-react-hooks": "4.6.0",
99
- "eslint-plugin-simple-import-sort": "^8.0.0",
101
+ "eslint-plugin-simple-import-sort": "^10.0.0",
100
102
  "eslint-plugin-sort-keys-fix": "^1.1.2",
101
- "eslint-plugin-testing-library": "^5.7.2",
102
- "eslint-plugin-unicorn": "^45.0.0",
103
+ "eslint-plugin-testing-library": "^5.11.0",
104
+ "eslint-plugin-unicorn": "^47.0.0",
103
105
  "eslint-plugin-you-dont-need-lodash-underscore": "^6.12.0",
104
106
  "eslint-plugin-you-dont-need-momentjs": "^1.6.0",
105
- "next": "^13.0.0",
106
- "next-test-api-route-handler": "^4.0.0-canary.1",
107
- "node-mocks-http": "^1.11.0",
108
- "prettier": "^2.7.1",
107
+ "next": "^13.1.5",
108
+ "node-mocks-http": "^1.12.2",
109
+ "prettier": "^2.8.8",
109
110
  "react": "^18.2.0",
110
111
  "react-dom": "^18.2.0",
111
- "read-pkg": "^7.1.0",
112
- "rimraf": "^3.0.2",
113
- "semantic-release": "^20.0.0",
114
- "tsup": "^6.2.3",
115
- "typescript": "^4.8.4",
116
- "vitest": "^0.26.1"
112
+ "read-pkg": "^8.0.0",
113
+ "rimraf": "^5.0.1",
114
+ "semantic-release": "^21.0.2",
115
+ "tsup": "^6.7.0",
116
+ "typescript": "^5.0.4",
117
+ "vitest": "^0.31.1"
117
118
  },
118
119
  "optionalDependencies": {
119
- "next": "^12.3.1"
120
+ "next": "^13.1.4"
120
121
  },
121
122
  "engines": {
122
- "node": ">=16.18.0 <=19.0"
123
+ "node": ">=16.18.0 <=20.*"
123
124
  },
124
125
  "publishConfig": {
125
126
  "access": "public"