Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,29 @@ on: [pull_request]

jobs:
build:
name: Test
name: Test (Node ${{ matrix.node-version }})
runs-on: ubuntu-latest
strategy:
matrix:
node-version: ['22.x', '24.x', '26.x']
steps:
- name: Checkout repository
uses: actions/checkout@v2
uses: actions/checkout@v4

- name: Set up Node.js
uses: actions/setup-node@v2.1.4
uses: actions/setup-node@v4
with:
node-version: '20.x'
node-version: ${{ matrix.node-version }}

# Node.js 25+ no longer ships Corepack, so Yarn is not preinstalled
- name: Install Yarn
run: npm install --global yarn@1.22.22

- name: Install dependencies
run: yarn
run: yarn --frozen-lockfile

- name: Lint
run: yarn lint

- name: Unit Test
run: yarn test
Expand Down
10 changes: 8 additions & 2 deletions .github/workflows/npm-publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ jobs:
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
node-version: '22'
registry-url: 'https://registry.npmjs.org'
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
Expand All @@ -36,8 +36,14 @@ jobs:
- name: Build
run: yarn build

# Prereleases (e.g. 8.0.0-beta) are published under their own dist-tag, so they never become "latest"
- name: Determine npm dist-tag
id: dist-tag
run: |
echo "tag=$(node -p "require('./package.json').version.match(/-([0-9A-Za-z]+)/)?.[1] ?? 'latest'")" >> "$GITHUB_OUTPUT"

- name: Publish if version has been updated
run: npm publish --access public
run: npm publish --access public --tag ${{ steps.dist-tag.outputs.tag }}
if: contains(github.event.head_commit.message, 'Release ')
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
27 changes: 27 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,33 @@ All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)

## [8.0.0-beta] - 2026-11-25

### Changed

- **BREAKING:** Minimum supported Node.js version is now 22. The library is tested on Node.js 22, 24 and 26.
- **BREAKING:** Upgrade `retry-axios` to 4. `retryOptions` is typed by the new `RetryConfig`, so `onRetryAttempt` must return a Promise and the `instance` option no longer exists.
- Upgrade `@aws-sdk/client-kms`, `@aws-sdk/client-secrets-manager`, `axios`, `axios-cache-interceptor`, `openapi-factory`, and the dev dependencies `@types/node` (26), `jest` (30), `@types/jest`, `ts-jest`, `lint-staged`, `eslint` (10), `prettier` (3) and `typescript` (6).
- Move `@types/node` to the dev dependencies, so consumers keep their own `@types/node` version.
- Replace the `uuid` dependency with Node's built-in `crypto.randomUUID()`.
- Compile with `nodenext` module resolution and an ES2023 target without DOM types. The package is still published as CommonJS.
- Type `openapi-factory` with this library's own request and response types instead of the package's looser typings, which removes the `@ts-ignore`. The `OpenApiModel` middlewares now return Promises.
- When `enableNewRelicTracking` is set but `newrelic` cannot be loaded, `OpenApiWrapper` logs a warning and continues without New Relic tracking.
- `createRedisStorage` now accepts any client matching the exported `RedisCacheClient` interface instead of importing types from `redis`, so consumers without `redis` installed no longer fail type-checking.
- Allow `redis` 6 as a peer dependency (`^5.10.0 || ^6.0.0`) and mark it optional, since it is only needed when using `RedisStorage`.
- Allow `newrelic` 13 and 14 as a peer dependency (`^12.0.0 || ^13.0.0 || ^14.0.0`) and mark it optional, since it is only loaded when `enableNewRelicTracking` is set.
- Run the CI build on Node.js 22, 24 and 26, and install Yarn explicitly because Node.js 25+ no longer ships Corepack.
- Publish prereleases such as `8.0.0-beta` under their own npm dist-tag (`beta`) instead of `latest`.

### Migrating from 7.x

- Use Node.js 22 or newer.
- If your service passes its own `SecretsManagerClient` or `KMSClient` to the library, upgrade your `@aws-sdk/client-secrets-manager` / `@aws-sdk/client-kms` to `^3.1172.0` or newer. Otherwise two copies of the SDK are installed and TypeScript reports the clients as incompatible.
- Use TypeScript 4.9 or newer. The published type definitions were tested on 4.9, 5.0, 5.5 and 5.9.
- If you pass `retryOptions`, update them for `retry-axios` 4: `onRetryAttempt` must return a Promise and the `instance` option no longer exists.
- If you use `createRedisStorage`, any client with `isReady`, `connect`, `get`, `set` and `del` is accepted; a `redis` 5 or 6 client works as before.
- `uuid` is no longer a dependency of this package. If your service imports `uuid` itself, keep it in your own `package.json`.

## [7.1.1] - 2026-11-20

### Changed
Expand Down
3 changes: 3 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import cimpressAtsquad from 'eslint-config-cimpress-atsquad';

