File size: 9,475 Bytes
a5d718a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var request_exports = {};
__export(request_exports, {
  HonoRequest: () => HonoRequest,
  cloneRawRequest: () => cloneRawRequest
});
module.exports = __toCommonJS(request_exports);
var import_http_exception = require("./http-exception");
var import_constants = require("./request/constants");
var import_body = require("./utils/body");
var import_url = require("./utils/url");
const tryDecodeURIComponent = (str) => (0, import_url.tryDecode)(str, import_url.decodeURIComponent_);
class HonoRequest {
  /**

   * `.raw` can get the raw Request object.

   *

   * @see {@link https://hono.dev/docs/api/request#raw}

   *

   * @example

   * ```ts

   * // For Cloudflare Workers

   * app.post('/', async (c) => {

   *   const metadata = c.req.raw.cf?.hostMetadata?

   *   ...

   * })

   * ```

   */
  raw;
  #validatedData;
  // Short name of validatedData
  #matchResult;
  routeIndex = 0;
  /**

   * `.path` can get the pathname of the request.

   *

   * @see {@link https://hono.dev/docs/api/request#path}

   *

   * @example

   * ```ts

   * app.get('/about/me', (c) => {

   *   const pathname = c.req.path // `/about/me`

   * })

   * ```

   */
  path;
  bodyCache = {};
  constructor(request, path = "/", matchResult = [[]]) {
    this.raw = request;
    this.path = path;
    this.#matchResult = matchResult;
    this.#validatedData = {};
  }
  param(key) {
    return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
  }
  #getDecodedParam(key) {
    const paramKey = this.#matchResult[0][this.routeIndex][1][key];
    const param = this.#getParamValue(paramKey);
    return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
  }
  #getAllDecodedParams() {
    const decoded = {};
    const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
    for (const key of keys) {
      const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
      if (value !== void 0) {
        decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
      }
    }
    return decoded;
  }
  #getParamValue(paramKey) {
    return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
  }
  query(key) {
    return (0, import_url.getQueryParam)(this.url, key);
  }
  queries(key) {
    return (0, import_url.getQueryParams)(this.url, key);
  }
  header(name) {
    if (name) {
      return this.raw.headers.get(name) ?? void 0;
    }
    const headerData = {};
    this.raw.headers.forEach((value, key) => {
      headerData[key] = value;
    });
    return headerData;
  }
  async parseBody(options) {
    return (0, import_body.parseBody)(this, options);
  }
  #cachedBody = (key) => {
    const { bodyCache, raw } = this;
    const cachedBody = bodyCache[key];
    if (cachedBody) {
      return cachedBody;
    }
    const anyCachedKey = Object.keys(bodyCache)[0];
    if (anyCachedKey) {
      return bodyCache[anyCachedKey].then((body) => {
        if (anyCachedKey === "json") {
          body = JSON.stringify(body);
        }
        return new Response(body)[key]();
      });
    }
    return bodyCache[key] = raw[key]();
  };
  /**

   * `.json()` can parse Request body of type `application/json`

   *

   * @see {@link https://hono.dev/docs/api/request#json}

   *

   * @example

   * ```ts

   * app.post('/entry', async (c) => {

   *   const body = await c.req.json()

   * })

   * ```

   */
  json() {
    return this.#cachedBody("text").then((text) => JSON.parse(text));
  }
  /**

   * `.text()` can parse Request body of type `text/plain`

   *

   * @see {@link https://hono.dev/docs/api/request#text}

   *

   * @example

   * ```ts

   * app.post('/entry', async (c) => {

   *   const body = await c.req.text()

   * })

   * ```

   */
  text() {
    return this.#cachedBody("text");
  }
  /**

   * `.arrayBuffer()` parse Request body as an `ArrayBuffer`

   *

   * @see {@link https://hono.dev/docs/api/request#arraybuffer}

   *

   * @example

   * ```ts

   * app.post('/entry', async (c) => {

   *   const body = await c.req.arrayBuffer()

   * })

   * ```

   */
  arrayBuffer() {
    return this.#cachedBody("arrayBuffer");
  }
  /**

   * `.bytes()` parses the request body as a `Uint8Array`.

   *

   * @see {@link https://hono.dev/docs/api/request#bytes}

   *

   * @example

   * ```ts

   * app.post('/entry', async (c) => {

   *   const body = await c.req.bytes()

   * })

   * ```

   */
  bytes() {
    return this.#cachedBody("arrayBuffer").then((buffer) => new Uint8Array(buffer));
  }
  /**

   * Parses the request body as a `Blob`.

   * @example

   * ```ts

   * app.post('/entry', async (c) => {

   *   const body = await c.req.blob();

   * });

   * ```

   * @see https://hono.dev/docs/api/request#blob

   */
  blob() {
    return this.#cachedBody("blob");
  }
  /**

   * Parses the request body as `FormData`.

   * @example

   * ```ts

   * app.post('/entry', async (c) => {

   *   const body = await c.req.formData();

   * });

   * ```

   * @see https://hono.dev/docs/api/request#formdata

   */
  formData() {
    return this.#cachedBody("formData");
  }
  /**

   * Adds validated data to the request.

   *

   * @param target - The target of the validation.

   * @param data - The validated data to add.

   */
  addValidatedData(target, data) {
    this.#validatedData[target] = data;
  }
  valid(target) {
    return this.#validatedData[target];
  }
  /**

   * `.url()` can get the request url strings.

   *

   * @see {@link https://hono.dev/docs/api/request#url}

   *

   * @example

   * ```ts

   * app.get('/about/me', (c) => {

   *   const url = c.req.url // `http://localhost:8787/about/me`

   *   ...

   * })

   * ```

   */
  get url() {
    return this.raw.url;
  }
  /**

   * `.method()` can get the method name of the request.

   *

   * @see {@link https://hono.dev/docs/api/request#method}

   *

   * @example

   * ```ts

   * app.get('/about/me', (c) => {

   *   const method = c.req.method // `GET`

   * })

   * ```

   */
  get method() {
    return this.raw.method;
  }
  get [import_constants.GET_MATCH_RESULT]() {
    return this.#matchResult;
  }
  /**

   * `.matchedRoutes()` can return a matched route in the handler

   *

   * @deprecated

   *

   * Use matchedRoutes helper defined in "hono/route" instead.

   *

   * @see {@link https://hono.dev/docs/api/request#matchedroutes}

   *

   * @example

   * ```ts

   * app.use('*', async function logger(c, next) {

   *   await next()

   *   c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {

   *     const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')

   *     console.log(

   *       method,

   *       ' ',

   *       path,

   *       ' '.repeat(Math.max(10 - path.length, 0)),

   *       name,

   *       i === c.req.routeIndex ? '<- respond from here' : ''

   *     )

   *   })

   * })

   * ```

   */
  get matchedRoutes() {
    return this.#matchResult[0].map(([[, route]]) => route);
  }
  /**

   * `routePath()` can retrieve the path registered within the handler

   *

   * @deprecated

   *

   * Use routePath helper defined in "hono/route" instead.

   *

   * @see {@link https://hono.dev/docs/api/request#routepath}

   *

   * @example

   * ```ts

   * app.get('/posts/:id', (c) => {

   *   return c.json({ path: c.req.routePath })

   * })

   * ```

   */
  get routePath() {
    return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
  }
}
const cloneRawRequest = async (req) => {
  if (!req.raw.bodyUsed) {
    return req.raw.clone();
  }
  const cacheKey = Object.keys(req.bodyCache)[0];
  if (!cacheKey) {
    throw new import_http_exception.HTTPException(500, {
      message: "Cannot clone request: body was already consumed and not cached. Please use HonoRequest methods (e.g., req.json(), req.text()) instead of consuming req.raw directly."
    });
  }
  const requestInit = {
    body: await req[cacheKey](),
    cache: req.raw.cache,
    credentials: req.raw.credentials,
    headers: req.header(),
    integrity: req.raw.integrity,
    keepalive: req.raw.keepalive,
    method: req.method,
    mode: req.raw.mode,
    redirect: req.raw.redirect,
    referrer: req.raw.referrer,
    referrerPolicy: req.raw.referrerPolicy,
    signal: req.raw.signal
  };
  return new Request(req.url, requestInit);
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  HonoRequest,
  cloneRawRequest
});