hono-utils 0.3.7 → 0.3.9

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.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;var __defProp = Object.defineProperty;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;var __defProp = Object.defineProperty;
2
2
  var __export = (target, all) => {
3
3
  for (var name in all)
4
4
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -19,23 +19,6 @@ var logger = (details, parentEventIdHeader) => _factory.createMiddleware.call(vo
19
19
  await next();
20
20
  });
21
21
 
22
- // src/middleware/withLogger.ts
23
-
24
- var withLogger = (name, middleware) => _factory.createMiddleware.call(void 0, async (c, next) => {
25
- const logger2 = c.get("logger");
26
- if (!logger2) {
27
- throw new Error("Logger should be initialized");
28
- }
29
- const loggerFunctions = logger2.getArea(`middleware:${name}`);
30
- await middleware(c, {
31
- ...loggerFunctions,
32
- eventId: logger2.eventId,
33
- parentEventId: logger2.parentEventId,
34
- dump: logger2.dump
35
- });
36
- await next();
37
- });
38
-
39
22
  // src/middleware/validator.ts
40
23
  var _httpexception = require('hono/http-exception');
41
24
  var _validator = require('hono/validator');
@@ -13822,19 +13805,31 @@ var jsonValidator = (schema) => _validator.validator.call(void 0, "json", (value
13822
13805
  // src/middleware/isBot.ts
13823
13806
 
13824
13807
 
13825
- var isBot = ({
13826
- threshold = 49,
13827
- allowVerifiedBot
13808
+
13809
+ var isBot = ({ threshold, allowVerifiedBot, useLogger } = {
13810
+ threshold: 49
13828
13811
  }) => _factory.createMiddleware.call(void 0, async (c, next) => {
13829
- const botManagement = _optionalChain([c, 'access', _183 => _183.req, 'access', _184 => _184.raw, 'access', _185 => _185.cf, 'optionalAccess', _186 => _186.botManagement]);
13812
+ const logger2 = useLogger ? (_nullishCoalesce(c.get("logger"), () => ( new (0, _hierarchicalarealogger.Logger)({
13813
+ details: {
13814
+ service: "dummy"
13815
+ }
13816
+ })))).getArea("middeware:isBot") : void 0;
13817
+ _optionalChain([logger2, 'optionalAccess', _183 => _183.debug, 'call', _184 => _184("Retrieving bot management data from cloudflare data")]);
13818
+ const botManagement = _optionalChain([c, 'access', _185 => _185.req, 'access', _186 => _186.raw, 'access', _187 => _187.cf, 'optionalAccess', _188 => _188.botManagement]);
13830
13819
  if (!botManagement) {
13831
13820
  throw new Error("botManagement is not available");
13832
13821
  }
13833
- const score = _nullishCoalesce(_optionalChain([botManagement, 'optionalAccess', _187 => _187.score]), () => ( 54));
13834
- const verifiedBot = _nullishCoalesce(_optionalChain([botManagement, 'optionalAccess', _188 => _188.verifiedBot]), () => ( false));
13822
+ const score = _nullishCoalesce(_optionalChain([botManagement, 'optionalAccess', _189 => _189.score]), () => ( 54));
13823
+ const verifiedBot = _nullishCoalesce(_optionalChain([botManagement, 'optionalAccess', _190 => _190.verifiedBot]), () => ( false));
13835
13824
  const isBotByScore = score < threshold;
13836
13825
  const isVerifiedAllowed = !!(allowVerifiedBot && verifiedBot);
13837
13826
  const isBot2 = isBotByScore;
13827
+ _optionalChain([logger2, 'optionalAccess', _191 => _191.debug, 'call', _192 => _192("Setting isBot variable in context", {
13828
+ isBotByScore,
13829
+ isVerifiedAllowed,
13830
+ isBot: isBot2
13831
+ })]);
13832
+ _optionalChain([logger2, 'optionalAccess', _193 => _193.info, 'call', _194 => _194("isBot variable set")]);
13838
13833
  c.set("isBot", isBot2);
13839
13834
  if (isBotByScore && !isVerifiedAllowed) {
13840
13835
  throw new (0, _httpexception.HTTPException)(401, { message: "Bot detected" });
@@ -13894,18 +13889,18 @@ var queue = ({
13894
13889
  }) => _factory.createMiddleware.call(void 0, async ({ env, set: set2, get }, next) => {
13895
13890
  const queueEnv = env[name];
13896
13891
  const language = get("language");
13897
- const logger2 = get("logger");
13898
13892
  if (!queueEnv) {
13899
13893
  throw new Error(
13900
13894
  `Queue environment variable ${name} is not defined`
13901
13895
  );
13902
13896
  }
13897
+ const logger2 = get("logger");
13903
13898
  let parentEventId;
13904
13899
  if (finalizeLogHandler) {
13905
13900
  if (!logger2) {
13906
13901
  throw new Error("Logger should be initialized before queue middleware");
13907
13902
  }
13908
- parentEventId = logger2.eventId;
13903
+ parentEventId = _optionalChain([logger2, 'optionalAccess', _195 => _195.eventId]);
13909
13904
  }
13910
13905
  const producer = queueHandler.getProducer(queueEnv, {
13911
13906
  parentEventId,
@@ -14045,11 +14040,18 @@ async function hash3({
14045
14040
  }
14046
14041
 
14047
14042
  // src/middleware/clientInfo.ts
14048
- var clientInfo = (config2) => _factory.createMiddleware.call(void 0, async ({ env, req, set: set2 }, next) => {
14043
+
14044
+ var clientInfo = (config2) => _factory.createMiddleware.call(void 0, async ({ env, req, set: set2, get }, next) => {
14045
+ const logger2 = _optionalChain([config2, 'optionalAccess', _196 => _196.useLogger]) ? (_nullishCoalesce(get("logger"), () => ( new (0, _hierarchicalarealogger.Logger)({
14046
+ details: {
14047
+ service: "dummy"
14048
+ }
14049
+ })))).getArea("middeware:clientInfo") : void 0;
14049
14050
  if (!req.raw.cf) {
14050
14051
  throw new Error("Cloudflare data is not available");
14051
14052
  }
14052
- const hashSecret = env[_nullishCoalesce(_optionalChain([config2, 'optionalAccess', _189 => _189.hashSecretBinding]), () => ( "HASH_SECRET"))];
14053
+ _optionalChain([logger2, 'optionalAccess', _197 => _197.debug, 'call', _198 => _198("Retrieving hash secret from environment")]);
14054
+ const hashSecret = env[_nullishCoalesce(_optionalChain([config2, 'optionalAccess', _199 => _199.hashSecretBinding]), () => ( "HASH_SECRET"))];
14053
14055
  if (!hashSecret) {
14054
14056
  throw new Error("Hash secret is not available");
14055
14057
  }
@@ -14067,6 +14069,7 @@ var clientInfo = (config2) => _factory.createMiddleware.call(void 0, async ({ en
14067
14069
  postalCode,
14068
14070
  timezone
14069
14071
  } = req.raw.cf;
14072
+ _optionalChain([logger2, 'optionalAccess', _200 => _200.debug, 'call', _201 => _201("Forming cloudflare client data object")]);
14070
14073
  const cf = {
14071
14074
  latitude,
14072
14075
  longitude,
@@ -14081,6 +14084,7 @@ var clientInfo = (config2) => _factory.createMiddleware.call(void 0, async ({ en
14081
14084
  postalCode,
14082
14085
  timezone
14083
14086
  };
14087
+ _optionalChain([logger2, 'optionalAccess', _202 => _202.debug, 'call', _203 => _203("Parsing user agent")]);
14084
14088
  const userAgent = _nullishCoalesce(req.raw.headers.get("user-agent"), () => ( "Unknown"));
14085
14089
  const parser = new (0, _uaparserjs.UAParser)(userAgent);
14086
14090
  const userAgentParsed = parser.getResult();
@@ -14105,27 +14109,20 @@ var clientInfo = (config2) => _factory.createMiddleware.call(void 0, async ({ en
14105
14109
  },
14106
14110
  cpu: _nullishCoalesce(cpu.architecture, () => ( "Unknown"))
14107
14111
  };
14112
+ _optionalChain([logger2, 'optionalAccess', _204 => _204.debug, 'call', _205 => _205("Getting ip address")]);
14108
14113
  const ip = _nullishCoalesce(req.raw.headers.get("CF-Connecting-IP"), () => ( "127.0.0.1"));
14109
14114
  const clientContent = { ...cf, ...ua, ip };
14115
+ _optionalChain([logger2, 'optionalAccess', _206 => _206.debug, 'call', _207 => _207("Setting client data into context")]);
14110
14116
  set2("client", {
14111
14117
  ...clientContent,
14112
14118
  userAgent,
14113
14119
  securityHash: await sha_exports.hash({
14114
- input: _nullishCoalesce(_optionalChain([config2, 'optionalAccess', _190 => _190.securityHashString, 'optionalCall', _191 => _191(clientContent)]), () => ( `${ip}${city}${country}${userAgent}`)),
14120
+ input: _nullishCoalesce(_optionalChain([config2, 'optionalAccess', _208 => _208.securityHashString, 'optionalCall', _209 => _209(clientContent)]), () => ( `${ip}${city}${country}${userAgent}`)),
14115
14121
  algorithm: "SHA-512",
14116
14122
  pepper: hashSecret
14117
14123
  })
14118
14124
  });
14119
- next();
14120
- });
14121
-
14122
- // src/middleware/hydrateVariable.ts
14123
-
14124
- var hydrateVariable = ({
14125
- variableName,
14126
- hydrate
14127
- }) => _factory.createMiddleware.call(void 0, async ({ set: set2, env, get }, next) => {
14128
- set2(variableName, hydrate({ ...env, get }));
14125
+ _optionalChain([logger2, 'optionalAccess', _210 => _210.info, 'call', _211 => _211("Client data variable set")]);
14129
14126
  await next();
14130
14127
  });
14131
14128
 
@@ -14216,7 +14213,7 @@ var onError = (parseError) => async (err, { json: json2, env, get }) => {
14216
14213
  const status = "status" in err ? err.status : 500;
14217
14214
  return json2(
14218
14215
  {
14219
- message: !parseError ? err.message : await parseError(err, env, get)
14216
+ message: !parseError ? err.message : await _asyncNullishCoalesce(await parseError(err, env, get), async () => ( defaultMessageMap.internalError))
14220
14217
  },
14221
14218
  status
14222
14219
  );
@@ -14247,32 +14244,31 @@ var createTypedClient = () => {
14247
14244
  headers: options.headers,
14248
14245
  fetch: options.fetch
14249
14246
  });
14250
- _optionalChain([callbacks, 'optionalAccess', _192 => _192.onStart, 'optionalCall', _193 => _193()]);
14247
+ _optionalChain([callbacks, 'optionalAccess', _212 => _212.onStart, 'optionalCall', _213 => _213()]);
14251
14248
  let responseHeaders = new Headers();
14252
14249
  try {
14253
14250
  const response2 = await fn(client);
14254
14251
  responseHeaders = response2.headers;
14255
14252
  const data = await _client.parseResponse.call(void 0, response2);
14256
- _optionalChain([callbacks, 'optionalAccess', _194 => _194.onSuccess, 'optionalCall', _195 => _195(data, responseHeaders)]);
14253
+ _optionalChain([callbacks, 'optionalAccess', _214 => _214.onSuccess, 'optionalCall', _215 => _215(data, responseHeaders)]);
14257
14254
  return data;
14258
14255
  } catch (err) {
14259
- const errorBody = { message: err.message };
14260
14256
  let status = 500;
14261
- if (err instanceof _client.DetailedError) {
14262
- const { detail, statusCode } = err;
14263
- status = _nullishCoalesce(statusCode, () => ( 500));
14264
- if (!detail) {
14265
- _optionalChain([options, 'access', _196 => _196.errorHandler, 'optionalCall', _197 => _197(500, {
14266
- message: "Fetch malformed"
14267
- })]);
14268
- throw new (0, _httpexception.HTTPException)(500, { message: "Fetch malformed" });
14269
- }
14270
- }
14271
- _optionalChain([callbacks, 'optionalAccess', _198 => _198.onError, 'optionalCall', _199 => _199(errorBody, responseHeaders)]);
14272
- _optionalChain([options, 'access', _200 => _200.errorHandler, 'optionalCall', _201 => _201(status, errorBody)]);
14273
- throw new (0, _httpexception.HTTPException)(status, errorBody);
14257
+ const { detail, statusCode } = err;
14258
+ status = _nullishCoalesce(statusCode, () => ( 500));
14259
+ if (!detail) {
14260
+ _optionalChain([options, 'access', _216 => _216.errorHandler, 'optionalCall', _217 => _217(status, {
14261
+ message: "Fetch malformed"
14262
+ })]);
14263
+ throw new (0, _httpexception.HTTPException)(status, { message: "Fetch malformed" });
14264
+ }
14265
+ const { message } = detail;
14266
+ const eventId = _nullishCoalesce(responseHeaders.get("x-event-id"), () => ( void 0));
14267
+ _optionalChain([options, 'access', _218 => _218.errorHandler, 'optionalCall', _219 => _219(status, { ...detail, eventId, status })]);
14268
+ _optionalChain([callbacks, 'optionalAccess', _220 => _220.onError, 'optionalCall', _221 => _221(detail, responseHeaders)]);
14269
+ throw new (0, _httpexception.HTTPException)(status, { message });
14274
14270
  } finally {
14275
- _optionalChain([callbacks, 'optionalAccess', _202 => _202.onEnd, 'optionalCall', _203 => _203()]);
14271
+ _optionalChain([callbacks, 'optionalAccess', _222 => _222.onEnd, 'optionalCall', _223 => _223()]);
14276
14272
  }
14277
14273
  };
14278
14274
  };
@@ -14290,7 +14286,5 @@ var createTypedClient = () => {
14290
14286
 
14291
14287
 
14292
14288
 
14293
-
14294
-
14295
- exports.PBKDF2 = pbkdf2_exports; exports.QueueHandler = QueueHandler; exports.SHA = sha_exports; exports.clientInfo = clientInfo; exports.createTypedClient = createTypedClient; exports.hydrateVariable = hydrateVariable; exports.i18n = i18n; exports.isBot = isBot; exports.jsonValidator = jsonValidator; exports.logger = logger; exports.onError = onError; exports.onNotFound = onNotFound; exports.queue = queue; exports.response = response; exports.withLogger = withLogger;
14289
+ exports.PBKDF2 = pbkdf2_exports; exports.QueueHandler = QueueHandler; exports.SHA = sha_exports; exports.clientInfo = clientInfo; exports.createTypedClient = createTypedClient; exports.i18n = i18n; exports.isBot = isBot; exports.jsonValidator = jsonValidator; exports.logger = logger; exports.onError = onError; exports.onNotFound = onNotFound; exports.queue = queue; exports.response = response;
14296
14290
  //# sourceMappingURL=index.cjs.map