@middy/util 5.0.0-alpha.0 → 5.0.0-alpha.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.
package/README.md CHANGED
@@ -19,8 +19,9 @@
19
19
  <a href="https://snyk.io/test/github/middyjs/middy">
20
20
  <img src="https://snyk.io/test/github/middyjs/middy/badge.svg" alt="Known Vulnerabilities" data-canonical-src="https://snyk.io/test/github/middyjs/middy" style="max-width:100%;">
21
21
  </a>
22
- <a href="https://lgtm.com/projects/g/middyjs/middy/context:javascript">
23
- <img src="https://img.shields.io/lgtm/grade/javascript/g/middyjs/middy.svg?logo=lgtm&logoWidth=18" alt="Language grade: JavaScript" style="max-width:100%;">
22
+ <a href="https://github.com/middyjs/middy/actions/workflows/sast.yml">
23
+ <img src="https://github.com/middyjs/middy/actions/workflows/sast.yml/badge.svg
24
+ ?branch=main&event=push" alt="CodeQL" style="max-width:100%;">
24
25
  </a>
25
26
  <a href="https://bestpractices.coreinfrastructure.org/projects/5280">
26
27
  <img src="https://bestpractices.coreinfrastructure.org/projects/5280/badge" alt="Core Infrastructure Initiative (CII) Best Practices" style="max-width:100%;">
package/index.d.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import middy from '@middy/core'
2
+ import { Context as LambdaContext } from 'aws-lambda'
3
+ import { ArrayValues, Choose, DeepAwaited, IsUnknown, SanitizeKey, SanitizeKeys } from './type-utils'
2
4
 
