@middy/util 2.5.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2017-2021 Luciano Mammino, will Farrell and the [Middy team](https://github.com/middyjs/middy/graphs/contributors)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,54 @@
1
+ # Middy Util
2
+
3
+ <div align="center">
4
+ <img alt="Middy logo" src="https://raw.githubusercontent.com/middyjs/middy/main/docs/img/middy-logo.png"/>
5
+ </div>
6
+
7
+ <div align="center">
8
+ <p><strong>Util component of the middy middleware, the stylish Node.js middleware engine for AWS Lambda</strong></p>
9
+ </div>
10
+
11
+ <div align="center">
12
+ <p>
13
+ <a href="http://badge.fury.io/js/%40middy%2Futil">
14
+ <img src="https://badge.fury.io/js/%40middy%2Futil.svg" alt="npm version" style="max-width:100%;">
15
+ </a>
16
+ <a href="https://snyk.io/test/github/middyjs/middy">
17
+ <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%;">
18
+ </a>
19
+ <a href="https://standardjs.com/">
20
+ <img src="https://img.shields.io/badge/code_style-standard-brightgreen.svg" alt="Standard Code Style" style="max-width:100%;">
21
+ </a>
22
+ <a href="https://gitter.im/middyjs/Lobby">
23
+ <img src="https://badges.gitter.im/gitterHQ/gitter.svg" alt="Chat on Gitter" style="max-width:100%;">
24
+ </a>
25
+ </p>
26
+ </div>
27
+
28
+
29
+ ## Install
30
+
31
+ To install middy you can use NPM:
32
+
33
+ ```bash
34
+ npm install --save @middy/util
35
+ ```
36
+
37
+
38
+ ## Documentation and examples
39
+
40
+ For documentation and examples, refers to the main [Middy monorepo on GitHub](https://github.com/middyjs/middy) or [Middy official website](https://middy.js.org).
41
+
42
+
43
+ ## Contributing
44
+
45
+ Everyone is very welcome to contribute to this repository. Feel free to [raise issues](https://github.com/middyjs/middy/issues) or to [submit Pull Requests](https://github.com/middyjs/middy/pulls).
46
+
47
+
48
+ ## License
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).
51
+
52
+ <a href="https://app.fossa.io/projects/git%2Bgithub.com%2Fmiddyjs%2Fmiddy?ref=badge_large">
53
+ <img src="https://app.fossa.io/api/projects/git%2Bgithub.com%2Fmiddyjs%2Fmiddy.svg?type=large" alt="FOSSA Status" style="max-width:100%;">
54
+ </a>
package/codes.json ADDED
@@ -0,0 +1,66 @@
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
+ }
package/index.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ import middy from '@middy/core'
2
+ import { captureAWSClient } from 'aws-xray-sdk'
3
+
4
+ interface Options<Client, ClientOptions> {
5
+ AwsClient?: new() => Client
6
+ awsClientOptions?: Partial<ClientOptions>
7
+ awsClientAssumeRole?: string
8
+ awsClientCapture?: typeof captureAWSClient
9
+ fetchData?: { [key: string]: string }
10
+ disablePrefetch?: boolean
11
+ cacheKey?: string
12
+ cacheExpiry?: number
13
+ setToEnv?: boolean
14
+ setToContext?: boolean
15
+ }
16
+
17
+ type HttpError = Error & {
18
+ status: number
19
+ statusCode: number
20
+ expose: boolean
21
+ [key: string]: any
22
+ [key: number]: any
23
+ }
24
+
25
+ declare function createPrefetchClient<Client, ClientOptions> (options: Options<Client, ClientOptions>): Client
26
+
27
+ declare function createClient<Client, ClientOptions> (options: Options<Client, ClientOptions>, request: middy.Request): Client
28
+
29
+ declare function canPrefetch<Client, ClientOptions> (options: Options<Client, ClientOptions>): boolean
30
+
31
+ declare function getInternal (variables: any, request: middy.Request): Promise<any>
32
+
33
+ declare function sanitizeKey (key: string): string
34
+
35
+ declare function processCache<Client, ClientOptions> (options: Options<Client, ClientOptions>, fetch: (request: middy.Request) => any, request: middy.Request): { value: any, expiry: number }
36
+
37
+ declare function getCache (keys: string): any
38
+
39
+ declare function clearCache (keys?: string | string[] | null): void
40
+
41
+ declare function jsonSafeParse (string: string, reviver?: (key: string, value: any) => any): any
42
+
43
+ declare function normalizeHttpResponse (response: any, fallbackResponse?: any): any
44
+
45
+ declare function createError (code: number, message: string, properties?: Record<string, any>): HttpError
46
+
47
+ declare function modifyCache (cacheKey: string, value: any): void
package/index.js ADDED
@@ -0,0 +1,275 @@
1
+ "use strict";
2
+
3
+ const {
4
+ Agent
5
+ } = require('https'); // const { NodeHttpHandler } = require('@aws-sdk/node-http-handler') // aws-sdk v3
6
+
7
+
8
+ const awsClientDefaultOptions = {
9
+ // AWS SDK v3
10
+ // Docs: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/enforcing-tls.html
11
+
12
+ /* requestHandler: new NodeHttpHandler({
13
+ httpsAgent: new Agent(
14
+ {
15
+ secureProtocol: 'TLSv1_2_method'
16
+ }
17
+ )
18
+ }) */
19
+ // Docs: https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/enforcing-tls.html
20
+ httpOptions: {
21
+ agent: new Agent({
22
+ secureProtocol: 'TLSv1_2_method'
23
+ })
24
+ }
25
+ };
26
+
27
+ const createPrefetchClient = options => {
28
+ const awsClientOptions = { ...awsClientDefaultOptions,
29
+ ...options.awsClientOptions
30
+ };
31
+ const client = new options.AwsClient(awsClientOptions); // AWS XRay
32
+
33
+ if (options.awsClientCapture) {
34
+ return options.awsClientCapture(client);
35
+ }
36
+
37
+ return client;
38
+ };
39
+
40
+ const createClient = async (options, request) => {
41
+ let awsClientCredentials = {}; // Role Credentials
42
+
43
+ if (options.awsClientAssumeRole) {
44
+ if (!request) throw new Error('Request required when assuming role');
45
+ awsClientCredentials = await getInternal({
46
+ credentials: options.awsClientAssumeRole
47
+ }, request);
48
+ }
49
+
50
+ awsClientCredentials = { ...awsClientCredentials,
51
+ ...options.awsClientOptions
52
+ };
53
+ return createPrefetchClient({ ...options,
54
+ awsClientOptions: awsClientCredentials
55
+ });
56
+ };
57
+
58
+ const canPrefetch = options => {
59
+ return !(options !== null && options !== void 0 && options.awsClientAssumeRole) && !(options !== null && options !== void 0 && options.disablePrefetch);
60
+ }; // Internal Context
61
+
62
+
63
+ const getInternal = async (variables, request) => {
64
+ if (!variables || !request) return {};
65
+ let keys = [];
66
+ let values = [];
67
+
68
+ if (variables === true) {
69
+ keys = values = Object.keys(request.internal);
70
+ } else if (typeof variables === 'string') {
71
+ keys = values = [variables];
72
+ } else if (Array.isArray(variables)) {
73
+ keys = values = variables;
74
+ } else if (typeof variables === 'object') {
75
+ keys = Object.keys(variables);
76
+ values = Object.values(variables);
77
+ }
78
+
79
+ const promises = [];
80
+
81
+ for (const internalKey of values) {
82
+ var _valuePromise;
83
+
84
+ // 'internal.key.sub_value' -> { [key]: internal.key.sub_value }
85
+ const pathOptionKey = internalKey.split('.');
86
+ const rootOptionKey = pathOptionKey.shift();
87
+ let valuePromise = request.internal[rootOptionKey];
88
+
89
+ if (typeof ((_valuePromise = valuePromise) === null || _valuePromise === void 0 ? void 0 : _valuePromise.then) !== 'function') {
90
+ valuePromise = Promise.resolve(valuePromise);
91
+ }
92
+
93
+ promises.push(valuePromise.then(value => pathOptionKey.reduce((p, c) => p === null || p === void 0 ? void 0 : p[c], value)));
94
+ } // ensure promise has resolved by the time it's needed
95
+ // If one of the promises throws it will bubble up to @middy/core
96
+
97
+
98
+ values = await Promise.allSettled(promises);
99
+ const errors = values.filter(res => res.status === 'rejected').map(res => res.reason.message);
100
+ if (errors.length) throw new Error(JSON.stringify(errors));
101
+ return keys.reduce((obj, key, index) => ({ ...obj,
102
+ [sanitizeKey(key)]: values[index].value
103
+ }), {});
104
+ };
105
+
106
+ const sanitizeKeyPrefixLeadingNumber = /^([0-9])/;
107
+ const sanitizeKeyRemoveDisallowedChar = /[^a-zA-Z0-9]+/g;
108
+
109
+ const sanitizeKey = key => {
110
+ return key.replace(sanitizeKeyPrefixLeadingNumber, '_$1').replace(sanitizeKeyRemoveDisallowedChar, '_');
111
+ }; // fetch Cache
112
+
113
+
114
+ const cache = {}; // key: { value:{fetchKey:Promise}, expiry }
115
+
116
+ const processCache = (options, fetch = () => undefined, request) => {
117
+ const {
118
+ cacheExpiry,
119
+ cacheKey
120
+ } = options;
121
+
122
+ if (cacheExpiry) {
123
+ const cached = getCache(cacheKey);
124
+ const unexpired = cached && (cacheExpiry < 0 || cached.expiry > Date.now());
125
+
126
+ if (unexpired && cached.modified) {
127
+ const value = fetch(request, cached.value);
128
+ cache[cacheKey] = {
129
+ value: { ...cached.value,
130
+ ...value
131
+ },
132
+ expiry: cached.expiry
133
+ };
134
+ return cache[cacheKey];
135
+ }
136
+
137
+ if (unexpired) {
138
+ return { ...cached,
139
+ cache: true
140
+ };
141
+ }
142
+ }
143
+
144
+ const value = fetch(request);
145
+ const expiry = Date.now() + cacheExpiry;
146
+
147
+ if (cacheExpiry) {
148
+ cache[cacheKey] = {
149
+ value,
150
+ expiry
151
+ };
152
+ }
153
+
154
+ return {
155
+ value,
156
+ expiry
157
+ };
158
+ };
159
+
160
+ const getCache = key => {
161
+ return cache[key];
162
+ }; // Used to remove parts of a cache
163
+
164
+
165
+ const modifyCache = (cacheKey, value) => {
166
+ if (!cache[cacheKey]) return;
167
+ cache[cacheKey] = { ...cache[cacheKey],
168
+ value,
169
+ modified: true
170
+ };
171
+ };
172
+
173
+ const clearCache = (keys = null) => {
174
+ var _keys;
175
+
176
+ keys = (_keys = keys) !== null && _keys !== void 0 ? _keys : Object.keys(cache);
177
+ if (!Array.isArray(keys)) keys = [keys];
178
+
179
+ for (const cacheKey of keys) {
180
+ cache[cacheKey] = undefined;
181
+ }
182
+ };
183
+
184
+ const jsonSafeParse = (string, reviver) => {
185
+ if (typeof string !== 'string') return string;
186
+ const firstChar = string[0];
187
+ if (firstChar !== '{' && firstChar !== '[' && firstChar !== '"') return string;
188
+
189
+ try {
190
+ return JSON.parse(string, reviver);
191
+ } catch (e) {}
192
+
193
+ return string;
194
+ };
195
+
196
+ const normalizeHttpResponse = response => {
197
+ var _response$headers, _response;
198
+
199
+ // May require updating to catch other types
200
+ if (response === undefined) {
201
+ response = {};
202
+ } else if (Array.isArray(response) || typeof response !== 'object' || response === null) {
203
+ response = {
204
+ body: response
205
+ };
206
+ }
207
+
208
+ response.headers = (_response$headers = (_response = response) === null || _response === void 0 ? void 0 : _response.headers) !== null && _response$headers !== void 0 ? _response$headers : {};
209
+ return response;
210
+ }; // smaller version of `http-errors`
211
+
212
+
213
+ const statuses = require('./codes.json');
214
+
215
+ const {
216
+ inherits
217
+ } = require('util');
218
+
219
+ const createErrorRegexp = /[^a-zA-Z]/g;
220
+
221
+ const createError = (code, message, properties = {}) => {
222
+ const name = statuses[code].replace(createErrorRegexp, '');
223
+ const className = name.substr(-5) !== 'Error' ? name + 'Error' : name;
224
+
225
+ function HttpError(message) {
226
+ // create the error object
227
+ const msg = message !== null && message !== void 0 ? message : statuses[code];
228
+ const err = new Error(msg); // capture a stack trace to the construction point
229
+
230
+ Error.captureStackTrace(err, HttpError); // adjust the [[Prototype]]
231
+
232
+ Object.setPrototypeOf(err, HttpError.prototype); // redefine the error message
233
+
234
+ Object.defineProperty(err, 'message', {
235
+ enumerable: true,
236
+ configurable: true,
237
+ value: msg,
238
+ writable: true
239
+ }); // redefine the error name
240
+
241
+ Object.defineProperty(err, 'name', {
242
+ enumerable: false,
243
+ configurable: true,
244
+ value: className,
245
+ writable: true
246
+ });
247
+ return err;
248
+ }
249
+
250
+ inherits(HttpError, Error);
251
+ const desc = Object.getOwnPropertyDescriptor(HttpError, 'name');
252
+ desc.value = className;
253
+ Object.defineProperty(HttpError, 'name', desc);
254
+ Object.assign(HttpError.prototype, {
255
+ status: code,
256
+ statusCode: code,
257
+ expose: code < 500
258
+ }, properties);
259
+ return new HttpError(message);
260
+ };
261
+
262
+ module.exports = {
263
+ createPrefetchClient,
264
+ createClient,
265
+ canPrefetch,
266
+ getInternal,
267
+ sanitizeKey,
268
+ processCache,
269
+ getCache,
270
+ modifyCache,
271
+ clearCache,
272
+ jsonSafeParse,
273
+ normalizeHttpResponse,
274
+ createError
275
+ };
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@middy/util",
3
+ "version": "2.5.2",
4
+ "description": "🛵 The stylish Node.js middleware engine for AWS Lambda (util package)",
5
+ "type": "commonjs",
6
+ "engines": {
7
+ "node": ">=12"
8
+ },
9
+ "engineStrict": true,
10
+ "publishConfig": {
11
+ "access": "public"
12
+ },
13
+ "main": "index.js",
14
+ "types": "index.d.ts",
15
+ "files": [
16
+ "index.d.ts",
17
+ "codes.json"
18
+ ],
19
+ "scripts": {
20
+ "test": "npm run test:unit",
21
+ "test:unit": "ava"
22
+ },
23
+ "license": "MIT",
24
+ "keywords": [
25
+ "Lambda",
26
+ "Middleware",
27
+ "Serverless",
28
+ "Framework",
29
+ "AWS",
30
+ "AWS Lambda",
31
+ "helper",
32
+ "util"
33
+ ],
34
+ "author": {
35
+ "name": "Middy contributors",
36
+ "url": "https://github.com/middyjs/middy/graphs/contributors"
37
+ },
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "github:middyjs/middy",
41
+ "directory": "packages/util"
42
+ },
43
+ "bugs": {
44
+ "url": "https://github.com/middyjs/middy/issues"
45
+ },
46
+ "devDependencies": {
47
+ "@middy/core": "^2.5.2",
48
+ "@types/aws-lambda": "^8.10.76",
49
+ "@types/node": "^16.0.0",
50
+ "aws-sdk": "^2.939.0",
51
+ "aws-xray-sdk": "^3.3.3"
52
+ },
53
+ "homepage": "https://github.com/middyjs/middy#readme",
54
+ "gitHead": "a2bb757a7a13638ae64277f8eecfcf11c1af17d4"
55
+ }