@cedarjs/api-server 6.0.0-canary.2788 → 6.0.0-canary.2792

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 (71) hide show
  1. package/package.json +29 -72
  2. package/dist/cjs/apiCLIConfig.d.ts +0 -6
  3. package/dist/cjs/apiCLIConfig.d.ts.map +0 -1
  4. package/dist/cjs/apiCLIConfig.js +0 -71
  5. package/dist/cjs/apiCLIConfigHandler.d.ts +0 -3
  6. package/dist/cjs/apiCLIConfigHandler.d.ts.map +0 -1
  7. package/dist/cjs/apiCLIConfigHandler.js +0 -67
  8. package/dist/cjs/bin.d.ts +0 -2
  9. package/dist/cjs/bin.d.ts.map +0 -1
  10. package/dist/cjs/bin.js +0 -1007
  11. package/dist/cjs/bothCLIConfig.d.ts +0 -6
  12. package/dist/cjs/bothCLIConfig.d.ts.map +0 -1
  13. package/dist/cjs/bothCLIConfig.js +0 -76
  14. package/dist/cjs/bothCLIConfigHandler.d.ts +0 -3
  15. package/dist/cjs/bothCLIConfigHandler.d.ts.map +0 -1
  16. package/dist/cjs/bothCLIConfigHandler.js +0 -107
  17. package/dist/cjs/buildManager.d.ts +0 -15
  18. package/dist/cjs/buildManager.d.ts.map +0 -1
  19. package/dist/cjs/buildManager.js +0 -79
  20. package/dist/cjs/cliHelpers.d.ts +0 -6
  21. package/dist/cjs/cliHelpers.d.ts.map +0 -1
  22. package/dist/cjs/cliHelpers.js +0 -57
  23. package/dist/cjs/createServer.d.ts +0 -30
  24. package/dist/cjs/createServer.d.ts.map +0 -1
  25. package/dist/cjs/createServer.js +0 -145
  26. package/dist/cjs/createServerHelpers.d.ts +0 -38
  27. package/dist/cjs/createServerHelpers.d.ts.map +0 -1
  28. package/dist/cjs/createServerHelpers.js +0 -112
  29. package/dist/cjs/fastify.d.ts +0 -13
  30. package/dist/cjs/fastify.d.ts.map +0 -1
  31. package/dist/cjs/fastify.js +0 -96
  32. package/dist/cjs/logFormatter/ambient.d.js +0 -1
  33. package/dist/cjs/logFormatter/bin.d.ts +0 -2
  34. package/dist/cjs/logFormatter/bin.d.ts.map +0 -1
  35. package/dist/cjs/logFormatter/bin.js +0 -369
  36. package/dist/cjs/logFormatter/formatters.d.ts +0 -30
  37. package/dist/cjs/logFormatter/formatters.d.ts.map +0 -1
  38. package/dist/cjs/logFormatter/formatters.js +0 -275
  39. package/dist/cjs/logFormatter/index.d.ts +0 -2
  40. package/dist/cjs/logFormatter/index.d.ts.map +0 -1
  41. package/dist/cjs/logFormatter/index.js +0 -184
  42. package/dist/cjs/package.json +0 -1
  43. package/dist/cjs/plugins/api.d.ts +0 -14
  44. package/dist/cjs/plugins/api.d.ts.map +0 -1
  45. package/dist/cjs/plugins/api.js +0 -78
  46. package/dist/cjs/plugins/graphql.d.ts +0 -10
  47. package/dist/cjs/plugins/graphql.d.ts.map +0 -1
  48. package/dist/cjs/plugins/graphql.js +0 -135
  49. package/dist/cjs/plugins/lambdaLoader.d.ts +0 -34
  50. package/dist/cjs/plugins/lambdaLoader.d.ts.map +0 -1
  51. package/dist/cjs/plugins/lambdaLoader.js +0 -199
  52. package/dist/cjs/requestHandlers/awsLambdaFastify.d.ts +0 -5
  53. package/dist/cjs/requestHandlers/awsLambdaFastify.d.ts.map +0 -1
  54. package/dist/cjs/requestHandlers/awsLambdaFastify.js +0 -105
  55. package/dist/cjs/requestHandlers/utils.d.ts +0 -26
  56. package/dist/cjs/requestHandlers/utils.d.ts.map +0 -1
  57. package/dist/cjs/requestHandlers/utils.js +0 -55
  58. package/dist/cjs/serverManager.d.ts +0 -8
  59. package/dist/cjs/serverManager.d.ts.map +0 -1
  60. package/dist/cjs/serverManager.js +0 -137
  61. package/dist/cjs/types.d.ts +0 -19
  62. package/dist/cjs/types.d.ts.map +0 -1
  63. package/dist/cjs/utils.d.ts +0 -6
  64. package/dist/cjs/utils.d.ts.map +0 -1
  65. package/dist/cjs/utils.js +0 -58
  66. package/dist/cjs/watch.d.ts +0 -10
  67. package/dist/cjs/watch.d.ts.map +0 -1
  68. package/dist/cjs/watch.js +0 -399
  69. package/dist/cjs/watchPaths.d.ts +0 -3
  70. package/dist/cjs/watchPaths.d.ts.map +0 -1
  71. package/dist/cjs/watchPaths.js +0 -140
