@webiny/handler 0.0.0-unstable.b14eaecf38 → 0.0.0-unstable.b6d7105cee

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 (100) hide show
  1. package/Context.d.ts +4 -5
  2. package/Context.js +11 -38
  3. package/Context.js.map +1 -1
  4. package/PreHandler/IPreHandler.d.ts +9 -0
  5. package/PreHandler/IPreHandler.js +8 -0
  6. package/PreHandler/IPreHandler.js.map +1 -0
  7. package/PreHandler/IfNotOptionsRequest.d.ts +9 -0
  8. package/PreHandler/IfNotOptionsRequest.js +18 -0
  9. package/PreHandler/IfNotOptionsRequest.js.map +1 -0
  10. package/PreHandler/IfOptionsRequest.d.ts +9 -0
  11. package/PreHandler/IfOptionsRequest.js +18 -0
  12. package/PreHandler/IfOptionsRequest.js.map +1 -0
  13. package/PreHandler/PreHandler.d.ts +9 -0
  14. package/PreHandler/PreHandler.js +16 -0
  15. package/PreHandler/PreHandler.js.map +1 -0
  16. package/PreHandler/ProcessBeforeHandlerPlugins.d.ts +10 -0
  17. package/PreHandler/ProcessBeforeHandlerPlugins.js +25 -0
  18. package/PreHandler/ProcessBeforeHandlerPlugins.js.map +1 -0
  19. package/PreHandler/ProcessContextPlugins.d.ts +10 -0
  20. package/PreHandler/ProcessContextPlugins.js +25 -0
  21. package/PreHandler/ProcessContextPlugins.js.map +1 -0
  22. package/PreHandler/ProcessHandlerOnRequestPlugins.d.ts +10 -0
  23. package/PreHandler/ProcessHandlerOnRequestPlugins.js +25 -0
  24. package/PreHandler/ProcessHandlerOnRequestPlugins.js.map +1 -0
  25. package/PreHandler/RegisterExtensions.d.ts +10 -0
  26. package/PreHandler/RegisterExtensions.js +13 -0
  27. package/PreHandler/RegisterExtensions.js.map +1 -0
  28. package/PreHandler/SendEarlyOptionsResponse.d.ts +9 -0
  29. package/PreHandler/SendEarlyOptionsResponse.js +26 -0
  30. package/PreHandler/SendEarlyOptionsResponse.js.map +1 -0
  31. package/PreHandler/SetDefaultHeaders.d.ts +9 -0
  32. package/PreHandler/SetDefaultHeaders.js +46 -0
  33. package/PreHandler/SetDefaultHeaders.js.map +1 -0
  34. package/README.md +10 -14
  35. package/ResponseHeaders.d.ts +24 -0
  36. package/ResponseHeaders.js +36 -0
  37. package/ResponseHeaders.js.map +1 -0
  38. package/abstractions/Reply.d.ts +5 -0
  39. package/abstractions/Reply.js +5 -0
  40. package/abstractions/Reply.js.map +1 -0
  41. package/abstractions/Request.d.ts +5 -0
  42. package/abstractions/Request.js +5 -0
  43. package/abstractions/Request.js.map +1 -0
  44. package/abstractions/Route.d.ts +25 -0
  45. package/abstractions/Route.js +30 -0
  46. package/abstractions/Route.js.map +1 -0
  47. package/exports/api.d.ts +1 -0
  48. package/exports/api.js +1 -0
  49. package/fastify.d.ts +8 -5
  50. package/fastify.js +306 -412
  51. package/fastify.js.map +1 -1
  52. package/index.d.ts +19 -9
  53. package/index.js +19 -104
  54. package/package.json +23 -29
  55. package/plugins/BeforeHandlerPlugin.d.ts +1 -1
  56. package/plugins/BeforeHandlerPlugin.js +16 -26
  57. package/plugins/BeforeHandlerPlugin.js.map +1 -1
  58. package/plugins/EventPlugin.d.ts +3 -3
  59. package/plugins/EventPlugin.js +13 -30
  60. package/plugins/EventPlugin.js.map +1 -1
  61. package/plugins/HandlerErrorPlugin.d.ts +6 -3
  62. package/plugins/HandlerErrorPlugin.js +16 -24
  63. package/plugins/HandlerErrorPlugin.js.map +1 -1
  64. package/plugins/HandlerOnRequestPlugin.d.ts +9 -8
  65. package/plugins/HandlerOnRequestPlugin.js +16 -24
  66. package/plugins/HandlerOnRequestPlugin.js.map +1 -1
  67. package/plugins/HandlerResultPlugin.d.ts +1 -1
  68. package/plugins/HandlerResultPlugin.js +16 -24
  69. package/plugins/HandlerResultPlugin.js.map +1 -1
  70. package/plugins/ModifyFastifyPlugin.d.ts +2 -2
  71. package/plugins/ModifyFastifyPlugin.js +16 -24
  72. package/plugins/ModifyFastifyPlugin.js.map +1 -1
  73. package/plugins/ModifyResponseHeadersPlugin.d.ts +14 -0
  74. package/plugins/ModifyResponseHeadersPlugin.js +19 -0
  75. package/plugins/ModifyResponseHeadersPlugin.js.map +1 -0
  76. package/plugins/OnRequestResponseSendPlugin.d.ts +26 -0
  77. package/plugins/OnRequestResponseSendPlugin.js +17 -0
  78. package/plugins/OnRequestResponseSendPlugin.js.map +1 -0
  79. package/plugins/OnRequestTimeoutPlugin.d.ts +12 -0
  80. package/plugins/OnRequestTimeoutPlugin.js +17 -0
  81. package/plugins/OnRequestTimeoutPlugin.js.map +1 -0
  82. package/plugins/RegisterExtensionPlugin.d.ts +12 -0
  83. package/plugins/RegisterExtensionPlugin.js +16 -0
  84. package/plugins/RegisterExtensionPlugin.js.map +1 -0
  85. package/plugins/RoutePlugin.d.ts +2 -2
  86. package/plugins/RoutePlugin.js +13 -21
  87. package/plugins/RoutePlugin.js.map +1 -1
  88. package/stringifyError.d.ts +5 -0
  89. package/stringifyError.js +15 -0
  90. package/stringifyError.js.map +1 -0
  91. package/suppressPunycodeWarnings.d.ts +1 -0
  92. package/suppressPunycodeWarnings.js +7 -0
  93. package/suppressPunycodeWarnings.js.map +1 -0
  94. package/types.d.ts +11 -14
  95. package/types.js +1 -18
  96. package/index.js.map +0 -1
  97. package/middleware.d.ts +0 -4
  98. package/middleware.js +0 -45
  99. package/middleware.js.map +0 -1
  100. package/types.js.map +0 -1