export default cimpressAtsquad;
50 changes: 27 additions & 23 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
{
"name": "lambda-essentials-ts",
"version": "7.1.1",
"version": "8.0.0-beta",
"description": "A selection of the finest modules supporting authorization, API routing, error handling, logging and sending HTTP requests.",
"main": "lib/index.js",
"private": false,
"files": [
"lib"
],
"scripts": {
"build": "tsc",
"build": "tsc -p tsconfig.build.json",
"test": "jest",
"lint": "eslint --ext .ts src tests"
"lint": "eslint src tests"
},
"publishConfig": {
"access": "public"
Expand All @@ -26,35 +26,31 @@
},
"homepage": "https://github.com/Cimpress-MCP/lambda-essentials-ts#readme",
"dependencies": {
"@aws-sdk/client-kms": "^3.930.0",
"@aws-sdk/client-secrets-manager": "^3.930.0",
"@types/node": "^25.0.3",
"@aws-sdk/client-kms": "^3.1172.0",
"@aws-sdk/client-secrets-manager": "^3.1172.0",
"axios": "1.21.1",
"axios-cache-interceptor": "1.13.0",
"fast-safe-stringify": "~2.1.1",
"is-error": "~2.2.2",
"jsonwebtoken": "9.0.3",
"md5": "~2.3.0",
"openapi-factory": "5.4.60",
"retry-axios": "~3.2.1",
"uuid": "~11.1.0"
"openapi-factory": "5.4.93",
"retry-axios": "~4.0.3"
},
"devDependencies": {
"@types/jest": "^29.5.14",
"@types/jest": "^30.0.0",
"@types/newrelic": "^9.14.8",
"@types/node": "^26.6.6",
"axios-mock-adapter": "^2.1.0",
"eslint": "^8.57.1",
"eslint-config-cimpress-atsquad": "^2.2.3",
"eslint": "^10.15.0",
"eslint-config-cimpress-atsquad": "^3.0.0",
"husky": "^9.1.7",
"jest": "^29.7.0",
"lint-staged": "^15.5.2",
"prettier": "^2.8.8",
"ts-jest": "^29.4.6",
"jest": "^30.5.2",
"lint-staged": "^17.6.1",
"prettier": "^3.10.1",
"ts-jest": "^29.4.15",
"ts-node": "^10.9.2",
"typescript": "^5.9.3"
},
"eslintConfig": {
"extends": "cimpress-atsquad"
"typescript": "^6.0.3"
},
"prettier": "eslint-config-cimpress-atsquad/prettier",
"husky": {
Expand All @@ -76,10 +72,18 @@
"collectCoverage": false
},
"engines": {
"node": ">=20.0.0"
"node": ">=22.0.0"
},
"peerDependencies": {
"newrelic": "^12.0.0",
"redis": "5.10.0"
"newrelic": "^12.0.0 || ^13.0.0 || ^14.0.0",
"redis": "^5.10.0 || ^6.0.0"
},
"peerDependenciesMeta": {
"newrelic": {
"optional": true
},
"redis": {
"optional": true
}
}
}
9 changes: 5 additions & 4 deletions src/httpClient/httpClient.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as uuid from 'uuid';
import { randomUUID } from 'node:crypto';
import axios, {
AxiosError,
AxiosHeaderValue,
Expand Down Expand Up @@ -83,9 +83,8 @@ export default class HttpClient {
if (this.enableRetry) {
this.client.defaults.raxConfig = {
...options?.retryOptions,
instance: this.client, // always attach retry-axios to the private axios client
httpMethodsToRetry: ['GET', 'HEAD', 'OPTIONS', 'DELETE', 'PUT', 'POST'], // extending the defaults to retry POST calls
onRetryAttempt: (err) => {
onRetryAttempt: async (err) => {
this.logFunction({
title: 'HTTP Response Error Retry',
level: 'INFO',
Expand Down Expand Up @@ -154,6 +153,7 @@ export default class HttpClient {

return response;
},
// eslint-disable-next-line complexity
(error: AxiosError | ClientException) => {
// when retries are configured, this middleware gets triggered for each retry
// it changes the error object to ClientException and therefore the transformation can be run only once
Expand Down Expand Up @@ -207,9 +207,10 @@ export default class HttpClient {
}

// implemented based on https://github.com/RasCarlito/axios-cache-adapter/blob/master/src/cache.js#L77
// eslint-disable-next-line complexity
public static generateCacheKey(req: AxiosRequestConfig): string {
const prefix: string = req.headers?.Authorization
? safeJwtCanonicalIdParse(req.headers.Authorization.replace('Bearer ', '')) ?? uuid.v4()
? (safeJwtCanonicalIdParse(req.headers.Authorization.replace('Bearer ', '')) ?? randomUUID())
: 'shared';
const url = `${req.baseURL ? req.baseURL : ''}${req.url}`;
const query = req.params ? JSON.stringify(req.params) : ''; // possible improvement: optimize cache-hit ratio by sorting the query params
Expand Down
23 changes: 14 additions & 9 deletions src/httpClient/redisStorage.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
import { buildStorage, canStale } from 'axios-cache-interceptor';
import type { StorageValue } from 'axios-cache-interceptor';
// eslint-disable-next-line import/no-extraneous-dependencies
// @ts-ignore
import { createClient } from 'redis';

export interface RedisCacheClient {
readonly isReady: boolean;
connect(): Promise<unknown>;
get(key: string): Promise<string | null>;
set(key: string, value: string, options: { PXAT?: number }): Promise<unknown>;
del(key: string): Promise<unknown>;
}

const KEY_PREFIX = 'axios-cache-';

const MIN_TTL = 60000;

export default function createRedisStorage(client: ReturnType<typeof createClient>) {
export default function createRedisStorage(client: RedisCacheClient) {
const connectionPromise: Promise<any> = client.connect();

const connectIfNeeded = async () => {
Expand Down Expand Up @@ -40,11 +45,11 @@ export default function createRedisStorage(client: ReturnType<typeof createClien
? Date.now() +
(req?.cache && typeof req.cache.ttl === 'number' ? req.cache.ttl : MIN_TTL)
: (value.state === 'stale' && value.ttl) ||
(value.state === 'cached' && !canStale(value))
? value.createdAt + value.ttl!
: // otherwise, we can't determine when it should expire, so we keep
// it indefinitely.
undefined,
(value.state === 'cached' && !canStale(value))
? value.createdAt + value.ttl!
: // otherwise, we can't determine when it should expire, so we keep
// it indefinitely.
undefined,
});
},

Expand Down
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import { InvalidDataException } from './exceptions/invalidDataException';
import { NotFoundException } from './exceptions/notFoundException';
import { ValidationException } from './exceptions/validationException';
import { serializeObject, serializeAxiosError } from './util';
import RedisStorage from './httpClient/redisStorage';
import RedisStorage, { RedisCacheClient } from './httpClient/redisStorage';

export {
Logger,
Expand Down Expand Up @@ -69,4 +69,5 @@ export type {
KmsTokenConfiguration,
SecretsManagerTokenProviderOptions,
SecretsManagerTokenConfiguration,
RedisCacheClient,
};
9 changes: 5 additions & 4 deletions src/logger/logger.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable no-console */

import * as uuid from 'uuid';
import { randomUUID } from 'node:crypto';
import stringify from 'fast-safe-stringify';
import isError from 'is-error';
import { redactSecret } from '../util';
Expand All @@ -20,14 +20,15 @@ export default class Logger {

private staticData: any;

// eslint-disable-next-line complexity
constructor(configuration?: LoggerConfiguration) {
this.logFunction = configuration?.logFunction ?? console.log;
this.jsonSpace = configuration?.jsonSpace ?? 2;
this.payloadLimit = !configuration?.payloadLimit
? DEFAULT_PAYLOAD_LIMIT
: configuration?.payloadLimit < MIN_PAYLOAD_LIMIT
? MIN_PAYLOAD_LIMIT
: configuration.payloadLimit;
? MIN_PAYLOAD_LIMIT
: configuration.payloadLimit;

this.invocationId = 'none';
}
Expand All @@ -39,7 +40,7 @@ export default class Logger {
*/
startInvocation(staticData?: any, invocationId?: string): void {
this.staticData = staticData;
this.invocationId = invocationId ?? uuid.v4();
this.invocationId = invocationId ?? randomUUID();
}

// eslint-disable-next-line complexity
Expand Down
27 changes: 15 additions & 12 deletions src/openApi/openApiModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,22 +27,25 @@ export interface OpenApiModel {
requestMiddleware: RequestMiddleware;
responseMiddleware: ResponseMiddleware;
errorMiddleware: ErrorMiddleware;

constructor(
options: {
requestMiddleware: RequestMiddleware;
responseMiddleware: ResponseMiddleware;
errorMiddleware: ErrorMiddleware;
},
overrideLogger?: () => void,
);
}

export type ApiControllerRoute<T = ApiRequest> = (
path: string,
handler: (request: T) => Promise<ApiResponse>,
) => void;

export type RequestMiddleware = (request: ApiRequest) => ApiRequest;
export type ResponseMiddleware = (request: ApiRequest, response: ApiResponse) => ApiResponse;
export type ErrorMiddleware = (request: ApiRequest, error: Exception | Error) => ApiResponse;
export type RequestMiddleware = (request: ApiRequest) => Promise<ApiRequest>;
export type ResponseMiddleware = (
request: ApiRequest,
response: ApiResponse,
) => Promise<ApiResponse>;
export type ErrorMiddleware = (
request: ApiRequest,
error: Exception | Error,
) => Promise<ApiResponse>;

export interface OpenApiOptions {
requestMiddleware: RequestMiddleware;
responseMiddleware: ResponseMiddleware;
errorMiddleware: ErrorMiddleware;
}
Loading
Loading