@middy/util 5.1.0 → 5.2.0

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 +274 -256
  2. package/package.json +3 -3
package/index.js CHANGED
@@ -1,263 +1,281 @@
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 getCache = (key) => {
138
+ if (!cache[key]) return {}
139
+ return cache[key]
140
+ }
141
+
142
+ // Used to remove parts of a cache
143
+ export const modifyCache = (cacheKey, value) => {
144
+ if (!cache[cacheKey]) return
145
+ clearTimeout(cache[cacheKey]?.refresh)
146
+ cache[cacheKey] = { ...cache[cacheKey], value, modified: true }
147
+ }
148
+
149
+ export const clearCache = (keys = null) => {
150
+ keys = keys ?? Object.keys(cache)
151
+ if (!Array.isArray(keys)) keys = [keys]
152
+ for (const cacheKey of keys) {
153
+ clearTimeout(cache[cacheKey]?.refresh)
154
+ cache[cacheKey] = undefined
155
+ }
156
+ }
157
+
158
+ export const jsonSafeParse = (text, reviver) => {
159
+ if (typeof text !== 'string') return text
160
+ const firstChar = text[0]
161
+ if (firstChar !== '{' && firstChar !== '[' && firstChar !== '"') return text
162
+ try {
163
+ return JSON.parse(text, reviver)
164
+ } catch (e) {}
165
+
166
+ return text
167
+ }
168
+
169
+ export const jsonSafeStringify = (value, replacer, space) => {
170
+ try {
171
+ return JSON.stringify(value, replacer, space)
172
+ } catch (e) {}
173
+
174
+ return value
175
+ }
176
+
177
+ export const normalizeHttpResponse = (request) => {
178
+ let { response } = request
179
+ if (typeof response === 'undefined') {
180
+ response = {}
181
+ } else if (
182
+ typeof response?.statusCode === 'undefined' &&
183
+ typeof response?.body === 'undefined' &&
184
+ typeof response?.headers === 'undefined'
185
+ ) {
186
+ response = { statusCode: 200, body: response }
187
+ }
188
+ response.statusCode ??= 500
189
+ response.headers ??= {}
190
+ request.response = response
191
+ return response
192
+ }
193
+
194
+ const createErrorRegexp = /[^a-zA-Z]/g
180
195
  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;
196
+ constructor (code, message, options = {}) {
197
+ if (message && typeof message !== 'string') {
198
+ options = message
199
+ message = undefined
192
200
  }
201
+ message ??= httpErrorCodes[code]
202
+ super(message, options)
203
+
204
+ const name = httpErrorCodes[code].replace(createErrorRegexp, '')
205
+ this.name = name.substr(-5) !== 'Error' ? name + 'Error' : name
206
+
207
+ this.status = this.statusCode = code // setting `status` for backwards compatibility w/ `http-errors`
208
+ this.expose = options.expose ?? code < 500
209
+ }
210
+ }
211
+
212
+ export const createError = (code, message, properties = {}) => {
213
+ return new HttpError(code, message, properties)
193
214
  }
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
215
 
216
+ const httpErrorCodes = {
217
+ 100: 'Continue',
218
+ 101: 'Switching Protocols',
219
+ 102: 'Processing',
220
+ 103: 'Early Hints',
221
+ 200: 'OK',
222
+ 201: 'Created',
223
+ 202: 'Accepted',
224
+ 203: 'Non-Authoritative Information',
225
+ 204: 'No Content',
226
+ 205: 'Reset Content',
227
+ 206: 'Partial Content',
228
+ 207: 'Multi-Status',
229
+ 208: 'Already Reported',
230
+ 226: 'IM Used',
231
+ 300: 'Multiple Choices',
232
+ 301: 'Moved Permanently',
233
+ 302: 'Found',
234
+ 303: 'See Other',
235
+ 304: 'Not Modified',
236
+ 305: 'Use Proxy',
237
+ 306: '(Unused)',
238
+ 307: 'Temporary Redirect',
239
+ 308: 'Permanent Redirect',
240
+ 400: 'Bad Request',
241
+ 401: 'Unauthorized',
242
+ 402: 'Payment Required',
243
+ 403: 'Forbidden',
244
+ 404: 'Not Found',
245
+ 405: 'Method Not Allowed',
246
+ 406: 'Not Acceptable',
247
+ 407: 'Proxy Authentication Required',
248
+ 408: 'Request Timeout',
249
+ 409: 'Conflict',
250
+ 410: 'Gone',
251
+ 411: 'Length Required',
252
+ 412: 'Precondition Failed',
253
+ 413: 'Payload Too Large',
254
+ 414: 'URI Too Long',
255
+ 415: 'Unsupported Media Type',
256
+ 416: 'Range Not Satisfiable',
257
+ 417: 'Expectation Failed',
258
+ 418: "I'm a teapot",
259
+ 421: 'Misdirected Request',
260
+ 422: 'Unprocessable Entity',
261
+ 423: 'Locked',
262
+ 424: 'Failed Dependency',
263
+ 425: 'Unordered Collection',
264
+ 426: 'Upgrade Required',
265
+ 428: 'Precondition Required',
266
+ 429: 'Too Many Requests',
267
+ 431: 'Request Header Fields Too Large',
268
+ 451: 'Unavailable For Legal Reasons',
269
+ 500: 'Internal Server Error',
270
+ 501: 'Not Implemented',
271
+ 502: 'Bad Gateway',
272
+ 503: 'Service Unavailable',
273
+ 504: 'Gateway Timeout',
274
+ 505: 'HTTP Version Not Supported',
275
+ 506: 'Variant Also Negotiates',
276
+ 507: 'Insufficient Storage',
277
+ 508: 'Loop Detected',
278
+ 509: 'Bandwidth Limit Exceeded',
279
+ 510: 'Not Extended',
280
+ 511: 'Network Authentication Required'
281
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@middy/util",
3
- "version": "5.1.0",
3
+ "version": "5.2.0",
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.0",
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": "2d9096a49cd8fb62359517be96d6c93609df41f0"
69
69
  }