@webiny/handler 0.0.0-unstable.9bd236cf5e → 0.0.0-unstable.9f53ea597d

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