3
5
  interface Options<Client, ClientOptions> {
4
- AwsClient?: new (...args: any[]) => Client
6
+ AwsClient?: new (...[config]: [any] | any) => Client
5
7
  awsClientOptions?: Partial<ClientOptions>
6
8
  awsClientAssumeRole?: string
7
9
  awsClientCapture?: (service: Client) => Client
@@ -12,7 +14,7 @@ interface Options<Client, ClientOptions> {
12
14
  setToContext?: boolean
13
15
  }
14
16
 
15
- type HttpError = Error & {
17
+ declare class HttpError extends Error {
16
18
  status: number
17
19
  statusCode: number
18
20
  expose: boolean
@@ -33,12 +35,77 @@ declare function canPrefetch<Client, ClientOptions> (
33
35
  options: Options<Client, ClientOptions>
34
36
  ): boolean
35
37
 
36
- declare function getInternal (
37
- variables: any,
38
- request: middy.Request
39
- ): Promise<any>
38
+ type InternalOutput<TVariables> = TVariables extends string[] ? { [key in TVariables[number]]: unknown } : never
39
+
40
+ // get an empty object if false is passed
41
+ declare function getInternal<
42
+ TContext extends LambdaContext,
43
+ TInternal extends Record<string, unknown>
44
+ > (
45
+ variables: false,
46
+ request: middy.Request<unknown, unknown, unknown, TContext, TInternal>
47
+ ): Promise<{}>
48
+
49
+ // get all internal values if true is passed (with promises resolved)
50
+ declare function getInternal<
51
+ TContext extends LambdaContext,
52
+ TInternal extends Record<string, unknown>
53
+ > (
54
+ variables: true,
55
+ request: middy.Request<unknown, unknown, unknown, TContext, TInternal>
56
+ ): Promise<DeepAwaited<TInternal>>
57
+
58
+ // get a single value
59
+ declare function getInternal<
60
+ TContext extends LambdaContext,
61
+ TInternal extends Record<string, unknown>,
62
+ TVars extends keyof TInternal | string
63
+ > (
64
+ variables: TVars,
65
+ request: middy.Request<unknown, unknown, unknown, TContext, TInternal>
66
+ ): TVars extends keyof TInternal
67
+ ? Promise<DeepAwaited<{ [_ in SanitizeKey<TVars>]: TInternal[TVars] }>>
68
+ : TVars extends string
69
+ ? IsUnknown<Choose<DeepAwaited<TInternal>, TVars>> extends true
70
+ ? unknown // could not find the path
71
+ : Promise<{ [_ in SanitizeKey<TVars>]: Choose<DeepAwaited<TInternal>, TVars> }>
72
+ : unknown // path is not a string or a keyof TInternal
73
+
74
+ // get multiple values
75
+ declare function getInternal<
76
+ TContext extends LambdaContext,
77
+ TInternal extends Record<string, unknown>,
78
+ TVars extends Array<keyof TInternal | string>
79
+ > (
80
+ variables: TVars,
81
+ request: middy.Request<unknown, unknown, unknown, TContext, TInternal>
82
+ ): Promise<SanitizeKeys<{
83
+ [TVar in ArrayValues<TVars>]:
84
+ TVar extends keyof TInternal
85
+ ? DeepAwaited<TInternal[TVar]>
86
+ : TVar extends string
87
+ ? Choose<DeepAwaited<TInternal>, TVar>
88
+ : unknown // path is not a string or a keyof TInternal
89
+ }>>
90
+
91
+ // remap object
92
+ declare function getInternal<
93
+ TContext extends LambdaContext,
94
+ TInternal extends Record<string, unknown>,
95
+ TMap extends Record<string, keyof TInternal | string>
96
+ > (
97
+ variables: TMap,
98
+ request: middy.Request<unknown, unknown, unknown, TContext, TInternal>
99
+ ): Promise<{
100
+ [P in keyof TMap]:
101
+ TMap[P] extends keyof TInternal
102
+ ? DeepAwaited<TInternal[TMap[P]]>
103
+ : TMap[P] extends string
104
+ ? Choose<DeepAwaited<TInternal>, TMap[P]>
105
+ : unknown // path is not a string or a keyof TInternal
106
+ }>
40
107
 
41
- declare function sanitizeKey (key: string): string
108
+ declare function sanitizeKey<T extends string> (key: T): SanitizeKey<T>
42
109
 
43
110
  declare function processCache<Client, ClientOptions> (
44
111
  options: Options<Client, ClientOptions>,
package/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  export const createPrefetchClient = (options)=>{
2
- const { awsClientOptions } = options;
2
+ const { awsClientOptions } = options;
3
3
  const client = new options.AwsClient(awsClientOptions);
4
+ // AWS XRay
4
5
  if (options.awsClientCapture && options.disablePrefetch) {
5
6
  return options.awsClientCapture(client);
6
7
  } else if (options.awsClientCapture) {
@@ -10,9 +11,14 @@ export const createPrefetchClient = (options)=>{
10
11
  };
11
12
  export const createClient = async (options, request)=>{
12
13
  let awsClientCredentials = {};
14
+ // Role Credentials
13
15
  if (options.awsClientAssumeRole) {
14
16
  if (!request) {
15
- throw new Error('Request required when assuming role');
17
+ throw new Error('Request required when assuming role', {
18
+ cause: {
19
+ package: '@middy/util'
20
+ }
21
+ });
16
22
  }
17
23
  awsClientCredentials = await getInternal({
18
24
  credentials: options.awsClientAssumeRole
@@ -30,6 +36,7 @@ export const createClient = async (options, request)=>{
30
36
  export const canPrefetch = (options = {})=>{
31
37
  return !options.awsClientAssumeRole && !options.disablePrefetch;
32
38
  };
39
+ // Internal Context
33
40
  export const getInternal = async (variables, request)=>{
34
41
  if (!variables || !request) return {};
35
42
  let keys = [];
@@ -48,6 +55,7 @@ export const getInternal = async (variables, request)=>{
48
55
  }
49
56
  const promises = [];
50
57
  for (const internalKey of values){
58
+ // 'internal.key.sub_value' -> { [key]: internal.key.sub_value }
51
59
  const pathOptionKey = internalKey.split('.');
52
60
  const rootOptionKey = pathOptionKey.shift();
53
61
  let valuePromise = request.internal[rootOptionKey];
@@ -56,11 +64,16 @@ export const getInternal = async (variables, request)=>{
56
64
  }
57
65
  promises.push(valuePromise.then((value)=>pathOptionKey.reduce((p, c)=>p?.[c], value)));
58
66
  }
67
+ // ensure promise has resolved by the time it's needed
68
+ // If one of the promises throws it will bubble up to @middy/core
59
69
  values = await Promise.allSettled(promises);
60
70
  const errors = values.filter((res)=>res.status === 'rejected').map((res)=>res.reason);
61
71
  if (errors.length) {
62
72
  throw new Error('Failed to resolve internal values', {
63
- cause: errors
73
+ cause: {
74
+ package: '@middy/util',
75
+ data: errors
76
+ }
64
77
  });
65
78
  }
66
79
  return keys.reduce((obj, key, index)=>({
@@ -74,9 +87,12 @@ const sanitizeKeyRemoveDisallowedChar = /[^a-zA-Z0-9]+/g;
74
87
  export const sanitizeKey = (key)=>{
75
88
  return key.replace(sanitizeKeyPrefixLeadingNumber, '_$1').replace(sanitizeKeyRemoveDisallowedChar, '_');
76
89
  };
77
- const cache = {};
90
+ // fetch Cache
91
+ const cache = {} // key: { value:{fetchKey:Promise}, expiry }
92
+ ;
78
93
  export const processCache = (options, fetch = ()=>undefined, request)=>{
79
- const { cacheExpiry , cacheKey } = options;
94
+ let { cacheKey, cacheKeyExpiry, cacheExpiry } = options;
95
+ cacheExpiry = cacheKeyExpiry?.[cacheKey] ?? cacheExpiry;
80
96
  if (cacheExpiry) {
81
97
  const cached = getCache(cacheKey);
82
98
  const unexpired = cached.expiry && (cacheExpiry < 0 || cached.expiry > Date.now());
@@ -99,9 +115,12 @@ export const processCache = (options, fetch = ()=>undefined, request)=>{
99
115
  }
100
116
  }
101
117
  const value = fetch(request);
102
- const expiry = Date.now() + cacheExpiry;
118
+ const now = Date.now();
119
+ // secrets-manager overrides to unix timestamp
120
+ const expiry = cacheExpiry > 86400000 ? cacheExpiry : now + cacheExpiry;
121
+ const duration = cacheExpiry > 86400000 ? cacheExpiry - now : cacheExpiry;
103
122
  if (cacheExpiry) {
104
- const refresh = cacheExpiry > 0 ? setInterval(()=>processCache(options, fetch, request), cacheExpiry) : undefined;
123
+ const refresh = duration > 0 ? setInterval(()=>processCache(options, fetch, request), duration) : undefined;
105
124
  cache[cacheKey] = {
106
125
  value,
107
126
  expiry,
@@ -117,6 +136,7 @@ export const getCache = (key)=>{
117
136
  if (!cache[key]) return {};
118
137
  return cache[key];
119
138
  };
139
+ // Used to remove parts of a cache
120
140
  export const modifyCache = (cacheKey, value)=>{
121
141
  if (!cache[cacheKey]) return;
122
142
  clearInterval(cache[cacheKey]?.refresh);
@@ -152,7 +172,7 @@ export const jsonSafeStringify = (value, replacer, space)=>{
152
172
  return value;
153
173
  };
154
174
  export const normalizeHttpResponse = (request)=>{
155
- let { response } = request;
175
+ let { response } = request;
156
176
  if (typeof response === 'undefined') {
157
177
  response = {};
158
178
  } else if (typeof response?.statusCode === 'undefined' && typeof response?.body === 'undefined' && typeof response?.headers === 'undefined') {
@@ -177,7 +197,8 @@ export class HttpError extends Error {
177
197
  super(message, options);
178
198
  const name = httpErrorCodes[code].replace(createErrorRegexp, '');
179
199
  this.name = name.substr(-5) !== 'Error' ? name + 'Error' : name;
180
- this.status = this.statusCode = code;
200
+ this.status = this.statusCode = code // setting `status` for backwards compatibility w/ `http-errors`
201
+ ;
181
202
  this.expose = options.expose ?? code < 500;
182
203
  }
183
204
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@middy/util",
3
- "version": "5.0.0-alpha.0",
3
+ "version": "5.0.0-alpha.2",
4
4
  "description": "🛵 The stylish Node.js middleware engine for AWS Lambda (util package)",
5
5
  "type": "module",
6
6
  "engines": {
@@ -10,24 +10,18 @@
10
10
  "publishConfig": {
11
11
  "access": "public"
12
12
  },
13
- "main": "./index.cjs",
14
13
  "module": "./index.js",
15
14
  "exports": {
16
15
  ".": {
17
16
  "import": {
18
17
  "types": "./index.d.ts",
19
18
  "default": "./index.js"
20
- },
21
- "require": {
22
- "types": "./index.d.ts",
23
- "default": "./index.cjs"
24
19
  }
25
20
  }
26
21
  },
27
22
  "types": "index.d.ts",
28
23
  "files": [
29
24
  "index.js",
30
- "index.cjs",
31
25
  "index.d.ts",
32
26
  "codes.js"
33
27
  ],
@@ -61,9 +55,9 @@
61
55
  },
62
56
  "devDependencies": {
63
57
  "@aws-sdk/client-ssm": "^3.0.0",
64
- "@middy/core": "5.0.0-alpha.0",
58
+ "@middy/core": "5.0.0-alpha.2",
65
59
  "@types/aws-lambda": "^8.10.76",
66
- "@types/node": "^18.0.0",
60
+ "@types/node": "^20.0.0",
67
61
  "aws-xray-sdk": "^3.3.3"
68
62
  },
69
63
  "homepage": "https://middy.js.org",
@@ -71,5 +65,5 @@
71
65
  "type": "github",
72
66
  "url": "https://github.com/sponsors/willfarrell"
73
67
  },
74
- "gitHead": "08c35e3dba9efdad0b86666ce206ce302cc65d07"
68
+ "gitHead": "ebce8d5df8783077fa49ba62ee9be20e8486a7f1"
75
69
  }
package/index.cjs DELETED
@@ -1,279 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", {
3
- value: true
4
- });
5
- function _export(target, all) {
6
- for(var name in all)Object.defineProperty(target, name, {
7
- enumerable: true,
8
- get: all[name]
9
- });
10
- }
11
- _export(exports, {
12
- createPrefetchClient: ()=>createPrefetchClient,
13
- createClient: ()=>createClient,
14
- canPrefetch: ()=>canPrefetch,
15
- getInternal: ()=>getInternal,
16
- sanitizeKey: ()=>sanitizeKey,
17
- processCache: ()=>processCache,
18
- getCache: ()=>getCache,
19
- modifyCache: ()=>modifyCache,
20
- clearCache: ()=>clearCache,
21
- jsonSafeParse: ()=>jsonSafeParse,
22
- jsonSafeStringify: ()=>jsonSafeStringify,
23
- normalizeHttpResponse: ()=>normalizeHttpResponse,
24
- HttpError: ()=>HttpError,
25
- createError: ()=>createError
26
- });
27
- const createPrefetchClient = (options)=>{
28
- const { awsClientOptions } = options;
29
- const client = new options.AwsClient(awsClientOptions);
30
- if (options.awsClientCapture && options.disablePrefetch) {
31
- return options.awsClientCapture(client);
32
- } else if (options.awsClientCapture) {
33
- console.warn('Unable to apply X-Ray outside of handler invocation scope.');
34
- }
35
- return client;
36
- };
37
- const createClient = async (options, request)=>{
38
- let awsClientCredentials = {};
39
- if (options.awsClientAssumeRole) {
40
- if (!request) {
41
- throw new Error('Request required when assuming role');
42
- }
43
- awsClientCredentials = await getInternal({
44
- credentials: options.awsClientAssumeRole
45
- }, request);
46
- }
47
- awsClientCredentials = {
48
- ...awsClientCredentials,
49
- ...options.awsClientOptions
50
- };
51
- return createPrefetchClient({
52
- ...options,
53
- awsClientOptions: awsClientCredentials
54
- });
55
- };
56
- const canPrefetch = (options = {})=>{
57
- return !options.awsClientAssumeRole && !options.disablePrefetch;
58
- };
59
- const getInternal = async (variables, request)=>{
60
- if (!variables || !request) return {};
61
- let keys = [];
62
- let values = [];
63
- if (variables === true) {
64
- keys = values = Object.keys(request.internal);
65
- } else if (typeof variables === 'string') {
66
- keys = values = [
67
- variables
68
- ];
69
- } else if (Array.isArray(variables)) {
70
- keys = values = variables;
71
- } else if (typeof variables === 'object') {
72
- keys = Object.keys(variables);
73
- values = Object.values(variables);
74
- }
75
- const promises = [];
76
- for (const internalKey of values){
77
- const pathOptionKey = internalKey.split('.');
78
- const rootOptionKey = pathOptionKey.shift();
79
- let valuePromise = request.internal[rootOptionKey];
80
- if (!isPromise(valuePromise)) {
81
- valuePromise = Promise.resolve(valuePromise);
82
- }
83
- promises.push(valuePromise.then((value)=>pathOptionKey.reduce((p, c)=>p?.[c], value)));
84
- }
85
- values = await Promise.allSettled(promises);
86
- const errors = values.filter((res)=>res.status === 'rejected').map((res)=>res.reason);
87
- if (errors.length) {
88
- throw new Error('Failed to resolve internal values', {
89
- cause: errors
90
- });
91
- }
92
- return keys.reduce((obj, key, index)=>({
93
- ...obj,
94
- [sanitizeKey(key)]: values[index].value
95
- }), {});
96
- };
97
- const isPromise = (promise)=>typeof promise?.then === 'function';
98
- const sanitizeKeyPrefixLeadingNumber = /^([0-9])/;
99
- const sanitizeKeyRemoveDisallowedChar = /[^a-zA-Z0-9]+/g;
100
- const sanitizeKey = (key)=>{
101
- return key.replace(sanitizeKeyPrefixLeadingNumber, '_$1').replace(sanitizeKeyRemoveDisallowedChar, '_');
102
- };
103
- const cache = {};
104
- const processCache = (options, fetch = ()=>undefined, request)=>{
105
- const { cacheExpiry , cacheKey } = options;
106
- if (cacheExpiry) {
107
- const cached = getCache(cacheKey);
108
- const unexpired = cached.expiry && (cacheExpiry < 0 || cached.expiry > Date.now());
109
- if (unexpired && cached.modified) {
110
- const value = fetch(request, cached.value);
111
- cache[cacheKey] = Object.create({
112
- value: {
113
- ...cached.value,
114
- ...value
115
- },
116
- expiry: cached.expiry
117
- });
118
- return cache[cacheKey];
119
- }
120
- if (unexpired) {
121
- return {
122
- ...cached,
123
- cache: true
124
- };
125
- }
126
- }
127
- const value = fetch(request);
128
- const expiry = Date.now() + cacheExpiry;
129
- if (cacheExpiry) {
130
- const refresh = cacheExpiry > 0 ? setInterval(()=>processCache(options, fetch, request), cacheExpiry) : undefined;
131
- cache[cacheKey] = {
132
- value,
133
- expiry,
134
- refresh
135
- };
136
- }
137
- return {
138
- value,
139
- expiry
140
- };
141
- };
142
- const getCache = (key)=>{
143
- if (!cache[key]) return {};
144
- return cache[key];
145
- };
146
- const modifyCache = (cacheKey, value)=>{
147
- if (!cache[cacheKey]) return;
148
- clearInterval(cache[cacheKey]?.refresh);
149
- cache[cacheKey] = {
150
- ...cache[cacheKey],
151
- value,
152
- modified: true
153
- };
154
- };
155
- const clearCache = (keys = null)=>{
156
- keys = keys ?? Object.keys(cache);
157
- if (!Array.isArray(keys)) keys = [
158
- keys
159
- ];
160
- for (const cacheKey of keys){
161
- clearInterval(cache[cacheKey]?.refresh);
162
- cache[cacheKey] = undefined;
163
- }
164
- };
165
- const jsonSafeParse = (text, reviver)=>{
166
- if (typeof text !== 'string') return text;
167
- const firstChar = text[0];
168
- if (firstChar !== '{' && firstChar !== '[' && firstChar !== '"') return text;
169
- try {
170
- return JSON.parse(text, reviver);
171
- } catch (e) {}
172
- return text;
173
- };
174
- const jsonSafeStringify = (value, replacer, space)=>{
175
- try {
176
- return JSON.stringify(value, replacer, space);
177
- } catch (e) {}
178
- return value;
179
- };
180
- const normalizeHttpResponse = (request)=>{
181
- let { response } = request;
182
- if (typeof response === 'undefined') {
183
- response = {};
184
- } else if (typeof response?.statusCode === 'undefined' && typeof response?.body === 'undefined' && typeof response?.headers === 'undefined') {
185
- response = {
186
- statusCode: 200,
187
- body: response
188
- };
189
- }
190
- response.statusCode ??= 500;
191
- response.headers ??= {};
192
- request.response = response;
193
- return response;
194
- };
195
- const createErrorRegexp = /[^a-zA-Z]/g;
196
- class HttpError extends Error {
197
- constructor(code, message, options = {}){
198
- if (message && typeof message !== 'string') {
199
- options = message;
200
- message = undefined;
201
- }
202
- message ??= httpErrorCodes[code];
203
- super(message, options);
204
- const name = httpErrorCodes[code].replace(createErrorRegexp, '');
205
- this.name = name.substr(-5) !== 'Error' ? name + 'Error' : name;
206
- this.status = this.statusCode = code;
207
- this.expose = options.expose ?? code < 500;
208
- }
209
- }
210
- const createError = (code, message, properties = {})=>{
211
- return new HttpError(code, message, properties);
212
- };
213
- const httpErrorCodes = {
214
- 100: 'Continue',
215
- 101: 'Switching Protocols',
216
- 102: 'Processing',
217
- 103: 'Early Hints',
218
- 200: 'OK',
219
- 201: 'Created',
220
- 202: 'Accepted',
221
- 203: 'Non-Authoritative Information',
222
- 204: 'No Content',
223
- 205: 'Reset Content',
224
- 206: 'Partial Content',
225
- 207: 'Multi-Status',
226
- 208: 'Already Reported',
227
- 226: 'IM Used',
228
- 300: 'Multiple Choices',
229
- 301: 'Moved Permanently',
230
- 302: 'Found',
231
- 303: 'See Other',
232
- 304: 'Not Modified',
233
- 305: 'Use Proxy',
234
- 306: '(Unused)',
235
- 307: 'Temporary Redirect',
236
- 308: 'Permanent Redirect',
237
- 400: 'Bad Request',
238
- 401: 'Unauthorized',
239
- 402: 'Payment Required',
240
- 403: 'Forbidden',
241
- 404: 'Not Found',
242
- 405: 'Method Not Allowed',
243
- 406: 'Not Acceptable',
244
- 407: 'Proxy Authentication Required',
245
- 408: 'Request Timeout',
246
- 409: 'Conflict',
247
- 410: 'Gone',
248
- 411: 'Length Required',
249
- 412: 'Precondition Failed',
250
- 413: 'Payload Too Large',
251
- 414: 'URI Too Long',
252
- 415: 'Unsupported Media Type',
253
- 416: 'Range Not Satisfiable',
254
- 417: 'Expectation Failed',
255
- 418: "I'm a teapot",
256
- 421: 'Misdirected Request',
257
- 422: 'Unprocessable Entity',
258
- 423: 'Locked',
259
- 424: 'Failed Dependency',
260
- 425: 'Unordered Collection',
261
- 426: 'Upgrade Required',
262
- 428: 'Precondition Required',
263
- 429: 'Too Many Requests',
264
- 431: 'Request Header Fields Too Large',
265
- 451: 'Unavailable For Legal Reasons',
266
- 500: 'Internal Server Error',
267
- 501: 'Not Implemented',
268
- 502: 'Bad Gateway',
269
- 503: 'Service Unavailable',
270
- 504: 'Gateway Timeout',
271
- 505: 'HTTP Version Not Supported',
272
- 506: 'Variant Also Negotiates',
273
- 507: 'Insufficient Storage',
274
- 508: 'Loop Detected',
275
- 509: 'Bandwidth Limit Exceeded',
276
- 510: 'Not Extended',
277
- 511: 'Network Authentication Required'
278
- };
279
-