@adonisjs/http-server 7.7.0 → 8.0.0-next.1

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 (65) hide show
  1. package/build/chunk-ASX56VAK.js +76 -0
  2. package/build/{chunk-6FSCILWX.js → chunk-HMYAZG76.js} +986 -616
  3. package/build/factories/http_context.d.ts +3 -3
  4. package/build/factories/http_server.d.ts +1 -1
  5. package/build/factories/main.d.ts +6 -6
  6. package/build/factories/main.js +87 -87
  7. package/build/factories/qs_parser_factory.d.ts +2 -2
  8. package/build/factories/request.d.ts +2 -2
  9. package/build/factories/response.d.ts +3 -3
  10. package/build/factories/router.d.ts +1 -1
  11. package/build/factories/server_factory.d.ts +2 -2
  12. package/build/factories/url_builder_factory.d.ts +25 -0
  13. package/build/index.d.ts +16 -15
  14. package/build/index.js +25 -23
  15. package/build/src/cookies/client.d.ts +2 -2
  16. package/build/src/cookies/parser.d.ts +2 -2
  17. package/build/src/cookies/serializer.d.ts +8 -2
  18. package/build/src/define_config.d.ts +1 -1
  19. package/build/src/define_middleware.d.ts +4 -3
  20. package/build/src/{exceptions.d.ts → errors.d.ts} +20 -6
  21. package/build/src/exception_handler.d.ts +4 -4
  22. package/build/src/helpers.d.ts +50 -15
  23. package/build/src/helpers.js +18 -0
  24. package/build/src/http_context/local_storage.d.ts +1 -1
  25. package/build/src/http_context/main.d.ts +5 -5
  26. package/build/src/qs.d.ts +3 -3
  27. package/build/src/redirect.d.ts +5 -5
  28. package/build/src/request.d.ts +12 -11
  29. package/build/src/response.d.ts +6 -6
  30. package/build/src/router/brisk.d.ts +6 -5
  31. package/build/src/router/executor.d.ts +4 -4
  32. package/build/src/router/factories/use_return_value.d.ts +6 -1
  33. package/build/src/router/group.d.ts +6 -6
  34. package/build/src/router/{lookup_store → legacy}/url_builder.d.ts +20 -4
  35. package/build/src/router/main.d.ts +117 -21
  36. package/build/src/router/resource.d.ts +4 -4
  37. package/build/src/router/route.d.ts +3 -3
  38. package/build/src/router/signed_url_builder.d.ts +15 -0
  39. package/build/src/router/store.d.ts +2 -2
  40. package/build/src/router/url_builder.d.ts +14 -0
  41. package/build/src/server/factories/middleware_handler.d.ts +4 -4
  42. package/build/src/server/factories/route_finder.d.ts +10 -0
  43. package/build/src/server/factories/write_response.d.ts +1 -1
  44. package/build/src/server/main.d.ts +12 -8
  45. package/build/src/tracing_channels.d.ts +23 -0
  46. package/build/src/types/main.d.ts +7 -7
  47. package/build/src/types/main.js +0 -1
  48. package/build/src/types/middleware.d.ts +35 -2
  49. package/build/src/types/request.d.ts +4 -0
  50. package/build/src/types/response.d.ts +1 -1
  51. package/build/src/types/route.d.ts +50 -49
  52. package/build/src/types/server.d.ts +5 -5
  53. package/build/src/types/tracing_channels.d.ts +6 -0
  54. package/build/src/types/url_builder.d.ts +147 -0
  55. package/build/src/utils.d.ts +28 -0
  56. package/package.json +45 -38
  57. package/build/chunk-6FSCILWX.js.map +0 -1
  58. package/build/factories/main.js.map +0 -1
  59. package/build/index.js.map +0 -1
  60. package/build/src/router/lookup_store/main.d.ts +0 -48
  61. package/build/src/router/lookup_store/route_finder.d.ts +0 -25
  62. package/build/src/router/parser.d.ts +0 -5
  63. package/build/src/server/factories/final_handler.d.ts +0 -10
  64. package/build/src/types/base.d.ts +0 -19
  65. package/build/src/types/main.js.map +0 -1
