@middy/util 5.1.0 → 5.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.js +281 -256
  2. package/package.json +3 -3
package/index.js CHANGED
@@ -1,263 +1,288 @@
1
- export const createPrefetchClient = (options)=>{
2
- const { awsClientOptions } = options;
3
- const client = new options.AwsClient(awsClientOptions);
4
- if (options.awsClientCapture && options.disablePrefetch) {
5
- return options.awsClientCapture(client);
6
- } else if (options.awsClientCapture) {
7
- console.warn('Unable to apply X-Ray outside of handler invocation scope.');
8
- }
9
- return client;
10
- };
11
- export const createClient = async (options, request)=>{
12
- let awsClientCredentials = {};
13
- if (options.awsClientAssumeRole) {
14
- if (!request) {
15
- throw new Error('Request required when assuming role', {
16
- cause: {
17
- package: '@middy/util'
18
- }
19
- });
20
- }
21
- awsClientCredentials = await getInternal({
22
- credentials: options.awsClientAssumeRole
23
- }, request);
24
- }
25
- awsClientCredentials = {
26
- ...awsClientCredentials,
27
- ...options.awsClientOptions
28
- };
29
- return createPrefetchClient({
30
- ...options,
31
- awsClientOptions: awsClientCredentials
32
- });
33
- };
34
- export const canPrefetch = (options = {})=>{
35
- return !options.awsClientAssumeRole && !options.disablePrefetch;
36
- };
37
- export const getInternal = async (variables, request)=>{
38
- if (!variables || !request) return {};
39
- let keys = [];
40
- let values = [];
41
- if (variables === true) {
42
- keys = values = Object.keys(request.internal);
43
- } else if (typeof variables === 'string') {
44
- keys = values = [
45
- variables
46
- ];
47
- } else if (Array.isArray(variables)) {
48
- keys = values = variables;
49
- } else if (typeof variables === 'object') {
50
- keys = Object.keys(variables);
51
- values = Object.values(variables);
52
- }
53
- const promises = [];
54
- for (const internalKey of values){
55
- const pathOptionKey = internalKey.split('.');
56
- const rootOptionKey = pathOptionKey.shift();
57
- let valuePromise = request.internal[rootOptionKey];
58
- if (!isPromise(valuePromise)) {
59
- valuePromise = Promise.resolve(valuePromise);
60
- }
61
- promises.push(valuePromise.then((value)=>pathOptionKey.reduce((p, c)=>p?.[c], value)));
62
- }
63
- values = await Promise.allSettled(promises);
64
- const errors = values.filter((res)=>res.status === 'rejected').map((res)=>res.reason);
65
- if (errors.length) {
66
- throw new Error('Failed to resolve internal values', {
67
- cause: {
68
- package: '@middy/util',
69
- data: errors
70
- }
71
- });
72
- }
73
- return keys.reduce((obj, key, index)=>({
74
- ...obj,
75
- [sanitizeKey(key)]: values[index].value
76
- }), {});
77
- };
78
- const isPromise = (promise)=>typeof promise?.then === 'function';
79
- const sanitizeKeyPrefixLeadingNumber = /^([0-9])/;
80
- const sanitizeKeyRemoveDisallowedChar = /[^a-zA-Z0-9]+/g;
81
- export const sanitizeKey = (key)=>{
82
- return key.replace(sanitizeKeyPrefixLeadingNumber, '_$1').replace(sanitizeKeyRemoveDisallowedChar, '_');
83
- };
84
- const cache = {};
85
- export const processCache = (options, fetch = ()=>undefined, request)=>{
86
- let { cacheKey, cacheKeyExpiry, cacheExpiry } = options;
87
- cacheExpiry = cacheKeyExpiry?.[cacheKey] ?? cacheExpiry;
88
- if (cacheExpiry) {
89
- const cached = getCache(cacheKey);
90
- const unexpired = cached.expiry && (cacheExpiry < 0 || cached.expiry > Date.now());
91
- if (unexpired && cached.modified) {
92
- const value = fetch(request, cached.value);
93
- cache[cacheKey] = Object.create({
94
- value: {
95
- ...cached.value,
96
- ...value
97
- },
98
- expiry: cached.expiry
99
- });
100
- return cache[cacheKey];
101
- }
102
- if (unexpired) {
103
- return {
104
- ...cached,
105
- cache: true
106
- };
107
- }
108
- }
109
- const value = fetch(request);
110
- const now = Date.now();
111
- const expiry = cacheExpiry > 86400000 ? cacheExpiry : now + cacheExpiry;
112
- const duration = cacheExpiry > 86400000 ? cacheExpiry - now : cacheExpiry;
113
- if (cacheExpiry) {
114
- const refresh = duration > 0 ? setInterval(()=>processCache(options, fetch, request), duration) : undefined;
115
- cache[cacheKey] = {
116
- value,
117
- expiry,
118
- refresh
119
- };
1
+ export const createPrefetchClient = (options) => {
2
+ const { awsClientOptions } = options
3
+ const client = new options.AwsClient(awsClientOptions)
4
+
5
+ // AWS XRay
6
+ if (options.awsClientCapture && options.disablePrefetch) {
7
+ return options.awsClientCapture(client)
8
+ } else if (options.awsClientCapture) {
9
+ console.warn('Unable to apply X-Ray outside of handler invocation scope.')
10
+ }
11
+
12
+ return client
13
+ }
14
+
15
+ export const createClient = async (options, request) => {
16
+ let awsClientCredentials = {}
17
+
18
+ // Role Credentials
19
+ if (options.awsClientAssumeRole) {
20
+ if (!request) {
21
+ throw new Error('Request required when assuming role', {
22
+ cause: { package: '@middy/util' }
23
+ })
120
24
  }
121
- return {
122
- value,
123
- expiry
124
- };
125
- };
126
- export const getCache = (key)=>{
127
- if (!cache[key]) return {};
128
- return cache[key];
129
- };
130
- export const modifyCache = (cacheKey, value)=>{
131
- if (!cache[cacheKey]) return;
132
- clearInterval(cache[cacheKey]?.refresh);
133
- cache[cacheKey] = {
134
- ...cache[cacheKey],
135
- value,
136
- modified: true
137
- };
138
- };
139
- export const clearCache = (keys = null)=>{
140
- keys = keys ?? Object.keys(cache);
141
- if (!Array.isArray(keys)) keys = [
142
- keys
143
- ];
144
- for (const cacheKey of keys){
145
- clearInterval(cache[cacheKey]?.refresh);
146
- cache[cacheKey] = undefined;
25
+ awsClientCredentials = await getInternal(
26
+ { credentials: options.awsClientAssumeRole },
27
+ request
28
+ )
29
+ }
30
+
31
+ awsClientCredentials = {
32
+ ...awsClientCredentials,
33
+ ...options.awsClientOptions
34
+ }
35
+
36
+ return createPrefetchClient({
37
+ ...options,
38
+ awsClientOptions: awsClientCredentials
39
+ })
40
+ }
41
+
42
+ export const canPrefetch = (options = {}) => {
43
+ return !options.awsClientAssumeRole && !options.disablePrefetch
44
+ }
45
+
46
+ // Internal Context
47
+ export const getInternal = async (variables, request) => {
48
+ if (!variables || !request) return {}
49
+ let keys = []
50
+ let values = []
51
+ if (variables === true) {
52
+ keys = values = Object.keys(request.internal)
53
+ } else if (typeof variables === 'string') {
54
+ keys = values = [variables]
55
+ } else if (Array.isArray(variables)) {
56
+ keys = values = variables
57
+ } else if (typeof variables === 'object') {
58
+ keys = Object.keys(variables)
59
+ values = Object.values(variables)
60
+ }
61
+ const promises = []
62
+ for (const internalKey of values) {
63
+ // 'internal.key.sub_value' -> { [key]: internal.key.sub_value }
64
+ const pathOptionKey = internalKey.split('.')
65
+ const rootOptionKey = pathOptionKey.shift()
66
+ let valuePromise = request.internal[rootOptionKey]
67
+ if (!isPromise(valuePromise)) {
68
+ valuePromise = Promise.resolve(valuePromise)
147
69
  }
148
- };
149
- export const jsonSafeParse = (text, reviver)=>{
150
- if (typeof text !== 'string') return text;
151
- const firstChar = text[0];
152
- if (firstChar !== '{' && firstChar !== '[' && firstChar !== '"') return text;
153
- try {
154
- return JSON.parse(text, reviver);
155
- } catch (e) {}
156
- return text;
157
- };
158
- export const jsonSafeStringify = (value, replacer, space)=>{
159
- try {
160
- return JSON.stringify(value, replacer, space);
161
- } catch (e) {}
162
- return value;
163
- };
164
- export const normalizeHttpResponse = (request)=>{
165
- let { response } = request;
166
- if (typeof response === 'undefined') {
167
- response = {};
168
- } else if (typeof response?.statusCode === 'undefined' && typeof response?.body === 'undefined' && typeof response?.headers === 'undefined') {
169
- response = {
170
- statusCode: 200,
171
- body: response
172
- };
70
+ promises.push(
71
+ valuePromise.then((value) =>
72
+ pathOptionKey.reduce((p, c) => p?.[c], value)
73
+ )
74
+ )
75
+ }
76
+ // ensure promise has resolved by the time it's needed
77
+ // If one of the promises throws it will bubble up to @middy/core
78
+ values = await Promise.allSettled(promises)
79
+ const errors = values
80
+ .filter((res) => res.status === 'rejected')
81
+ .map((res) => res.reason)
82
+ if (errors.length) {
83
+ throw new Error('Failed to resolve internal values', {
84
+ cause: { package: '@middy/util', data: errors }
85
+ })
86
+ }
87
+ return keys.reduce(
88
+ (obj, key, index) => ({ ...obj, [sanitizeKey(key)]: values[index].value }),
89
+ {}
90
+ )
91
+ }
92
+
93
+ const isPromise = (promise) => typeof promise?.then === 'function'
94
+
95
+ const sanitizeKeyPrefixLeadingNumber = /^([0-9])/
96
+ const sanitizeKeyRemoveDisallowedChar = /[^a-zA-Z0-9]+/g
97
+ export const sanitizeKey = (key) => {
98
+ return key
99
+ .replace(sanitizeKeyPrefixLeadingNumber, '_$1')
100
+ .replace(sanitizeKeyRemoveDisallowedChar, '_')
101
+ }
102
+
103
+ // fetch Cache
104
+ const cache = {} // key: { value:{fetchKey:Promise}, expiry }
105
+ export const processCache = (options, fetch = () => undefined, request) => {
106
+ let { cacheKey, cacheKeyExpiry, cacheExpiry } = options
107
+ cacheExpiry = cacheKeyExpiry?.[cacheKey] ?? cacheExpiry
108
+ const now = Date.now()
109
+ if (cacheExpiry) {
110
+ const cached = getCache(cacheKey)
111
+ const unexpired = cached.expiry && (cacheExpiry < 0 || cached.expiry > now)
112
+
113
+ if (unexpired) {
114
+ if (cached.modified) {
115
+ const value = fetch(request, cached.value)
116
+ Object.assign(cached.value, value)
117
+ cache[cacheKey] = { value: cached.value, expiry: cached.expiry }
118
+ return cache[cacheKey]
119
+ }
120
+ return { ...cached, cache: true }
173
121
  }
174
- response.statusCode ??= 500;
175
- response.headers ??= {};
176
- request.response = response;
177
- return response;
178
- };
179
- const createErrorRegexp = /[^a-zA-Z]/g;
122
+ }
123
+ const value = fetch(request)
124
+ // secrets-manager can override to unix timestamp
125
+ const expiry = cacheExpiry > 86400000 ? cacheExpiry : now + cacheExpiry
126
+ const duration = cacheExpiry > 86400000 ? cacheExpiry - now : cacheExpiry
127
+ if (cacheExpiry) {
128
+ const refresh =
129
+ duration > 0
130
+ ? setTimeout(() => processCache(options, fetch, request), duration)
131
+ : undefined
132
+ cache[cacheKey] = { value, expiry, refresh }
133
+ }
134
+ return { value, expiry }
135
+ }
136
+
137
+ export const catchInvalidSignatureException = (e, client, command) => {
138
+ if (e.__type === 'InvalidSignatureException') {
139
+ return client.send(command)
140
+ }
141
+ throw e
142
+ }
143
+
144
+ export const getCache = (key) => {
145
+ if (!cache[key]) return {}
146
+ return cache[key]
147
+ }
148
+
149
+ // Used to remove parts of a cache
150
+ export const modifyCache = (cacheKey, value) => {
151
+ if (!cache[cacheKey]) return
152
+ clearTimeout(cache[cacheKey]?.refresh)
153
+ cache[cacheKey] = { ...cache[cacheKey], value, modified: true }
154
+ }
155
+
156
+ export const clearCache = (keys = null) => {
157
+ keys = keys ?? Object.keys(cache)
158
+ if (!Array.isArray(keys)) keys = [keys]
159
+ for (const cacheKey of keys) {
160
+ clearTimeout(cache[cacheKey]?.refresh)
161
+ cache[cacheKey] = undefined
162
+ }
163
+ }
164
+
165
+ export 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
+
173
+ return text
174
+ }
175
+
176
+ export const jsonSafeStringify = (value, replacer, space) => {
177
+ try {
178
+ return JSON.stringify(value, replacer, space)
179
+ } catch (e) {}
180
+
181
+ return value
182
+ }
183
+
184
+ export const normalizeHttpResponse = (request) => {
185
+ let { response } = request
186
+ if (typeof response === 'undefined') {
187
+ response = {}
188
+ } else if (
189
+ typeof response?.statusCode === 'undefined' &&
190
+ typeof response?.body === 'undefined' &&
191
+ typeof response?.headers === 'undefined'
192
+ ) {
193
+ response = { statusCode: 200, body: response }
194
+ }
195
+ response.statusCode ??= 500
196
+ response.headers ??= {}
197
+ request.response = response
198
+ return response
199
+ }
200
+
201
+ const createErrorRegexp = /[^a-zA-Z]/g
180
202
  export class HttpError extends Error {
181
- constructor(code, message, options = {}){
182
- if (message && typeof message !== 'string') {
183
- options = message;
184
- message = undefined;
185
- }
186
- message ??= httpErrorCodes[code];
187
- super(message, options);
188
- const name = httpErrorCodes[code].replace(createErrorRegexp, '');
189
- this.name = name.substr(-5) !== 'Error' ? name + 'Error' : name;
190
- this.status = this.statusCode = code;
191
- this.expose = options.expose ?? code < 500;
203
+ constructor (code, message, options = {}) {
204
+ if (message && typeof message !== 'string') {
205
+ options = message
206
+ message = undefined
192
207
  }
208
+ message ??= httpErrorCodes[code]
209
+ super(message, options)
210
+
211
+ const name = httpErrorCodes[code].replace(createErrorRegexp, '')
212
+ this.name = name.substr(-5) !== 'Error' ? name + 'Error' : name
213
+
214
+ this.status = this.statusCode = code // setting `status` for backwards compatibility w/ `http-errors`
215
+ this.expose = options.expose ?? code < 500
216
+ }
217
+ }
218
+
219
+ export const createError = (code, message, properties = {}) => {
220
+ return new HttpError(code, message, properties)
193
221
  }
194
- export const createError = (code, message, properties = {})=>{
195
- return new HttpError(code, message, properties);
196
- };
197
- const httpErrorCodes = {
198
- 100: 'Continue',
199
- 101: 'Switching Protocols',
200
- 102: 'Processing',
201
- 103: 'Early Hints',
202
- 200: 'OK',
203
- 201: 'Created',
204
- 202: 'Accepted',
205
- 203: 'Non-Authoritative Information',
206
- 204: 'No Content',
207
- 205: 'Reset Content',
208
- 206: 'Partial Content',
209
- 207: 'Multi-Status',
210
- 208: 'Already Reported',
211
- 226: 'IM Used',
212
- 300: 'Multiple Choices',
213
- 301: 'Moved Permanently',
214
- 302: 'Found',
215
- 303: 'See Other',
216
- 304: 'Not Modified',
217
- 305: 'Use Proxy',
218
- 306: '(Unused)',
219
- 307: 'Temporary Redirect',
220
- 308: 'Permanent Redirect',
221
- 400: 'Bad Request',
222
- 401: 'Unauthorized',
223
- 402: 'Payment Required',
224
- 403: 'Forbidden',
225
- 404: 'Not Found',
226
- 405: 'Method Not Allowed',
227
- 406: 'Not Acceptable',
228
- 407: 'Proxy Authentication Required',
229
- 408: 'Request Timeout',
230
- 409: 'Conflict',
231
- 410: 'Gone',
232
- 411: 'Length Required',
233
- 412: 'Precondition Failed',
234
- 413: 'Payload Too Large',
235
- 414: 'URI Too Long',
236
- 415: 'Unsupported Media Type',
237
- 416: 'Range Not Satisfiable',
238
- 417: 'Expectation Failed',
239
- 418: "I'm a teapot",
240
- 421: 'Misdirected Request',
241
- 422: 'Unprocessable Entity',
242
- 423: 'Locked',
243
- 424: 'Failed Dependency',
244
- 425: 'Unordered Collection',
245
- 426: 'Upgrade Required',
246
- 428: 'Precondition Required',
247
- 429: 'Too Many Requests',
248
- 431: 'Request Header Fields Too Large',
249
- 451: 'Unavailable For Legal Reasons',
250
- 500: 'Internal Server Error',
251
- 501: 'Not Implemented',
252
- 502: 'Bad Gateway',
253
- 503: 'Service Unavailable',
254
- 504: 'Gateway Timeout',
255
- 505: 'HTTP Version Not Supported',
256
- 506: 'Variant Also Negotiates',
257
- 507: 'Insufficient Storage',
258
- 508: 'Loop Detected',
259
- 509: 'Bandwidth Limit Exceeded',
260
- 510: 'Not Extended',
261
- 511: 'Network Authentication Required'
262
- };
263
222
 
223
+ const httpErrorCodes = {
224
+ 100: 'Continue',
225
+ 101: 'Switching Protocols',
226
+ 102: 'Processing',
227
+ 103: 'Early Hints',
228
+ 200: 'OK',
229
+ 201: 'Created',
230
+ 202: 'Accepted',
231
+ 203: 'Non-Authoritative Information',
232
+ 204: 'No Content',
233
+ 205: 'Reset Content',
234
+ 206: 'Partial Content',
235
+ 207: 'Multi-Status',
236
+ 208: 'Already Reported',
237
+ 226: 'IM Used',
238
+ 300: 'Multiple Choices',
239
+ 301: 'Moved Permanently',
240
+ 302: 'Found',
241
+ 303: 'See Other',
242
+ 304: 'Not Modified',
243
+ 305: 'Use Proxy',
244
+ 306: '(Unused)',
245
+ 307: 'Temporary Redirect',
246
+ 308: 'Permanent Redirect',
247
+ 400: 'Bad Request',
248
+ 401: 'Unauthorized',
249
+ 402: 'Payment Required',
250
+ 403: 'Forbidden',
251
+ 404: 'Not Found',
252
+ 405: 'Method Not Allowed',
253
+ 406: 'Not Acceptable',
254
+ 407: 'Proxy Authentication Required',
255
+ 408: 'Request Timeout',
256
+ 409: 'Conflict',
257
+ 410: 'Gone',
258
+ 411: 'Length Required',
259
+ 412: 'Precondition Failed',
260
+ 413: 'Payload Too Large',
261
+ 414: 'URI Too Long',
262
+ 415: 'Unsupported Media Type',
263
+ 416: 'Range Not Satisfiable',
264
+ 417: 'Expectation Failed',
265
+ 418: "I'm a teapot",
266
+ 421: 'Misdirected Request',
267
+ 422: 'Unprocessable Entity',
268
+ 423: 'Locked',
269
+ 424: 'Failed Dependency',
270
+ 425: 'Unordered Collection',
271
+ 426: 'Upgrade Required',
272
+ 428: 'Precondition Required',
273
+ 429: 'Too Many Requests',
274
+ 431: 'Request Header Fields Too Large',
275
+ 451: 'Unavailable For Legal Reasons',
276
+ 500: 'Internal Server Error',
277
+ 501: 'Not Implemented',
278
+ 502: 'Bad Gateway',
279
+ 503: 'Service Unavailable',
280
+ 504: 'Gateway Timeout',
281
+ 505: 'HTTP Version Not Supported',
282
+ 506: 'Variant Also Negotiates',
283
+ 507: 'Insufficient Storage',
284
+ 508: 'Loop Detected',
285
+ 509: 'Bandwidth Limit Exceeded',
286
+ 510: 'Not Extended',
287
+ 511: 'Network Authentication Required'
288
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@middy/util",
3
- "version": "5.1.0",
3
+ "version": "5.2.1",
4
4
  "description": "🛵 The stylish Node.js middleware engine for AWS Lambda (util package)",
5
5
  "type": "module",
6
6
  "engines": {
@@ -55,7 +55,7 @@
55
55
  },
56
56
  "devDependencies": {
57
57
  "@aws-sdk/client-ssm": "^3.0.0",
58
- "@middy/core": "5.1.0",
58
+ "@middy/core": "5.2.1",
59
59
  "@types/aws-lambda": "^8.10.76",
60
60
  "@types/node": "^20.0.0",
61
61
  "aws-xray-sdk": "^3.3.3"
@@ -65,5 +65,5 @@
65
65
  "type": "github",
66
66
  "url": "https://github.com/sponsors/willfarrell"
67
67
  },
68
- "gitHead": "bbdaf5843914921804ba085dd58117273febe6b5"
68
+ "gitHead": "4d55da221b9165b4b3e59a12632fd40a149a1e92"
69
69
  }