package/dist/cjs/bin.js DELETED
@@ -1,1007 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- var __create = Object.create;
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getProtoOf = Object.getPrototypeOf;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __esm = (fn, res, err) => function __init() {
10
- if (err) throw err[0];
11
- try {
12
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
13
- } catch (e) {
14
- throw err = [e], e;
15
- }
16
- };
17
- var __export = (target, all) => {
18
- for (var name in all)
19
- __defProp(target, name, { get: all[name], enumerable: true });
20
- };
21
- var __copyProps = (to, from, except, desc) => {
22
- if (from && typeof from === "object" || typeof from === "function") {
23
- for (let key of __getOwnPropNames(from))
24
- if (!__hasOwnProp.call(to, key) && key !== except)
25
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
26
- }
27
- return to;
28
- };
29
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
30
- // If the importer is in node compatibility mode or this is not an ESM
31
- // file that has been converted to a CommonJS file using a Babel-
32
- // compatible transform (i.e. "__esModule" has not been set), then set
33
- // "default" to the CommonJS "module.exports" for node compatibility.
34
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
35
- mod
36
- ));
37
-
38
- // src/cliHelpers.ts
39
- function getAPIHost() {
40
- let host = process.env.REDWOOD_API_HOST;
41
- host ??= (0, import_project_config.getConfig)().api.host;
42
- host ??= process.env.NODE_ENV === "production" ? "0.0.0.0" : "::";
43
- return host;
44
- }
45
- function getAPIPort() {
46
- return process.env.REDWOOD_API_PORT ? parseInt(process.env.REDWOOD_API_PORT) : (0, import_project_config.getConfig)().api.port;
47
- }
48
- function getAPIRootPath() {
49
- return process.env.CEDAR_API_ROOT_PATH ?? "/";
50
- }
51
- function getWebHost() {
52
- let host = process.env.REDWOOD_WEB_HOST;
53
- host ??= (0, import_project_config.getConfig)().web.host;
54
- host ??= process.env.NODE_ENV === "production" ? "0.0.0.0" : "::";
55
- return host;
56
- }
57
- function getWebPort() {
58
- return process.env.REDWOOD_WEB_PORT ? parseInt(process.env.REDWOOD_WEB_PORT) : (0, import_project_config.getConfig)().web.port;
59
- }
60
- var import_project_config;
61
- var init_cliHelpers = __esm({
62
- "src/cliHelpers.ts"() {
63
- "use strict";
64
- import_project_config = require("@cedarjs/project-config");
65
- }
66
- });
67
-
68
- // src/createServerHelpers.ts
69
- function isCustomLoggerInstance(logger) {
70
- return !!logger && typeof logger === "object" && "info" in logger;
71
- }
72
- function resolveOptions(options = {}, args) {
73
- options.parseArgs ??= true;
74
- const defaults = getDefaultCreateServerOptions();
75
- const logger = options.logger ?? defaults.logger;
76
- const resolvedOptions = {
77
- apiRootPath: options.apiRootPath ?? defaults.apiRootPath,
78
- fastifyServerOptions: options.fastifyServerOptions ?? {
79
- requestTimeout: defaults.fastifyServerOptions.requestTimeout,
80
- bodyLimit: defaults.fastifyServerOptions.bodyLimit
81
- },
82
- discoverFunctionsGlob: options.discoverFunctionsGlob ?? defaults.discoverFunctionsGlob,
83
- configureApiServer: options.configureApiServer ?? defaults.configureApiServer,
84
- apiHost: options.apiHost ?? defaults.apiHost,
85
- apiPort: options.apiPort ?? defaults.apiPort
86
- };
87
- resolvedOptions.fastifyServerOptions.requestTimeout ??= defaults.fastifyServerOptions.requestTimeout;
88
- if (isCustomLoggerInstance(logger)) {
89
- resolvedOptions.fastifyServerOptions.loggerInstance = logger;
90
- } else {
91
- resolvedOptions.fastifyServerOptions.logger = logger;
92
- }
93
- if (options.parseArgs) {
94
- const { values } = (0, import_util.parseArgs)({
95
- options: {
96
- apiHost: {
97
- type: "string"
98
- },
99
- apiPort: {
100
- type: "string",
101
- short: "p"
102
- },
103
- apiRootPath: {
104
- type: "string"
105
- }
106
- },
107
- strict: false,
108
- ...args && { args }
109
- });
110
- if (values.apiHost && typeof values.apiHost !== "string") {
111
- throw new Error("`apiHost` must be a string");
112
- }
113
- if (values.apiHost) {
114
- resolvedOptions.apiHost = values.apiHost;
115
- }
116
- if (values.apiPort) {
117
- resolvedOptions.apiPort = +values.apiPort;
118
- if (isNaN(resolvedOptions.apiPort)) {
119
- throw new Error("`apiPort` must be an integer");
120
- }
121
- }
122
- if (values.apiRootPath && typeof values.apiRootPath !== "string") {
123
- throw new Error("`apiRootPath` must be a string");
124
- }
125
- if (values.apiRootPath) {
126
- resolvedOptions.apiRootPath = values.apiRootPath;
127
- }
128
- }
129
- resolvedOptions.apiRootPath = (0, import_helpers.coerceRootPath)(resolvedOptions.apiRootPath);
130
- return resolvedOptions;
131
- }
132
- var import_util, import_helpers, getDefaultCreateServerOptions;
133
- var init_createServerHelpers = __esm({
134
- "src/createServerHelpers.ts"() {
135
- "use strict";
136
- import_util = require("util");
137
- import_helpers = require("@cedarjs/fastify-web/dist/helpers.js");
138
- init_cliHelpers();
139
- getDefaultCreateServerOptions = () => ({
140
- apiRootPath: getAPIRootPath(),
141
- logger: {
142
- level: process.env.LOG_LEVEL ?? (process.env.NODE_ENV === "development" ? "debug" : "warn")
143
- },
144
- fastifyServerOptions: {
145
- requestTimeout: 15e3,
146
- bodyLimit: 1024 * 1024 * 100
147
- // 100MB
148
- },
149
- discoverFunctionsGlob: "dist/functions/**/*.{ts,js}",
150
- configureApiServer: () => {
151
- },
152
- parseArgs: true,
153
- apiHost: getAPIHost(),
154
- apiPort: getAPIPort()
155
- });
156
- }
157
- });
158
-
159
- // src/fastify.ts
160
- async function loadFastifyConfig() {
161
- const serverConfigPath = import_path.default.join(
162
- (0, import_project_config2.getPaths)().base,
163
- (0, import_project_config2.getConfig)().api.serverConfig
164
- );
165
- if (!import_node_fs.default.existsSync(serverConfigPath)) {
166
- return serverConfigFile;
167
- }
168
- if (loadedServerConfigPath !== serverConfigPath) {
169
- isServerConfigLoaded = false;
170
- }
171
- if (!isServerConfigLoaded) {
172
- console.log(`Loading server config from ${serverConfigPath}`);
173
- console.log(`Loading server config from URL file://${serverConfigPath}`);
174
- console.log(
175
- `Loading server config from URL ${(0, import_url.pathToFileURL)(serverConfigPath).href}`
176
- );
177
- const config3 = await import((0, import_url.pathToFileURL)(serverConfigPath).href);
178
- serverConfigFile = { ...config3.default };
179
- loadedServerConfigPath = serverConfigPath;
180
- isServerConfigLoaded = true;
181
- }
182
- return serverConfigFile;
183
- }
184
- var import_node_fs, import_path, import_url, import_fastify, import_store, import_project_config2, DEFAULT_OPTIONS, isServerConfigLoaded, loadedServerConfigPath, serverConfigFile, createFastifyInstance;
185
- var init_fastify = __esm({
186
- "src/fastify.ts"() {
187
- "use strict";
188
- import_node_fs = __toESM(require("node:fs"), 1);
189
- import_path = __toESM(require("path"), 1);
190
- import_url = require("url");
191
- import_fastify = __toESM(require("fastify"), 1);
192
- import_store = require("@cedarjs/context/dist/store");
193
- import_project_config2 = require("@cedarjs/project-config");
194
- DEFAULT_OPTIONS = {
195
- logger: {
196
- level: process.env.NODE_ENV === "development" ? "debug" : "info"
197
- }
198
- };
199
- isServerConfigLoaded = false;
200
- serverConfigFile = {
201
- config: DEFAULT_OPTIONS,
202
- configureFastify: async (fastify2, options) => {
203
- fastify2.log.trace(
204
- options,
205
- `In configureFastify hook for side: ${options?.side}`
206
- );
207
- return fastify2;
208
- }
209
- };
210
- createFastifyInstance = async (options) => {
211
- const { config: config3 } = await loadFastifyConfig();
212
- const fastify2 = (0, import_fastify.default)(options || config3 || DEFAULT_OPTIONS);
213
- fastify2.addHook("onRequest", (_req, _reply, done) => {
214
- (0, import_store.getAsyncStoreInstance)().run(/* @__PURE__ */ new Map(), done);
215
- });
216
- return fastify2;
217
- };
218
- }
219
- });
220
-
221
- // src/requestHandlers/utils.ts
222
- var parseBody, mergeMultiValueHeaders;
223
- var init_utils = __esm({
224
- "src/requestHandlers/utils.ts"() {
225
- "use strict";
226
- parseBody = (rawBody) => {
227
- if (typeof rawBody === "string") {
228
- return { body: rawBody, isBase64Encoded: false };
229
- }
230
- if (rawBody instanceof Buffer) {
231
- return { body: rawBody.toString("base64"), isBase64Encoded: true };
232
- }
233
- return { body: "", isBase64Encoded: false };
234
- };
235
- mergeMultiValueHeaders = (headers, multiValueHeaders) => {
236
- const mergedHeaders = Object.entries(
237
- headers || {}
238
- ).reduce((acc, [name, value]) => {
239
- acc[name.toLowerCase()] = [value];
240
- return acc;
241
- }, {});
242
- Object.entries(multiValueHeaders || {}).forEach(([headerName, values]) => {
243
- const name = headerName.toLowerCase();
244
- if (name.toLowerCase() === "set-cookie") {
245
- mergedHeaders["set-cookie"] = values;
246
- } else {
247
- mergedHeaders[name] = [values.join("; ")];
248
- }
249
- });
250
- return mergedHeaders;
251
- };
252
- }
253
- });
254
-
255
- // src/requestHandlers/awsLambdaFastify.ts
256
- var import_picoquery, lambdaEventForFastifyRequest, fastifyResponseForLambdaResult, fastifyResponseForLambdaError, requestHandler;
257
- var init_awsLambdaFastify = __esm({
258
- "src/requestHandlers/awsLambdaFastify.ts"() {
259
- "use strict";
260
- import_picoquery = require("picoquery");
261
- init_utils();
262
- lambdaEventForFastifyRequest = (request) => {
263
- const qsParams = (0, import_picoquery.parse)(
264
- request.url.split(/\?(.+)/)[1],
265
- {
266
- nestingSyntax: "index",
267
- arrayRepeat: true,
268
- arrayRepeatSyntax: "bracket"
269
- }
270
- );
271
- return {
272
- httpMethod: request.method,
273
- headers: {
274
- "x-forwarded-proto": request.protocol,
275
- ...request.headers
276
- },
277
- path: request.urlData("path"),
278
- queryStringParameters: qsParams,
279
- requestContext: {
280
- requestId: request.id,
281
- identity: {
282
- sourceIp: request.ip
283
- },
284
- domainName: request.hostname
285
- },
286
- ...parseBody(request.rawBody || "")
287
- // adds `body` and `isBase64Encoded`
288
- };
289
- };
290
- fastifyResponseForLambdaResult = (reply, lambdaResult) => {
291
- const {
292
- statusCode = 200,
293
- headers,
294
- body = "",
295
- multiValueHeaders
296
- } = lambdaResult;
297
- const mergedHeaders = mergeMultiValueHeaders(headers, multiValueHeaders);
298
- Object.entries(mergedHeaders).forEach(
299
- ([name, values]) => values.forEach((value) => reply.header(name, value))
300
- );
301
- reply.status(statusCode);
302
- if (lambdaResult.isBase64Encoded) {
303
- return reply.send(Buffer.from(body, "base64"));
304
- } else {
305
- return reply.send(body);
306
- }
307
- };
308
- fastifyResponseForLambdaError = (req, reply, error) => {
309
- req.log.error(error);
310
- reply.status(500).send();
311
- };
312
- requestHandler = async (req, reply, handler3) => {
313
- const event = lambdaEventForFastifyRequest(req);
314
- const handlerCallback = (reply2) => (error, lambdaResult) => {
315
- if (error) {
316
- fastifyResponseForLambdaError(req, reply2, error);
317
- return;
318
- }
319
- fastifyResponseForLambdaResult(reply2, lambdaResult);
320
- };
321
- const handlerPromise = handler3(
322
- event,
323
- // @ts-expect-error - Add support for context: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/0bb210867d16170c4a08d9ce5d132817651a0f80/types/aws-lambda/index.d.ts#L443-L467
324
- {},
325
- handlerCallback(reply)
326
- );
327
- if (handlerPromise && typeof handlerPromise.then === "function") {
328
- try {
329
- const lambdaResponse = await handlerPromise;
330
- return fastifyResponseForLambdaResult(reply, lambdaResponse);
331
- } catch (error) {
332
- return fastifyResponseForLambdaError(req, reply, error);
333
- }
334
- }
335
- };
336
- }
337
- });
338
-
339
- // src/utils.ts
340
- function escape(string) {
341
- const htmlEscapes = {
342
- "&": "&",
343
- "<": "&lt;",
344
- ">": "&gt;",
345
- '"': "&quot;",
346
- "'": "&#39;"
347
- };
348
- return string.replace(/[&<>"']/g, (char) => htmlEscapes[char]);
349
- }
350
- var init_utils2 = __esm({
351
- "src/utils.ts"() {
352
- "use strict";
353
- }
354
- });
355
-
356
- // src/plugins/lambdaLoader.ts
357
- var import_node_path, import_node_url, import_ansis, import_fast_glob, import_termi_link, import_runtime, import_project_config3, LAMBDA_FUNCTIONS, CEDAR_HANDLERS, cedarRouteManifest, setLambdaFunctions, loadFunctionsFromDist, findApiDistFunctions, lambdaRequestHandler;
358
- var init_lambdaLoader = __esm({
359
- "src/plugins/lambdaLoader.ts"() {
360
- "use strict";
361
- import_node_path = __toESM(require("node:path"), 1);
362
- import_node_url = require("node:url");
363
- import_ansis = __toESM(require("ansis"), 1);
364
- import_fast_glob = __toESM(require("fast-glob"), 1);
365
- import_termi_link = require("termi-link");
366
- import_runtime = require("@cedarjs/api/runtime");
367
- import_project_config3 = require("@cedarjs/project-config");
368
- init_awsLambdaFastify();
369
- init_utils2();
370
- LAMBDA_FUNCTIONS = /* @__PURE__ */ new Map();
371
- CEDAR_HANDLERS = /* @__PURE__ */ new Map();
372
- cedarRouteManifest = [];
373
- setLambdaFunctions = async (foundFunctions) => {
374
- const tsImport = Date.now();
375
- console.log(import_ansis.default.dim.italic("Importing Server Functions... "));
376
- cedarRouteManifest.length = 0;
377
- LAMBDA_FUNCTIONS.clear();
378
- CEDAR_HANDLERS.clear();
379
- const imports = foundFunctions.map(async (fnPath) => {
380
- const ts = Date.now();
381
- const routeName = import_node_path.default.basename(fnPath).replace(".js", "");
382
- const routePath = `/${routeName}`;
383
- const fnImport = await import((0, import_node_url.pathToFileURL)(fnPath).href);
384
- const handler3 = (() => {
385
- if ("handler" in fnImport) {
386
- return fnImport.handler;
387
- }
388
- if ("default" in fnImport) {
389
- if ("handler" in fnImport.default) {
390
- return fnImport.default.handler;
391
- }
392
- }
393
- return void 0;
394
- })();
395
- const cedarHandler = (() => {
396
- if ("handleRequest" in fnImport && typeof fnImport.handleRequest === "function") {
397
- return fnImport.handleRequest;
398
- }
399
- if ("default" in fnImport && fnImport.default && "handleRequest" in fnImport.default && typeof fnImport.default.handleRequest === "function") {
400
- return fnImport.default.handleRequest;
401
- }
402
- return void 0;
403
- })();
404
- if (handler3) {
405
- LAMBDA_FUNCTIONS.set(routeName, handler3);
406
- }
407
- if (cedarHandler) {
408
- CEDAR_HANDLERS.set(routeName, cedarHandler);
409
- } else if (handler3) {
410
- CEDAR_HANDLERS.set(routeName, (0, import_runtime.wrapLegacyHandler)(handler3));
411
- }
412
- if (!handler3 && !cedarHandler) {
413
- console.warn(
414
- routeName,
415
- "at",
416
- fnPath,
417
- "does not have a function called handler or handleRequest defined."
418
- );
419
- }
420
- cedarRouteManifest.push({
421
- id: routePath,
422
- path: routePath,
423
- methods: routeName === "graphql" ? ["GET", "POST", "OPTIONS"] : [],
424
- type: routeName === "graphql" ? "graphql" : routeName === "health" ? "health" : routeName.toLowerCase().includes("auth") ? "auth" : "function",
425
- entry: fnPath
426
- });
427
- console.log(
428
- (0, import_termi_link.terminalLink)(import_ansis.default.magenta("/" + routeName), (0, import_node_url.pathToFileURL)(fnPath).href),
429
- import_ansis.default.dim.italic(Date.now() - ts + " ms")
430
- );
431
- });
432
- await Promise.all(imports);
433
- console.log(
434
- import_ansis.default.dim.italic("...Done importing in " + (Date.now() - tsImport) + " ms")
435
- );
436
- };
437
- loadFunctionsFromDist = async (options = {}) => {
438
- const serverFunctions = findApiDistFunctions({
439
- cwd: (0, import_project_config3.getPaths)().api.base,
440
- options: options?.fastGlobOptions,
441
- discoverFunctionsGlob: options?.discoverFunctionsGlob
442
- });
443
- const i = serverFunctions.findIndex((x) => import_node_path.default.basename(x) === "graphql.js");
444
- if (i >= 0) {
445
- const graphQLFn = serverFunctions.splice(i, 1)[0];
446
- serverFunctions.unshift(graphQLFn);
447
- }
448
- await setLambdaFunctions(serverFunctions);
449
- };
450
- findApiDistFunctions = (params) => {
451
- const {
452
- cwd = (0, import_project_config3.getPaths)().api.base,
453
- options = {},
454
- discoverFunctionsGlob = "dist/functions/**/*.{ts,js}"
455
- } = params;
456
- return import_fast_glob.default.sync(discoverFunctionsGlob, {
457
- cwd,
458
- // We don't support deeply nested api functions, to maximise compatibility
459
- // with deployment providers
460
- deep: 2,
461
- absolute: true,
462
- ...options
463
- });
464
- };
465
- lambdaRequestHandler = async (req, reply) => {
466
- const { routeName } = req.params;
467
- const cedarHandlerCandidate = CEDAR_HANDLERS.get(routeName);
468
- const cedarHandler = typeof cedarHandlerCandidate === "function" ? cedarHandlerCandidate : void 0;
469
- if (cedarHandler) {
470
- const requestBody = req.method === "GET" || req.method === "HEAD" ? void 0 : typeof req.rawBody === "string" ? req.rawBody : req.rawBody ? Buffer.from(req.rawBody).toString() : void 0;
471
- const href = `${req.protocol}://${req.hostname}${req.raw.url ?? "/"}`;
472
- const request = new Request(href, {
473
- method: req.method,
474
- headers: req.headers,
475
- body: requestBody
476
- });
477
- const ctx = await (0, import_runtime.buildCedarContext)(request, {
478
- params: {
479
- routeName
480
- }
481
- });
482
- const response = await cedarHandler(request, ctx);
483
- reply.status(response.status);
484
- response.headers.forEach((value, name) => {
485
- reply.header(name, value);
486
- });
487
- const body = await response.arrayBuffer();
488
- reply.send(Buffer.from(body));
489
- return;
490
- }
491
- const handler3 = LAMBDA_FUNCTIONS.get(routeName);
492
- if (handler3) {
493
- return requestHandler(req, reply, handler3);
494
- } else {
495
- const errorMessage = `Function "${routeName}" was not found.`;
496
- req.log.error(errorMessage);
497
- reply.status(404);
498
- if (process.env.NODE_ENV === "development") {
499
- const devError = {
500
- error: errorMessage,
501
- availableFunctions: [
502
- .../* @__PURE__ */ new Set([...LAMBDA_FUNCTIONS.keys(), ...CEDAR_HANDLERS.keys()])
503
- ]
504
- };
505
- reply.send(devError);
506
- } else {
507
- reply.send(escape(errorMessage));
508
- }
509
- return;
510
- }
511
- };
512
- }
513
- });
514
-
515
- // src/plugins/api.ts
516
- async function cedarFastifyAPI(fastify2, opts) {
517
- const cedarOptions = opts.redwood ?? {};
518
- cedarOptions.apiRootPath ??= "/";
519
- cedarOptions.apiRootPath = (0, import_helpers2.coerceRootPath)(cedarOptions.apiRootPath);
520
- cedarOptions.fastGlobOptions ??= {};
521
- cedarOptions.loadUserConfig ??= false;
522
- fastify2.register(import_url_data.default);
523
- await fastify2.register(import_fastify_raw_body.default);
524
- fastify2.addHook("onRequest", (_req, _reply, done) => {
525
- (0, import_store2.getAsyncStoreInstance)().run(/* @__PURE__ */ new Map(), done);
526
- });
527
- fastify2.addContentTypeParser(
528
- ["application/x-www-form-urlencoded", "multipart/form-data"],
529
- { parseAs: "string" },
530
- fastify2.defaultTextParser
531
- );
532
- if (cedarOptions.loadUserConfig) {
533
- const { configureFastify } = await loadFastifyConfig();
534
- if (configureFastify) {
535
- await configureFastify(fastify2, {
536
- side: "api",
537
- apiRootPath: cedarOptions.apiRootPath
538
- });
539
- }
540
- }
541
- if (cedarOptions.configureServer) {
542
- await cedarOptions.configureServer(fastify2);
543
- }
544
- fastify2.all(`${cedarOptions.apiRootPath}:routeName`, lambdaRequestHandler);
545
- fastify2.all(`${cedarOptions.apiRootPath}:routeName/*`, lambdaRequestHandler);
546
- await loadFunctionsFromDist({
547
- fastGlobOptions: cedarOptions.fastGlobOptions,
548
- discoverFunctionsGlob: cedarOptions.discoverFunctionsGlob
549
- });
550
- }
551
- var import_url_data, import_fastify_raw_body, import_store2, import_helpers2;
552
- var init_api = __esm({
553
- "src/plugins/api.ts"() {
554
- "use strict";
555
- import_url_data = __toESM(require("@fastify/url-data"), 1);
556
- import_fastify_raw_body = __toESM(require("fastify-raw-body"), 1);
557
- import_store2 = require("@cedarjs/context/dist/store");
558
- import_helpers2 = require("@cedarjs/fastify-web/dist/helpers.js");
559
- init_fastify();
560
- init_lambdaLoader();
561
- }
562
- });
563
-
564
- // src/plugins/graphql.ts
565
- var graphql_exports = {};
566
- __export(graphql_exports, {
567
- redwoodFastifyGraphQLServer: () => redwoodFastifyGraphQLServer
568
- });
569
- async function redwoodFastifyGraphQLServer(fastify2, options) {
570
- const redwoodOptions = options.redwood ?? {};
571
- redwoodOptions.apiRootPath ??= "/";
572
- redwoodOptions.apiRootPath = (0, import_helpers3.coerceRootPath)(redwoodOptions.apiRootPath);
573
- fastify2.register(import_url_data2.default);
574
- fastify2.register(import_multipart.default);
575
- const method = ["GET", "POST", "OPTIONS"];
576
- fastify2.addHook("onRequest", (_req, _reply, done) => {
577
- (0, import_store3.getAsyncStoreInstance)().run(/* @__PURE__ */ new Map(), done);
578
- });
579
- try {
580
- if (!redwoodOptions.graphql) {
581
- const [graphqlFunctionPath] = await (0, import_fast_glob2.default)("dist/functions/graphql.{ts,js}", {
582
- cwd: (0, import_project_config4.getPaths)().api.base,
583
- absolute: true
584
- });
585
- const filePath = (0, import_node_url2.pathToFileURL)(graphqlFunctionPath).href;
586
- const { __cedar_graphqlOptions } = await import(filePath);
587
- if (!__cedar_graphqlOptions) {
588
- return;
589
- }
590
- redwoodOptions.graphql = __cedar_graphqlOptions;
591
- }
592
- const graphqlOptions = redwoodOptions.graphql;
593
- if (graphqlOptions?.realtime?.subscriptions) {
594
- method.push("PUT");
595
- }
596
- const { yoga } = await (0, import_graphql_server.createGraphQLYoga)(graphqlOptions);
597
- const graphqlEndpoint = trimSlashes(yoga.graphqlEndpoint);
598
- const routePaths = ["", "/health", "/readiness", "/stream"];
599
- for (const routePath of routePaths) {
600
- fastify2.route({
601
- url: `${redwoodOptions.apiRootPath}${graphqlEndpoint}${routePath}`,
602
- method,
603
- handler: async (req, reply) => {
604
- const request = createFetchRequest(req, reply);
605
- const cedarContext = await (0, import_runtime2.buildCedarContext)(request, {
606
- authDecoder: graphqlOptions.authDecoder
607
- });
608
- try {
609
- return await yoga.handle(request, {
610
- request,
611
- cedarContext,
612
- event: lambdaEventForFastifyRequest(req),
613
- requestContext: void 0
614
- });
615
- } catch (e) {
616
- if (!!e && typeof e === "object" && "code" in e && e.code === "ERR_STREAM_PREMATURE_CLOSE") {
617
- return new Response(null, { status: 499 });
618
- }
619
- throw e;
620
- }
621
- }
622
- });
623
- }
624
- fastify2.addHook("onReady", (done) => {
625
- console.info(`GraphQL Yoga Server endpoint at ${graphqlEndpoint}`);
626
- console.info(
627
- `GraphQL Yoga Server Health Check endpoint at ${graphqlEndpoint}/health`
628
- );
629
- console.info(
630
- `GraphQL Yoga Server Readiness endpoint at ${graphqlEndpoint}/readiness`
631
- );
632
- done();
633
- });
634
- } catch (e) {
635
- console.log(e);
636
- }
637
- }
638
- function trimSlashes(path5) {
639
- return path5.replace(/^\/|\/$/g, "");
640
- }
641
- function createFetchRequest(req, reply) {
642
- const controller = new AbortController();
643
- reply.raw.on("close", () => {
644
- if (!reply.raw.writableFinished) {
645
- controller.abort();
646
- }
647
- });
648
- const requestBody = req.method === "GET" || req.method === "HEAD" ? void 0 : typeof req.body === "string" ? req.body : req.body ? JSON.stringify(req.body) : void 0;
649
- const href = `${req.protocol}://${req.hostname}${req.raw.url ?? "/"}`;
650
- return new Request(href, {
651
- method: req.method,
652
- headers: req.headers,
653
- body: requestBody,
654
- signal: controller.signal
655
- });
656
- }
657
- var import_node_url2, import_multipart, import_url_data2, import_fast_glob2, import_runtime2, import_store3, import_helpers3, import_graphql_server, import_project_config4;
658
- var init_graphql = __esm({
659
- "src/plugins/graphql.ts"() {
660
- "use strict";
661
- import_node_url2 = require("node:url");
662
- import_multipart = __toESM(require("@fastify/multipart"), 1);
663
- import_url_data2 = __toESM(require("@fastify/url-data"), 1);
664
- import_fast_glob2 = __toESM(require("fast-glob"), 1);
665
- import_runtime2 = require("@cedarjs/api/runtime");
666
- import_store3 = require("@cedarjs/context/dist/store");
667
- import_helpers3 = require("@cedarjs/fastify-web/dist/helpers.js");
668
- import_graphql_server = require("@cedarjs/graphql-server");
669
- import_project_config4 = require("@cedarjs/project-config");
670
- init_awsLambdaFastify();
671
- }
672
- });
673
-
674
- // src/createServer.ts
675
- async function createServer(options = {}) {
676
- const {
677
- apiRootPath,
678
- fastifyServerOptions,
679
- discoverFunctionsGlob,
680
- configureApiServer,
681
- apiPort,
682
- apiHost
683
- } = resolveOptions(options);
684
- const serverConfigPath = import_node_path2.default.join(
685
- (0, import_project_config5.getPaths)().base,
686
- (0, import_project_config5.getConfig)().api.serverConfig
687
- );
688
- if (import_node_fs2.default.existsSync(serverConfigPath)) {
689
- console.warn(
690
- import_ansis2.default.yellow(
691
- [
692
- "",
693
- `Ignoring \`config\` and \`configureServer\` in api/server.config.js.`,
694
- `Migrate them to api/src/server.{ts,js}:`,
695
- "",
696
- `\`\`\`js title="api/src/server.{ts,js}"`,
697
- "// Pass your config to `createServer`",
698
- "const server = createServer({",
699
- " fastifyServerOptions: myFastifyConfig",
700
- "})",
701
- "",
702
- "// Then inline your `configureFastify` logic:",
703
- "server.register(myFastifyPlugin)",
704
- "```",
705
- ""
706
- ].join("\n")
707
- )
708
- );
709
- }
710
- const server = Object.assign((0, import_fastify3.default)(fastifyServerOptions), {
711
- // `start` will get replaced further down in this file
712
- start: async () => {
713
- throw new Error("Not implemented yet");
714
- }
715
- });
716
- server.addHook("onRequest", (_req, _reply, done) => {
717
- (0, import_store4.getAsyncStoreInstance)().run(/* @__PURE__ */ new Map(), done);
718
- });
719
- await server.register(cedarFastifyAPI, {
720
- redwood: {
721
- apiRootPath,
722
- fastGlobOptions: {
723
- ignore: ["**/dist/functions/graphql.js"]
724
- },
725
- discoverFunctionsGlob,
726
- configureServer: configureApiServer
727
- }
728
- });
729
- const [graphqlFunctionPath] = await (0, import_fast_glob3.default)("dist/functions/graphql.{ts,js}", {
730
- cwd: (0, import_project_config5.getPaths)().api.base,
731
- absolute: true
732
- });
733
- if (graphqlFunctionPath) {
734
- const { redwoodFastifyGraphQLServer: redwoodFastifyGraphQLServer2 } = await Promise.resolve().then(() => (init_graphql(), graphql_exports));
735
- const { __cedar_graphqlOptions } = await import((0, import_node_url3.pathToFileURL)(graphqlFunctionPath).href);
736
- await server.register(redwoodFastifyGraphQLServer2, {
737
- redwood: {
738
- apiRootPath,
739
- graphql: __cedar_graphqlOptions
740
- }
741
- });
742
- }
743
- server.addHook("onReady", (done) => {
744
- process.send?.("ready");
745
- done();
746
- });
747
- server.addHook("onListen", (done) => {
748
- console.log(
749
- `Server listening at ${import_ansis2.default.magenta(
750
- `${server.listeningOrigin}${apiRootPath}`
751
- )}`
752
- );
753
- done();
754
- });
755
- server.start = (options2 = {}) => {
756
- return server.listen({
757
- ...options2,
758
- port: apiPort,
759
- host: apiHost
760
- });
761
- };
762
- return server;
763
- }
764
- var import_node_fs2, import_node_path2, import_node_url3, import_ansis2, import_dotenv_defaults, import_fast_glob3, import_fastify3, import_store4, import_project_config5;
765
- var init_createServer = __esm({
766
- "src/createServer.ts"() {
767
- "use strict";
768
- import_node_fs2 = __toESM(require("node:fs"), 1);
769
- import_node_path2 = __toESM(require("node:path"), 1);
770
- import_node_url3 = require("node:url");
771
- import_ansis2 = __toESM(require("ansis"), 1);
772
- import_dotenv_defaults = require("dotenv-defaults");
773
- import_fast_glob3 = __toESM(require("fast-glob"), 1);
774
- import_fastify3 = __toESM(require("fastify"), 1);
775
- import_store4 = require("@cedarjs/context/dist/store");
776
- import_project_config5 = require("@cedarjs/project-config");
777
- init_createServerHelpers();
778
- init_api();
779
- if (!process.env.CEDAR_ENV_FILES_LOADED) {
780
- (0, import_dotenv_defaults.config)({
781
- path: import_node_path2.default.join((0, import_project_config5.getPaths)().base, ".env"),
782
- defaults: import_node_path2.default.join((0, import_project_config5.getPaths)().base, ".env.defaults"),
783
- multiline: true
784
- });
785
- process.env.CEDAR_ENV_FILES_LOADED = "true";
786
- }
787
- }
788
- });
789
-
790
- // src/apiCLIConfigHandler.ts
791
- async function handler(options = {}) {
792
- const timeStart = Date.now();
793
- console.log(import_ansis3.default.dim.italic("Starting API Server..."));
794
- options.apiRootPath = (0, import_fastify_web.coerceRootPath)(options.apiRootPath ?? "/");
795
- const fastify2 = await createServer({
796
- apiRootPath: options.apiRootPath,
797
- apiHost: options.host,
798
- apiPort: options.port
799
- });
800
- await fastify2.start();
801
- fastify2.log.trace(
802
- { custom: { ...fastify2.initialConfig } },
803
- "Fastify server configuration"
804
- );
805
- fastify2.log.trace(`Registered plugins
806
- ${fastify2.printPlugins()}`);
807
- console.log(import_ansis3.default.dim.italic("Took " + (Date.now() - timeStart) + " ms"));
808
- let address = fastify2.listeningOrigin;
809
- if (process.env.NODE_ENV !== "production") {
810
- address = address.replace(/http:\/\/\[::\]/, "http://localhost");
811
- }
812
- const apiServer = import_ansis3.default.magenta(`${address}${options.apiRootPath}`);
813
- const graphqlEndpoint = import_ansis3.default.magenta(`${apiServer}graphql`);
814
- console.log(`API server listening at ${apiServer}`);
815
- console.log(`GraphQL endpoint at ${graphqlEndpoint}`);
816
- process?.send?.("ready");
817
- }
818
- var import_ansis3, import_fastify_web;
819
- var init_apiCLIConfigHandler = __esm({
820
- "src/apiCLIConfigHandler.ts"() {
821
- "use strict";
822
- import_ansis3 = __toESM(require("ansis"), 1);
823
- import_fastify_web = require("@cedarjs/fastify-web");
824
- init_createServer();
825
- }
826
- });
827
-
828
- // src/bothCLIConfigHandler.ts
829
- async function handler2(options) {
830
- const timeStart = Date.now();
831
- console.log(import_ansis4.default.dim.italic("Starting API and Web Servers..."));
832
- options.webHost ??= getWebHost();
833
- options.webPort ??= getWebPort();
834
- options.apiHost ??= getAPIHost();
835
- options.apiPort ??= getAPIPort();
836
- options.apiRootPath = (0, import_fastify_web2.coerceRootPath)(options.apiRootPath ?? "/");
837
- const apiProxyTarget = [
838
- "http://",
839
- options.apiHost.includes(":") ? `[${options.apiHost}]` : options.apiHost,
840
- ":",
841
- options.apiPort,
842
- options.apiRootPath
843
- ].join("");
844
- const webFastify = await createFastifyInstance();
845
- webFastify.register(import_fastify_web2.redwoodFastifyWeb, {
846
- redwood: {
847
- apiProxyTarget
848
- }
849
- });
850
- const apiFastify = await createServer({
851
- apiRootPath: options.apiRootPath
852
- });
853
- await webFastify.listen({
854
- port: options.webPort,
855
- host: options.webHost,
856
- listenTextResolver: getListenTextResolver("Web")
857
- });
858
- webFastify.log.trace(
859
- { custom: { ...webFastify.initialConfig } },
860
- "Fastify server configuration"
861
- );
862
- webFastify.log.trace(`Registered plugins
863
- ${webFastify.printPlugins()}`);
864
- await apiFastify.listen({
865
- port: options.apiPort,
866
- host: options.apiHost,
867
- listenTextResolver: getListenTextResolver("API")
868
- });
869
- apiFastify.log.trace(
870
- { custom: { ...apiFastify.initialConfig } },
871
- "Fastify server configuration"
872
- );
873
- apiFastify.log.trace(`Registered plugins
874
- ${apiFastify.printPlugins()}`);
875
- console.log(import_ansis4.default.dim.italic("Took " + (Date.now() - timeStart) + " ms"));
876
- const webServer = import_ansis4.default.green(webFastify.listeningOrigin);
877
- const apiServer = import_ansis4.default.magenta(
878
- `${apiFastify.listeningOrigin}${options.apiRootPath}`
879
- );
880
- const graphqlEndpoint = import_ansis4.default.magenta(`${apiServer}graphql`);
881
- console.log(`Web server listening at ${webServer}`);
882
- console.log(`API server listening at ${apiServer}`);
883
- console.log(`GraphQL endpoint at ${graphqlEndpoint}`);
884
- process?.send?.("ready");
885
- }
886
- function getListenTextResolver(side) {
887
- return (address) => {
888
- if (process.env.NODE_ENV !== "production") {
889
- address = address.replace(/http:\/\/\[::\]/, "http://localhost");
890
- }
891
- return `${side} server listening at ${address}`;
892
- };
893
- }
894
- var import_ansis4, import_fastify_web2;
895
- var init_bothCLIConfigHandler = __esm({
896
- "src/bothCLIConfigHandler.ts"() {
897
- "use strict";
898
- import_ansis4 = __toESM(require("ansis"), 1);
899
- import_fastify_web2 = require("@cedarjs/fastify-web");
900
- init_cliHelpers();
901
- init_createServer();
902
- init_fastify();
903
- }
904
- });
905
-
906
- // src/bin.ts
907
- var import_path2 = __toESM(require("path"), 1);
908
- var import_dotenv_defaults2 = require("dotenv-defaults");
909
- var import_helpers4 = require("yargs/helpers");
910
- var import_yargs = __toESM(require("yargs/yargs"), 1);
911
- var import_project_config6 = require("@cedarjs/project-config");
912
- var import_web_server = require("@cedarjs/web-server");
913
-
914
- // src/apiCLIConfig.ts
915
- var description = "Start a server for serving the api side";
916
- function builder(yargs2) {
917
- yargs2.options({
918
- port: {
919
- description: "The port to listen at",
920
- type: "number",
921
- alias: "p"
922
- },
923
- host: {
924
- description: "The host to listen at. Note that you most likely want this to be '0.0.0.0' in production",
925
- type: "string"
926
- },
927
- apiRootPath: {
928
- description: "Root path where your api functions are served",
929
- type: "string",
930
- alias: ["api-root-path", "rootPath", "root-path"],
931
- default: "/"
932
- },
933
- // This became a no-op in v7 because env files weren't loaded by default
934
- // but removing it would break yargs parsing for older projects,
935
- // so leaving it here so that yargs doesn't throw an error
936
- loadEnvFiles: {
937
- hidden: true
938
- }
939
- });
940
- }
941
-
942
- // src/bin.ts
943
- init_apiCLIConfigHandler();
944
-
945
- // src/bothCLIConfig.ts
946
- var description2 = "Start a server for serving the api and web sides";
947
- function builder2(yargs2) {
948
- yargs2.options({
949
- webPort: {
950
- description: "The port for the web server to listen on",
951
- type: "number",
952
- alias: ["web-port"]
953
- },
954
- webHost: {
955
- description: "The host for the web server to listen on. Note that you most likely want this to be '0.0.0.0' in production",
956
- type: "string",
957
- alias: ["web-host"]
958
- },
959
- apiPort: {
960
- description: "The port for the api server to listen on",
961
- type: "number",
962
- alias: ["api-port"]
963
- },
964
- apiHost: {
965
- description: "The host for the api server to listen on. Note that you most likely want this to be '0.0.0.0' in production",
966
- type: "string",
967
- alias: ["api-host"]
968
- },
969
- apiRootPath: {
970
- description: "Root path where your api functions are served",
971
- type: "string",
972
- alias: ["api-root-path", "rootPath", "root-path"],
973
- default: "/"
974
- }
975
- });
976
- }
977
-
978
- // src/bin.ts
979
- init_bothCLIConfigHandler();
980
- if (!process.env.CEDAR_ENV_FILES_LOADED) {
981
- (0, import_dotenv_defaults2.config)({
982
- path: import_path2.default.join((0, import_project_config6.getPaths)().base, ".env"),
983
- defaults: import_path2.default.join((0, import_project_config6.getPaths)().base, ".env.defaults"),
984
- multiline: true
985
- });
986
- process.env.CEDAR_ENV_FILES_LOADED = "true";
987
- }
988
- process.env.NODE_ENV ??= "production";
989
- (0, import_yargs.default)((0, import_helpers4.hideBin)(process.argv)).scriptName("cedar-server").strict().alias("h", "help").alias("v", "version").command(
990
- "$0",
991
- description2,
992
- // @ts-expect-error The yargs types seem wrong; it's ok for builder to be a function
993
- builder2,
994
- handler2
995
- ).command(
996
- "api",
997
- description,
998
- // @ts-expect-error The yargs types seem wrong; it's ok for builder to be a function
999
- builder,
1000
- handler
1001
- ).command(
1002
- "web",
1003
- import_web_server.description,
1004
- // @ts-expect-error The yargs types seem wrong; it's ok for builder to be a function
1005
- import_web_server.builder,
1006
- import_web_server.handler
1007
- ).parse();