@adonisjs/http-server 8.0.0-next.11 → 8.0.0-next.13

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.
@@ -1,1176 +0,0 @@
1
- import {
2
- __export,
3
- createURL
4
- } from "./chunk-2QM3D5BN.js";
5
-
6
- // src/helpers.ts
7
- import cookie from "cookie";
8
- import matchit from "@poppinss/matchit";
9
- import string3 from "@poppinss/utils/string";
10
- import { parseBindingReference } from "@adonisjs/fold";
11
-
12
- // src/utils.ts
13
- import Cache from "tmp-cache";
14
- import { InvalidArgumentsException } from "@poppinss/utils/exception";
15
-
16
- // src/router/group.ts
17
- import Macroable4 from "@poppinss/macroable";
18
-
19
- // src/router/brisk.ts
20
- import Macroable2 from "@poppinss/macroable";
21
-
22
- // src/router/route.ts
23
- import is from "@sindresorhus/is";
24
- import Macroable from "@poppinss/macroable";
25
- import Middleware from "@poppinss/middleware";
26
- import { RuntimeException } from "@poppinss/utils/exception";
27
- import { moduleCaller, moduleImporter } from "@adonisjs/fold";
28
-
29
- // src/debug.ts
30
- import { debuglog } from "util";
31
- var debug_default = debuglog("adonisjs:http");
32
-
33
- // src/router/factories/use_return_value.ts
34
- function canWriteResponseBody(value, ctx) {
35
- return value !== void 0 && // Return value is explicitly defined
36
- !ctx.response.hasLazyBody && // Lazy body is not set
37
- value !== ctx.response;
38
- }
39
- function useReturnValue(ctx) {
40
- return function(value) {
41
- if (canWriteResponseBody(value, ctx)) {
42
- ctx.response.send(value);
43
- }
44
- };
45
- }
46
-
47
- // src/tracing_channels.ts
48
- var tracing_channels_exports = {};
49
- __export(tracing_channels_exports, {
50
- httpExceptionHandler: () => httpExceptionHandler,
51
- httpMiddleware: () => httpMiddleware,
52
- httpRequest: () => httpRequest,
53
- httpResponseSerializer: () => httpResponseSerializer,
54
- httpRouteHandler: () => httpRouteHandler
55
- });
56
- import diagnostics_channel from "diagnostics_channel";
57
- var httpRequest = diagnostics_channel.tracingChannel("adonisjs.http.request");
58
- var httpMiddleware = diagnostics_channel.tracingChannel("adonisjs.http.middleware");
59
- var httpExceptionHandler = diagnostics_channel.tracingChannel(
60
- "adonisjs.http.exception.handler"
61
- );
62
- var httpRouteHandler = diagnostics_channel.tracingChannel("adonisjs.http.route.handler");
63
- var httpResponseSerializer = diagnostics_channel.tracingChannel(
64
- "adonisjs.http.response.serializer"
65
- );
66
-
67
- // src/router/executor.ts
68
- function execute(route, resolver, ctx, errorResponder) {
69
- return route.middleware.runner().errorHandler((error) => errorResponder(error, ctx)).finalHandler(() => {
70
- if (typeof route.handler === "function") {
71
- return httpRouteHandler.tracePromise(
72
- ($ctx) => Promise.resolve(route.handler($ctx)),
73
- httpRouteHandler.hasSubscribers ? { route } : void 0,
74
- void 0,
75
- ctx
76
- ).then(useReturnValue(ctx));
77
- }
78
- return httpRouteHandler.tracePromise(
79
- route.handler.handle,
80
- httpRouteHandler.hasSubscribers ? { route } : void 0,
81
- void 0,
82
- resolver,
83
- ctx
84
- ).then(useReturnValue(ctx));
85
- }).run(async (middleware, next) => {
86
- if (typeof middleware === "function") {
87
- return httpMiddleware.tracePromise(
88
- middleware,
89
- httpMiddleware.hasSubscribers ? { middleware } : void 0,
90
- void 0,
91
- ctx,
92
- next
93
- );
94
- }
95
- return httpMiddleware.tracePromise(
96
- middleware.handle,
97
- httpMiddleware.hasSubscribers ? { middleware } : void 0,
98
- void 0,
99
- resolver,
100
- ctx,
101
- next,
102
- middleware.args
103
- );
104
- });
105
- }
106
-
107
- // src/router/route.ts
108
- import StringBuilder from "@poppinss/utils/string_builder";
109
- import string from "@poppinss/utils/string";
110
- var Route = class extends Macroable {
111
- /**
112
- * Route pattern
113
- */
114
- #pattern;
115
- /**
116
- * HTTP Methods for the route
117
- */
118
- #methods;
119
- /**
120
- * A unique name for the route
121
- */
122
- #name;
123
- /**
124
- * A boolean to prevent route from getting registered within
125
- * the store.
126
- *
127
- * This flag must be set before "Router.commit" method
128
- */
129
- #isDeleted = false;
130
- /**
131
- * Route handler
132
- */
133
- #handler;
134
- /**
135
- * Matchers inherited from the router
136
- */
137
- #globalMatchers;
138
- /**
139
- * Reference to the AdonisJS application
140
- */
141
- #app;
142
- /**
143
- * Middleware registered on the router
144
- */
145
- #routerMiddleware;
146
- /**
147
- * By default the route is part of the `root` domain. Root domain is used
148
- * when no domain is defined
149
- */
150
- #routeDomain = "root";
151
- /**
152
- * An object of matchers to be forwarded to the store. The matchers
153
- * list is populated by calling `where` method
154
- */
155
- #matchers = {};
156
- /**
157
- * Custom prefixes defined on the route or the route parent
158
- * groups
159
- */
160
- #prefixes = [];
161
- /**
162
- * Middleware defined directly on the route or the route parent
163
- * routes. We mantain an array for each layer of the stack
164
- */
165
- #middleware = [];
166
- /**
167
- * Creates a new Route instance
168
- * @param app - The AdonisJS application instance
169
- * @param routerMiddleware - Array of global middleware registered on the router
170
- * @param options - Configuration options for the route
171
- */
172
- constructor(app, routerMiddleware, options) {
173
- super();
174
- this.#app = app;
175
- this.#routerMiddleware = routerMiddleware;
176
- this.#pattern = options.pattern;
177
- this.#methods = options.methods;
178
- this.#globalMatchers = options.globalMatchers;
179
- const { handler, routeName } = this.#resolveRouteHandle(options.handler);
180
- this.#handler = handler;
181
- this.#name = routeName;
182
- }
183
- /**
184
- * Resolves the route handler string expression to a
185
- * handler method object
186
- */
187
- #resolveRouteHandle(handler) {
188
- if (typeof handler === "string") {
189
- const parts = handler.split(".");
190
- const method = parts.length === 1 ? "handle" : parts.pop();
191
- const moduleRefId = parts.join(".");
192
- return {
193
- handler: {
194
- method,
195
- reference: handler,
196
- importExpression: moduleRefId,
197
- ...moduleImporter(() => this.#app.import(moduleRefId), method).toHandleMethod(),
198
- name: handler
199
- },
200
- routeName: `${new StringBuilder(moduleRefId.split("/").pop()).removeSuffix("controller").snakeCase()}.${string.snakeCase(method)}`
201
- };
202
- }
203
- if (Array.isArray(handler)) {
204
- const controller = handler[0];
205
- const method = handler[1] ?? "handle";
206
- if (is.class(controller)) {
207
- return {
208
- handler: {
209
- method,
210
- reference: handler,
211
- importExpression: null,
212
- ...moduleCaller(controller, method).toHandleMethod()
213
- },
214
- routeName: `${new StringBuilder(controller.name).removeSuffix("controller").snakeCase()}.${string.snakeCase(method)}`
215
- };
216
- }
217
- return {
218
- handler: {
219
- method,
220
- reference: handler,
221
- importExpression: String(controller),
222
- ...moduleImporter(controller, method).toHandleMethod()
223
- },
224
- routeName: controller.name ? `${new StringBuilder(controller.name).removeSuffix("controller").snakeCase()}.${string.snakeCase(method)}` : void 0
225
- };
226
- }
227
- return { handler };
228
- }
229
- /**
230
- * Returns an object of param matchers by merging global and local
231
- * matchers. The local copy is given preference over the global
232
- * one's
233
- */
234
- #getMatchers() {
235
- return { ...this.#globalMatchers, ...this.#matchers };
236
- }
237
- /**
238
- * Returns a normalized pattern string by prefixing the `prefix` (if defined).
239
- */
240
- #computePattern() {
241
- const pattern = dropSlash(this.#pattern);
242
- const prefix = this.#prefixes.slice().reverse().map((one) => dropSlash(one)).join("");
243
- return prefix ? `${prefix}${pattern === "/" ? "" : pattern}` : pattern;
244
- }
245
- /**
246
- * Define matcher for a given param. If a matcher exists, then we do not
247
- * override that, since the routes inside a group will set matchers
248
- * before the group, so they should have priority over the group
249
- * matchers.
250
- *
251
- * ```ts
252
- * Route.group(() => {
253
- * Route.get('/:id', 'handler').where('id', /^[0-9]$/)
254
- * }).where('id', /[^a-z$]/)
255
- * ```
256
- *
257
- * The `/^[0-9]$/` will win over the matcher defined by the group
258
- */
259
- where(param, matcher) {
260
- if (this.#matchers[param]) {
261
- return this;
262
- }
263
- if (typeof matcher === "string") {
264
- this.#matchers[param] = { match: new RegExp(matcher) };
265
- } else if (is.regExp(matcher)) {
266
- this.#matchers[param] = { match: matcher };
267
- } else {
268
- this.#matchers[param] = matcher;
269
- }
270
- return this;
271
- }
272
- /**
273
- * Define prefix for the route. Calling this method multiple times
274
- * applies multiple prefixes in the reverse order.
275
- * @param prefix - The prefix to add to the route
276
- * @returns Current Route instance for method chaining
277
- */
278
- prefix(prefix) {
279
- this.#prefixes.push(prefix);
280
- return this;
281
- }
282
- /**
283
- * Define a custom domain for the route. We do not overwrite the domain
284
- * unless `overwrite` flag is set to true.
285
- */
286
- domain(domain, overwrite = false) {
287
- if (this.#routeDomain === "root" || overwrite) {
288
- this.#routeDomain = domain;
289
- }
290
- return this;
291
- }
292
- /**
293
- * Define one or more middleware to be executed before the route
294
- * handler.
295
- *
296
- * Named middleware can be referenced using the name registered with
297
- * the router middleware store.
298
- */
299
- use(middleware) {
300
- this.#middleware.push(Array.isArray(middleware) ? middleware : [middleware]);
301
- return this;
302
- }
303
- /**
304
- * Alias for {@link Route.use}
305
- */
306
- middleware(middleware) {
307
- return this.use(middleware);
308
- }
309
- /**
310
- * Give a unique name to the route. Assinging a new unique removes the
311
- * existing name of the route.
312
- *
313
- * Setting prepends to true prefixes the name to the existing name.
314
- */
315
- as(name, prepend = false) {
316
- if (prepend) {
317
- if (!this.#name) {
318
- throw new RuntimeException(
319
- `Routes inside a group must have names before calling "router.group.as"`
320
- );
321
- }
322
- this.#name = `${name}.${this.#name}`;
323
- return this;
324
- }
325
- this.#name = name;
326
- return this;
327
- }
328
- /**
329
- * Check if the route was marked to be deleted
330
- */
331
- isDeleted() {
332
- return this.#isDeleted;
333
- }
334
- /**
335
- * Mark route as deleted. Deleted routes are not registered
336
- * with the route store
337
- */
338
- markAsDeleted() {
339
- this.#isDeleted = true;
340
- }
341
- /**
342
- * Get the route name
343
- */
344
- getName() {
345
- return this.#name;
346
- }
347
- /**
348
- * Get the route pattern
349
- */
350
- getPattern() {
351
- return this.#pattern;
352
- }
353
- /**
354
- * Set the route pattern
355
- */
356
- setPattern(pattern) {
357
- this.#pattern = pattern;
358
- return this;
359
- }
360
- /**
361
- * Returns the stack of middleware registered on the route.
362
- * The value is shared by reference.
363
- */
364
- getMiddleware() {
365
- return this.#middleware;
366
- }
367
- /**
368
- * Returns the middleware instance for persistence inside the
369
- * store
370
- */
371
- #getMiddlewareForStore() {
372
- const middleware = new Middleware();
373
- this.#routerMiddleware.forEach((one) => {
374
- debug_default("adding global middleware to route %s, %O", this.#pattern, one);
375
- middleware.add(one);
376
- });
377
- this.#middleware.flat().forEach((one) => {
378
- debug_default("adding named middleware to route %s, %O", this.#pattern, one);
379
- middleware.add(one);
380
- });
381
- middleware.freeze();
382
- return middleware;
383
- }
384
- /**
385
- * Returns JSON representation of the route
386
- */
387
- toJSON() {
388
- const pattern = this.#computePattern();
389
- const matchers = this.#getMatchers();
390
- return {
391
- domain: this.#routeDomain,
392
- pattern,
393
- matchers,
394
- tokens: parseRoute(pattern, matchers),
395
- meta: {},
396
- name: this.#name,
397
- handler: this.#handler,
398
- methods: this.#methods,
399
- middleware: this.#getMiddlewareForStore(),
400
- execute
401
- };
402
- }
403
- };
404
-
405
- // src/router/brisk.ts
406
- var BriskRoute = class extends Macroable2 {
407
- /**
408
- * Route pattern
409
- */
410
- #pattern;
411
- /**
412
- * Matchers inherited from the router
413
- */
414
- #globalMatchers;
415
- /**
416
- * Reference to the AdonisJS application
417
- */
418
- #app;
419
- /**
420
- * Middleware registered on the router
421
- */
422
- #routerMiddleware;
423
- /**
424
- * Reference to route instance. Set after `setHandler` is called
425
- */
426
- route = null;
427
- /**
428
- * Creates a new BriskRoute instance
429
- * @param app - The AdonisJS application instance
430
- * @param routerMiddleware - Array of global middleware registered on the router
431
- * @param options - Configuration options for the brisk route
432
- */
433
- constructor(app, routerMiddleware, options) {
434
- super();
435
- this.#app = app;
436
- this.#routerMiddleware = routerMiddleware;
437
- this.#pattern = options.pattern;
438
- this.#globalMatchers = options.globalMatchers;
439
- }
440
- /**
441
- * Set handler for the brisk route
442
- * @param handler - The route handler function
443
- * @returns The created route instance
444
- */
445
- setHandler(handler) {
446
- this.route = new Route(this.#app, this.#routerMiddleware, {
447
- pattern: this.#pattern,
448
- globalMatchers: this.#globalMatchers,
449
- methods: ["GET", "HEAD"],
450
- handler
451
- });
452
- return this.route;
453
- }
454
- /**
455
- * Redirects to a given route. Params from the original request will
456
- * be used when no custom params are defined.
457
- * @param args - Route identifier, parameters, and options for building the redirect URL
458
- * @returns The created route instance
459
- */
460
- redirect(...args) {
461
- const [identifier, params, options] = args;
462
- function redirectsToRoute(ctx) {
463
- const redirector = ctx.response.redirect();
464
- if (options?.status) {
465
- redirector.status(options.status);
466
- }
467
- return redirector.toRoute(identifier, params || ctx.params, options);
468
- }
469
- Object.defineProperty(redirectsToRoute, "listArgs", { value: identifier, writable: false });
470
- return this.setHandler(redirectsToRoute);
471
- }
472
- /**
473
- * Redirect request to a fixed URL
474
- * @param url - The URL to redirect to
475
- * @param options - Optional redirect options including HTTP status code
476
- * @returns The created route instance
477
- */
478
- redirectToPath(url, options) {
479
- function redirectsToPath(ctx) {
480
- const redirector = ctx.response.redirect();
481
- if (options?.status) {
482
- redirector.status(options.status);
483
- }
484
- return redirector.toPath(url);
485
- }
486
- Object.defineProperty(redirectsToPath, "listArgs", { value: url, writable: false });
487
- return this.setHandler(redirectsToPath);
488
- }
489
- };
490
-
491
- // src/router/resource.ts
492
- import string2 from "@poppinss/utils/string";
493
- import Macroable3 from "@poppinss/macroable";
494
- import { RuntimeException as RuntimeException2 } from "@poppinss/utils/exception";
495
- var RouteResource = class extends Macroable3 {
496
- /**
497
- * Resource identifier. Nested resources are separated
498
- * with a dot notation
499
- */
500
- #resource;
501
- /**
502
- * The controller to handle resource routing requests
503
- */
504
- #controller;
505
- /**
506
- * Is it a shallow resource? Shallow resources URLs do not have parent
507
- * resource name and id once they can be identified with the id.
508
- */
509
- #shallow = false;
510
- /**
511
- * Matchers inherited from the router
512
- */
513
- #globalMatchers;
514
- /**
515
- * Reference to the AdonisJS application
516
- */
517
- #app;
518
- /**
519
- * Middleware registered on the router
520
- */
521
- #routerMiddleware;
522
- /**
523
- * Parameter names for the resources. Defaults to `id` for
524
- * a singular resource and `resource_id` for nested
525
- * resources.
526
- */
527
- #params = {};
528
- /**
529
- * Base name for the routes. We suffix action names
530
- * on top of the base name
531
- */
532
- #routesBaseName;
533
- /**
534
- * A collection of routes instances that belongs to this resource
535
- */
536
- routes = [];
537
- /**
538
- * Creates a new RouteResource instance
539
- * @param app - The AdonisJS application instance
540
- * @param routerMiddleware - Array of global middleware registered on the router
541
- * @param options - Configuration options for the route resource
542
- */
543
- constructor(app, routerMiddleware, options) {
544
- super();
545
- this.#validateResourceName(options.resource);
546
- this.#app = app;
547
- this.#shallow = options.shallow;
548
- this.#routerMiddleware = routerMiddleware;
549
- this.#controller = options.controller;
550
- this.#globalMatchers = options.globalMatchers;
551
- this.#resource = this.#normalizeResourceName(options.resource);
552
- this.#routesBaseName = this.#getRoutesBaseName();
553
- this.#buildRoutes();
554
- }
555
- /**
556
- * Normalizes the resource name to dropping leading and trailing
557
- * slashes.
558
- */
559
- #normalizeResourceName(resource) {
560
- return resource.replace(/^\//, "").replace(/\/$/, "");
561
- }
562
- /**
563
- * Ensure resource name is not an empty string
564
- */
565
- #validateResourceName(resource) {
566
- if (!resource || resource === "/") {
567
- throw new RuntimeException2(`Invalid resource name "${resource}"`);
568
- }
569
- }
570
- /**
571
- * Converting segments of a resource to snake case to
572
- * make the route name.
573
- */
574
- #getRoutesBaseName() {
575
- return this.#resource.split(".").map((token) => string2.snakeCase(token)).join(".");
576
- }
577
- /**
578
- * Create a new route for the given pattern, methods and controller action
579
- */
580
- #createRoute(pattern, methods, action) {
581
- const route = new Route(this.#app, this.#routerMiddleware, {
582
- pattern,
583
- methods,
584
- handler: typeof this.#controller === "string" ? `${this.#controller}.${action}` : [this.#controller, action],
585
- globalMatchers: this.#globalMatchers
586
- });
587
- route.as(`${this.#routesBaseName}.${action}`);
588
- this.routes.push(route);
589
- }
590
- /**
591
- * Returns the `resource_id` name for a given resource. The
592
- * resource name is converted to singular form and
593
- * transformed to snake case.
594
- *
595
- * photos becomes photo_id
596
- * users becomes user_id
597
- */
598
- #getResourceId(resource) {
599
- return `${string2.snakeCase(string2.singular(resource))}_id`;
600
- }
601
- /**
602
- * Build routes for the given resource
603
- */
604
- #buildRoutes() {
605
- const resources = this.#resource.split(".");
606
- const mainResource = resources.pop();
607
- this.#params[mainResource] = ":id";
608
- const baseURI = `${resources.map((resource) => {
609
- const paramName = `:${this.#getResourceId(resource)}`;
610
- this.#params[resource] = paramName;
611
- return `${resource}/${paramName}`;
612
- }).join("/")}/${mainResource}`;
613
- this.#createRoute(baseURI, ["GET", "HEAD"], "index");
614
- this.#createRoute(`${baseURI}/create`, ["GET", "HEAD"], "create");
615
- this.#createRoute(baseURI, ["POST"], "store");
616
- this.#createRoute(`${this.#shallow ? mainResource : baseURI}/:id`, ["GET", "HEAD"], "show");
617
- this.#createRoute(`${this.#shallow ? mainResource : baseURI}/:id/edit`, ["GET", "HEAD"], "edit");
618
- this.#createRoute(`${this.#shallow ? mainResource : baseURI}/:id`, ["PUT", "PATCH"], "update");
619
- this.#createRoute(`${this.#shallow ? mainResource : baseURI}/:id`, ["DELETE"], "destroy");
620
- }
621
- /**
622
- * Filter the routes based on their partial names
623
- */
624
- #filter(names, inverse) {
625
- const actions = Array.isArray(names) ? names : [names];
626
- return this.routes.filter((route) => {
627
- const match = actions.find((name) => route.getName().endsWith(name));
628
- return inverse ? !match : match;
629
- });
630
- }
631
- /**
632
- * Register only given routes and remove others
633
- * @param names - Array of action names to keep
634
- * @returns Current RouteResource instance with filtered actions
635
- */
636
- only(names) {
637
- this.#filter(names, true).forEach((route) => route.markAsDeleted());
638
- return this;
639
- }
640
- /**
641
- * Register all routes, except the one's defined
642
- * @param names - Array of action names to exclude
643
- * @returns Current RouteResource instance with filtered actions
644
- */
645
- except(names) {
646
- this.#filter(names, false).forEach((route) => route.markAsDeleted());
647
- return this;
648
- }
649
- /**
650
- * Register api only routes. The `create` and `edit` routes, which
651
- * are meant to show forms will not be registered
652
- * @returns Current RouteResource instance without create and edit actions
653
- */
654
- apiOnly() {
655
- return this.except(["create", "edit"]);
656
- }
657
- /**
658
- * Define matcher for params inside the resource
659
- * @param key - The parameter name to match
660
- * @param matcher - The matcher pattern (RegExp, string, or RouteMatcher)
661
- * @returns Current RouteResource instance for method chaining
662
- */
663
- where(key, matcher) {
664
- this.routes.forEach((route) => {
665
- route.where(key, matcher);
666
- });
667
- return this;
668
- }
669
- tap(actions, callback) {
670
- if (typeof actions === "function") {
671
- this.routes.forEach((route) => {
672
- if (!route.isDeleted()) {
673
- actions(route);
674
- }
675
- });
676
- return this;
677
- }
678
- this.#filter(actions, false).forEach((route) => {
679
- if (!route.isDeleted()) {
680
- callback(route);
681
- }
682
- });
683
- return this;
684
- }
685
- /**
686
- * Set the param name for a given resource
687
- * @param resources - Object mapping resource names to parameter names
688
- * @returns Current RouteResource instance for method chaining
689
- */
690
- params(resources) {
691
- Object.keys(resources).forEach((resource) => {
692
- const param = resources[resource];
693
- const existingParam = this.#params[resource];
694
- this.#params[resource] = `:${param}`;
695
- this.routes.forEach((route) => {
696
- route.setPattern(
697
- route.getPattern().replace(`${resource}/${existingParam}`, `${resource}/:${param}`)
698
- );
699
- });
700
- });
701
- return this;
702
- }
703
- /**
704
- * Define one or more middleware on the routes created by
705
- * the resource.
706
- *
707
- * Calling this method multiple times will append middleware
708
- * to existing list.
709
- * @param actions - Action name(s) or '*' for all actions
710
- * @param middleware - Middleware function(s) to apply
711
- * @returns Current RouteResource instance for method chaining
712
- */
713
- use(actions, middleware) {
714
- if (actions === "*") {
715
- this.tap((route) => route.use(middleware));
716
- } else {
717
- this.tap(actions, (route) => route.use(middleware));
718
- }
719
- return this;
720
- }
721
- /**
722
- * Alias for {@link RouteResource.use}
723
- * @param actions - Action name(s) or '*' for all actions
724
- * @param middleware - Middleware function(s) to apply
725
- * @returns Current RouteResource instance for method chaining
726
- */
727
- middleware(actions, middleware) {
728
- return this.use(actions, middleware);
729
- }
730
- /**
731
- * Prepend name to all the routes
732
- * @param name - The name to prepend to all route names
733
- * @param normalizeName - Whether to normalize the name to snake_case
734
- * @returns Current RouteResource instance for method chaining
735
- */
736
- as(name, normalizeName = true) {
737
- name = normalizeName ? string2.snakeCase(name) : name;
738
- this.routes.forEach((route) => {
739
- route.as(route.getName().replace(this.#routesBaseName, name), false);
740
- });
741
- this.#routesBaseName = name;
742
- return this;
743
- }
744
- };
745
-
746
- // src/router/group.ts
747
- var RouteGroup = class _RouteGroup extends Macroable4 {
748
- /**
749
- * Creates a new RouteGroup instance
750
- * @param routes - Array of routes that belong to this group
751
- */
752
- constructor(routes) {
753
- super();
754
- this.routes = routes;
755
- }
756
- /**
757
- * Array of middleware registered on the group.
758
- */
759
- #middleware = [];
760
- /**
761
- * Shares midldeware stack with the routes. The method is invoked recursively
762
- * to only register middleware with the route class and not with the
763
- * resource or the child group
764
- */
765
- #shareMiddlewareStackWithRoutes(route) {
766
- if (route instanceof _RouteGroup) {
767
- route.routes.forEach((child) => this.#shareMiddlewareStackWithRoutes(child));
768
- return;
769
- }
770
- if (route instanceof RouteResource) {
771
- route.routes.forEach((child) => child.getMiddleware().unshift(this.#middleware));
772
- return;
773
- }
774
- if (route instanceof BriskRoute) {
775
- route.route.getMiddleware().unshift(this.#middleware);
776
- return;
777
- }
778
- route.getMiddleware().unshift(this.#middleware);
779
- }
780
- /**
781
- * Updates the route name. The method is invoked recursively to only update
782
- * the name with the route class and not with the resource or the child
783
- * group.
784
- */
785
- #updateRouteName(route, name) {
786
- if (route instanceof _RouteGroup) {
787
- route.routes.forEach((child) => this.#updateRouteName(child, name));
788
- return;
789
- }
790
- if (route instanceof RouteResource) {
791
- route.routes.forEach((child) => child.as(name, true));
792
- return;
793
- }
794
- if (route instanceof BriskRoute) {
795
- route.route.as(name, true);
796
- return;
797
- }
798
- route.as(name, true);
799
- }
800
- /**
801
- * Sets prefix on the route. The method is invoked recursively to only set
802
- * the prefix with the route class and not with the resource or the
803
- * child group.
804
- */
805
- #setRoutePrefix(route, prefix) {
806
- if (route instanceof _RouteGroup) {
807
- route.routes.forEach((child) => this.#setRoutePrefix(child, prefix));
808
- return;
809
- }
810
- if (route instanceof RouteResource) {
811
- route.routes.forEach((child) => child.prefix(prefix));
812
- return;
813
- }
814
- if (route instanceof BriskRoute) {
815
- route.route.prefix(prefix);
816
- return;
817
- }
818
- route.prefix(prefix);
819
- }
820
- /**
821
- * Updates domain on the route. The method is invoked recursively to only update
822
- * the domain with the route class and not with the resource or the child
823
- * group.
824
- */
825
- #updateRouteDomain(route, domain) {
826
- if (route instanceof _RouteGroup) {
827
- route.routes.forEach((child) => this.#updateRouteDomain(child, domain));
828
- return;
829
- }
830
- if (route instanceof RouteResource) {
831
- route.routes.forEach((child) => child.domain(domain));
832
- return;
833
- }
834
- if (route instanceof BriskRoute) {
835
- route.route.domain(domain, false);
836
- return;
837
- }
838
- route.domain(domain, false);
839
- }
840
- /**
841
- * Updates matchers on the route. The method is invoked recursively to only update
842
- * the matchers with the route class and not with the resource or the child
843
- * group.
844
- */
845
- #updateRouteMatchers(route, param, matcher) {
846
- if (route instanceof _RouteGroup) {
847
- route.routes.forEach((child) => this.#updateRouteMatchers(child, param, matcher));
848
- return;
849
- }
850
- if (route instanceof RouteResource) {
851
- route.routes.forEach((child) => child.where(param, matcher));
852
- return;
853
- }
854
- if (route instanceof BriskRoute) {
855
- route.route.where(param, matcher);
856
- return;
857
- }
858
- route.where(param, matcher);
859
- }
860
- /**
861
- * Define route param matcher
862
- *
863
- * ```ts
864
- * Route.group(() => {
865
- * }).where('id', /^[0-9]+/)
866
- * ```
867
- * @param param - The parameter name to match
868
- * @param matcher - The matcher pattern (RegExp, string, or RouteMatcher)
869
- * @returns Current RouteGroup instance for method chaining
870
- */
871
- where(param, matcher) {
872
- this.routes.forEach((route) => this.#updateRouteMatchers(route, param, matcher));
873
- return this;
874
- }
875
- /**
876
- * Define prefix all the routes in the group.
877
- *
878
- * ```ts
879
- * Route.group(() => {
880
- * }).prefix('v1')
881
- * ```
882
- * @param prefix - The prefix to add to all routes in the group
883
- * @returns Current RouteGroup instance for method chaining
884
- */
885
- prefix(prefix) {
886
- this.routes.forEach((route) => this.#setRoutePrefix(route, prefix));
887
- return this;
888
- }
889
- /**
890
- * Define domain for all the routes.
891
- *
892
- * ```ts
893
- * Route.group(() => {
894
- * }).domain(':name.adonisjs.com')
895
- * ```
896
- * @param domain - The domain pattern for all routes in the group
897
- * @returns Current RouteGroup instance for method chaining
898
- */
899
- domain(domain) {
900
- this.routes.forEach((route) => this.#updateRouteDomain(route, domain));
901
- return this;
902
- }
903
- /**
904
- * Prepend name to the routes name.
905
- *
906
- * ```ts
907
- * Route.group(() => {
908
- * }).as('version1')
909
- * ```
910
- * @param name - The name to prepend to all route names in the group
911
- * @returns Current RouteGroup instance for method chaining
912
- */
913
- as(name) {
914
- this.routes.forEach((route) => this.#updateRouteName(route, name));
915
- return this;
916
- }
917
- /**
918
- * Prepend an array of middleware to all routes middleware.
919
- *
920
- * ```ts
921
- * Route.group(() => {
922
- * }).use(middleware.auth())
923
- * ```
924
- * @param middleware - Middleware function(s) to apply to all routes in the group
925
- * @returns Current RouteGroup instance for method chaining
926
- */
927
- use(middleware) {
928
- if (!this.#middleware.length) {
929
- this.routes.forEach((route) => this.#shareMiddlewareStackWithRoutes(route));
930
- }
931
- if (Array.isArray(middleware)) {
932
- for (let one of middleware) {
933
- this.#middleware.push(one);
934
- }
935
- } else {
936
- this.#middleware.push(middleware);
937
- }
938
- return this;
939
- }
940
- /**
941
- * Alias for {@link RouteGroup.use}
942
- * @param middleware - Middleware function(s) to apply to all routes in the group
943
- * @returns Current RouteGroup instance for method chaining
944
- */
945
- middleware(middleware) {
946
- return this.use(middleware);
947
- }
948
- };
949
-
950
- // src/utils.ts
951
- var proxyCache = new Cache({ max: 200 });
952
- function dropSlash(input) {
953
- if (input === "/") {
954
- return "/";
955
- }
956
- return `/${input.replace(/^\//, "").replace(/\/$/, "")}`;
957
- }
958
- function toRoutesJSON(routes) {
959
- return routes.reduce((list, route) => {
960
- if (route instanceof RouteGroup) {
961
- list = list.concat(toRoutesJSON(route.routes));
962
- return list;
963
- }
964
- if (route instanceof RouteResource) {
965
- list = list.concat(toRoutesJSON(route.routes));
966
- return list;
967
- }
968
- if (route instanceof BriskRoute) {
969
- if (route.route && !route.route.isDeleted()) {
970
- list.push(route.route.toJSON());
971
- }
972
- return list;
973
- }
974
- if (!route.isDeleted()) {
975
- list.push(route.toJSON());
976
- }
977
- return list;
978
- }, []);
979
- }
980
- function trustProxy(remoteAddress, proxyFn) {
981
- if (proxyCache.has(remoteAddress)) {
982
- return proxyCache.get(remoteAddress);
983
- }
984
- const result = proxyFn(remoteAddress, 0);
985
- proxyCache.set(remoteAddress, result);
986
- return result;
987
- }
988
- function parseRange(range, value) {
989
- const parts = range.split("..");
990
- const min = Number(parts[0]);
991
- const max = Number(parts[1]);
992
- if (parts.length === 1 && !Number.isNaN(min)) {
993
- return {
994
- [min]: value
995
- };
996
- }
997
- if (Number.isNaN(min) || Number.isNaN(max)) {
998
- return {};
999
- }
1000
- if (min === max) {
1001
- return {
1002
- [min]: value
1003
- };
1004
- }
1005
- if (max < min) {
1006
- throw new InvalidArgumentsException(`Invalid range "${range}"`);
1007
- }
1008
- return [...Array(max - min + 1).keys()].reduce(
1009
- (result, step) => {
1010
- result[min + step] = value;
1011
- return result;
1012
- },
1013
- {}
1014
- );
1015
- }
1016
- function decodeComponentChar(highCharCode, lowCharCode) {
1017
- if (highCharCode === 50) {
1018
- if (lowCharCode === 53) return "%";
1019
- if (lowCharCode === 51) return "#";
1020
- if (lowCharCode === 52) return "$";
1021
- if (lowCharCode === 54) return "&";
1022
- if (lowCharCode === 66) return "+";
1023
- if (lowCharCode === 98) return "+";
1024
- if (lowCharCode === 67) return ",";
1025
- if (lowCharCode === 99) return ",";
1026
- if (lowCharCode === 70) return "/";
1027
- if (lowCharCode === 102) return "/";
1028
- return null;
1029
- }
1030
- if (highCharCode === 51) {
1031
- if (lowCharCode === 65) return ":";
1032
- if (lowCharCode === 97) return ":";
1033
- if (lowCharCode === 66) return ";";
1034
- if (lowCharCode === 98) return ";";
1035
- if (lowCharCode === 68) return "=";
1036
- if (lowCharCode === 100) return "=";
1037
- if (lowCharCode === 70) return "?";
1038
- if (lowCharCode === 102) return "?";
1039
- return null;
1040
- }
1041
- if (highCharCode === 52 && lowCharCode === 48) {
1042
- return "@";
1043
- }
1044
- return null;
1045
- }
1046
- function safeDecodeURI(path, useSemicolonDelimiter) {
1047
- let shouldDecode = false;
1048
- let shouldDecodeParam = false;
1049
- let querystring = "";
1050
- for (let i = 1; i < path.length; i++) {
1051
- const charCode = path.charCodeAt(i);
1052
- if (charCode === 37) {
1053
- const highCharCode = path.charCodeAt(i + 1);
1054
- const lowCharCode = path.charCodeAt(i + 2);
1055
- if (decodeComponentChar(highCharCode, lowCharCode) === null) {
1056
- shouldDecode = true;
1057
- } else {
1058
- shouldDecodeParam = true;
1059
- if (highCharCode === 50 && lowCharCode === 53) {
1060
- shouldDecode = true;
1061
- path = path.slice(0, i + 1) + "25" + path.slice(i + 1);
1062
- i += 2;
1063
- }
1064
- i += 2;
1065
- }
1066
- } else if (charCode === 63 || charCode === 35 || charCode === 59 && useSemicolonDelimiter) {
1067
- querystring = path.slice(i + 1);
1068
- path = path.slice(0, i);
1069
- break;
1070
- }
1071
- }
1072
- const decodedPath = shouldDecode ? decodeURI(path) : path;
1073
- return { pathname: decodedPath, query: querystring, shouldDecodeParam };
1074
- }
1075
-
1076
- // src/helpers.ts
1077
- import { default as default2 } from "encodeurl";
1078
- import { default as default3 } from "mime-types";
1079
- function parseRoute(pattern, matchers) {
1080
- const tokens = matchit.parse(pattern, matchers);
1081
- return tokens;
1082
- }
1083
- function createSignedURL(identifier, tokens, searchParamsStringifier, encryption, params, options) {
1084
- const signature = encryption.verifier.sign(
1085
- createURL(identifier, tokens, searchParamsStringifier, params, {
1086
- ...options,
1087
- prefixUrl: void 0
1088
- }),
1089
- options?.expiresIn,
1090
- options?.purpose
1091
- );
1092
- return createURL(identifier, tokens, searchParamsStringifier, params, {
1093
- ...options,
1094
- qs: { ...options?.qs, signature }
1095
- });
1096
- }
1097
- function matchRoute(url, patterns) {
1098
- const tokensBucket = patterns.map((pattern) => parseRoute(pattern));
1099
- const match = matchit.match(url, tokensBucket);
1100
- if (!match.length) {
1101
- return null;
1102
- }
1103
- return matchit.exec(url, match);
1104
- }
1105
- function serializeCookie(key, value, options) {
1106
- let expires;
1107
- let maxAge;
1108
- if (options) {
1109
- expires = typeof options.expires === "function" ? options.expires() : options.expires;
1110
- maxAge = options.maxAge ? string3.seconds.parse(options.maxAge) : void 0;
1111
- }
1112
- return cookie.serialize(key, value, { ...options, maxAge, expires });
1113
- }
1114
- async function middlewareInfo(middleware) {
1115
- if (typeof middleware === "function") {
1116
- return {
1117
- type: "closure",
1118
- name: middleware.name || "closure"
1119
- };
1120
- }
1121
- if ("args" in middleware) {
1122
- return {
1123
- type: "named",
1124
- name: middleware.name,
1125
- args: middleware.args,
1126
- ...await parseBindingReference([middleware.reference])
1127
- };
1128
- }
1129
- return {
1130
- type: "global",
1131
- name: middleware.name,
1132
- ...await parseBindingReference([middleware.reference])
1133
- };
1134
- }
1135
- async function routeInfo(route) {
1136
- return "reference" in route.handler ? {
1137
- type: "controller",
1138
- ...await parseBindingReference(route.handler.reference)
1139
- } : {
1140
- type: "closure",
1141
- name: route.handler.name || "closure",
1142
- args: "listArgs" in route.handler ? String(route.handler.listArgs) : void 0
1143
- };
1144
- }
1145
- function appendQueryString(uri, queryString, qsParser) {
1146
- const { query, pathname } = safeDecodeURI(uri, false);
1147
- const mergedQueryString = qsParser.stringify(Object.assign(qsParser.parse(query), queryString));
1148
- return mergedQueryString ? `${pathname}?${mergedQueryString}` : pathname;
1149
- }
1150
-
1151
- export {
1152
- debug_default,
1153
- canWriteResponseBody,
1154
- httpRequest,
1155
- httpMiddleware,
1156
- httpExceptionHandler,
1157
- httpResponseSerializer,
1158
- tracing_channels_exports,
1159
- parseRoute,
1160
- createSignedURL,
1161
- matchRoute,
1162
- serializeCookie,
1163
- middlewareInfo,
1164
- routeInfo,
1165
- appendQueryString,
1166
- default2 as default,
1167
- default3 as default2,
1168
- Route,
1169
- BriskRoute,
1170
- RouteResource,
1171
- RouteGroup,
1172
- toRoutesJSON,
1173
- trustProxy,
1174
- parseRange,
1175
- safeDecodeURI
1176
- };