@cedarjs/api-server 9.0.0-canary.1784 → 9.0.0-canary.3124

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