package/fastify.js CHANGED
@@ -1,427 +1,321 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
- Object.defineProperty(exports, "__esModule", {
5
- value: true
6
- });
7
- exports.createHandler = void 0;
8
- var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
9
- var _fastify = _interopRequireDefault(require("fastify"));
10
- var _utils = require("@webiny/utils");
11
- var _Context = require("./Context");
12
- var _error = _interopRequireDefault(require("@webiny/error"));
13
- var _RoutePlugin = require("./plugins/RoutePlugin");
14
- var _handlerClient = require("@webiny/handler-client");
15
- var _cookie = _interopRequireDefault(require("@fastify/cookie"));
16
- var _compress = _interopRequireDefault(require("@fastify/compress"));
17
- var _middleware = require("./middleware");
18
- var _api = require("@webiny/api");
19
- var _BeforeHandlerPlugin = require("./plugins/BeforeHandlerPlugin");
20
- var _HandlerResultPlugin = require("./plugins/HandlerResultPlugin");
21
- var _HandlerErrorPlugin = require("./plugins/HandlerErrorPlugin");
22
- var _ModifyFastifyPlugin = require("./plugins/ModifyFastifyPlugin");
23
- var _HandlerOnRequestPlugin = require("./plugins/HandlerOnRequestPlugin");
24
- const DEFAULT_HEADERS = (0, _objectSpread2.default)({
25
- "Cache-Control": "no-store",
26
- "Content-Type": "application/json; charset=utf-8",
27
- "Access-Control-Allow-Origin": "*",
28
- "Access-Control-Allow-Headers": "*",
29
- "Access-Control-Allow-Methods": "OPTIONS,POST,GET,DELETE,PUT,PATCH"
30
- }, (0, _utils.getWebinyVersionHeaders)());
31
- const getDefaultHeaders = routes => {
32
- /**
33
- * If we are accepting all headers, just output that one.
34
- */
35
- const keys = Object.keys(routes);
36
- const all = keys.every(key => routes[key].length > 0);
37
- if (all) {
38
- return (0, _objectSpread2.default)((0, _objectSpread2.default)({}, DEFAULT_HEADERS), {}, {
39
- "Access-Control-Allow-Methods": "*"
1
+ import { PluginsContainer } from "@webiny/plugins/types.js";
2
+ import fastify, { LogController } from "fastify";
3
+ import { middleware } from "@webiny/utils";
4
+ import { Context } from "./Context.js";
5
+ import _webiny_error from "@webiny/error";
6
+ import { RoutePlugin } from "./plugins/RoutePlugin.js";
7
+ import cookie from "@fastify/cookie";
8
+ import compress from "@fastify/compress";
9
+ import { ContextPlugin } from "@webiny/api";
10
+ import { BeforeHandlerPlugin } from "./plugins/BeforeHandlerPlugin.js";
11
+ import { HandlerResultPlugin } from "./plugins/HandlerResultPlugin.js";
12
+ import { HandlerErrorPlugin } from "./plugins/HandlerErrorPlugin.js";
13
+ import { ModifyFastifyPlugin } from "./plugins/ModifyFastifyPlugin.js";
14
+ import { HandlerOnRequestPlugin } from "./plugins/HandlerOnRequestPlugin.js";
15
+ import { ResponseHeaders } from "./ResponseHeaders.js";
16
+ import { ModifyResponseHeadersPlugin } from "./plugins/ModifyResponseHeadersPlugin.js";
17
+ import { SetDefaultHeaders } from "./PreHandler/SetDefaultHeaders.js";
18
+ import { PreHandler } from "./PreHandler/PreHandler.js";
19
+ import { stringifyError } from "./stringifyError.js";
20
+ import { ProcessHandlerOnRequestPlugins } from "./PreHandler/ProcessHandlerOnRequestPlugins.js";
21
+ import { ProcessContextPlugins } from "./PreHandler/ProcessContextPlugins.js";
22
+ import { IfNotOptionsRequest } from "./PreHandler/IfNotOptionsRequest.js";
23
+ import { ProcessBeforeHandlerPlugins } from "./PreHandler/ProcessBeforeHandlerPlugins.js";
24
+ import { IfOptionsRequest } from "./PreHandler/IfOptionsRequest.js";
25
+ import { SendEarlyOptionsResponse } from "./PreHandler/SendEarlyOptionsResponse.js";
26
+ import { OnRequestTimeoutPlugin } from "./plugins/OnRequestTimeoutPlugin.js";
27
+ import { OnRequestResponseSendPlugin } from "./plugins/OnRequestResponseSendPlugin.js";
28
+ import { Request } from "./abstractions/Request.js";
29
+ import { Reply } from "./abstractions/Reply.js";
30
+ import { RegisterExtensionPlugin } from "./plugins/RegisterExtensionPlugin.js";
31
+ import { RegisterExtensions } from "./PreHandler/RegisterExtensions.js";
32
+ const modifyResponseHeaders = (app, request, reply)=>{
33
+ const modifyHeaders = app.webiny.plugins.byType(ModifyResponseHeadersPlugin.type);
34
+ const replyHeaders = reply.getHeaders();
35
+ const headers = ResponseHeaders.create(replyHeaders);
36
+ modifyHeaders.forEach((plugin)=>{
37
+ plugin.modify(request, headers);
40
38
  });
41
- }
42
- return (0, _objectSpread2.default)((0, _objectSpread2.default)({}, DEFAULT_HEADERS), {}, {
43
- "Access-Control-Allow-Methods": keys.filter(type => {
44
- if (!routes[type] || Array.isArray(routes[type]) === false) {
45
- return false;
46
- }
47
- return routes[type].length > 0;
48
- }).sort().join(",")
49
- });
50
- };
51
- const stringifyError = error => {
52
- var _error$constructor;
53
- const {
54
- name,
55
- message,
56
- code,
57
- stack,
58
- data
59
- } = error;
60
- return JSON.stringify((0, _objectSpread2.default)((0, _objectSpread2.default)({}, error), {}, {
61
- constructorName: ((_error$constructor = error.constructor) === null || _error$constructor === void 0 ? void 0 : _error$constructor.name) || "UnknownError",
62
- name: name || "No error name",
63
- message: message || "No error message",
64
- code: code || "NO_CODE",
65
- data,
66
- stack: process.env.DEBUG === "true" ? stack : "Turn on the debug flag to see the stack."
67
- }));
68
- };
69
- const OPTIONS_HEADERS = {
70
- "Access-Control-Max-Age": "86400",
71
- "Cache-Control": "public, max-age=86400"
39
+ const headersToSet = headers.getHeaders();
40
+ delete headersToSet["set-cookie"];
41
+ reply.headers(headersToSet);
72
42
  };
73
- const createHandler = params => {
74
- const definedRoutes = {
75
- POST: [],
76
- GET: [],
77
- OPTIONS: [],
78
- DELETE: [],
79
- PATCH: [],
80
- PUT: [],
81
- HEAD: [],
82
- COPY: [],
83
- LOCK: [],
84
- MKCOL: [],
85
- MOVE: [],
86
- PROPFIND: [],
87
- PROPPATCH: [],
88
- SEARCH: [],
89
- TRACE: [],
90
- UNLOCK: []
91
- };
92
- const throwOnDefinedRoute = (type, path, options) => {
93
- if (type === "ALL") {
94
- const all = Object.keys(definedRoutes).find(key => {
95
- const routes = definedRoutes[key];
96
- return routes.includes(path);
97
- });
98
- if (!all) {
99
- return;
100
- }
101
- console.error(`Error while registering onAll route. One of the routes is already defined.`);
102
- console.error(JSON.stringify(all));
103
- throw new _error.default(`You cannot override a route with onAll() method, please remove unnecessary route from the system.`, "OVERRIDE_ROUTE_ERROR", {
104
- type,
105
- path
106
- });
107
- } else if (definedRoutes[type].includes(path) === false) {
108
- return;
109
- } else if ((options === null || options === void 0 ? void 0 : options.override) === true) {
110
- return;
111
- }
112
- console.error(`Error while trying to override route: [${type}] ${path}`);
113
- throw new _error.default(`When you are trying to override existing route, you must send "override" parameter when adding that route.`, "OVERRIDE_ROUTE_ERROR", {
114
- type,
115
- path
43
+ const createHandler = (params)=>{
44
+ const definedRoutes = {
45
+ POST: [],
46
+ GET: [],
47
+ OPTIONS: [],
48
+ DELETE: [],
49
+ PATCH: [],
50
+ PUT: [],
51
+ HEAD: [],
52
+ COPY: [],
53
+ LOCK: [],
54
+ MKCOL: [],
55
+ MOVE: [],
56
+ PROPFIND: [],
57
+ PROPPATCH: [],
58
+ SEARCH: [],
59
+ TRACE: [],
60
+ UNLOCK: [],
61
+ REPORT: [],
62
+ MKCALENDAR: []
63
+ };
64
+ const throwOnDefinedRoute = (type, path, options)=>{
65
+ if ("ALL" === type) {
66
+ const all = Object.keys(definedRoutes).find((k)=>{
67
+ const key = k.toUpperCase();
68
+ const routes = definedRoutes[key];
69
+ return routes.includes(path);
70
+ });
71
+ if (!all) return;
72
+ console.error("Error while registering onAll route. One of the routes is already defined.");
73
+ console.error(JSON.stringify(all));
74
+ throw new _webiny_error("You cannot override a route with onAll() method, please remove unnecessary route from the system.", "OVERRIDE_ROUTE_ERROR", {
75
+ type,
76
+ path
77
+ });
78
+ }
79
+ if (false === definedRoutes[type].includes(path)) return;
80
+ if (options?.override === true) return;
81
+ console.error(`Error while trying to override route: [${type}] ${path}`);
82
+ throw new _webiny_error('When you are trying to override existing route, you must send "override" parameter when adding that route.', "OVERRIDE_ROUTE_ERROR", {
83
+ type,
84
+ path
85
+ });
86
+ };
87
+ const addDefinedRoute = (input, path)=>{
88
+ const type = input.toUpperCase();
89
+ if (!definedRoutes[type]) return;
90
+ if (definedRoutes[type].includes(path)) return;
91
+ definedRoutes[type].push(path);
92
+ };
93
+ const app = fastify({
94
+ bodyLimit: 536870912,
95
+ logController: new LogController({
96
+ disableRequestLogging: true
97
+ }),
98
+ allowErrorHandlerOverride: true,
99
+ ...params.options || {}
116
100
  });
117
- };
118
- const addDefinedRoute = (type, path) => {
119
- if (!definedRoutes[type]) {
120
- return;
121
- } else if (definedRoutes[type].includes(path)) {
122
- return;
123
- }
124
- definedRoutes[type].push(path);
125
- };
126
- /**
127
- * We must attach the server to our internal context if we want to have it accessible.
128
- */
129
- const app = (0, _fastify.default)((0, _objectSpread2.default)({}, params.options || {}));
130
- /**
131
- * We need to register routes in our system so we can output headers later on and dissallow overriding routes.
132
- */
133
- app.addHook("onRoute", route => {
134
- const method = route.method;
135
- if (Array.isArray(method)) {
136
- for (const m of method) {
137
- addDefinedRoute(m, route.path);
138
- }
139
- return;
140
- }
141
- addDefinedRoute(method, route.path);
142
- });
143
- /**
144
- * ############################
145
- * Register the Fastify plugins.
146
- */
147
- /**
148
- * Package @fastify/cookie
149
- *
150
- * https://github.com/fastify/fastify-cookie
151
- */
152
- app.register(_cookie.default, {
153
- parseOptions: {} // options for parsing cookies
154
- });
155
- /**
156
- * Package @fastify/compress
157
- *
158
- * https://github.com/fastify/fastify-compress
159
- */
160
- app.register(_compress.default, {
161
- global: true,
162
- threshold: 1024,
163
- onUnsupportedEncoding: (encoding, _, reply) => {
164
- reply.code(406);
165
- return `We do not support the ${encoding} encoding.`;
166
- },
167
- inflateIfDeflated: true
168
- });
169
- /**
170
- * Route helpers - mostly for users.
171
- */
172
- const routes = {
173
- defined: definedRoutes,
174
- onPost: (path, handler, options) => {
175
- throwOnDefinedRoute("POST", path, options);
176
- app.post(path, handler);
177
- },
178
- onGet: (path, handler, options) => {
179
- throwOnDefinedRoute("GET", path, options);
180
- app.get(path, handler);
181
- },
182
- onOptions: (path, handler, options) => {
183
- throwOnDefinedRoute("OPTIONS", path, options);
184
- app.options(path, handler);
185
- },
186
- onDelete: (path, handler, options) => {
187
- throwOnDefinedRoute("DELETE", path, options);
188
- app.delete(path, handler);
189
- },
190
- onPatch: (path, handler, options) => {
191
- throwOnDefinedRoute("PATCH", path, options);
192
- app.patch(path, handler);
193
- },
194
- onPut: (path, handler, options) => {
195
- throwOnDefinedRoute("PUT", path, options);
196
- app.put(path, handler);
197
- },
198
- onAll: (path, handler, options) => {
199
- throwOnDefinedRoute("ALL", path, options);
200
- app.all(path, handler);
201
- },
202
- onHead: (path, handler, options) => {
203
- throwOnDefinedRoute("HEAD", path, options);
204
- app.head(path, handler);
205
- }
206
- };
207
- let context;
208
- try {
209
- context = new _Context.Context({
210
- plugins: [
211
- /**
212
- * We must have handlerClient by default.
213
- * And it must be one of the first context plugins applied.
214
- */
215
- (0, _handlerClient.createHandlerClient)(), ...(params.plugins || [])],
216
- /**
217
- * Inserted via webpack on build time.
218
- */
219
- WEBINY_VERSION: process.env.WEBINY_VERSION,
220
- server: app,
221
- routes
101
+ app.addHook("onRoute", (route)=>{
102
+ const method = route.method;
103
+ if (Array.isArray(method)) {
104
+ for (const m of method)addDefinedRoute(m, route.path);
105
+ return;
106
+ }
107
+ addDefinedRoute(method, route.path);
222
108
  });
223
- } catch (ex) {
224
- console.error(`Error while constructing the Context.`);
225
- console.error(stringifyError(ex));
226
- throw ex;
227
- }
228
-
229
- /**
230
- * We are attaching our custom context to webiny variable on the fastify app, so it is accessible everywhere.
231
- */
232
- app.decorate("webiny", context);
233
-
234
- /**
235
- * We have few types of triggers:
236
- * * Events - EventPlugin
237
- * * Routes - RoutePlugin
238
- *
239
- * Routes are registered in fastify but events must be handled in package which implements cloud specific methods.
240
- */
241
- const routePlugins = app.webiny.plugins.byType(_RoutePlugin.RoutePlugin.type);
242
-
243
- /**
244
- * Add routes to the system.
245
- */
246
- let routePluginName;
247
- try {
248
- for (const plugin of routePlugins) {
249
- routePluginName = plugin.name;
250
- plugin.cb((0, _objectSpread2.default)((0, _objectSpread2.default)({}, app.webiny.routes), {}, {
251
- context: app.webiny
252
- }));
253
- }
254
- } catch (ex) {
255
- console.error(`Error while running the "RoutePlugin" ${routePluginName ? `(${routePluginName})` : ""} plugin in the beginning of the "createHandler" callable.`);
256
- console.error(stringifyError(ex));
257
- throw ex;
258
- }
259
-
260
- /**
261
- * On every request we add default headers, which can be changed later.
262
- * Also, if it is an options request, we skip everything after this hook and output options headers.
263
- */
264
- app.addHook("onRequest", async (request, reply) => {
265
- /**
266
- * Our default headers are always set. Users can override them.
267
- */
268
- const defaultHeaders = getDefaultHeaders(definedRoutes);
269
- reply.headers(defaultHeaders);
270
- /**
271
- * Users can define their own custom handlers for the onRequest event - so let's run them first.
272
- */
273
- const plugins = app.webiny.plugins.byType(_HandlerOnRequestPlugin.HandlerOnRequestPlugin.type);
274
- let name;
275
- try {
276
- for (const plugin of plugins) {
277
- name = plugin.name;
278
- const result = await plugin.exec(request, reply);
279
- if (result === false) {
280
- return;
109
+ app.register(cookie, {
110
+ parseOptions: {}
111
+ });
112
+ app.register(compress, {
113
+ global: true,
114
+ threshold: 1024,
115
+ onUnsupportedEncoding: (encoding, _, reply)=>{
116
+ reply.code(406);
117
+ return `We do not support the ${encoding} encoding.`;
118
+ },
119
+ inflateIfDeflated: true
120
+ });
121
+ const routes = {
122
+ defined: definedRoutes,
123
+ onPost: (path, handler, options)=>{
124
+ throwOnDefinedRoute("POST", path, options);
125
+ app.post(path, handler);
126
+ },
127
+ onGet: (path, handler, options)=>{
128
+ throwOnDefinedRoute("GET", path, options);
129
+ app.get(path, handler);
130
+ },
131
+ onOptions: (path, handler, options)=>{
132
+ throwOnDefinedRoute("OPTIONS", path, options);
133
+ app.options(path, handler);
134
+ },
135
+ onDelete: (path, handler, options)=>{
136
+ throwOnDefinedRoute("DELETE", path, options);
137
+ app.delete(path, handler);
138
+ },
139
+ onPatch: (path, handler, options)=>{
140
+ throwOnDefinedRoute("PATCH", path, options);
141
+ app.patch(path, handler);
142
+ },
143
+ onPut: (path, handler, options)=>{
144
+ throwOnDefinedRoute("PUT", path, options);
145
+ app.put(path, handler);
146
+ },
147
+ onAll: (path, handler, options)=>{
148
+ throwOnDefinedRoute("ALL", path, options);
149
+ app.all(path, handler);
150
+ },
151
+ onHead: (path, handler, options)=>{
152
+ throwOnDefinedRoute("HEAD", path, options);
153
+ app.head(path, handler);
281
154
  }
282
- }
283
- } catch (ex) {
284
- console.error(`Error while running the "HandlerOnRequestPlugin" ${name ? `(${name})` : ""} plugin in the onRequest hook.`);
285
- console.error(stringifyError(ex));
286
- throw ex;
287
- }
288
- /**
289
- * When we receive the OPTIONS request, we end it before it goes any further as there is no need for anything to run after this - at least for our use cases.
290
- *
291
- * Users can prevent this by creating their own HandlerOnRequestPlugin and returning false as the result of the callable.
292
- */
293
- if (request.method !== "OPTIONS") {
294
- return;
295
- }
296
- if (reply.sent) {
297
- /**
298
- * At this point throwing an exception will not do anything with the response. So just log it.
299
- */
300
- console.error(JSON.stringify({
301
- message: `Output was already sent. Please check custom plugins of type "HandlerOnRequestPlugin".`,
302
- explanation: "This error can happen if the user plugin ended the reply, but did not return false as response."
303
- }));
304
- return;
305
- }
306
- reply.headers((0, _objectSpread2.default)((0, _objectSpread2.default)({}, defaultHeaders), OPTIONS_HEADERS)).code(204).send("").hijack();
307
- });
308
- app.addHook("preParsing", async (request, reply) => {
309
- app.webiny.request = request;
310
- app.webiny.reply = reply;
311
- const plugins = app.webiny.plugins.byType(_api.ContextPlugin.type);
312
- let name;
155
+ };
156
+ let context;
157
+ const plugins = new PluginsContainer([]);
158
+ plugins.merge(params.plugins || []);
313
159
  try {
314
- for (const plugin of plugins) {
315
- name = plugin.name;
316
- await plugin.apply(app.webiny);
317
- }
160
+ context = new Context({
161
+ plugins,
162
+ WEBINY_VERSION: process.env.WEBINY_VERSION,
163
+ routes
164
+ });
318
165
  } catch (ex) {
319
- console.error(`Error while running the "ContextPlugin" ${name ? `(${name})` : ""} plugin in the preParsing hook.`);
320
- console.error(stringifyError(ex));
321
- throw ex;
166
+ console.error("Error while constructing the Context.");
167
+ console.error(stringifyError(ex));
168
+ throw ex;
322
169
  }
323
- });
324
- /**
325
- *
326
- */
327
- app.addHook("preHandler", async () => {
328
- const plugins = app.webiny.plugins.byType(_BeforeHandlerPlugin.BeforeHandlerPlugin.type);
329
- let name;
170
+ app.decorate("webiny", context);
171
+ app.addContentTypeParser("application/json", {
172
+ parseAs: "string",
173
+ bodyLimit: 1048576
174
+ }, (req, body, done)=>{
175
+ if ("OPTIONS" === req.method) return void done(null, void 0);
176
+ try {
177
+ const json = "string" == typeof body ? body : body.toString("utf8");
178
+ done(null, JSON.parse(json));
179
+ } catch (err) {
180
+ done(err);
181
+ }
182
+ });
183
+ app.addHook("onRequest", async (request)=>{
184
+ if ("OPTIONS" === request.method && void 0 === request.body) request.headers["content-type"] = void 0;
185
+ });
186
+ app.addHook("preHandler", async (request, reply)=>{
187
+ app.webiny.request = request;
188
+ app.webiny.reply = reply;
189
+ if (app.webiny.container) {
190
+ app.webiny.container.registerInstance(Request, request);
191
+ app.webiny.container.registerInstance(Reply, reply);
192
+ }
193
+ reply.code(200);
194
+ const handlerOnRequestPlugins = app.webiny.plugins.byType(HandlerOnRequestPlugin.type);
195
+ const contextPlugins = app.webiny.plugins.byType(ContextPlugin.type);
196
+ const beforeHandlerPlugins = app.webiny.plugins.byType(BeforeHandlerPlugin.type);
197
+ const modifyHeadersPlugins = app.webiny.plugins.byType(ModifyResponseHeadersPlugin.type);
198
+ const registerExtensionPlugins = app.webiny.plugins.byType(RegisterExtensionPlugin.type);
199
+ const preHandler = new PreHandler([
200
+ new RegisterExtensions(registerExtensionPlugins),
201
+ new SetDefaultHeaders(definedRoutes),
202
+ new ProcessHandlerOnRequestPlugins(handlerOnRequestPlugins),
203
+ new IfNotOptionsRequest([
204
+ new ProcessContextPlugins(app.webiny, contextPlugins),
205
+ new ProcessBeforeHandlerPlugins(app.webiny, beforeHandlerPlugins)
206
+ ]),
207
+ new IfOptionsRequest([
208
+ new SendEarlyOptionsResponse(modifyHeadersPlugins)
209
+ ])
210
+ ]);
211
+ await preHandler.execute(request, reply, app.webiny);
212
+ });
213
+ app.addHook("preSerialization", async (_, __, payload)=>{
214
+ const plugins = app.webiny.plugins.byType(HandlerResultPlugin.type);
215
+ let name;
216
+ try {
217
+ for (const plugin of plugins){
218
+ name = plugin.name;
219
+ await plugin.handle(app.webiny, payload);
220
+ }
221
+ } catch (ex) {
222
+ console.error(`Error while running the "HandlerResultPlugin" ${name ? `(${name})` : ""} plugin in the preSerialization hook.`);
223
+ console.error(stringifyError(ex));
224
+ throw ex;
225
+ }
226
+ return payload;
227
+ });
228
+ app.setErrorHandler(async (error, _, reply)=>{
229
+ if (reply.sent) {
230
+ console.warn("Reply already sent, cannot send the result (handler:setErrorHandler).");
231
+ return reply;
232
+ }
233
+ if (error.code?.startsWith("Authentication/")) return reply.status(401).headers({
234
+ "Cache-Control": "no-store"
235
+ }).send(JSON.stringify({
236
+ message: error.message,
237
+ code: error.code
238
+ }));
239
+ if ("Tenancy/TenantDisabled" === error.code) return reply.status(503).headers({
240
+ "Cache-Control": "no-store"
241
+ }).send(JSON.stringify({
242
+ message: error.message,
243
+ code: error.code
244
+ }));
245
+ return reply.status(500).headers({
246
+ "Cache-Control": "no-store"
247
+ }).send(JSON.stringify({
248
+ message: error.message,
249
+ code: error.code,
250
+ data: error.data
251
+ }));
252
+ });
253
+ app.addHook("onError", async (_, reply, error)=>{
254
+ const plugins = app.webiny.plugins.byType(HandlerErrorPlugin.type);
255
+ console.error("Logging error in @webiny/handler");
256
+ try {
257
+ console.error(stringifyError(error));
258
+ } catch (ex) {
259
+ console.warn("Could not stringify error:");
260
+ console.log(error);
261
+ console.error("Stringify error:", ex);
262
+ }
263
+ if (reply.sent) console.warn("Reply already sent, cannot send the result (handler:addHook:onError).");
264
+ else reply.status(500).headers({
265
+ "Cache-Control": "no-store"
266
+ }).send(JSON.stringify({
267
+ message: error.message,
268
+ code: error.code,
269
+ data: error.data
270
+ }));
271
+ const handler = middleware(plugins.map((pl)=>(context, error, next)=>pl.handle(context, error, next)));
272
+ await handler(app.webiny, error);
273
+ return reply;
274
+ });
275
+ app.addHook("onSend", async (request, reply, input)=>{
276
+ modifyResponseHeaders(app, request, reply);
277
+ const plugins = app.webiny.plugins.byType(OnRequestResponseSendPlugin.type);
278
+ let payload = input;
279
+ for (const plugin of plugins)payload = await plugin.exec(request, reply, payload);
280
+ return payload;
281
+ });
282
+ app.addHook("onResponse", async ()=>{
283
+ await context.benchmark.output();
284
+ });
285
+ app.addHook("onTimeout", async (request, reply)=>{
286
+ const plugins = app.webiny.plugins.byType(OnRequestTimeoutPlugin.type);
287
+ for (const plugin of plugins)await plugin.exec(request, reply);
288
+ await context.benchmark.output();
289
+ });
290
+ const modifyPlugins = app.webiny.plugins.byType(ModifyFastifyPlugin.type);
291
+ let modifyFastifyPluginName;
330
292
  try {
331
- for (const plugin of plugins) {
332
- name = plugin.name;
333
- await plugin.apply(app.webiny);
334
- }
293
+ for (const plugin of modifyPlugins){
294
+ modifyFastifyPluginName = plugin.name;
295
+ plugin.modify(app);
296
+ }
335
297
  } catch (ex) {
336
- console.error(`Error while running the "BeforeHandlerPlugin" ${name ? `(${name})` : ""} plugin in the preHandler hook.`);
337
- console.error(stringifyError(ex));
338
- throw ex;
298
+ console.error(`Error while running the "ModifyFastifyPlugin" ${modifyFastifyPluginName ? `(${modifyFastifyPluginName})` : ""} plugin in the end of the "createHandler" callable.`);
299
+ console.error(stringifyError(ex));
300
+ throw ex;
339
301
  }
340
- });
341
-
342
- /**
343
- *
344
- */
345
- const preSerialization = async (_, __, payload) => {
346
- const plugins = app.webiny.plugins.byType(_HandlerResultPlugin.HandlerResultPlugin.type);
347
- let name;
302
+ const routePlugins = app.webiny.plugins.byType(RoutePlugin.type);
303
+ let routePluginName;
348
304
  try {
349
- for (const plugin of plugins) {
350
- name = plugin.name;
351
- await plugin.handle(app.webiny, payload);
352
- }
305
+ for (const plugin of routePlugins){
306
+ routePluginName = plugin.name;
307
+ plugin.cb({
308
+ ...app.webiny.routes,
309
+ context: app.webiny
310
+ });
311
+ }
353
312
  } catch (ex) {
354
- console.error(`Error while running the "HandlerResultPlugin" ${name ? `(${name})` : ""} plugin in the preSerialization hook.`);
355
- console.error(stringifyError(ex));
356
- throw ex;
313
+ console.error(`Error while running the "RoutePlugin" ${routePluginName ? `(${routePluginName})` : ""} plugin in the beginning of the "createHandler" callable.`);
314
+ console.error(stringifyError(ex));
315
+ throw ex;
357
316
  }
358
- return payload;
359
- };
360
- app.addHook("preSerialization", preSerialization);
361
- app.setErrorHandler(async (error, request, reply) => {
362
- return reply.status(500).headers({
363
- "Cache-Control": "no-store"
364
- }).send(
365
- /**
366
- * When we are sending the error in the response, we cannot send the whole error object, as it might contain some sensitive data.
367
- */
368
- JSON.stringify({
369
- message: error.message,
370
- code: error.code,
371
- data: error.data
372
- }));
373
- });
374
- app.addHook("onError", async (_, reply, error) => {
375
- const plugins = app.webiny.plugins.byType(_HandlerErrorPlugin.HandlerErrorPlugin.type);
376
- /**
377
- * Log error to cloud, as these can be extremely annoying to debug!
378
- */
379
- console.error("@webiny/handler");
380
- console.error(stringifyError(error));
381
- reply.status(500).headers({
382
- "Cache-Control": "no-store"
383
- }).send(
384
- /**
385
- * When we are sending the error in the response, we cannot send the whole error object, as it might contain some sensitive data.
386
- */
387
- JSON.stringify({
388
- message: error.message,
389
- code: error.code,
390
- data: error.data
391
- }));
392
- const handler = (0, _middleware.middleware)(plugins.map(pl => {
393
- return (context, error, next) => {
394
- return pl.handle(context, error, next);
395
- };
396
- }));
397
- await handler(app.webiny, error);
398
- return reply;
399
- });
400
- /**
401
- * We need to output the benchmark results at the end of the request in both response and timeout cases
402
- */
403
- app.addHook("onResponse", async () => {
404
- await context.benchmark.output();
405
- });
406
- app.addHook("onTimeout", async () => {
407
- await context.benchmark.output();
408
- });
409
-
410
- /**
411
- * With these plugins we give users possibility to do anything they want on our fastify instance.
412
- */
413
- const modifyPlugins = app.webiny.plugins.byType(_ModifyFastifyPlugin.ModifyFastifyPlugin.type);
414
- let modifyFastifyPluginName;
415
- try {
416
- for (const plugin of modifyPlugins) {
417
- modifyFastifyPluginName = plugin.name;
418
- plugin.modify(app);
419
- }
420
- } catch (ex) {
421
- console.error(`Error while running the "ModifyFastifyPlugin" ${modifyFastifyPluginName ? `(${modifyFastifyPluginName})` : ""} plugin in the end of the "createHandler" callable.`);
422
- console.error(stringifyError(ex));
423
- throw ex;
424
- }
425
- return app;
317
+ return app;
426
318
  };
427
- exports.createHandler = createHandler;
319
+ export { createHandler };
320
+
321
+ //# sourceMappingURL=fastify.js.map