forked from GoogleCloudPlatform/functions-framework-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloader.ts
176 lines (162 loc) · 5.43 KB
/
loader.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// loader.ts
/**
* This package contains the logic to load user's function.
* @packageDocumentation
*/
import * as path from 'path';
import * as semver from 'semver';
import * as readPkgUp from 'read-pkg-up';
/**
* Import function signature type's definition.
*/
import {HandlerFunction} from './functions';
// Dynamic import function required to load user code packaged as an
// ES module is only available on Node.js v13.2.0 and up.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#browser_compatibility
// Exported for testing.
export const MIN_NODE_VERSION_ESMODULES = '13.2.0';
/**
* Determines format of the given module (CommonJS vs ES module).
*
* Implements "algorithm" described at:
* https://nodejs.org/api/packages.html#packages_type
*
* In words:
* 1. A module with .mjs extension is an ES module.
* 2. A module with .clj extension is CommonJS.
* 3. A module with .js extensions where the nearest package.json's
* with "type": "module" is an ES module
* 4. Otherwise, it is CommonJS.
*
* @returns {Promise<'commonjs' | 'module'>} Module format ('commonjs' or 'module')
*/
async function moduleFormat(
modulePath: string
): Promise<'commonjs' | 'module'> {
if (/\.mjs$/.test(modulePath)) return 'module';
if (/\.cjs$/.test(modulePath)) return 'commonjs';
const pkg = await readPkgUp({
cwd: path.dirname(modulePath),
normalize: false,
});
// Default to commonjs unless package.json specifies type as 'module'.
return pkg?.packageJson.type === 'module' ? 'module' : 'commonjs';
}
/**
* Dynamically load import function to prevent TypeScript from
* transpiling into a require.
*
* See https://github.com/microsoft/TypeScript/issues/43329.
*/
const dynamicImport = new Function(
'modulePath',
'return import(modulePath)'
) as (modulePath: string) => Promise<any>;
/**
* Returns user's function from function file.
* Returns null if function can't be retrieved.
* @return User's function or null.
*/
export async function getUserFunction(
codeLocation: string,
functionTarget: string
): Promise<HandlerFunction | null> {
try {
const functionModulePath = getFunctionModulePath(codeLocation);
if (functionModulePath === null) {
console.error('Provided code is not a loadable module.');
return null;
}
let functionModule;
if ((await moduleFormat(functionModulePath)) === 'module') {
if (semver.lt(process.version, MIN_NODE_VERSION_ESMODULES)) {
console.error(
`Cannot load ES Module on Node.js ${process.version}. ` +
'Please upgrade to Node.js v13.2.0 and up.'
);
return null;
}
functionModule = await dynamicImport(functionModulePath);
} else {
functionModule = require(functionModulePath);
}
let userFunction = functionTarget
.split('.')
.reduce((code, functionTargetPart) => {
if (typeof code === 'undefined') {
return undefined;
} else {
return code[functionTargetPart];
}
}, functionModule);
// TODO: do we want 'function' fallback?
if (typeof userFunction === 'undefined') {
// eslint-disable-next-line no-prototype-builtins
if (functionModule.hasOwnProperty('function')) {
userFunction = functionModule['function'];
} else {
console.error(
`Function '${functionTarget}' is not defined in the provided ` +
'module.\nDid you specify the correct target function to execute?'
);
return null;
}
}
if (typeof userFunction !== 'function') {
console.error(
`'${functionTarget}' needs to be of type function. Got: ` +
`${typeof userFunction}`
);
return null;
}
return userFunction as HandlerFunction;
} catch (ex) {
let additionalHint: string;
// TODO: this should be done based on ex.code rather than string matching.
if (ex.stack && ex.stack.includes('Cannot find module')) {
additionalHint =
'Did you list all required modules in the package.json ' +
'dependencies?\n';
} else {
additionalHint = 'Is there a syntax error in your code?\n';
}
console.error(
`Provided module can't be loaded.\n${additionalHint}` +
`Detailed stack trace: ${ex.stack}`
);
return null;
}
}
/**
* Returns resolved path to the module containing the user function.
* Returns null if the module can not be identified.
* @param codeLocation Directory with user's code.
* @return Resolved path or null.
*/
function getFunctionModulePath(codeLocation: string): string | null {
let path: string | null = null;
try {
path = require.resolve(codeLocation);
} catch (ex) {
try {
// TODO: Decide if we want to keep this fallback.
path = require.resolve(codeLocation + '/function.js');
} catch (ex) {
return path;
}
}
return path;
}