This repository has been archived by the owner on May 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
/
index.ts
200 lines (162 loc) · 6.12 KB
/
index.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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import type { ArgumentPlaceholder, Expression, SpreadElement, JSXNamespacedName } from '@babel/types'
import { InvocationMode, INVOCATION_MODE } from '../../../function.js'
import { FunctionBundlingUserError } from '../../../utils/error.js'
import { nonNullable } from '../../../utils/non_nullable.js'
import { getRoutes, Route } from '../../../utils/routes.js'
import { RUNTIME } from '../../runtime.js'
import { NODE_BUNDLER } from '../bundlers/types.js'
import { createBindingsMethod } from '../parser/bindings.js'
import { traverseNodes } from '../parser/exports.js'
import { getImports } from '../parser/imports.js'
import { safelyParseSource, safelyReadSource } from '../parser/index.js'
import type { ModuleFormat } from '../utils/module_format.js'
import { parse as parseSchedule } from './properties/schedule.js'
export const IN_SOURCE_CONFIG_MODULE = '@netlify/functions'
export type ISCValues = {
routes?: Route[]
schedule?: string
methods?: string[]
}
export interface StaticAnalysisResult extends ISCValues {
inputModuleFormat?: ModuleFormat
invocationMode?: InvocationMode
runtimeAPIVersion?: number
}
interface FindISCDeclarationsOptions {
functionName: string
}
const validateScheduleFunction = (functionFound: boolean, scheduleFound: boolean, functionName: string): void => {
if (!functionFound) {
throw new FunctionBundlingUserError(
"The `schedule` helper was imported but we couldn't find any usages. If you meant to schedule a function, please check that `schedule` is invoked and `handler` correctly exported.",
{ functionName, runtime: RUNTIME.JAVASCRIPT },
)
}
if (!scheduleFound) {
throw new FunctionBundlingUserError(
'Unable to find cron expression for scheduled function. The cron expression (first argument) for the `schedule` helper needs to be accessible inside the file and cannot be imported.',
{ functionName, runtime: RUNTIME.JAVASCRIPT },
)
}
}
/**
* Normalizes method names into arrays of uppercase strings.
* (e.g. "get" becomes ["GET"])
*/
const normalizeMethods = (input: unknown, name: string): string[] | undefined => {
const methods = Array.isArray(input) ? input : [input]
return methods.map((method) => {
if (typeof method !== 'string') {
throw new FunctionBundlingUserError(
`Could not parse method declaration of function '${name}'. Expecting HTTP Method, got ${method}`,
{
functionName: name,
runtime: RUNTIME.JAVASCRIPT,
bundler: NODE_BUNDLER.ESBUILD,
},
)
}
return method.toUpperCase()
})
}
/**
* Loads a file at a given path, parses it into an AST, and returns a series of
* data points, such as in-source configuration properties and other metadata.
*/
export const parseFile = async (
sourcePath: string,
{ functionName }: FindISCDeclarationsOptions,
): Promise<StaticAnalysisResult> => {
const source = await safelyReadSource(sourcePath)
if (source === null) {
return {}
}
return parseSource(source, { functionName })
}
/**
* Takes a JS/TS source as a string, parses it into an AST, and returns a
* series of data points, such as in-source configuration properties and
* other metadata.
*/
export const parseSource = (source: string, { functionName }: FindISCDeclarationsOptions): StaticAnalysisResult => {
const ast = safelyParseSource(source)
if (ast === null) {
return {}
}
const imports = ast.body.flatMap((node) => getImports(node, IN_SOURCE_CONFIG_MODULE))
const scheduledFunctionExpected = imports.some(({ imported }) => imported === 'schedule')
let scheduledFunctionFound = false
let scheduleFound = false
const getAllBindings = createBindingsMethod(ast.body)
const { configExport, handlerExports, hasDefaultExport, inputModuleFormat } = traverseNodes(ast.body, getAllBindings)
const isV2API = handlerExports.length === 0 && hasDefaultExport
if (isV2API) {
const result: StaticAnalysisResult = {
inputModuleFormat,
runtimeAPIVersion: 2,
}
if (typeof configExport.schedule === 'string') {
result.schedule = configExport.schedule
}
if (configExport.method !== undefined) {
result.methods = normalizeMethods(configExport.method, functionName)
}
result.routes = getRoutes({
functionName,
methods: result.methods ?? [],
path: configExport.path,
preferStatic: configExport.preferStatic === true,
})
return result
}
const iscExports = handlerExports
.map((node) => {
// We're only interested in exports with call expressions, since that's
// the pattern we use for the wrapper functions.
if (node.type !== 'call-expression') {
return null
}
const { args, local: exportName } = node
const matchingImport = imports.find(({ local: importName }) => importName === exportName)
if (matchingImport === undefined) {
return null
}
switch (matchingImport.imported) {
case 'schedule': {
const parsed = parseSchedule({ args }, getAllBindings)
scheduledFunctionFound = true
if (parsed.schedule) {
scheduleFound = true
}
return parsed
}
case 'stream': {
return {
invocationMode: INVOCATION_MODE.Stream,
}
}
default:
// no-op
}
return null
})
.filter(nonNullable)
if (scheduledFunctionExpected) {
validateScheduleFunction(scheduledFunctionFound, scheduleFound, functionName)
}
const mergedExports: ISCValues = iscExports.reduce((acc, obj) => ({ ...acc, ...obj }), {})
return { ...mergedExports, inputModuleFormat, runtimeAPIVersion: 1 }
}
export type ISCHandlerArg = ArgumentPlaceholder | Expression | SpreadElement | JSXNamespacedName
export type ISCExportWithCallExpression = {
type: 'call-expression'
args: ISCHandlerArg[]
local: string
}
export type ISCExportWithObject = {
type: 'object-expression'
object: Record<string, unknown>
}
export type ISCExportOther = { type: 'other' }
export type ISCDefaultExport = { type: 'default' }
export type ISCExport = ISCExportWithCallExpression | ISCExportWithObject | ISCExportOther | ISCDefaultExport