@middy/util 2.5.6 → 3.0.0-alpha.3

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/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2017-2021 Luciano Mammino, will Farrell and the [Middy team](https://github.com/middyjs/middy/graphs/contributors)
3
+ Copyright (c) 2017-2022 Luciano Mammino, will Farrell and the [Middy team](https://github.com/middyjs/middy/graphs/contributors)
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -47,7 +47,7 @@ Everyone is very welcome to contribute to this repository. Feel free to [raise i
47
47
 
48
48
  ## License
49
49
 
50
- Licensed under [MIT License](LICENSE). Copyright (c) 2017-2021 Luciano Mammino, will Farrell, and the [Middy team](https://github.com/middyjs/middy/graphs/contributors).
50
+ Licensed under [MIT License](LICENSE). Copyright (c) 2017-2022 Luciano Mammino, will Farrell, and the [Middy team](https://github.com/middyjs/middy/graphs/contributors).
51
51
 
52
52
  <a href="https://app.fossa.io/projects/git%2Bgithub.com%2Fmiddyjs%2Fmiddy?ref=badge_large">
53
53
  <img src="https://app.fossa.io/api/projects/git%2Bgithub.com%2Fmiddyjs%2Fmiddy.svg?type=large" alt="FOSSA Status" style="max-width:100%;">
package/codes.js ADDED
@@ -0,0 +1,66 @@
1
+ export default {
2
+ 100: 'Continue',
3
+ 101: 'Switching Protocols',
4
+ 102: 'Processing',
5
+ 103: 'Early Hints',
6
+ 200: 'OK',
7
+ 201: 'Created',
8
+ 202: 'Accepted',
9
+ 203: 'Non-Authoritative Information',
10
+ 204: 'No Content',
11
+ 205: 'Reset Content',
12
+ 206: 'Partial Content',
13
+ 207: 'Multi-Status',
14
+ 208: 'Already Reported',
15
+ 226: 'IM Used',
16
+ 300: 'Multiple Choices',
17
+ 301: 'Moved Permanently',
18
+ 302: 'Found',
19
+ 303: 'See Other',
20
+ 304: 'Not Modified',
21
+ 305: 'Use Proxy',
22
+ 306: '(Unused)',
23
+ 307: 'Temporary Redirect',
24
+ 308: 'Permanent Redirect',
25
+ 400: 'Bad Request',
26
+ 401: 'Unauthorized',
27
+ 402: 'Payment Required',
28
+ 403: 'Forbidden',
29
+ 404: 'Not Found',
30
+ 405: 'Method Not Allowed',
31
+ 406: 'Not Acceptable',
32
+ 407: 'Proxy Authentication Required',
33
+ 408: 'Request Timeout',
34
+ 409: 'Conflict',
35
+ 410: 'Gone',
36
+ 411: 'Length Required',
37
+ 412: 'Precondition Failed',
38
+ 413: 'Payload Too Large',
39
+ 414: 'URI Too Long',
40
+ 415: 'Unsupported Media Type',
41
+ 416: 'Range Not Satisfiable',
42
+ 417: 'Expectation Failed',
43
+ 418: "I'm a teapot",
44
+ 421: 'Misdirected Request',
45
+ 422: 'Unprocessable Entity',
46
+ 423: 'Locked',
47
+ 424: 'Failed Dependency',
48
+ 425: 'Unordered Collection',
49
+ 426: 'Upgrade Required',
50
+ 428: 'Precondition Required',
51
+ 429: 'Too Many Requests',
52
+ 431: 'Request Header Fields Too Large',
53
+ 451: 'Unavailable For Legal Reasons',
54
+ 500: 'Internal Server Error',
55
+ 501: 'Not Implemented',
56
+ 502: 'Bad Gateway',
57
+ 503: 'Service Unavailable',
58
+ 504: 'Gateway Timeout',
59
+ 505: 'HTTP Version Not Supported',
60
+ 506: 'Variant Also Negotiates',
61
+ 507: 'Insufficient Storage',
62
+ 508: 'Loop Detected',
63
+ 509: 'Bandwidth Limit Exceeded',
64
+ 510: 'Not Extended',
65
+ 511: 'Network Authentication Required'
66
+ }
package/index.d.ts CHANGED
@@ -9,7 +9,6 @@ interface Options<Client, ClientOptions> {
9
9
  disablePrefetch?: boolean
10
10
  cacheKey?: string
11
11
  cacheExpiry?: number
12
- setToEnv?: boolean
13
12
  setToContext?: boolean
14
13
  }
15
14
 
@@ -39,7 +38,7 @@ declare function clearCache (keys?: string | string[] | null): void
39
38
 
40
39
  declare function jsonSafeParse (string: string, reviver?: (key: string, value: any) => any): any
41
40
 
42
- declare function normalizeHttpResponse (response: any, fallbackResponse?: any): any
41
+ declare function normalizeHttpResponse (request: any, fallbackResponse?: any): any
43
42
 
44
43
  declare function createError (code: number, message: string, properties?: Record<string, any>): HttpError
45
44
 
package/index.js CHANGED
@@ -1,7 +1,11 @@
1
- const { Agent } = require('https')
2
- // const { NodeHttpHandler } = require('@aws-sdk/node-http-handler') // aws-sdk v3
1
+ import { Agent } from 'https'
3
2
 
4
- const awsClientDefaultOptions = {
3
+ // smaller version of `http-errors`
4
+ import statuses from './codes.js'
5
+ import { inherits } from 'util'
6
+ // import { NodeHttpHandler } from '@aws-sdk/node-http-handler' // aws-sdk v3
7
+
8
+ export const awsClientDefaultOptions = {
5
9
  // AWS SDK v3
6
10
  // Docs: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/enforcing-tls.html
7
11
  /* requestHandler: new NodeHttpHandler({
@@ -19,7 +23,7 @@ const awsClientDefaultOptions = {
19
23
  }
20
24
  }
21
25
 
22
- const createPrefetchClient = (options) => {
26
+ export const createPrefetchClient = (options) => {
23
27
  const awsClientOptions = {
24
28
  ...awsClientDefaultOptions,
25
29
  ...options.awsClientOptions
@@ -27,14 +31,16 @@ const createPrefetchClient = (options) => {
27
31
  const client = new options.AwsClient(awsClientOptions)
28
32
 
29
33
  // AWS XRay
30
- if (options.awsClientCapture) {
34
+ if (options.awsClientCapture && options.disablePrefetch) {
31
35
  return options.awsClientCapture(client)
36
+ } else if (options.awsClientCapture) {
37
+ console.warn('Unable to apply X-Ray outside of handler invocation scope.')
32
38
  }
33
39
 
34
40
  return client
35
41
  }
36
42
 
37
- const createClient = async (options, request) => {
43
+ export const createClient = async (options, request) => {
38
44
  let awsClientCredentials = {}
39
45
 
40
46
  // Role Credentials
@@ -57,12 +63,12 @@ const createClient = async (options, request) => {
57
63
  })
58
64
  }
59
65
 
60
- const canPrefetch = (options) => {
61
- return !options?.awsClientAssumeRole && !options?.disablePrefetch
66
+ export const canPrefetch = (options = {}) => {
67
+ return !options.awsClientAssumeRole && !options.disablePrefetch
62
68
  }
63
69
 
64
70
  // Internal Context
65
- const getInternal = async (variables, request) => {
71
+ export const getInternal = async (variables, request) => {
66
72
  if (!variables || !request) return {}
67
73
  let keys = []
68
74
  let values = []
@@ -82,7 +88,7 @@ const getInternal = async (variables, request) => {
82
88
  const pathOptionKey = internalKey.split('.')
83
89
  const rootOptionKey = pathOptionKey.shift()
84
90
  let valuePromise = request.internal[rootOptionKey]
85
- if (typeof valuePromise?.then !== 'function') {
91
+ if (typeof valuePromise.then !== 'function') {
86
92
  valuePromise = Promise.resolve(valuePromise)
87
93
  }
88
94
  promises.push(
@@ -96,8 +102,13 @@ const getInternal = async (variables, request) => {
96
102
  values = await Promise.allSettled(promises)
97
103
  const errors = values
98
104
  .filter((res) => res.status === 'rejected')
99
- .map((res) => res.reason.message)
100
- if (errors.length) throw new Error(JSON.stringify(errors))
105
+ .map((res) => res.reason)
106
+ if (errors.length) {
107
+ // throw new Error('Failed to resolve internal values', { cause: errors })
108
+ const error = new Error('Failed to resolve internal values')
109
+ error.cause = errors
110
+ throw error
111
+ }
101
112
  return keys.reduce(
102
113
  (obj, key, index) => ({ ...obj, [sanitizeKey(key)]: values[index].value }),
103
114
  {}
@@ -105,7 +116,7 @@ const getInternal = async (variables, request) => {
105
116
  }
106
117
  const sanitizeKeyPrefixLeadingNumber = /^([0-9])/
107
118
  const sanitizeKeyRemoveDisallowedChar = /[^a-zA-Z0-9]+/g
108
- const sanitizeKey = (key) => {
119
+ export const sanitizeKey = (key) => {
109
120
  return key
110
121
  .replace(sanitizeKeyPrefixLeadingNumber, '_$1')
111
122
  .replace(sanitizeKeyRemoveDisallowedChar, '_')
@@ -113,11 +124,11 @@ const sanitizeKey = (key) => {
113
124
 
114
125
  // fetch Cache
115
126
  const cache = {} // key: { value:{fetchKey:Promise}, expiry }
116
- const processCache = (options, fetch = () => undefined, request) => {
127
+ export const processCache = (options, fetch = () => undefined, request) => {
117
128
  const { cacheExpiry, cacheKey } = options
118
129
  if (cacheExpiry) {
119
130
  const cached = getCache(cacheKey)
120
- const unexpired = cached && (cacheExpiry < 0 || cached.expiry > Date.now())
131
+ const unexpired = cached.expiry && (cacheExpiry < 0 || cached.expiry > Date.now())
121
132
 
122
133
  if (unexpired && cached.modified) {
123
134
  const value = fetch(request, cached.value)
@@ -140,17 +151,18 @@ const processCache = (options, fetch = () => undefined, request) => {
140
151
  return { value, expiry }
141
152
  }
142
153
 
143
- const getCache = (key) => {
154
+ export const getCache = (key) => {
155
+ if (!cache[key]) return {}
144
156
  return cache[key]
145
157
  }
146
158
 
147
159
  // Used to remove parts of a cache
148
- const modifyCache = (cacheKey, value) => {
160
+ export const modifyCache = (cacheKey, value) => {
149
161
  if (!cache[cacheKey]) return
150
162
  cache[cacheKey] = { ...cache[cacheKey], value, modified: true }
151
163
  }
152
164
 
153
- const clearCache = (keys = null) => {
165
+ export const clearCache = (keys = null) => {
154
166
  keys = keys ?? Object.keys(cache)
155
167
  if (!Array.isArray(keys)) keys = [keys]
156
168
  for (const cacheKey of keys) {
@@ -158,7 +170,7 @@ const clearCache = (keys = null) => {
158
170
  }
159
171
  }
160
172
 
161
- const jsonSafeParse = (string, reviver) => {
173
+ export const jsonSafeParse = (string, reviver) => {
162
174
  if (typeof string !== 'string') return string
163
175
  const firstChar = string[0]
164
176
  if (firstChar !== '{' && firstChar !== '[' && firstChar !== '"') return string
@@ -169,27 +181,20 @@ const jsonSafeParse = (string, reviver) => {
169
181
  return string
170
182
  }
171
183
 
172
- const normalizeHttpResponse = (response) => {
173
- // May require updating to catch other types
184
+ export const normalizeHttpResponse = (request) => {
185
+ let { response } = request
174
186
  if (response === undefined) {
175
187
  response = {}
176
- } else if (
177
- Array.isArray(response) ||
178
- typeof response !== 'object' ||
179
- response === null
180
- ) {
188
+ } else if (response?.statusCode === undefined && response?.body === undefined && response?.headers === undefined) {
181
189
  response = { body: response }
182
190
  }
183
- response.headers = response?.headers ?? {}
191
+ response.headers ??= {}
192
+ request.response = response
184
193
  return response
185
194
  }
186
195
 
187
- // smaller version of `http-errors`
188
- const statuses = require('./codes.json')
189
- const { inherits } = require('util')
190
-
191
196
  const createErrorRegexp = /[^a-zA-Z]/g
192
- const createError = (code, message, properties = {}) => {
197
+ export const createError = (code, message, properties = {}) => {
193
198
  const name = statuses[code].replace(createErrorRegexp, '')
194
199
  const className = name.substr(-5) !== 'Error' ? name + 'Error' : name
195
200
 
@@ -237,7 +242,7 @@ const createError = (code, message, properties = {}) => {
237
242
  return new HttpError(message)
238
243
  }
239
244
 
240
- module.exports = {
245
+ export default {
241
246
  createPrefetchClient,
242
247
  createClient,
243
248
  canPrefetch,
package/package.json CHANGED
@@ -1,24 +1,26 @@
1
1
  {
2
2
  "name": "@middy/util",
3
- "version": "2.5.6",
3
+ "version": "3.0.0-alpha.3",
4
4
  "description": "🛵 The stylish Node.js middleware engine for AWS Lambda (util package)",
5
- "type": "commonjs",
5
+ "type": "module",
6
6
  "engines": {
7
- "node": ">=12"
7
+ "node": ">=14"
8
8
  },
9
9
  "engineStrict": true,
10
10
  "publishConfig": {
11
11
  "access": "public"
12
12
  },
13
- "main": "index.js",
13
+ "exports": "./index.js",
14
14
  "types": "index.d.ts",
15
15
  "files": [
16
+ "index.js",
16
17
  "index.d.ts",
17
- "codes.json"
18
+ "codes.js"
18
19
  ],
19
20
  "scripts": {
20
21
  "test": "npm run test:unit",
21
- "test:unit": "ava"
22
+ "test:unit": "ava",
23
+ "test:benchmark": "node __benchmarks__/index.js"
22
24
  },
23
25
  "license": "MIT",
24
26
  "keywords": [
@@ -44,12 +46,12 @@
44
46
  "url": "https://github.com/middyjs/middy/issues"
45
47
  },
46
48
  "devDependencies": {
47
- "@middy/core": "^2.5.6",
49
+ "@middy/core": "^3.0.0-alpha.3",
48
50
  "@types/aws-lambda": "^8.10.76",
49
- "@types/node": "^16.0.0",
51
+ "@types/node": "^17.0.0",
50
52
  "aws-sdk": "^2.939.0",
51
53
  "aws-xray-sdk": "^3.3.3"
52
54
  },
53
55
  "homepage": "https://github.com/middyjs/middy#readme",
54
- "gitHead": "0c789f55b4adf691f977b0d9904d1a805bb3bb2b"
56
+ "gitHead": "1441158711580313765e6d156046ef0fade0d156"
55
57
  }
package/codes.json DELETED
@@ -1,66 +0,0 @@
1
- {
2
- "100": "Continue",
3
- "101": "Switching Protocols",
4
- "102": "Processing",
5
- "103": "Early Hints",
6
- "200": "OK",
7
- "201": "Created",
8
- "202": "Accepted",
9
- "203": "Non-Authoritative Information",
10
- "204": "No Content",
11
- "205": "Reset Content",
12
- "206": "Partial Content",
13
- "207": "Multi-Status",
14
- "208": "Already Reported",
15
- "226": "IM Used",
16
- "300": "Multiple Choices",
17
- "301": "Moved Permanently",
18
- "302": "Found",
19
- "303": "See Other",
20
- "304": "Not Modified",
21
- "305": "Use Proxy",
22
- "306": "(Unused)",
23
- "307": "Temporary Redirect",
24
- "308": "Permanent Redirect",
25
- "400": "Bad Request",
26
- "401": "Unauthorized",
27
- "402": "Payment Required",
28
- "403": "Forbidden",
29
- "404": "Not Found",
30
- "405": "Method Not Allowed",
31
- "406": "Not Acceptable",
32
- "407": "Proxy Authentication Required",
33
- "408": "Request Timeout",
34
- "409": "Conflict",
35
- "410": "Gone",
36
- "411": "Length Required",
37
- "412": "Precondition Failed",
38
- "413": "Payload Too Large",
39
- "414": "URI Too Long",
40
- "415": "Unsupported Media Type",
41
- "416": "Range Not Satisfiable",
42
- "417": "Expectation Failed",
43
- "418": "I'm a teapot",
44
- "421": "Misdirected Request",
45
- "422": "Unprocessable Entity",
46
- "423": "Locked",
47
- "424": "Failed Dependency",
48
- "425": "Unordered Collection",
49
- "426": "Upgrade Required",
50
- "428": "Precondition Required",
51
- "429": "Too Many Requests",
52
- "431": "Request Header Fields Too Large",
53
- "451": "Unavailable For Legal Reasons",
54
- "500": "Internal Server Error",
55
- "501": "Not Implemented",
56
- "502": "Bad Gateway",
57
- "503": "Service Unavailable",
58
- "504": "Gateway Timeout",
59
- "505": "HTTP Version Not Supported",
60
- "506": "Variant Also Negotiates",
61
- "507": "Insufficient Storage",
62
- "508": "Loop Detected",
63
- "509": "Bandwidth Limit Exceeded",
64
- "510": "Not Extended",
65
- "511": "Network Authentication Required"
66
- }