@@ -1,22 +1,211 @@
1
- var __defProp = Object.defineProperty;
2
- var __export = (target, all) => {
3
- for (var name in all)
4
- __defProp(target, name, { get: all[name], enumerable: true });
1
+ import {
2
+ __export,
3
+ default as default2,
4
+ default2 as default3,
5
+ parseRoute,
6
+ serializeCookie
7
+ } from "./chunk-ASX56VAK.js";
8
+
9
+ // src/errors.ts
10
+ var errors_exports = {};
11
+ __export(errors_exports, {
12
+ E_CANNOT_LOOKUP_ROUTE: () => E_CANNOT_LOOKUP_ROUTE,
13
+ E_HTTP_EXCEPTION: () => E_HTTP_EXCEPTION,
14
+ E_HTTP_REQUEST_ABORTED: () => E_HTTP_REQUEST_ABORTED,
15
+ E_ROUTE_NOT_FOUND: () => E_ROUTE_NOT_FOUND
16
+ });
17
+ import { createError, Exception } from "@poppinss/utils/exception";
18
+ var E_ROUTE_NOT_FOUND = createError(
19
+ "Cannot %s:%s",
20
+ "E_ROUTE_NOT_FOUND",
21
+ 404
22
+ );
23
+ var E_CANNOT_LOOKUP_ROUTE = createError(
24
+ 'Cannot lookup route "%s"',
25
+ "E_CANNOT_LOOKUP_ROUTE",
26
+ 500
27
+ );
28
+ var E_HTTP_EXCEPTION = class HttpException extends Exception {
29
+ body;
30
+ static code = "E_HTTP_EXCEPTION";
31
+ /**
32
+ * This method returns an instance of the exception class
33
+ */
34
+ static invoke(body, status, code = "E_HTTP_EXCEPTION") {
35
+ if (body === null || body === void 0) {
36
+ const error2 = new this("HTTP Exception", { status, code });
37
+ error2.body = "Internal server error";
38
+ return error2;
39
+ }
40
+ if (typeof body === "object") {
41
+ const error2 = new this(body.message || "HTTP Exception", { status, code });
42
+ error2.body = body;
43
+ return error2;
44
+ }
45
+ const error = new this(body, { status, code });
46
+ error.body = body;
47
+ return error;
48
+ }
49
+ };
50
+ var E_HTTP_REQUEST_ABORTED = class AbortException extends E_HTTP_EXCEPTION {
51
+ handle(error, ctx) {
52
+ ctx.response.status(error.status).send(error.body);
53
+ }
54
+ };
55
+
56
+ // src/cookies/drivers/plain.ts
57
+ import base64 from "@poppinss/utils/base64";
58
+ import { MessageBuilder } from "@poppinss/utils";
59
+ function pack(value) {
60
+ if (value === void 0 || value === null) {
61
+ return null;
62
+ }
63
+ return base64.urlEncode(new MessageBuilder().build(value));
64
+ }
65
+ function canUnpack(encodedValue) {
66
+ return typeof encodedValue === "string";
67
+ }
68
+ function unpack(encodedValue) {
69
+ return new MessageBuilder().verify(base64.urlDecode(encodedValue, "utf-8", false));
70
+ }
71
+
72
+ // src/cookies/drivers/signed.ts
73
+ function pack2(key, value, encryption) {
74
+ if (value === void 0 || value === null) {
75
+ return null;
76
+ }
77
+ return `s:${encryption.verifier.sign(value, void 0, key)}`;
78
+ }
79
+ function canUnpack2(signedValue) {
80
+ return typeof signedValue === "string" && signedValue.substring(0, 2) === "s:";
81
+ }
82
+ function unpack2(key, signedValue, encryption) {
83
+ const value = signedValue.slice(2);
84
+ if (!value) {
85
+ return null;
86
+ }
87
+ return encryption.verifier.unsign(value, key);
88
+ }
89
+
90
+ // src/cookies/drivers/encrypted.ts
91
+ function pack3(key, value, encryption) {
92
+ if (value === void 0 || value === null) {
93
+ return null;
94
+ }
95
+ return `e:${encryption.encrypt(value, void 0, key)}`;
96
+ }
97
+ function canUnpack3(encryptedValue) {
98
+ return typeof encryptedValue === "string" && encryptedValue.substring(0, 2) === "e:";
99
+ }
100
+ function unpack3(key, encryptedValue, encryption) {
101
+ const value = encryptedValue.slice(2);
102
+ if (!value) {
103
+ return null;
104
+ }
105
+ return encryption.decrypt(value, key);
106
+ }
107
+
108
+ // src/cookies/client.ts
109
+ var CookieClient = class {
110
+ #encryption;
111
+ constructor(encryption) {
112
+ this.#encryption = encryption;
113
+ }
114
+ /**
115
+ * Encrypt a key value pair to be sent in the cookie header
116
+ */
117
+ encrypt(key, value) {
118
+ return pack3(key, value, this.#encryption);
119
+ }
120
+ /**
121
+ * Sign a key value pair to be sent in the cookie header
122
+ */
123
+ sign(key, value) {
124
+ return pack2(key, value, this.#encryption);
125
+ }
126
+ /**
127
+ * Encode a key value pair to be sent in the cookie header
128
+ */
129
+ encode(_, value, stringify2 = true) {
130
+ return stringify2 ? pack(value) : value;
131
+ }
132
+ /**
133
+ * Unsign a signed cookie value
134
+ */
135
+ unsign(key, value) {
136
+ return canUnpack2(value) ? unpack2(key, value, this.#encryption) : null;
137
+ }
138
+ /**
139
+ * Decrypt an encrypted cookie value
140
+ */
141
+ decrypt(key, value) {
142
+ return canUnpack3(value) ? unpack3(key, value, this.#encryption) : null;
143
+ }
144
+ /**
145
+ * Decode an encoded cookie value
146
+ */
147
+ decode(_, value, stringified = true) {
148
+ if (!stringified) {
149
+ return value;
150
+ }
151
+ return canUnpack(value) ? unpack(value) : null;
152
+ }
153
+ /**
154
+ * Parse response cookie
155
+ */
156
+ parse(key, value) {
157
+ if (canUnpack2(value)) {
158
+ return unpack2(key, value, this.#encryption);
159
+ }
160
+ if (canUnpack3(value)) {
161
+ return unpack3(key, value, this.#encryption);
162
+ }
163
+ if (canUnpack(value)) {
164
+ return unpack(value);
165
+ }
166
+ }
5
167
  };
6
168
 
169
+ // src/tracing_channels.ts
170
+ var tracing_channels_exports = {};
171
+ __export(tracing_channels_exports, {
172
+ httpExceptionHandler: () => httpExceptionHandler,
173
+ httpMiddleware: () => httpMiddleware,
174
+ httpRequest: () => httpRequest,
175
+ httpResponseSerializer: () => httpResponseSerializer,
176
+ httpRouteHandler: () => httpRouteHandler
177
+ });
178
+ import diagnostics_channel from "diagnostics_channel";
179
+ var httpRequest = diagnostics_channel.tracingChannel("adonisjs:http.request");
180
+ var httpMiddleware = diagnostics_channel.tracingChannel("adonisjs:http.middleware");
181
+ var httpExceptionHandler = diagnostics_channel.tracingChannel(
182
+ "adonisjs:http.exception.handler"
183
+ );
184
+ var httpRouteHandler = diagnostics_channel.tracingChannel("adonisjs:http.route.handler");
185
+ var httpResponseSerializer = diagnostics_channel.tracingChannel(
186
+ "adonisjs:http.response.serializer"
187
+ );
188
+
7
189
  // src/router/route.ts
8
190
  import is from "@sindresorhus/is";
9
191
  import Macroable4 from "@poppinss/macroable";
10
192
  import Middleware from "@poppinss/middleware";
11
- import { RuntimeException as RuntimeException2 } from "@poppinss/utils";
193
+ import { RuntimeException as RuntimeException2 } from "@poppinss/utils/exception";
12
194
  import { moduleCaller, moduleImporter } from "@adonisjs/fold";
13
195
 
196
+ // src/debug.ts
197
+ import { debuglog } from "util";
198
+ var debug_default = debuglog("adonisjs:http");
199
+
14
200
  // src/router/factories/use_return_value.ts
201
+ function canWriteResponseBody(value, ctx) {
202
+ return value !== void 0 && // Return value is explicitly defined
203
+ !ctx.response.hasLazyBody && // Lazy body is not set
204
+ value !== ctx.response;
205
+ }
15
206
  function useReturnValue(ctx) {
16
207
  return function(value) {
17
- if (value !== void 0 && // Return value is explicitly defined
18
- !ctx.response.hasLazyBody && // Lazy body is not set
19
- value !== ctx.response) {
208
+ if (canWriteResponseBody(value, ctx)) {
20
209
  ctx.response.send(value);
21
210
  }
22
211
  };
@@ -24,22 +213,50 @@ function useReturnValue(ctx) {
24
213
 
25
214
  // src/router/executor.ts
26
215
  function execute(route, resolver, ctx, errorResponder) {
27
- return route.middleware.runner().errorHandler((error) => errorResponder(error, ctx)).finalHandler(async () => {
216
+ return route.middleware.runner().errorHandler((error) => errorResponder(error, ctx)).finalHandler(() => {
28
217
  if (typeof route.handler === "function") {
29
- return Promise.resolve(route.handler(ctx)).then(useReturnValue(ctx));
30
- }
31
- return route.handler.handle(resolver, ctx).then(useReturnValue(ctx));
218
+ return httpRouteHandler.tracePromise(
219
+ ($ctx) => Promise.resolve(route.handler($ctx)),
220
+ route,
221
+ void 0,
222
+ ctx
223
+ ).then(useReturnValue(ctx));
224
+ }
225
+ return httpRouteHandler.tracePromise(
226
+ route.handler.handle,
227
+ route,
228
+ void 0,
229
+ resolver,
230
+ ctx
231
+ ).then(useReturnValue(ctx));
32
232
  }).run(async (middleware, next) => {
33
233
  if (typeof middleware === "function") {
34
- return middleware(ctx, next);
234
+ return httpMiddleware.tracePromise(
235
+ middleware,
236
+ middleware,
237
+ void 0,
238
+ ctx,
239
+ next
240
+ );
35
241
  }
36
- return middleware.handle(resolver, ctx, next, middleware.args);
242
+ return httpMiddleware.tracePromise(
243
+ middleware.handle,
244
+ middleware,
245
+ void 0,
246
+ resolver,
247
+ ctx,
248
+ next,
249
+ middleware.args
250
+ );
37
251
  });
38
252
  }
39
253
 
40
- // src/helpers.ts
254
+ // src/utils.ts
41
255
  import Cache from "tmp-cache";
42
- import { InvalidArgumentsException } from "@poppinss/utils";
256
+ import { InvalidArgumentsException } from "@poppinss/utils/exception";
257
+
258
+ // src/router/group.ts
259
+ import Macroable3 from "@poppinss/macroable";
43
260
 
44
261
  // src/router/brisk.ts
45
262
  import Macroable from "@poppinss/macroable";
@@ -87,7 +304,8 @@ var BriskRoute = class extends Macroable {
87
304
  * Redirects to a given route. Params from the original request will
88
305
  * be used when no custom params are defined.
89
306
  */
90
- redirect(identifier, params, options) {
307
+ redirect(...args) {
308
+ const [identifier, params, options] = args;
91
309
  function redirectsToRoute(ctx) {
92
310
  const redirector = ctx.response.redirect();
93
311
  if (options?.status) {
@@ -114,13 +332,10 @@ var BriskRoute = class extends Macroable {
114
332
  }
115
333
  };
116
334
 
117
- // src/router/group.ts
118
- import Macroable3 from "@poppinss/macroable";
119
-
120
335
  // src/router/resource.ts
121
336
  import string from "@poppinss/utils/string";
122
337
  import Macroable2 from "@poppinss/macroable";
123
- import { RuntimeException } from "@poppinss/utils";
338
+ import { RuntimeException } from "@poppinss/utils/exception";
124
339
  var RouteResource = class extends Macroable2 {
125
340
  /**
126
341
  * Resource identifier. Nested resources are separated
@@ -534,7 +749,7 @@ var RouteGroup = class _RouteGroup extends Macroable3 {
534
749
  }
535
750
  };
536
751
 
537
- // src/helpers.ts
752
+ // src/utils.ts
538
753
  var proxyCache = new Cache({ max: 200 });
539
754
  function dropSlash(input) {
540
755
  if (input === "/") {
@@ -600,10 +815,65 @@ function parseRange(range, value) {
600
815
  {}
601
816
  );
602
817
  }
603
-
604
- // src/debug.ts
605
- import { debuglog } from "util";
606
- var debug_default = debuglog("adonisjs:http");
818
+ function decodeComponentChar(highCharCode, lowCharCode) {
819
+ if (highCharCode === 50) {
820
+ if (lowCharCode === 53) return "%";
821
+ if (lowCharCode === 51) return "#";
822
+ if (lowCharCode === 52) return "$";
823
+ if (lowCharCode === 54) return "&";
824
+ if (lowCharCode === 66) return "+";
825
+ if (lowCharCode === 98) return "+";
826
+ if (lowCharCode === 67) return ",";
827
+ if (lowCharCode === 99) return ",";
828
+ if (lowCharCode === 70) return "/";
829
+ if (lowCharCode === 102) return "/";
830
+ return null;
831
+ }
832
+ if (highCharCode === 51) {
833
+ if (lowCharCode === 65) return ":";
834
+ if (lowCharCode === 97) return ":";
835
+ if (lowCharCode === 66) return ";";
836
+ if (lowCharCode === 98) return ";";
837
+ if (lowCharCode === 68) return "=";
838
+ if (lowCharCode === 100) return "=";
839
+ if (lowCharCode === 70) return "?";
840
+ if (lowCharCode === 102) return "?";
841
+ return null;
842
+ }
843
+ if (highCharCode === 52 && lowCharCode === 48) {
844
+ return "@";
845
+ }
846
+ return null;
847
+ }
848
+ function safeDecodeURI(path, useSemicolonDelimiter) {
849
+ let shouldDecode = false;
850
+ let shouldDecodeParam = false;
851
+ let querystring = "";
852
+ for (let i = 1; i < path.length; i++) {
853
+ const charCode = path.charCodeAt(i);
854
+ if (charCode === 37) {
855
+ const highCharCode = path.charCodeAt(i + 1);
856
+ const lowCharCode = path.charCodeAt(i + 2);
857
+ if (decodeComponentChar(highCharCode, lowCharCode) === null) {
858
+ shouldDecode = true;
859
+ } else {
860
+ shouldDecodeParam = true;
861
+ if (highCharCode === 50 && lowCharCode === 53) {
862
+ shouldDecode = true;
863
+ path = path.slice(0, i + 1) + "25" + path.slice(i + 1);
864
+ i += 2;
865
+ }
866
+ i += 2;
867
+ }
868
+ } else if (charCode === 63 || charCode === 35 || charCode === 59 && useSemicolonDelimiter) {
869
+ querystring = path.slice(i + 1);
870
+ path = path.slice(0, i);
871
+ break;
872
+ }
873
+ }
874
+ const decodedPath = shouldDecode ? decodeURI(path) : path;
875
+ return { pathname: decodedPath, query: querystring, shouldDecodeParam };
876
+ }
607
877
 
608
878
  // src/router/route.ts
609
879
  var Route = class extends Macroable4 {
@@ -850,16 +1120,20 @@ var Route = class extends Macroable4 {
850
1120
  debug_default("adding named middleware to route %s, %O", this.#pattern, one);
851
1121
  middleware.add(one);
852
1122
  });
1123
+ middleware.freeze();
853
1124
  return middleware;
854
1125
  }
855
1126
  /**
856
1127
  * Returns JSON representation of the route
857
1128
  */
858
1129
  toJSON() {
1130
+ const pattern = this.#computePattern();
1131
+ const matchers = this.#getMatchers();
859
1132
  return {
860
1133
  domain: this.#routeDomain,
861
- pattern: this.#computePattern(),
862
- matchers: this.#getMatchers(),
1134
+ pattern,
1135
+ matchers,
1136
+ tokens: parseRoute(pattern, matchers),
863
1137
  meta: {},
864
1138
  name: this.#name,
865
1139
  handler: this.#handler,
@@ -870,135 +1144,24 @@ var Route = class extends Macroable4 {
870
1144
  }
871
1145
  };
872
1146
 
873
- // src/cookies/drivers/plain.ts
874
- import { base64, MessageBuilder } from "@poppinss/utils";
875
- function pack(value) {
876
- if (value === void 0 || value === null) {
877
- return null;
878
- }
879
- return base64.urlEncode(new MessageBuilder().build(value));
880
- }
881
- function canUnpack(encodedValue) {
882
- return typeof encodedValue === "string";
883
- }
884
- function unpack(encodedValue) {
885
- return new MessageBuilder().verify(base64.urlDecode(encodedValue, "utf-8", false));
886
- }
887
-
888
- // src/cookies/drivers/signed.ts
889
- function pack2(key, value, encryption) {
890
- if (value === void 0 || value === null) {
891
- return null;
892
- }
893
- return `s:${encryption.verifier.sign(value, void 0, key)}`;
894
- }
895
- function canUnpack2(signedValue) {
896
- return typeof signedValue === "string" && signedValue.substring(0, 2) === "s:";
897
- }
898
- function unpack2(key, signedValue, encryption) {
899
- const value = signedValue.slice(2);
900
- if (!value) {
901
- return null;
902
- }
903
- return encryption.verifier.unsign(value, key);
904
- }
905
-
906
- // src/cookies/drivers/encrypted.ts
907
- function pack3(key, value, encryption) {
908
- if (value === void 0 || value === null) {
909
- return null;
910
- }
911
- return `e:${encryption.encrypt(value, void 0, key)}`;
912
- }
913
- function canUnpack3(encryptedValue) {
914
- return typeof encryptedValue === "string" && encryptedValue.substring(0, 2) === "e:";
915
- }
916
- function unpack3(key, encryptedValue, encryption) {
917
- const value = encryptedValue.slice(2);
918
- if (!value) {
919
- return null;
920
- }
921
- return encryption.decrypt(value, key);
922
- }
1147
+ // src/request.ts
1148
+ import fresh from "fresh";
1149
+ import typeIs from "type-is";
1150
+ import accepts from "accepts";
1151
+ import { isIP } from "net";
1152
+ import is2 from "@sindresorhus/is";
1153
+ import proxyaddr from "proxy-addr";
1154
+ import { safeEqual } from "@poppinss/utils";
1155
+ import Macroable5 from "@poppinss/macroable";
1156
+ import lodash from "@poppinss/utils/lodash";
923
1157
 
924
- // src/cookies/client.ts
925
- var CookieClient = class {
926
- #encryption;
927
- constructor(encryption) {
928
- this.#encryption = encryption;
929
- }
1158
+ // src/cookies/parser.ts
1159
+ import cookie from "cookie";
1160
+ var CookieParser = class {
1161
+ #client;
930
1162
  /**
931
- * Encrypt a key value pair to be sent in the cookie header
932
- */
933
- encrypt(key, value) {
934
- return pack3(key, value, this.#encryption);
935
- }
936
- /**
937
- * Sign a key value pair to be sent in the cookie header
938
- */
939
- sign(key, value) {
940
- return pack2(key, value, this.#encryption);
941
- }
942
- /**
943
- * Encode a key value pair to be sent in the cookie header
944
- */
945
- encode(_, value) {
946
- return pack(value);
947
- }
948
- /**
949
- * Unsign a signed cookie value
950
- */
951
- unsign(key, value) {
952
- return canUnpack2(value) ? unpack2(key, value, this.#encryption) : null;
953
- }
954
- /**
955
- * Decrypt an encrypted cookie value
956
- */
957
- decrypt(key, value) {
958
- return canUnpack3(value) ? unpack3(key, value, this.#encryption) : null;
959
- }
960
- /**
961
- * Decode an encoded cookie value
962
- */
963
- decode(_, value) {
964
- return canUnpack(value) ? unpack(value) : null;
965
- }
966
- /**
967
- * Parse response cookie
968
- */
969
- parse(key, value) {
970
- if (canUnpack2(value)) {
971
- return unpack2(key, value, this.#encryption);
972
- }
973
- if (canUnpack3(value)) {
974
- return unpack3(key, value, this.#encryption);
975
- }
976
- if (canUnpack(value)) {
977
- return unpack(value);
978
- }
979
- }
980
- };
981
-
982
- // src/request.ts
983
- import fresh from "fresh";
984
- import typeIs from "type-is";
985
- import accepts from "accepts";
986
- import { isIP } from "net";
987
- import is2 from "@sindresorhus/is";
988
- import proxyaddr from "proxy-addr";
989
- import { safeEqual } from "@poppinss/utils";
990
- import Macroable5 from "@poppinss/macroable";
991
- import lodash from "@poppinss/utils/lodash";
992
- import { createId } from "@paralleldrive/cuid2";
993
- import { parse } from "url";
994
-
995
- // src/cookies/parser.ts
996
- import cookie from "cookie";
997
- var CookieParser = class {
998
- #client;
999
- /**
1000
- * A copy of cached cookies, they are cached during a request after
1001
- * initial decoding, unsigning or decrypting.
1163
+ * A copy of cached cookies, they are cached during a request after
1164
+ * initial decoding, unsigning or decrypting.
1002
1165
  */
1003
1166
  #cachedCookies = {
1004
1167
  signedCookies: {},
@@ -1025,10 +1188,10 @@ var CookieParser = class {
1025
1188
  }
1026
1189
  /**
1027
1190
  * Attempts to decode a cookie by the name. When calling this method,
1028
- * you are assuming that the cookie was just encoded in the first
1191
+ * you are assuming that the cookie was just stringified in the first
1029
1192
  * place and not signed or encrypted.
1030
1193
  */
1031
- decode(key, encoded = true) {
1194
+ decode(key, stringified = true) {
1032
1195
  const value = this.#cookies[key];
1033
1196
  if (value === null || value === void 0) {
1034
1197
  return null;
@@ -1037,7 +1200,7 @@ var CookieParser = class {
1037
1200
  if (cache[key] !== void 0) {
1038
1201
  return cache[key];
1039
1202
  }
1040
- const parsed = encoded ? this.#client.decode(key, value) : value;
1203
+ const parsed = this.#client.decode(key, value, stringified);
1041
1204
  if (parsed !== null) {
1042
1205
  cache[key] = parsed;
1043
1206
  }
@@ -1100,7 +1263,7 @@ var Request = class extends Macroable5 {
1100
1263
  this.#qsParser = qsParser;
1101
1264
  this.#config = config;
1102
1265
  this.#encryption = encryption;
1103
- this.parsedUrl = parse(this.request.url, false);
1266
+ this.parsedUrl = safeDecodeURI(request.url, false);
1104
1267
  this.#parseQueryString();
1105
1268
  }
1106
1269
  /**
@@ -1147,9 +1310,7 @@ var Request = class extends Macroable5 {
1147
1310
  */
1148
1311
  #cookieParser;
1149
1312
  /**
1150
- * Parses copy of the URL with query string as a string and not
1151
- * object. This is done to build URL's with query string without
1152
- * stringifying the object
1313
+ * Parsed URL with query string stored as a string.
1153
1314
  */
1154
1315
  parsedUrl;
1155
1316
  /**
@@ -1189,7 +1350,7 @@ var Request = class extends Macroable5 {
1189
1350
  id() {
1190
1351
  let requestId = this.header("x-request-id");
1191
1352
  if (!requestId && this.#config.generateRequestId) {
1192
- requestId = createId();
1353
+ requestId = this.#config.createRequestId();
1193
1354
  this.request.headers["x-request-id"] = requestId;
1194
1355
  }
1195
1356
  return requestId;
@@ -1207,14 +1368,7 @@ var Request = class extends Macroable5 {
1207
1368
  throw new Error('Cannot re-set initial body. Use "request.updateBody" instead');
1208
1369
  }
1209
1370
  this.updateBody(body);
1210
- this.#originalRequestData = Object.freeze(
1211
- lodash.cloneDeepWith(this.#requestData, (value) => {
1212
- if (is2.primitive(value) || Array.isArray(value) || is2.plainObject(value)) {
1213
- return void 0;
1214
- }
1215
- return null;
1216
- })
1217
- );
1371
+ this.#originalRequestData = Object.freeze(lodash.cloneDeep(this.#requestData));
1218
1372
  }
1219
1373
  /**
1220
1374
  * Update the request body with new data object. The `all` property
@@ -1469,11 +1623,11 @@ var Request = class extends Macroable5 {
1469
1623
  if ("encrypted" in this.request.socket) {
1470
1624
  return "https";
1471
1625
  }
1472
- if (!trustProxy(this.request.socket.remoteAddress, this.#config.trustProxy)) {
1473
- return this.parsedUrl.protocol || "http";
1626
+ if (trustProxy(this.request.socket.remoteAddress, this.#config.trustProxy)) {
1627
+ const forwardedProtocol = this.header("X-Forwarded-Proto");
1628
+ return forwardedProtocol ? forwardedProtocol.split(/\s*,\s*/)[0] : "http";
1474
1629
  }
1475
- const forwardedProtocol = this.header("X-Forwarded-Proto");
1476
- return forwardedProtocol ? forwardedProtocol.split(/\s*,\s*/)[0] : "http";
1630
+ return "http";
1477
1631
  }
1478
1632
  /**
1479
1633
  * Returns a boolean telling if request is served over `https`
@@ -1903,8 +2057,7 @@ var Request = class extends Macroable5 {
1903
2057
  };
1904
2058
 
1905
2059
  // src/redirect.ts
1906
- import { parse as parse2 } from "url";
1907
- import encodeUrl from "encodeurl";
2060
+ import { parse } from "url";
1908
2061
  var Redirect = class {
1909
2062
  /**
1910
2063
  * A boolean to forward the existing query string
@@ -1935,7 +2088,7 @@ var Redirect = class {
1935
2088
  const stringified = this.#qs.stringify(query);
1936
2089
  url = stringified ? `${url}?${stringified}` : url;
1937
2090
  debug_default('redirecting to url "%s"', url);
1938
- this.#response.location(encodeUrl(url));
2091
+ this.#response.location(default2(url));
1939
2092
  this.#response.safeStatus(this.#statusCode);
1940
2093
  this.#response.type("text/plain; charset=utf-8");
1941
2094
  this.#response.send(`Redirecting to ${url}`);
@@ -1981,7 +2134,7 @@ var Redirect = class {
1981
2134
  back() {
1982
2135
  let query = {};
1983
2136
  const referrerUrl = this.#getReferrerUrl();
1984
- const url = parse2(referrerUrl);
2137
+ const url = parse(referrerUrl);
1985
2138
  debug_default('referrer url "%s"', referrerUrl);
1986
2139
  debug_default('referrer base url "%s"', url.pathname);
1987
2140
  if (this.#forwardQueryString) {
@@ -1993,12 +2146,13 @@ var Redirect = class {
1993
2146
  /**
1994
2147
  * Redirect the request using a route identifier.
1995
2148
  */
1996
- toRoute(routeIdentifier, params, options) {
2149
+ toRoute(...args) {
2150
+ const [identifier, params, options] = args;
1997
2151
  if (options && options.qs) {
1998
2152
  this.withQs(options.qs);
1999
2153
  options.qs = void 0;
2000
2154
  }
2001
- const url = this.#router.makeUrl(routeIdentifier, params, options);
2155
+ const url = this.#router.urlBuilder.urlFor(identifier, params, options);
2002
2156
  return this.toPath(url);
2003
2157
  }
2004
2158
  /**
@@ -2007,60 +2161,13 @@ var Redirect = class {
2007
2161
  toPath(url) {
2008
2162
  let query = {};
2009
2163
  if (this.#forwardQueryString) {
2010
- query = this.#qs.parse(parse2(this.#request.url).query || "");
2164
+ query = this.#qs.parse(parse(this.#request.url).query || "");
2011
2165
  }
2012
2166
  Object.assign(query, this.#queryString);
2013
2167
  this.#sendResponse(url, query);
2014
2168
  }
2015
2169
  };
2016
2170
 
2017
- // src/exceptions.ts
2018
- var exceptions_exports = {};
2019
- __export(exceptions_exports, {
2020
- E_CANNOT_LOOKUP_ROUTE: () => E_CANNOT_LOOKUP_ROUTE,
2021
- E_HTTP_EXCEPTION: () => E_HTTP_EXCEPTION,
2022
- E_HTTP_REQUEST_ABORTED: () => E_HTTP_REQUEST_ABORTED,
2023
- E_ROUTE_NOT_FOUND: () => E_ROUTE_NOT_FOUND
2024
- });
2025
- import { createError, Exception } from "@poppinss/utils";
2026
- var E_ROUTE_NOT_FOUND = createError(
2027
- "Cannot %s:%s",
2028
- "E_ROUTE_NOT_FOUND",
2029
- 404
2030
- );
2031
- var E_CANNOT_LOOKUP_ROUTE = createError(
2032
- 'Cannot lookup route "%s"',
2033
- "E_CANNOT_LOOKUP_ROUTE",
2034
- 500
2035
- );
2036
- var E_HTTP_EXCEPTION = class HttpException extends Exception {
2037
- body;
2038
- static code = "E_HTTP_EXCEPTION";
2039
- /**
2040
- * This method returns an instance of the exception class
2041
- */
2042
- static invoke(body, status, code = "E_HTTP_EXCEPTION") {
2043
- if (body === null || body === void 0) {
2044
- const error2 = new this("HTTP Exception", { status, code });
2045
- error2.body = "Internal server error";
2046
- return error2;
2047
- }
2048
- if (typeof body === "object") {
2049
- const error2 = new this(body.message || "HTTP Exception", { status, code });
2050
- error2.body = body;
2051
- return error2;
2052
- }
2053
- const error = new this(body, { status, code });
2054
- error.body = body;
2055
- return error;
2056
- }
2057
- };
2058
- var E_HTTP_REQUEST_ABORTED = class AbortException extends E_HTTP_EXCEPTION {
2059
- handle(error, ctx) {
2060
- ctx.response.status(error.status).send(error.body);
2061
- }
2062
- };
2063
-
2064
2171
  // src/response_status.ts
2065
2172
  var ResponseStatus = {
2066
2173
  Continue: 100,
@@ -2128,58 +2235,44 @@ var ResponseStatus = {
2128
2235
  };
2129
2236
 
2130
2237
  // src/response.ts
2131
- import { Buffer as Buffer2 } from "buffer";
2132
2238
  import etag from "etag";
2133
2239
  import vary from "vary";
2134
2240
  import fresh2 from "fresh";
2135
- import mime from "mime-types";
2136
2241
  import destroy from "destroy";
2137
2242
  import { extname } from "path";
2243
+ import { Buffer } from "buffer";
2138
2244
  import onFinished from "on-finished";
2139
- import json from "@poppinss/utils/json";
2245
+ import { stat } from "fs/promises";
2140
2246
  import Macroable6 from "@poppinss/macroable";
2141
2247
  import { createReadStream } from "fs";
2142
- import { stat } from "fs/promises";
2143
- import { RuntimeException as RuntimeException3 } from "@poppinss/utils";
2144
2248
  import contentDisposition from "content-disposition";
2249
+ import { safeStringify } from "@poppinss/utils/json";
2250
+ import { RuntimeException as RuntimeException3 } from "@poppinss/utils/exception";
2145
2251
 
2146
2252
  // src/cookies/serializer.ts
2147
- import cookie2 from "cookie";
2148
- import string2 from "@poppinss/utils/string";
2149
2253
  var CookieSerializer = class {
2150
2254
  #client;
2151
2255
  constructor(encryption) {
2152
2256
  this.#client = new CookieClient(encryption);
2153
2257
  }
2154
- /**
2155
- * Serializes the key-value pair to a string, that can be set on the
2156
- * `Set-Cookie` header.
2157
- */
2158
- #serializeAsCookie(key, value, options) {
2159
- let expires = options?.expires;
2160
- if (typeof expires === "function") {
2161
- expires = expires();
2162
- }
2163
- let maxAge = options?.maxAge ? string2.seconds.parse(options?.maxAge) : void 0;
2164
- const parsedOptions = Object.assign({}, options, { maxAge, expires });
2165
- return cookie2.serialize(key, value, parsedOptions);
2166
- }
2167
2258
  /**
2168
2259
  * Encodes value as a plain cookie. By default, the plain value will be converted
2169
2260
  * to a string using "JSON.stringify" method and then encoded as a base64 string.
2170
2261
  *
2171
- * You can disable encoding of the cookie by setting `options.encoded = false`.
2262
+ * You can disable cookie stringifaction by setting `options.stringify = false`.
2172
2263
  *
2173
2264
  * ```ts
2174
2265
  * serializer.encode('name', 'virk')
2266
+ * serializer.encode('name', 'virk', { stringify: false })
2175
2267
  * ```
2176
2268
  */
2177
2269
  encode(key, value, options) {
2178
- const packedValue = options?.encode === false ? value : this.#client.encode(key, value);
2270
+ const stringify2 = options?.stringify ?? options?.encode;
2271
+ const packedValue = this.#client.encode(key, value, stringify2);
2179
2272
  if (packedValue === null || packedValue === void 0) {
2180
2273
  return null;
2181
2274
  }
2182
- return this.#serializeAsCookie(key, packedValue, options);
2275
+ return serializeCookie(key, packedValue, options);
2183
2276
  }
2184
2277
  /**
2185
2278
  * Sign a key-value pair to a signed cookie. The signed value has a
@@ -2190,7 +2283,7 @@ var CookieSerializer = class {
2190
2283
  if (packedValue === null) {
2191
2284
  return null;
2192
2285
  }
2193
- return this.#serializeAsCookie(key, packedValue, options);
2286
+ return serializeCookie(key, packedValue, options);
2194
2287
  }
2195
2288
  /**
2196
2289
  * Encrypts a key-value pair to an encrypted cookie.
@@ -2200,7 +2293,7 @@ var CookieSerializer = class {
2200
2293
  if (packedValue === null) {
2201
2294
  return null;
2202
2295
  }
2203
- return this.#serializeAsCookie(key, packedValue, options);
2296
+ return serializeCookie(key, packedValue, options);
2204
2297
  }
2205
2298
  };
2206
2299
 
@@ -2351,20 +2444,20 @@ var Response = class extends Macroable6 {
2351
2444
  * - Buffer
2352
2445
  */
2353
2446
  #getDataType(content) {
2354
- if (content instanceof Uint8Array) {
2355
- return "buffer";
2356
- }
2357
- if (content instanceof Date) {
2358
- return "date";
2359
- }
2360
- if (content instanceof RegExp) {
2361
- return "regexp";
2362
- }
2363
2447
  const dataType = typeof content;
2364
2448
  if (dataType === "number" || dataType === "boolean" || dataType === "string" || dataType === "bigint") {
2365
2449
  return dataType;
2366
2450
  }
2367
2451
  if (dataType === "object") {
2452
+ if (content instanceof Uint8Array) {
2453
+ return "buffer";
2454
+ }
2455
+ if (content instanceof RegExp) {
2456
+ return "regexp";
2457
+ }
2458
+ if (content instanceof Date) {
2459
+ return "date";
2460
+ }
2368
2461
  return "object";
2369
2462
  }
2370
2463
  throw new RuntimeException3(`Cannot serialize "${dataType}" to HTTP response`);
@@ -2394,12 +2487,29 @@ var Response = class extends Macroable6 {
2394
2487
  return;
2395
2488
  }
2396
2489
  const dataType = this.#getDataType(content);
2397
- if (dataType === "object") {
2398
- content = json.safeStringify(content);
2399
- } else if (dataType === "number" || dataType === "boolean" || dataType === "bigint" || dataType === "regexp") {
2400
- content = String(content);
2401
- } else if (dataType === "date") {
2402
- content = content.toISOString();
2490
+ let contentType;
2491
+ switch (dataType) {
2492
+ case "string":
2493
+ contentType = content.trimStart().startsWith("<") ? "text/html; charset=utf-8" : "text/plain; charset=utf-8";
2494
+ break;
2495
+ case "number":
2496
+ case "boolean":
2497
+ case "bigint":
2498
+ case "regexp":
2499
+ content = String(content);
2500
+ contentType = "text/plain; charset=utf-8";
2501
+ break;
2502
+ case "date":
2503
+ content = content.toISOString();
2504
+ contentType = "text/plain; charset=utf-8";
2505
+ break;
2506
+ case "buffer":
2507
+ contentType = "application/octet-stream; charset=utf-8";
2508
+ break;
2509
+ case "object":
2510
+ content = safeStringify(content);
2511
+ contentType = "application/json; charset=utf-8";
2512
+ break;
2403
2513
  }
2404
2514
  if (jsonpCallbackName) {
2405
2515
  content = content.replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
@@ -2416,30 +2526,12 @@ var Response = class extends Macroable6 {
2416
2526
  return;
2417
2527
  }
2418
2528
  this.setRequestId();
2419
- this.header("Content-Length", Buffer2.byteLength(content));
2529
+ this.header("Content-Length", Buffer.byteLength(content));
2420
2530
  if (jsonpCallbackName) {
2421
2531
  this.header("X-Content-Type-Options", "nosniff");
2422
2532
  this.safeHeader("Content-Type", "text/javascript; charset=utf-8");
2423
2533
  } else {
2424
- switch (dataType) {
2425
- case "string":
2426
- const type = /^\s*</.test(content) ? "text/html" : "text/plain";
2427
- this.safeHeader("Content-Type", `${type}; charset=utf-8`);
2428
- break;
2429
- case "number":
2430
- case "boolean":
2431
- case "date":
2432
- case "bigint":
2433
- case "regexp":
2434
- this.safeHeader("Content-Type", "text/plain; charset=utf-8");
2435
- break;
2436
- case "buffer":
2437
- this.safeHeader("Content-Type", "application/octet-stream; charset=utf-8");
2438
- break;
2439
- case "object":
2440
- this.safeHeader("Content-Type", "application/json; charset=utf-8");
2441
- break;
2442
- }
2534
+ this.safeHeader("Content-type", contentType);
2443
2535
  }
2444
2536
  this.#endResponse(content);
2445
2537
  }
@@ -2676,7 +2768,7 @@ var Response = class extends Macroable6 {
2676
2768
  */
2677
2769
  type(type, charset) {
2678
2770
  type = charset ? `${type}; charset=${charset}` : type;
2679
- this.header("Content-Type", mime.contentType(type));
2771
+ this.header("Content-Type", default3.contentType(type));
2680
2772
  return this;
2681
2773
  }
2682
2774
  /**
@@ -2963,7 +3055,7 @@ var Response = class extends Macroable6 {
2963
3055
  return;
2964
3056
  }
2965
3057
  if (this.content) {
2966
- this.writeBody(...this.content);
3058
+ httpResponseSerializer.traceSync(this.writeBody, void 0, this, ...this.content);
2967
3059
  return;
2968
3060
  }
2969
3061
  if (this.lazyBody.stream) {
@@ -3275,21 +3367,11 @@ var Response = class extends Macroable6 {
3275
3367
  // src/router/main.ts
3276
3368
  import is3 from "@sindresorhus/is";
3277
3369
  import { moduleImporter as moduleImporter3 } from "@adonisjs/fold";
3278
- import { RuntimeException as RuntimeException6 } from "@poppinss/utils";
3370
+ import { RuntimeException as RuntimeException5 } from "@poppinss/utils/exception";
3279
3371
 
3280
3372
  // src/router/store.ts
3281
- import matchit2 from "@poppinss/matchit";
3282
- import lodash2 from "@poppinss/utils/lodash";
3283
- import { RuntimeException as RuntimeException4 } from "@poppinss/utils";
3284
-
3285
- // src/router/parser.ts
3286
3373
  import matchit from "@poppinss/matchit";
3287
- function parseRoutePattern(pattern, matchers) {
3288
- const tokens = matchit.parse(pattern, matchers);
3289
- return tokens;
3290
- }
3291
-
3292
- // src/router/store.ts
3374
+ import { RuntimeException as RuntimeException4 } from "@poppinss/utils/exception";
3293
3375
  var RoutesStore = class {
3294
3376
  /**
3295
3377
  * A flag to know if routes for explicit domains
@@ -3305,7 +3387,7 @@ var RoutesStore = class {
3305
3387
  */
3306
3388
  #getDomainNode(domain) {
3307
3389
  if (!this.tree.domains[domain]) {
3308
- this.tree.tokens.push(parseRoutePattern(domain));
3390
+ this.tree.tokens.push(parseRoute(domain));
3309
3391
  this.tree.domains[domain] = {};
3310
3392
  }
3311
3393
  return this.tree.domains[domain];
@@ -3374,14 +3456,10 @@ var RoutesStore = class {
3374
3456
  if (route.domain !== "root") {
3375
3457
  this.usingDomains = true;
3376
3458
  }
3377
- const tokens = parseRoutePattern(route.pattern, route.matchers);
3378
- const routeNode = lodash2.merge(
3379
- { meta: {} },
3380
- lodash2.pick(route, ["pattern", "handler", "meta", "middleware", "name", "execute"])
3381
- );
3382
- routeNode.meta.params = this.#collectRouteParams(routeNode, tokens);
3459
+ const routeNode = { ...route };
3460
+ routeNode.meta.params = this.#collectRouteParams(routeNode, route.tokens);
3383
3461
  route.methods.forEach((method) => {
3384
- this.#registerRoute(route.domain, method, tokens, routeNode);
3462
+ this.#registerRoute(route.domain, method, route.tokens, routeNode);
3385
3463
  });
3386
3464
  return this;
3387
3465
  }
@@ -3394,7 +3472,7 @@ var RoutesStore = class {
3394
3472
  * qualified runtime domain. You must call `matchDomain` first to fetch
3395
3473
  * the pattern for qualified domain
3396
3474
  */
3397
- match(url, method, domain) {
3475
+ match(url, method, shouldDecodeParam, domain) {
3398
3476
  const domainName = domain?.tokens[0]?.old || "root";
3399
3477
  const matchedDomain = this.tree.domains[domainName];
3400
3478
  if (!matchedDomain) {
@@ -3404,7 +3482,7 @@ var RoutesStore = class {
3404
3482
  if (!matchedMethod) {
3405
3483
  return null;
3406
3484
  }
3407
- const matchedRoute = matchit2.match(url, matchedMethod.tokens);
3485
+ const matchedRoute = matchit.match(url, matchedMethod.tokens);
3408
3486
  if (!matchedRoute.length) {
3409
3487
  return null;
3410
3488
  }
@@ -3412,8 +3490,8 @@ var RoutesStore = class {
3412
3490
  return {
3413
3491
  route,
3414
3492
  routeKey: matchedMethod.routeKeys[route.pattern],
3415
- params: matchit2.exec(url, matchedRoute),
3416
- subdomains: domain?.hostname ? matchit2.exec(domain.hostname, domain.tokens) : {}
3493
+ params: matchit.exec(url, matchedRoute, shouldDecodeParam),
3494
+ subdomains: domain?.hostname ? matchit.exec(domain.hostname, domain.tokens) : {}
3417
3495
  };
3418
3496
  }
3419
3497
  /**
@@ -3423,20 +3501,12 @@ var RoutesStore = class {
3423
3501
  if (!hostname || !this.usingDomains) {
3424
3502
  return [];
3425
3503
  }
3426
- return matchit2.match(hostname, this.tree.tokens);
3504
+ return matchit.match(hostname, this.tree.tokens);
3427
3505
  }
3428
3506
  };
3429
3507
 
3430
- // src/router/lookup_store/main.ts
3431
- import Macroable7 from "@poppinss/macroable";
3432
-
3433
- // src/router/lookup_store/url_builder.ts
3434
- import { RuntimeException as RuntimeException5 } from "@poppinss/utils";
3508
+ // src/router/legacy/url_builder.ts
3435
3509
  var UrlBuilder = class {
3436
- /**
3437
- * Query string parser
3438
- */
3439
- #qsParser;
3440
3510
  /**
3441
3511
  * The parameters to apply on the route
3442
3512
  */
@@ -3454,89 +3524,19 @@ var UrlBuilder = class {
3454
3524
  * BaseURL to append to the constructored URL
3455
3525
  */
3456
3526
  #baseUrl;
3457
- /**
3458
- * Encryption class for making signed URLs
3459
- */
3460
- #encryption;
3461
3527
  /**
3462
3528
  * Route finder for finding route pattern
3463
3529
  */
3464
- #routeFinder;
3465
- constructor(encryption, routeFinder, qsParser) {
3466
- this.#qsParser = qsParser;
3467
- this.#encryption = encryption;
3468
- this.#routeFinder = routeFinder;
3469
- }
3470
- /**
3471
- * Raises exception when wildcard values array is missing or
3472
- * has length of zero.
3473
- */
3474
- #ensureHasWildCardValues(pattern, values) {
3475
- if (!values || !Array.isArray(values) || !values.length) {
3476
- throw new RuntimeException5(
3477
- `Cannot make URL for "${pattern}" route. Invalid value provided for wildcard param`
3478
- );
3479
- }
3480
- }
3481
- /*
3482
- * Raises exception when value is not defined
3483
- */
3484
- #ensureHasParamValue(pattern, param, value) {
3485
- if (value === void 0 || value === null) {
3486
- throw new RuntimeException5(
3487
- `Cannot make URL for "${pattern}" route. Missing value for "${param}" param`
3488
- );
3489
- }
3490
- }
3491
- /**
3492
- * Processes the pattern against the params
3493
- */
3494
- #processPattern(pattern) {
3495
- const uriSegments = [];
3496
- const paramsArray = Array.isArray(this.#params) ? this.#params : null;
3497
- const paramsObject = !Array.isArray(this.#params) ? this.#params : {};
3498
- let paramsIndex = 0;
3499
- const tokens = parseRoutePattern(pattern);
3500
- for (const token of tokens) {
3501
- if (token.type === 0) {
3502
- uriSegments.push(token.val === "/" ? "" : `${token.val}${token.end}`);
3503
- } else if (token.type === 2) {
3504
- const values = paramsArray ? paramsArray.slice(paramsIndex) : paramsObject["*"];
3505
- this.#ensureHasWildCardValues(pattern, values);
3506
- uriSegments.push(`${values.join("/")}${token.end}`);
3507
- break;
3508
- } else {
3509
- const paramName = token.val;
3510
- const value = paramsArray ? paramsArray[paramsIndex] : paramsObject[paramName];
3511
- if (token.type === 1) {
3512
- this.#ensureHasParamValue(pattern, paramName, value);
3513
- }
3514
- paramsIndex++;
3515
- if (value !== void 0 && value !== null) {
3516
- uriSegments.push(`${value}${token.end}`);
3517
- }
3518
- }
3519
- }
3520
- return `/${uriSegments.join("/")}`;
3521
- }
3522
- /**
3523
- * Suffix the query string to the URL
3524
- */
3525
- #suffixQueryString(url, qs) {
3526
- if (qs) {
3527
- const queryString = this.#qsParser.stringify(qs);
3528
- url = queryString ? `${url}?${queryString}` : url;
3529
- }
3530
- return url;
3531
- }
3532
- /**
3533
- * Prefixes base URL to the uri string
3534
- */
3535
- #prefixBaseUrl(uri) {
3536
- return this.#baseUrl ? `${this.#baseUrl}${uri}` : uri;
3530
+ #router;
3531
+ #domain;
3532
+ constructor(router, domain) {
3533
+ this.#router = router;
3534
+ this.#domain = domain;
3537
3535
  }
3538
3536
  /**
3539
3537
  * Prefix a custom base URL to the final URI
3538
+ * @deprecated
3539
+ * Instead use "@adonisjs/core/services/url_builder" instead
3540
3540
  */
3541
3541
  prefixUrl(url) {
3542
3542
  this.#baseUrl = url;
@@ -3545,6 +3545,8 @@ var UrlBuilder = class {
3545
3545
  /**
3546
3546
  * Disable route lookup. Calling this method considers
3547
3547
  * the "identifier" as the route pattern
3548
+ * @deprecated
3549
+ * Instead use "@adonisjs/core/services/url_builder" instead
3548
3550
  */
3549
3551
  disableRouteLookup() {
3550
3552
  this.#shouldPerformLookup = false;
@@ -3552,6 +3554,8 @@ var UrlBuilder = class {
3552
3554
  }
3553
3555
  /**
3554
3556
  * Append query string to the final URI
3557
+ * @deprecated
3558
+ * Instead use "@adonisjs/core/services/url_builder" instead
3555
3559
  */
3556
3560
  qs(queryString) {
3557
3561
  if (!queryString) {
@@ -3562,6 +3566,8 @@ var UrlBuilder = class {
3562
3566
  }
3563
3567
  /**
3564
3568
  * Specify params to apply to the route pattern
3569
+ * @deprecated
3570
+ * Instead use "@adonisjs/core/services/url_builder" instead
3565
3571
  */
3566
3572
  params(params) {
3567
3573
  if (!params) {
@@ -3574,174 +3580,41 @@ var UrlBuilder = class {
3574
3580
  * Generate URL for the given route identifier. The identifier can be the
3575
3581
  * route name, controller.method name or the route pattern
3576
3582
  * itself.
3583
+ *
3584
+ * @deprecated
3585
+ * Instead use "@adonisjs/core/services/url_builder" instead
3577
3586
  */
3578
3587
  make(identifier) {
3579
- let url;
3580
- if (this.#shouldPerformLookup) {
3581
- const route = this.#routeFinder.findOrFail(identifier);
3582
- url = this.#processPattern(route.pattern);
3583
- } else {
3584
- url = this.#processPattern(identifier);
3585
- }
3586
- return this.#suffixQueryString(this.#prefixBaseUrl(url), this.#qs);
3588
+ return this.#router.makeUrl(identifier, this.#params, {
3589
+ prefixUrl: this.#baseUrl,
3590
+ disableRouteLookup: !this.#shouldPerformLookup,
3591
+ domain: this.#domain,
3592
+ qs: this.#qs
3593
+ });
3587
3594
  }
3588
3595
  /**
3589
3596
  * Generate a signed URL for the given route identifier. The identifier can be the
3590
3597
  * route name, controller.method name or the route pattern
3591
3598
  * itself.
3592
- */
3593
- makeSigned(identifier, options) {
3594
- let url;
3595
- if (this.#shouldPerformLookup) {
3596
- const route = this.#routeFinder.findOrFail(identifier);
3597
- url = this.#processPattern(route.pattern);
3598
- } else {
3599
- url = this.#processPattern(identifier);
3600
- }
3601
- const signature = this.#encryption.verifier.sign(
3602
- this.#suffixQueryString(url, this.#qs),
3603
- options?.expiresIn,
3604
- options?.purpose
3605
- );
3606
- const qs = Object.assign({}, this.#qs, { signature });
3607
- return this.#suffixQueryString(this.#prefixBaseUrl(url), qs);
3608
- }
3609
- };
3610
-
3611
- // src/router/lookup_store/route_finder.ts
3612
- var RouteFinder = class {
3613
- #routes = [];
3614
- register(route) {
3615
- this.#routes.push(route);
3616
- }
3617
- /**
3618
- * Find a route by indentifier
3619
- */
3620
- find(routeIdentifier) {
3621
- return this.#routes.find(({ name, pattern, handler }) => {
3622
- if (name === routeIdentifier || pattern === routeIdentifier) {
3623
- return true;
3624
- }
3625
- if (typeof handler === "function") {
3626
- return false;
3627
- }
3628
- return handler.reference === routeIdentifier;
3629
- }) || null;
3630
- }
3631
- /**
3632
- * Find a route by indentifier or fail
3633
- */
3634
- findOrFail(routeIdentifier) {
3635
- const route = this.find(routeIdentifier);
3636
- if (!route) {
3637
- throw new E_CANNOT_LOOKUP_ROUTE([routeIdentifier]);
3638
- }
3639
- return route;
3640
- }
3641
- /**
3642
- * Find if a route exists
3643
- */
3644
- has(routeIdentifier) {
3645
- return !!this.find(routeIdentifier);
3646
- }
3647
- /**
3648
- * Returns an array of registered routes
3649
- */
3650
- toJSON() {
3651
- return this.#routes;
3652
- }
3653
- };
3654
-
3655
- // src/router/lookup_store/main.ts
3656
- var LookupStore = class extends Macroable7 {
3657
- /**
3658
- * List of route finders grouped by domains
3659
- */
3660
- #routes = {};
3661
- /**
3662
- * Encryption for making URLs
3663
- */
3664
- #encryption;
3665
- /**
3666
- * Query string parser for making URLs
3667
- */
3668
- #qsParser;
3669
- constructor(encryption, qsParser) {
3670
- super();
3671
- this.#encryption = encryption;
3672
- this.#qsParser = qsParser;
3673
- }
3674
- /**
3675
- * Register route JSON payload
3676
- */
3677
- register(route) {
3678
- this.#routes[route.domain] = this.#routes[route.domain] || new RouteFinder();
3679
- this.#routes[route.domain].register(route);
3680
- }
3681
- /**
3682
- * Returns an instance of the URL builder for making
3683
- * route URIs
3684
- */
3685
- builder() {
3686
- return this.builderForDomain("root");
3687
- }
3688
- /**
3689
- * Returns an instance of the URL builder for a specific
3690
- * domain.
3691
- */
3692
- builderForDomain(domain) {
3693
- const finder = this.#routes[domain];
3694
- return new UrlBuilder(this.#encryption, finder || new RouteFinder(), this.#qsParser);
3695
- }
3696
- /**
3697
- * Finds a route by its identifier. The identifier can be the
3698
- * route name, controller.method name or the route pattern
3699
- * itself.
3700
- */
3701
- find(routeIdentifier, domain) {
3702
- const finder = this.#routes[domain || "root"];
3703
- if (!finder) {
3704
- return null;
3705
- }
3706
- return finder.find(routeIdentifier);
3707
- }
3708
- /**
3709
- * Finds a route by its identifier. The identifier can be the
3710
- * route name, controller.method name or the route pattern
3711
- * itself.
3712
3599
  *
3713
- * An error is raised when unable to find the route.
3714
- */
3715
- findOrFail(routeIdentifier, domain) {
3716
- const finder = this.#routes[domain || "root"];
3717
- if (!finder) {
3718
- throw new E_CANNOT_LOOKUP_ROUTE([routeIdentifier]);
3719
- }
3720
- return finder.findOrFail(routeIdentifier);
3721
- }
3722
- /**
3723
- * Check if a route exists. The identifier can be the
3724
- * route name, controller.method name or the route pattern
3725
- * itself.
3600
+ * @deprecated
3601
+ * Instead use "@adonisjs/core/services/url_builder" instead
3602
+ *
3726
3603
  */
3727
- has(routeIdentifier, domain) {
3728
- const finder = this.#routes[domain || "root"];
3729
- if (!finder) {
3730
- return false;
3731
- }
3732
- return finder.has(routeIdentifier);
3733
- }
3734
- toJSON() {
3735
- return Object.keys(this.#routes).reduce((result, domain) => {
3736
- result[domain] = this.#routes[domain].toJSON();
3737
- return result;
3738
- }, {});
3604
+ makeSigned(identifier, options) {
3605
+ return this.#router.makeSignedUrl(identifier, this.#params, {
3606
+ prefixUrl: this.#baseUrl,
3607
+ disableRouteLookup: !this.#shouldPerformLookup,
3608
+ domain: this.#domain,
3609
+ qs: this.#qs,
3610
+ ...options
3611
+ });
3739
3612
  }
3740
3613
  };
3741
3614
 
3742
3615
  // src/router/matchers.ts
3743
- import Macroable8 from "@poppinss/macroable";
3744
- var RouteMatchers = class extends Macroable8 {
3616
+ import Macroable7 from "@poppinss/macroable";
3617
+ var RouteMatchers = class extends Macroable7 {
3745
3618
  /**
3746
3619
  * Enforce value to be a number and also casts it to number data
3747
3620
  * type
@@ -3766,6 +3639,127 @@ var RouteMatchers = class extends Macroable8 {
3766
3639
  }
3767
3640
  };
3768
3641
 
3642
+ // src/router/url_builder.ts
3643
+ function createURL(identifier, tokens, searchParamsStringifier, params, options) {
3644
+ const uriSegments = [];
3645
+ const paramsArray = Array.isArray(params) ? params : null;
3646
+ const paramsObject = !Array.isArray(params) ? params ?? {} : {};
3647
+ let paramsIndex = 0;
3648
+ for (const token of tokens) {
3649
+ if (token.type === 0) {
3650
+ uriSegments.push(token.val === "/" ? "" : `${token.val}${token.end}`);
3651
+ continue;
3652
+ }
3653
+ if (token.type === 2) {
3654
+ const values = paramsArray ? paramsArray.slice(paramsIndex) : paramsObject["*"];
3655
+ if (!Array.isArray(values) || !values.length) {
3656
+ throw new Error(
3657
+ `Cannot make URL for "${identifier}". Invalid value provided for the wildcard param`
3658
+ );
3659
+ }
3660
+ uriSegments.push(`${values.join("/")}${token.end}`);
3661
+ break;
3662
+ }
3663
+ const paramName = token.val;
3664
+ const value = paramsArray ? paramsArray[paramsIndex] : paramsObject[paramName];
3665
+ const isDefined = value !== void 0 && value !== null;
3666
+ if (token.type === 1 && !isDefined) {
3667
+ throw new Error(
3668
+ `Cannot make URL for "${identifier}". Missing value for the "${paramName}" param`
3669
+ );
3670
+ }
3671
+ if (isDefined) {
3672
+ uriSegments.push(`${value}${token.end}`);
3673
+ }
3674
+ paramsIndex++;
3675
+ }
3676
+ let URI = `/${uriSegments.join("/")}`;
3677
+ if (options?.prefixUrl) {
3678
+ URI = `${options?.prefixUrl.replace(/\/$/, "")}${URI}`;
3679
+ }
3680
+ if (options?.qs) {
3681
+ const queryString = searchParamsStringifier(options?.qs);
3682
+ URI = queryString ? `${URI}?${queryString}` : URI;
3683
+ }
3684
+ return URI;
3685
+ }
3686
+ function createUrlBuilder(router, searchParamsStringifier) {
3687
+ let domainsList;
3688
+ function createUrlForRoute(identifier, params, options, method) {
3689
+ if (!domainsList) {
3690
+ domainsList = Object.keys(router.toJSON()).filter((domain2) => domain2 !== "root");
3691
+ }
3692
+ const domain = domainsList.find((name) => identifier.startsWith(`${name}@`));
3693
+ const routeIdentifier = domain ? identifier.replace(new RegExp(`^${domain}@`), "") : identifier;
3694
+ const route = router.findOrFail(routeIdentifier, domain, method, true);
3695
+ return createURL(
3696
+ route.name ?? route.pattern,
3697
+ route.tokens,
3698
+ searchParamsStringifier,
3699
+ params,
3700
+ options
3701
+ );
3702
+ }
3703
+ const urlFor = function route(...[identifier, params, options]) {
3704
+ return createUrlForRoute(identifier, params, options);
3705
+ };
3706
+ urlFor.get = function urlForMethodGet(...[identifier, params, options]) {
3707
+ return {
3708
+ url: createUrlForRoute(identifier, params, options, "GET"),
3709
+ method: "get",
3710
+ toString() {
3711
+ return this.url;
3712
+ }
3713
+ };
3714
+ };
3715
+ urlFor.post = function urlForMethodPost(...[identifier, params, options]) {
3716
+ return {
3717
+ url: createUrlForRoute(identifier, params, options, "POST"),
3718
+ method: "post",
3719
+ toString() {
3720
+ return this.url;
3721
+ }
3722
+ };
3723
+ };
3724
+ urlFor.put = function urlForMethodPut(...[identifier, params, options]) {
3725
+ return {
3726
+ url: createUrlForRoute(identifier, params, options, "PUT"),
3727
+ method: "put",
3728
+ toString() {
3729
+ return this.url;
3730
+ }
3731
+ };
3732
+ };
3733
+ urlFor.patch = function urlForMethodPatch(...[identifier, params, options]) {
3734
+ return {
3735
+ url: createUrlForRoute(identifier, params, options, "PATCH"),
3736
+ method: "patch",
3737
+ toString() {
3738
+ return this.url;
3739
+ }
3740
+ };
3741
+ };
3742
+ urlFor.delete = function urlForMethodDelete(...[identifier, params, options]) {
3743
+ return {
3744
+ url: createUrlForRoute(identifier, params, options, "DELETE"),
3745
+ method: "delete",
3746
+ toString() {
3747
+ return this.url;
3748
+ }
3749
+ };
3750
+ };
3751
+ urlFor.method = function urlForCustomMethod(method, ...[identifier, params, options]) {
3752
+ return {
3753
+ url: createUrlForRoute(identifier, params, options, method),
3754
+ method,
3755
+ toString() {
3756
+ return this.url;
3757
+ }
3758
+ };
3759
+ };
3760
+ return urlFor;
3761
+ }
3762
+
3769
3763
  // src/define_middleware.ts
3770
3764
  import { moduleImporter as moduleImporter2 } from "@adonisjs/fold";
3771
3765
  function middlewareReferenceBuilder(name, middleware) {
@@ -3774,6 +3768,7 @@ function middlewareReferenceBuilder(name, middleware) {
3774
3768
  return {
3775
3769
  ...handler,
3776
3770
  name,
3771
+ reference: middleware,
3777
3772
  args: args[0]
3778
3773
  };
3779
3774
  };
@@ -3788,8 +3783,104 @@ function defineNamedMiddleware(collection) {
3788
3783
  );
3789
3784
  }
3790
3785
 
3786
+ // src/router/signed_url_builder.ts
3787
+ function createSignedURL(identifier, tokens, searchParamsStringifier, encryption, params, options) {
3788
+ const signature = encryption.verifier.sign(
3789
+ createURL(identifier, tokens, searchParamsStringifier, params, {
3790
+ ...options,
3791
+ prefixUrl: void 0
3792
+ }),
3793
+ options?.expiresIn,
3794
+ options?.purpose
3795
+ );
3796
+ return createURL(identifier, tokens, searchParamsStringifier, params, {
3797
+ ...options,
3798
+ qs: { ...options?.qs, signature }
3799
+ });
3800
+ }
3801
+ function createSignedUrlBuilder(router, encryption, searchParamsStringifier) {
3802
+ let domainsList;
3803
+ function createSignedUrlForRoute(identifier, params, options, method) {
3804
+ if (!domainsList) {
3805
+ domainsList = Object.keys(router.toJSON()).filter((domain2) => domain2 !== "root");
3806
+ }
3807
+ const domain = domainsList.find((name) => identifier.startsWith(`${name}@`));
3808
+ const routeIdentifier = domain ? identifier.replace(new RegExp(`^${domain}@`), "") : identifier;
3809
+ const route = router.findOrFail(routeIdentifier, domain, method, true);
3810
+ return createSignedURL(
3811
+ route.name ?? route.pattern,
3812
+ route.tokens,
3813
+ searchParamsStringifier,
3814
+ encryption,
3815
+ params,
3816
+ options
3817
+ );
3818
+ }
3819
+ const signedRoute = function route(...[identifier, params, options]) {
3820
+ return createSignedUrlForRoute(identifier, params, options);
3821
+ };
3822
+ signedRoute.get = function routeGet(...[identifier, params, options]) {
3823
+ return {
3824
+ url: createSignedUrlForRoute(identifier, params, options, "GET"),
3825
+ method: "get",
3826
+ toString() {
3827
+ return this.url;
3828
+ }
3829
+ };
3830
+ };
3831
+ signedRoute.post = function routePost(...[identifier, params, options]) {
3832
+ return {
3833
+ url: createSignedUrlForRoute(identifier, params, options, "POST"),
3834
+ method: "post",
3835
+ toString() {
3836
+ return this.url;
3837
+ }
3838
+ };
3839
+ };
3840
+ signedRoute.put = function routePut(...[identifier, params, options]) {
3841
+ return {
3842
+ url: createSignedUrlForRoute(identifier, params, options, "PUT"),
3843
+ method: "put",
3844
+ toString() {
3845
+ return this.url;
3846
+ }
3847
+ };
3848
+ };
3849
+ signedRoute.patch = function routePatch(...[identifier, params, options]) {
3850
+ return {
3851
+ url: createSignedUrlForRoute(identifier, params, options, "PATCH"),
3852
+ method: "patch",
3853
+ toString() {
3854
+ return this.url;
3855
+ }
3856
+ };
3857
+ };
3858
+ signedRoute.delete = function routeDelete(...[identifier, params, options]) {
3859
+ return {
3860
+ url: createSignedUrlForRoute(identifier, params, options, "DELETE"),
3861
+ method: "delete",
3862
+ toString() {
3863
+ return this.url;
3864
+ }
3865
+ };
3866
+ };
3867
+ signedRoute.method = function routeGet(method, ...[identifier, params, options]) {
3868
+ return {
3869
+ url: createSignedUrlForRoute(identifier, params, options, method),
3870
+ method,
3871
+ toString() {
3872
+ return this.url;
3873
+ }
3874
+ };
3875
+ };
3876
+ return signedRoute;
3877
+ }
3878
+
3791
3879
  // src/router/main.ts
3792
- var Router = class extends LookupStore {
3880
+ var Router = class {
3881
+ /**
3882
+ * Flag to avoid re-comitting routes to the store
3883
+ */
3793
3884
  #commited = false;
3794
3885
  /**
3795
3886
  * Application is needed to resolve string based controller expressions
@@ -3799,6 +3890,10 @@ var Router = class extends LookupStore {
3799
3890
  * Store with tokenized routes
3800
3891
  */
3801
3892
  #store = new RoutesStore();
3893
+ /**
3894
+ * Encryption for making signed URLs
3895
+ */
3896
+ #encryption;
3802
3897
  /**
3803
3898
  * Global matchers to test route params against regular expressions.
3804
3899
  */
@@ -3813,10 +3908,10 @@ var Router = class extends LookupStore {
3813
3908
  */
3814
3909
  #openedGroups = [];
3815
3910
  /**
3816
- * Collection of routes, including route resource and route
3817
- * group. To get a flat list of routes, call `router.toJSON()`
3911
+ * Collection of routes to be committed with the store, including
3912
+ * route resource and route group.
3818
3913
  */
3819
- routes = [];
3914
+ #routesToBeCommitted = [];
3820
3915
  /**
3821
3916
  * A flag to know if routes for explicit domains have been registered.
3822
3917
  * The boolean is computed after calling the "commit" method.
@@ -3834,9 +3929,37 @@ var Router = class extends LookupStore {
3834
3929
  get commited() {
3835
3930
  return this.#commited;
3836
3931
  }
3932
+ /**
3933
+ * Query string parser for making URLs
3934
+ */
3935
+ qs;
3936
+ /**
3937
+ * The URLBuilder offers a type-safe API for creating URL for pre-registered
3938
+ * routes or the route patterns.
3939
+ *
3940
+ * We recommend using the URLBuilder over the "makeUrl" and "makeSignedUrl"
3941
+ * methods.
3942
+ */
3943
+ urlBuilder;
3944
+ /**
3945
+ * List of route references kept for lookup.
3946
+ */
3947
+ routes = {};
3837
3948
  constructor(app, encryption, qsParser) {
3838
- super(encryption, qsParser);
3839
3949
  this.#app = app;
3950
+ this.#encryption = encryption;
3951
+ this.qs = qsParser;
3952
+ this.urlBuilder = {
3953
+ urlFor: createUrlBuilder(this, this.qs.stringify),
3954
+ signedUrlFor: createSignedUrlBuilder(this, this.#encryption, this.qs.stringify)
3955
+ };
3956
+ }
3957
+ /**
3958
+ * Register route JSON payload
3959
+ */
3960
+ register(route) {
3961
+ this.routes[route.domain] = this.routes[route.domain] || [];
3962
+ this.routes[route.domain].push(route);
3840
3963
  }
3841
3964
  /**
3842
3965
  * Push a give router entity to the list of routes or the
@@ -3848,13 +3971,13 @@ var Router = class extends LookupStore {
3848
3971
  openedGroup.routes.push(entity);
3849
3972
  return;
3850
3973
  }
3851
- this.routes.push(entity);
3974
+ this.#routesToBeCommitted.push(entity);
3852
3975
  }
3853
3976
  /**
3854
3977
  * Parses the route pattern
3855
3978
  */
3856
3979
  parsePattern(pattern, matchers) {
3857
- return parseRoutePattern(pattern, matchers);
3980
+ return parseRoute(pattern, matchers);
3858
3981
  }
3859
3982
  /**
3860
3983
  * Define an array of middleware to use on all the routes.
@@ -3863,7 +3986,10 @@ var Router = class extends LookupStore {
3863
3986
  */
3864
3987
  use(middleware) {
3865
3988
  middleware.forEach(
3866
- (one) => this.#middleware.push(moduleImporter3(one, "handle").toHandleMethod())
3989
+ (one) => this.#middleware.push({
3990
+ reference: one,
3991
+ ...moduleImporter3(one, "handle").toHandleMethod()
3992
+ })
3867
3993
  );
3868
3994
  return this;
3869
3995
  }
@@ -4001,13 +4127,13 @@ var Router = class extends LookupStore {
4001
4127
  }
4002
4128
  debug_default("Committing routes to the routes store");
4003
4129
  const routeNamesByDomain = /* @__PURE__ */ new Map();
4004
- toRoutesJSON(this.routes).forEach((route) => {
4130
+ toRoutesJSON(this.#routesToBeCommitted).forEach((route) => {
4005
4131
  if (!routeNamesByDomain.has(route.domain)) {
4006
4132
  routeNamesByDomain.set(route.domain, /* @__PURE__ */ new Set());
4007
4133
  }
4008
4134
  const routeNames = routeNamesByDomain.get(route.domain);
4009
4135
  if (route.name && routeNames.has(route.name)) {
4010
- throw new RuntimeException6(
4136
+ throw new RuntimeException5(
4011
4137
  `Route with duplicate name found. A route with name "${route.name}" already exists`
4012
4138
  );
4013
4139
  }
@@ -4019,51 +4145,263 @@ var Router = class extends LookupStore {
4019
4145
  });
4020
4146
  routeNamesByDomain.clear();
4021
4147
  this.usingDomains = this.#store.usingDomains;
4022
- this.routes = [];
4148
+ this.#routesToBeCommitted = [];
4023
4149
  this.#globalMatchers = {};
4024
4150
  this.#middleware = [];
4151
+ this.#openedGroups = [];
4025
4152
  this.#commited = true;
4026
4153
  }
4154
+ /**
4155
+ * The lookup strategies to follow when generating URL builder
4156
+ * types and client
4157
+ */
4158
+ lookupStrategies = ["name", "pattern"];
4159
+ /**
4160
+ * Define the lookup strategies to follow when generating URL builder
4161
+ * types and client.
4162
+ */
4163
+ updateLookupStrategies(strategies) {
4164
+ this.lookupStrategies = strategies;
4165
+ return this;
4166
+ }
4167
+ /**
4168
+ * Finds a route by its identifier. The identifier can be the
4169
+ * route name, controller.method name or the route pattern
4170
+ * itself.
4171
+ *
4172
+ * When "followLookupStrategy" is enabled, the lookup will be performed
4173
+ * on the basis of the lookup strategy enabled via the "lookupStrategies"
4174
+ * method. The default lookupStrategy is "name" and "pattern".
4175
+ */
4176
+ find(routeIdentifier, domain, method, followLookupStrategy) {
4177
+ if (!domain) {
4178
+ let route = null;
4179
+ for (const routeDomain of Object.keys(this.routes)) {
4180
+ route = this.find(routeIdentifier, routeDomain, method, followLookupStrategy);
4181
+ if (route) {
4182
+ break;
4183
+ }
4184
+ }
4185
+ return route;
4186
+ }
4187
+ const routes = this.routes[domain];
4188
+ if (!routes) {
4189
+ return null;
4190
+ }
4191
+ const lookupByName = !followLookupStrategy || this.lookupStrategies.includes("name");
4192
+ const lookupByPattern = !followLookupStrategy || this.lookupStrategies.includes("pattern");
4193
+ const lookupByController = !followLookupStrategy || this.lookupStrategies.includes("controller");
4194
+ return routes.find((route) => {
4195
+ if (method && !route.methods.includes(method)) {
4196
+ return false;
4197
+ }
4198
+ if (route.name === routeIdentifier && lookupByName || route.pattern === routeIdentifier && lookupByPattern) {
4199
+ return true;
4200
+ }
4201
+ if (typeof route.handler === "function" || !lookupByController) {
4202
+ return false;
4203
+ }
4204
+ return route.handler.reference === routeIdentifier;
4205
+ }) || null;
4206
+ }
4207
+ /**
4208
+ * Finds a route by its identifier. The identifier can be the
4209
+ * route name, controller.method name or the route pattern
4210
+ * itself.
4211
+ *
4212
+ * An error is raised when unable to find the route.
4213
+ *
4214
+ * When "followLookupStrategy" is enabled, the lookup will be performed
4215
+ * on the basis of the lookup strategy enabled via the "lookupStrategies"
4216
+ * method. The default lookupStrategy is "name" and "pattern".
4217
+ */
4218
+ findOrFail(routeIdentifier, domain, method, followLookupStrategy) {
4219
+ const route = this.find(routeIdentifier, domain, method, followLookupStrategy);
4220
+ if (!route) {
4221
+ throw new Error(`Cannot lookup route "${routeIdentifier}"`);
4222
+ }
4223
+ return route;
4224
+ }
4225
+ /**
4226
+ * Check if a route exists. The identifier can be the
4227
+ * route name, controller.method name or the route pattern
4228
+ * itself.
4229
+ *
4230
+ * When "followLookupStrategy" is enabled, the lookup will be performed
4231
+ * on the basis of the lookup strategy enabled via the "lookupStrategies"
4232
+ * method. The default lookupStrategy is "name" and "pattern".
4233
+ */
4234
+ has(routeIdentifier, domain, method, followLookupStrategy) {
4235
+ return !!this.find(routeIdentifier, domain, method, followLookupStrategy);
4236
+ }
4237
+ /**
4238
+ * Returns a list of routes grouped by their domain names
4239
+ */
4240
+ toJSON() {
4241
+ return this.routes;
4242
+ }
4243
+ /**
4244
+ * Generates types for the URL builder. These types must
4245
+ * be written inside a file for the URL builder to
4246
+ * pick them up.
4247
+ */
4248
+ generateTypes(indentation = 0) {
4249
+ const routesList = {};
4250
+ function trackRoute(route, domain) {
4251
+ let params = [];
4252
+ let paramsTuple = [];
4253
+ let hasRequiredParams = false;
4254
+ for (let token of route.tokens) {
4255
+ if (token.type === 1) {
4256
+ hasRequiredParams = true;
4257
+ params.push(`'${token.val}': string`);
4258
+ paramsTuple.push("string");
4259
+ } else if (token.type === 3) {
4260
+ params.push(`'${token.val}'?: string`);
4261
+ paramsTuple.push("string?");
4262
+ } else if (token.type === 2) {
4263
+ hasRequiredParams = true;
4264
+ params.push(`'*': string[]`);
4265
+ paramsTuple.push("...string[]");
4266
+ break;
4267
+ }
4268
+ }
4269
+ route.methods.forEach((method) => {
4270
+ routesList["ALL"] = routesList["ALL"] ?? {};
4271
+ routesList[method] = routesList[method] ?? {};
4272
+ const identifiers = [];
4273
+ if (this.lookupStrategies.includes("pattern")) {
4274
+ if (!routesList[method][route.pattern]) {
4275
+ identifiers.push(route.pattern);
4276
+ }
4277
+ }
4278
+ if (this.lookupStrategies.includes("name") && route.name) {
4279
+ identifiers.push(
4280
+ domain && routesList[method][route.name] ? `${domain}@${route.name}` : route.name
4281
+ );
4282
+ }
4283
+ if (this.lookupStrategies.includes("controller") && "reference" in route.handler && typeof route.handler.reference === "string") {
4284
+ identifiers.push(
4285
+ domain && routesList[method][route.handler.reference] ? `${domain}@${route.handler.reference}` : route.handler.reference
4286
+ );
4287
+ }
4288
+ identifiers.forEach((identifier) => {
4289
+ routesList["ALL"][identifier] = {
4290
+ params,
4291
+ paramsTuple,
4292
+ hasRequiredParams
4293
+ };
4294
+ routesList[method][identifier] = {
4295
+ params,
4296
+ paramsTuple,
4297
+ hasRequiredParams
4298
+ };
4299
+ });
4300
+ });
4301
+ }
4302
+ const domains = Object.keys(this.routes).filter((domain) => domain !== "root");
4303
+ this.routes["root"].forEach((route) => trackRoute.bind(this)(route));
4304
+ domains.forEach(
4305
+ (domain) => this.routes[domain].forEach((route) => trackRoute.bind(this)(route, domain))
4306
+ );
4307
+ return Object.keys(routesList).reduce((result, method) => {
4308
+ result.push(`${" ".repeat(indentation)}'${method}': {`);
4309
+ Object.keys(routesList[method]).forEach((identifier) => {
4310
+ const key = `'${identifier}'`;
4311
+ const { paramsTuple, hasRequiredParams, params } = routesList[method][identifier];
4312
+ const dictName = hasRequiredParams ? "params" : "params?";
4313
+ const tupleName = hasRequiredParams ? "paramsTuple" : "paramsTuple?";
4314
+ const dictValue = `{${params.join(",")}}`;
4315
+ const tupleValue = `[${paramsTuple?.join(",")}]`;
4316
+ const value = `{ ${tupleName}: ${tupleValue}, ${dictName}: ${dictValue} }`;
4317
+ result.push(`${" ".repeat(indentation + 2)}${key}: ${value},`);
4318
+ });
4319
+ result.push(`${" ".repeat(indentation)}},`);
4320
+ return result;
4321
+ }, []).join("\n");
4322
+ }
4027
4323
  /**
4028
4324
  * Find route for a given URL, method and optionally domain
4029
4325
  */
4030
- match(url, method, hostname) {
4326
+ match(uri, method, shouldDecodeParam, hostname) {
4031
4327
  const matchingDomain = this.#store.matchDomain(hostname);
4032
- return matchingDomain.length ? this.#store.match(url, method, {
4328
+ return matchingDomain.length ? this.#store.match(uri, method, shouldDecodeParam, {
4033
4329
  tokens: matchingDomain,
4034
4330
  hostname
4035
- }) : this.#store.match(url, method);
4331
+ }) : this.#store.match(uri, method, shouldDecodeParam);
4332
+ }
4333
+ /**
4334
+ * Create URL builder instance.
4335
+ * @deprecated
4336
+ *
4337
+ * Instead use "@adonisjs/core/services/url_builder" instead
4338
+ */
4339
+ builder() {
4340
+ return new UrlBuilder(this);
4341
+ }
4342
+ /**
4343
+ * Create URL builder instance for a given domain.
4344
+ * @deprecated
4345
+ *
4346
+ * Instead use "@adonisjs/core/services/url_builder"
4347
+ */
4348
+ builderForDomain(domain) {
4349
+ return new UrlBuilder(this, domain);
4036
4350
  }
4037
4351
  /**
4038
4352
  * Make URL to a pre-registered route
4353
+ *
4354
+ * @deprecated
4355
+ * Instead use "@adonisjs/core/services/url_builder"
4039
4356
  */
4040
4357
  makeUrl(routeIdentifier, params, options) {
4041
4358
  const normalizedOptions = Object.assign({}, options);
4042
- const builder = normalizedOptions.domain ? this.builderForDomain(normalizedOptions.domain) : this.builder();
4043
- builder.params(params);
4044
- builder.qs(normalizedOptions.qs);
4045
- normalizedOptions.prefixUrl && builder.prefixUrl(normalizedOptions.prefixUrl);
4046
- normalizedOptions.disableRouteLookup && builder.disableRouteLookup();
4047
- return builder.make(routeIdentifier);
4359
+ if (options?.disableRouteLookup) {
4360
+ return createURL(
4361
+ routeIdentifier,
4362
+ parseRoute(routeIdentifier),
4363
+ this.qs.stringify,
4364
+ params,
4365
+ options
4366
+ );
4367
+ }
4368
+ const route = this.findOrFail(routeIdentifier, normalizedOptions.domain);
4369
+ return createURL(route.name ?? route.pattern, route.tokens, this.qs.stringify, params, options);
4048
4370
  }
4049
4371
  /**
4050
4372
  * Makes a signed URL to a pre-registered route.
4373
+ *
4374
+ * @deprecated
4375
+ * Instead use "@adonisjs/core/services/url_builder"
4051
4376
  */
4052
4377
  makeSignedUrl(routeIdentifier, params, options) {
4053
4378
  const normalizedOptions = Object.assign({}, options);
4054
- const builder = normalizedOptions.domain ? this.builderForDomain(normalizedOptions.domain) : this.builder();
4055
- builder.params(params);
4056
- builder.qs(normalizedOptions.qs);
4057
- normalizedOptions.prefixUrl && builder.prefixUrl(normalizedOptions.prefixUrl);
4058
- normalizedOptions.disableRouteLookup && builder.disableRouteLookup();
4059
- return builder.makeSigned(routeIdentifier, normalizedOptions);
4379
+ if (options?.disableRouteLookup) {
4380
+ return createSignedURL(
4381
+ routeIdentifier,
4382
+ parseRoute(routeIdentifier),
4383
+ this.qs.stringify,
4384
+ this.#encryption,
4385
+ params,
4386
+ options
4387
+ );
4388
+ }
4389
+ const route = this.findOrFail(routeIdentifier, normalizedOptions.domain);
4390
+ return createSignedURL(
4391
+ route.name ?? route.pattern,
4392
+ route.tokens,
4393
+ this.qs.stringify,
4394
+ this.#encryption,
4395
+ params,
4396
+ options
4397
+ );
4060
4398
  }
4061
4399
  };
4062
4400
 
4063
4401
  // src/http_context/main.ts
4064
4402
  import { inspect } from "util";
4065
- import Macroable9 from "@poppinss/macroable";
4066
- import { RuntimeException as RuntimeException7 } from "@poppinss/utils";
4403
+ import Macroable8 from "@poppinss/macroable";
4404
+ import { RuntimeException as RuntimeException6 } from "@poppinss/utils/exception";
4067
4405
 
4068
4406
  // src/http_context/local_storage.ts
4069
4407
  import { AsyncLocalStorage } from "async_hooks";
@@ -4096,7 +4434,7 @@ var asyncLocalStorage = {
4096
4434
  };
4097
4435
 
4098
4436
  // src/http_context/main.ts
4099
- var HttpContext = class extends Macroable9 {
4437
+ var HttpContext = class extends Macroable8 {
4100
4438
  constructor(request, response, logger, containerResolver) {
4101
4439
  super();
4102
4440
  this.request = request;
@@ -4129,13 +4467,13 @@ var HttpContext = class extends Macroable9 {
4129
4467
  */
4130
4468
  static getOrFail() {
4131
4469
  if (!this.usingAsyncLocalStorage || !asyncLocalStorage.storage) {
4132
- throw new RuntimeException7(
4470
+ throw new RuntimeException6(
4133
4471
  'HTTP context is not available. Enable "useAsyncLocalStorage" inside "config/app.ts" file'
4134
4472
  );
4135
4473
  }
4136
4474
  const store = this.get();
4137
4475
  if (!store) {
4138
- throw new RuntimeException7("Http context is not available outside of an HTTP request");
4476
+ throw new RuntimeException6("Http context is not available outside of an HTTP request");
4139
4477
  }
4140
4478
  return store;
4141
4479
  }
@@ -4181,27 +4519,27 @@ import Middleware2 from "@poppinss/middleware";
4181
4519
  import { moduleCaller as moduleCaller2, moduleImporter as moduleImporter4 } from "@adonisjs/fold";
4182
4520
 
4183
4521
  // src/qs.ts
4184
- import { parse as parse3, stringify } from "qs";
4522
+ import { parse as parse2, stringify } from "qs";
4185
4523
  var Qs = class {
4186
4524
  #config;
4187
4525
  constructor(config) {
4188
4526
  this.#config = config;
4189
4527
  }
4190
- parse(value) {
4191
- return parse3(value, this.#config.parse);
4192
- }
4193
- stringify(value) {
4528
+ parse = (value) => {
4529
+ return parse2(value, this.#config.parse);
4530
+ };
4531
+ stringify = (value) => {
4194
4532
  return stringify(value, this.#config.stringify);
4195
- }
4533
+ };
4196
4534
  };
4197
4535
 
4198
- // src/server/factories/final_handler.ts
4199
- function finalHandler(router, resolver, ctx, errorResponder) {
4536
+ // src/server/factories/route_finder.ts
4537
+ function routeFinder(router, resolver, ctx, errorResponder) {
4200
4538
  return function() {
4201
4539
  const url = ctx.request.url();
4202
4540
  const method = ctx.request.method();
4203
4541
  const hostname = router.usingDomains ? ctx.request.hostname() : void 0;
4204
- const route = router.match(url, method, hostname);
4542
+ const route = router.match(url, method, ctx.request.parsedUrl.shouldDecodeParam, hostname);
4205
4543
  if (route) {
4206
4544
  ctx.params = route.params;
4207
4545
  ctx.subdomains = route.subdomains;
@@ -4230,7 +4568,14 @@ function writeResponse(ctx) {
4230
4568
  function middlewareHandler(resolver, ctx) {
4231
4569
  return function(fn, next) {
4232
4570
  debug_default("executing middleware %s", fn.name);
4233
- return fn.handle(resolver, ctx, next);
4571
+ return httpMiddleware.tracePromise(
4572
+ fn.handle,
4573
+ fn,
4574
+ void 0,
4575
+ resolver,
4576
+ ctx,
4577
+ next
4578
+ );
4234
4579
  };
4235
4580
  }
4236
4581
 
@@ -4308,7 +4653,13 @@ var Server = class {
4308
4653
  */
4309
4654
  #requestErrorResponder = (error, ctx) => {
4310
4655
  this.#resolvedErrorHandler.report(error, ctx);
4311
- return this.#resolvedErrorHandler.handle(error, ctx);
4656
+ return httpExceptionHandler.tracePromise(
4657
+ this.#resolvedErrorHandler.handle,
4658
+ void 0,
4659
+ void 0,
4660
+ error,
4661
+ ctx
4662
+ );
4312
4663
  };
4313
4664
  /**
4314
4665
  * Check if the server has already been booted
@@ -4357,7 +4708,7 @@ var Server = class {
4357
4708
  * Handles the HTTP request
4358
4709
  */
4359
4710
  #handleRequest(ctx, resolver) {
4360
- return this.#serverMiddlewareStack.runner().errorHandler((error) => this.#requestErrorResponder(error, ctx)).finalHandler(finalHandler(this.#router, resolver, ctx, this.#requestErrorResponder)).run(middlewareHandler(resolver, ctx)).catch((error) => {
4711
+ return this.#serverMiddlewareStack.runner().errorHandler((error) => this.#requestErrorResponder(error, ctx)).finalHandler(routeFinder(this.#router, resolver, ctx, this.#requestErrorResponder)).run(middlewareHandler(resolver, ctx)).catch((error) => {
4361
4712
  ctx.logger.fatal({ err: error }, "Exception raised by error handler");
4362
4713
  return this.#defaultErrorHandler.handle(error, ctx);
4363
4714
  }).finally(writeResponse(ctx));
@@ -4368,7 +4719,10 @@ var Server = class {
4368
4719
  pipeline(middleware) {
4369
4720
  const middlewareStack = new Middleware2();
4370
4721
  middleware.forEach((one) => {
4371
- middlewareStack.add(moduleCaller2(one, "handle").toHandleMethod());
4722
+ middlewareStack.add({
4723
+ reference: one,
4724
+ ...moduleCaller2(one, "handle").toHandleMethod()
4725
+ });
4372
4726
  });
4373
4727
  middlewareStack.freeze();
4374
4728
  const stackRunner = middlewareStack.runner();
@@ -4395,7 +4749,10 @@ var Server = class {
4395
4749
  */
4396
4750
  use(middleware) {
4397
4751
  middleware.forEach(
4398
- (one) => this.#middleware.push(moduleImporter4(one, "handle").toHandleMethod())
4752
+ (one) => this.#middleware.push({
4753
+ reference: one,
4754
+ ...moduleImporter4(one, "handle").toHandleMethod()
4755
+ })
4399
4756
  );
4400
4757
  return this;
4401
4758
  }
@@ -4476,6 +4833,12 @@ var Server = class {
4476
4833
  resolver
4477
4834
  );
4478
4835
  }
4836
+ /**
4837
+ * Returns a list of server middleware stack
4838
+ */
4839
+ getMiddlewareList() {
4840
+ return this.#serverMiddlewareStack ? Array.from(this.#serverMiddlewareStack.all()) : [...this.#middleware];
4841
+ }
4479
4842
  /**
4480
4843
  * Handle request
4481
4844
  */
@@ -4497,23 +4860,29 @@ var Server = class {
4497
4860
  });
4498
4861
  }
4499
4862
  if (this.usingAsyncLocalStorage) {
4500
- return asyncLocalStorage.storage.run(ctx, () => this.#handleRequest(ctx, resolver));
4863
+ return asyncLocalStorage.storage.run(
4864
+ ctx,
4865
+ () => httpRequest.tracePromise(this.#handleRequest, ctx, this, ctx, resolver)
4866
+ );
4501
4867
  }
4502
- return this.#handleRequest(ctx, resolver);
4868
+ return httpRequest.tracePromise(this.#handleRequest, ctx, this, ctx, resolver);
4503
4869
  }
4504
4870
  };
4505
4871
 
4506
4872
  // src/define_config.ts
4507
4873
  import proxyAddr from "proxy-addr";
4508
- import string3 from "@poppinss/utils/string";
4509
- import lodash3 from "@poppinss/utils/lodash";
4874
+ import string2 from "@poppinss/utils/string";
4875
+ import lodash2 from "@poppinss/utils/lodash";
4510
4876
  function defineConfig(config) {
4511
4877
  const { trustProxy: trustProxy2, ...rest } = config;
4512
4878
  const defaults = {
4513
4879
  allowMethodSpoofing: false,
4514
4880
  trustProxy: proxyAddr.compile("loopback"),
4515
4881
  subdomainOffset: 2,
4516
- generateRequestId: false,
4882
+ generateRequestId: !!config.createRequestId,
4883
+ createRequestId() {
4884
+ return crypto.randomUUID();
4885
+ },
4517
4886
  useAsyncLocalStorage: false,
4518
4887
  etag: false,
4519
4888
  jsonpCallbackName: "callback",
@@ -4540,9 +4909,9 @@ function defineConfig(config) {
4540
4909
  }
4541
4910
  }
4542
4911
  };
4543
- const normalizedConfig = lodash3.merge({}, defaults, rest);
4912
+ const normalizedConfig = lodash2.merge({}, defaults, rest);
4544
4913
  if (normalizedConfig.cookie.maxAge) {
4545
- normalizedConfig.cookie.maxAge = string3.seconds.parse(normalizedConfig.cookie.maxAge);
4914
+ normalizedConfig.cookie.maxAge = string2.seconds.parse(normalizedConfig.cookie.maxAge);
4546
4915
  }
4547
4916
  if (typeof trustProxy2 === "boolean") {
4548
4917
  const tpValue = trustProxy2;
@@ -4557,19 +4926,21 @@ function defineConfig(config) {
4557
4926
  }
4558
4927
 
4559
4928
  export {
4929
+ E_ROUTE_NOT_FOUND,
4930
+ E_CANNOT_LOOKUP_ROUTE,
4931
+ E_HTTP_EXCEPTION,
4932
+ E_HTTP_REQUEST_ABORTED,
4933
+ errors_exports,
4934
+ CookieClient,
4935
+ canWriteResponseBody,
4936
+ tracing_channels_exports,
4560
4937
  Route,
4561
4938
  BriskRoute,
4562
4939
  RouteResource,
4563
4940
  RouteGroup,
4564
4941
  parseRange,
4565
- CookieClient,
4566
4942
  Request,
4567
4943
  Redirect,
4568
- E_ROUTE_NOT_FOUND,
4569
- E_CANNOT_LOOKUP_ROUTE,
4570
- E_HTTP_EXCEPTION,
4571
- E_HTTP_REQUEST_ABORTED,
4572
- exceptions_exports,
4573
4944
  ResponseStatus,
4574
4945
  Response,
4575
4946
  Qs,
@@ -4578,4 +4949,3 @@ export {
4578
4949
  Server,
4579
4950
  defineConfig
4580
4951
  };
4581
- //# sourceMappingURL=chunk-6FSCILWX.js.map