pi-cursor-sdk 0.1.62 → 0.2.0

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 (128) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +5 -5
  3. package/docs/cursor-live-smoke-checklist.md +4 -4
  4. package/docs/cursor-model-ux-spec.md +5 -3
  5. package/docs/cursor-native-tool-visual-audit.md +1 -1
  6. package/docs/cursor-testing-lessons.md +1 -1
  7. package/docs/platform-smoke.md +3 -3
  8. package/node_modules/fast-uri/index.js +37 -1
  9. package/node_modules/fast-uri/package.json +1 -1
  10. package/node_modules/fast-uri/test/security.test.js +136 -0
  11. package/node_modules/hono/dist/cjs/context.js +28 -13
  12. package/node_modules/hono/dist/cjs/helper/proxy/index.js +4 -0
  13. package/node_modules/hono/dist/cjs/helper/streaming/sse.js +1 -1
  14. package/node_modules/hono/dist/cjs/hono-base.js +3 -2
  15. package/node_modules/hono/dist/cjs/jsx/base.js +27 -23
  16. package/node_modules/hono/dist/cjs/jsx/hooks/index.js +16 -13
  17. package/node_modules/hono/dist/cjs/middleware/cache/index.js +103 -8
  18. package/node_modules/hono/dist/cjs/middleware/compress/index.js +5 -0
  19. package/node_modules/hono/dist/cjs/middleware/cors/index.js +2 -2
  20. package/node_modules/hono/dist/cjs/middleware/etag/index.js +1 -1
  21. package/node_modules/hono/dist/cjs/middleware/jwk/jwk.js +9 -4
  22. package/node_modules/hono/dist/cjs/middleware/jwt/jwt.js +9 -4
  23. package/node_modules/hono/dist/cjs/middleware/language/language.js +10 -6
  24. package/node_modules/hono/dist/cjs/middleware/method-not-allowed/index.js +90 -0
  25. package/node_modules/hono/dist/cjs/middleware/secure-headers/secure-headers.js +10 -4
  26. package/node_modules/hono/dist/cjs/request.js +7 -9
  27. package/node_modules/hono/dist/cjs/router/reg-exp-router/node.js +55 -56
  28. package/node_modules/hono/dist/cjs/router/reg-exp-router/router.js +64 -85
  29. package/node_modules/hono/dist/cjs/router/reg-exp-router/trie.js +13 -5
  30. package/node_modules/hono/dist/cjs/router.js +1 -1
  31. package/node_modules/hono/dist/cjs/utils/accept.js +1 -1
  32. package/node_modules/hono/dist/cjs/utils/cookie.js +3 -2
  33. package/node_modules/hono/dist/cjs/utils/url.js +8 -8
  34. package/node_modules/hono/dist/context.js +28 -13
  35. package/node_modules/hono/dist/helper/proxy/index.js +4 -0
  36. package/node_modules/hono/dist/helper/streaming/sse.js +1 -1
  37. package/node_modules/hono/dist/hono-base.js +3 -2
  38. package/node_modules/hono/dist/jsx/base.js +27 -23
  39. package/node_modules/hono/dist/jsx/hooks/index.js +16 -13
  40. package/node_modules/hono/dist/middleware/cache/index.js +103 -8
  41. package/node_modules/hono/dist/middleware/compress/index.js +5 -0
  42. package/node_modules/hono/dist/middleware/cors/index.js +2 -2
  43. package/node_modules/hono/dist/middleware/etag/index.js +1 -1
  44. package/node_modules/hono/dist/middleware/jwk/jwk.js +9 -4
  45. package/node_modules/hono/dist/middleware/jwt/jwt.js +9 -4
  46. package/node_modules/hono/dist/middleware/language/language.js +10 -6
  47. package/node_modules/hono/dist/middleware/method-not-allowed/index.js +68 -0
  48. package/node_modules/hono/dist/middleware/secure-headers/secure-headers.js +10 -4
  49. package/node_modules/hono/dist/request.js +8 -10
  50. package/node_modules/hono/dist/router/reg-exp-router/node.js +55 -56
  51. package/node_modules/hono/dist/router/reg-exp-router/router.js +64 -85
  52. package/node_modules/hono/dist/router/reg-exp-router/trie.js +13 -5
  53. package/node_modules/hono/dist/router.js +1 -1
  54. package/node_modules/hono/dist/types/adapter/aws-lambda/types.d.ts +9 -0
  55. package/node_modules/hono/dist/types/client/types.d.ts +1 -1
  56. package/node_modules/hono/dist/types/hono-base.d.ts +4 -3
  57. package/node_modules/hono/dist/types/jsx/base.d.ts +4 -2
  58. package/node_modules/hono/dist/types/jsx/dom/index.d.ts +5 -5
  59. package/node_modules/hono/dist/types/jsx/dom/intrinsic-element/components.d.ts +2 -2
  60. package/node_modules/hono/dist/types/jsx/dom/server.d.ts +5 -5
  61. package/node_modules/hono/dist/types/jsx/hooks/index.d.ts +8 -6
  62. package/node_modules/hono/dist/types/jsx/index.d.ts +5 -5
  63. package/node_modules/hono/dist/types/middleware/cache/index.d.ts +6 -4
  64. package/node_modules/hono/dist/types/middleware/cors/index.d.ts +1 -1
  65. package/node_modules/hono/dist/types/middleware/jsx-renderer/index.d.ts +2 -2
  66. package/node_modules/hono/dist/types/middleware/jwk/jwk.d.ts +2 -0
  67. package/node_modules/hono/dist/types/middleware/jwt/jwt.d.ts +2 -0
  68. package/node_modules/hono/dist/types/middleware/method-not-allowed/index.d.ts +49 -0
  69. package/node_modules/hono/dist/types/router/reg-exp-router/node.d.ts +1 -1
  70. package/node_modules/hono/dist/types/router/reg-exp-router/trie.d.ts +2 -1
  71. package/node_modules/hono/dist/types/router.d.ts +1 -1
  72. package/node_modules/hono/dist/types/utils/headers.d.ts +2 -2
  73. package/node_modules/hono/dist/types/utils/url.d.ts +1 -0
  74. package/node_modules/hono/dist/utils/accept.js +1 -1
  75. package/node_modules/hono/dist/utils/cookie.js +4 -3
  76. package/node_modules/hono/dist/utils/url.js +6 -7
  77. package/node_modules/hono/package.json +10 -3
  78. package/node_modules/ip-address/README.md +146 -126
  79. package/node_modules/ip-address/dist/common.d.ts +29 -0
  80. package/node_modules/ip-address/dist/common.js +44 -5
  81. package/node_modules/ip-address/dist/common.js.map +1 -1
  82. package/node_modules/ip-address/dist/ipv4.d.ts +8 -1
  83. package/node_modules/ip-address/dist/ipv4.js +24 -20
  84. package/node_modules/ip-address/dist/ipv4.js.map +1 -1
  85. package/node_modules/ip-address/dist/ipv6.d.ts +68 -3
  86. package/node_modules/ip-address/dist/ipv6.js +180 -53
  87. package/node_modules/ip-address/dist/ipv6.js.map +1 -1
  88. package/node_modules/ip-address/dist/v4/constants.js +5 -1
  89. package/node_modules/ip-address/dist/v4/constants.js.map +1 -1
  90. package/node_modules/ip-address/dist/v6/constants.js +3 -2
  91. package/node_modules/ip-address/dist/v6/constants.js.map +1 -1
  92. package/node_modules/ip-address/package.json +6 -4
  93. package/package.json +5 -5
  94. package/scripts/platform-smoke/live-suite-runner.mjs +15 -39
  95. package/scripts/platform-smoke/platform-build-windows.ps1 +1 -1
  96. package/scripts/platform-smoke/scenarios.mjs +1 -1
  97. package/scripts/platform-smoke.mjs +5 -5
  98. package/scripts/refresh-cursor-model-snapshots.mjs +16 -7
  99. package/shared/cursor-model-selection-identities.d.mts +21 -0
  100. package/shared/cursor-model-selection-identities.mjs +95 -0
  101. package/src/bundled-context-windows.ts +18 -12
  102. package/src/context.ts +1 -1
  103. package/src/cursor-context-tools.ts +1 -1
  104. package/src/cursor-display-only-trace.ts +1 -1
  105. package/src/cursor-fallback-models.generated.ts +875 -361
  106. package/src/cursor-live-run-accounting.ts +1 -1
  107. package/src/cursor-live-run-coordinator.ts +1 -1
  108. package/src/cursor-native-replay-routing.ts +1 -1
  109. package/src/cursor-partial-content-emitter.ts +1 -1
  110. package/src/cursor-pi-tool-bridge-mcp.ts +1 -1
  111. package/src/cursor-pi-tool-bridge-run.ts +1 -1
  112. package/src/cursor-pi-tool-bridge-types.ts +1 -1
  113. package/src/cursor-provider-lazy.ts +1 -1
  114. package/src/cursor-provider-live-run-drain.ts +1 -1
  115. package/src/cursor-provider-overflow.ts +1 -1
  116. package/src/cursor-provider-run-finalizer.ts +1 -1
  117. package/src/cursor-provider-turn-coordinator.ts +1 -1
  118. package/src/cursor-provider-turn-lifecycle-emitter.ts +1 -1
  119. package/src/cursor-provider-turn-prepare.ts +1 -1
  120. package/src/cursor-provider-turn-types.ts +1 -1
  121. package/src/cursor-provider.ts +1 -1
  122. package/src/cursor-run-final-text.ts +1 -1
  123. package/src/cursor-sdk-event-debug.ts +1 -1
  124. package/src/cursor-session-agent.ts +1 -1
  125. package/src/cursor-session-send-policy.ts +1 -1
  126. package/src/cursor-usage-accounting.ts +1 -1
  127. package/src/model-discovery.ts +32 -89
  128. package/node_modules/cross-spawn/node_modules/which/CHANGELOG.md +0 -166
@@ -263,7 +263,7 @@ const useCallback = (callback, deps) => {
263
263
  }
264
264
  return callback;
265
265
  };
266
- const useRef = (initialValue) => {
266
+ function useRef(initialValue) {
267
267
  const buildData = import_render.buildDataStack.at(-1);
268
268
  if (!buildData) {
269
269
  return { current: initialValue };
@@ -272,7 +272,7 @@ const useRef = (initialValue) => {
272
272
  const refArray = node[import_constants.DOM_STASH][1][STASH_REF] ||= [];
273
273
  const hookIndex = node[import_constants.DOM_STASH][0]++;
274
274
  return refArray[hookIndex] ||= { current: initialValue };
275
- };
275
+ }
276
276
  const use = (promise) => {
277
277
  const cachedRes = resolvedPromiseValueMap.get(promise);
278
278
  if (cachedRes) {
@@ -330,19 +330,22 @@ const useSyncExternalStore = (subscribe, getSnapshot, getServerSnapshot) => {
330
330
  }
331
331
  return getServerSnapshot();
332
332
  }
333
- const [serverSnapshotIsUsed] = useState(!!(buildData[0][4] && getServerSnapshot));
334
- const [state, setState] = useState(
335
- () => serverSnapshotIsUsed ? getServerSnapshot() : getSnapshot()
336
- );
333
+ const snapshot = buildData[0][4] && getServerSnapshot ? getServerSnapshot() : getSnapshot();
334
+ const [, setVersion] = useState(0);
335
+ const latestSnapshot = useRef([snapshot, getSnapshot]);
336
+ latestSnapshot.current = [snapshot, getSnapshot];
337
+ const unsubscribeRef = useRef(null);
337
338
  useEffect(() => {
338
- if (serverSnapshotIsUsed) {
339
- setState(getSnapshot());
339
+ const update2 = () => setVersion((version) => version + 1);
340
+ unsubscribeRef.current?.();
341
+ unsubscribeRef.current = subscribe(update2);
342
+ const [snapshot2, getSnapshot2] = latestSnapshot.current;
343
+ if (!Object.is(snapshot2, getSnapshot2())) {
344
+ update2();
340
345
  }
341
- return subscribe(() => {
342
- setState(getSnapshot());
343
- });
344
- }, []);
345
- return state;
346
+ }, [subscribe]);
347
+ useEffect(() => () => unsubscribeRef.current?.(), []);
348
+ return snapshot;
346
349
  };
347
350
  // Annotate the CommonJS export names for ESM import in node:
348
351
  0 && (module.exports = {
@@ -20,7 +20,21 @@ __export(cache_exports, {
20
20
  cache: () => cache
21
21
  });
22
22
  module.exports = __toCommonJS(cache_exports);
23
+ var import_request = require("../../request");
24
+ var import_crypto = require("../../utils/crypto");
23
25
  const defaultCacheableStatusCodes = [200];
26
+ const defaultMaxQueryBodySize = 64 * 1024;
27
+ const cacheKeyPath = "/.hono/cache";
28
+ const cacheKeyParameter = "__hono_cache_key";
29
+ const cacheMethodKeyParameter = "__hono_cache_method";
30
+ const queryDigestKeyParameter = "__hono_query_digest";
31
+ const cacheVaryKeyParameter = "__hono_cache_vary";
32
+ const queryRepresentationMetadataHeaders = [
33
+ "content-type",
34
+ "content-encoding",
35
+ "content-language",
36
+ "content-location"
37
+ ];
24
38
  const shouldSkipCacheControl = (cacheControl) => !!cacheControl && /(?:^|,\s*)(?:private|no-(?:store|cache))(?:\s*(?:=|,|$))/i.test(cacheControl);
25
39
  const parseVaryDirectives = (vary) => {
26
40
  if (vary == null) {
@@ -28,17 +42,86 @@ const parseVaryDirectives = (vary) => {
28
42
  }
29
43
  return (Array.isArray(vary) ? vary : vary.split(",")).map((directive) => directive.trim().toLowerCase()).filter(Boolean);
30
44
  };
45
+ const createCacheKey = (key, requestUrl, request, varyHeaders) => {
46
+ const url = new URL(cacheKeyPath, requestUrl);
47
+ url.searchParams.append(cacheKeyParameter, key.split("#", 1)[0]);
48
+ url.searchParams.append(cacheMethodKeyParameter, request.method);
49
+ if (request.method === "QUERY") {
50
+ url.searchParams.append(queryDigestKeyParameter, request.digest);
51
+ }
52
+ for (const header of varyHeaders) {
53
+ url.searchParams.append(cacheVaryKeyParameter, JSON.stringify(header));
54
+ }
55
+ return url.href;
56
+ };
31
57
  const shouldSkipCache = (res, optionsVaryDirectives, responseVary) => responseVary.length && (!optionsVaryDirectives || responseVary.some((name) => !optionsVaryDirectives.has(name))) || shouldSkipCacheControl(res.headers.get("Cache-Control")) || res.headers.has("Set-Cookie");
58
+ const reportCacheNotAvailable = (onCacheNotAvailable, reason) => {
59
+ if (onCacheNotAvailable === false) {
60
+ } else if (onCacheNotAvailable) {
61
+ onCacheNotAvailable(reason);
62
+ } else {
63
+ console.log(reason);
64
+ }
65
+ };
66
+ const createQueryDigest = async (c, maxQueryBodySize) => {
67
+ if (!globalThis.crypto?.subtle) {
68
+ return void 0;
69
+ }
70
+ if (c.req.raw.bodyUsed && Object.keys(c.req.bodyCache)[0] === "formData") {
71
+ return void 0;
72
+ }
73
+ try {
74
+ const requestHeaders = c.req.raw.headers;
75
+ const metadata = new TextEncoder().encode(
76
+ JSON.stringify(
77
+ queryRepresentationMetadataHeaders.map((header) => [header, requestHeaders.get(header)])
78
+ )
79
+ );
80
+ const body = (await (0, import_request.cloneRawRequest)(c.req)).body;
81
+ const chunks = [];
82
+ let bodySize = 0;
83
+ if (body) {
84
+ const reader = body.getReader();
85
+ for (; ; ) {
86
+ const { done, value } = await reader.read();
87
+ if (done) {
88
+ break;
89
+ }
90
+ bodySize += value.byteLength;
91
+ if (bodySize > maxQueryBodySize) {
92
+ void reader.cancel().catch(() => {
93
+ });
94
+ return void 0;
95
+ }
96
+ chunks.push(value);
97
+ }
98
+ }
99
+ const data = new Uint8Array(metadata.byteLength + bodySize);
100
+ data.set(metadata);
101
+ let offset = metadata.byteLength;
102
+ for (const chunk of chunks) {
103
+ data.set(chunk, offset);
104
+ offset += chunk.byteLength;
105
+ }
106
+ return await (0, import_crypto.sha256)(data) ?? void 0;
107
+ } catch {
108
+ return void 0;
109
+ }
110
+ };
32
111
  const cache = (options) => {
33
112
  if (!globalThis.caches) {
34
- if (options.onCacheNotAvailable === false) {
35
- } else if (options.onCacheNotAvailable) {
36
- options.onCacheNotAvailable();
37
- } else {
38
- console.log("Cache Middleware is not enabled because caches is not defined.");
39
- }
113
+ reportCacheNotAvailable(
114
+ options.onCacheNotAvailable,
115
+ "Cache Middleware is not enabled because caches is not defined."
116
+ );
40
117
  return async (_c, next) => await next();
41
118
  }
119
+ if (!globalThis.crypto?.subtle) {
120
+ reportCacheNotAvailable(
121
+ options.onCacheNotAvailable,
122
+ "Cache Middleware cannot cache QUERY requests because Web Crypto is not available."
123
+ );
124
+ }
42
125
  if (options.wait === void 0) {
43
126
  options.wait = false;
44
127
  }
@@ -53,6 +136,7 @@ const cache = (options) => {
53
136
  const cacheableStatusCodes = new Set(
54
137
  options.cacheableStatusCodes ?? defaultCacheableStatusCodes
55
138
  );
139
+ const maxQueryBodySize = options.maxQueryBodySize ?? defaultMaxQueryBodySize;
56
140
  const addHeader = (c, responseVary) => {
57
141
  if (cacheControlDirectives) {
58
142
  const existingDirectives = c.res.headers.get("Cache-Control")?.split(",").map((d) => d.trim().split("=", 1)[0].toLowerCase()) ?? [];
@@ -81,20 +165,31 @@ const cache = (options) => {
81
165
  }
82
166
  };
83
167
  return async function cache2(c, next) {
84
- if (c.req.method !== "GET" || c.req.raw.headers.has("Authorization")) {
168
+ if (c.req.method !== "GET" && c.req.method !== "QUERY" || c.req.raw.headers.has("Authorization")) {
85
169
  await next();
86
170
  return;
87
171
  }
172
+ let cacheKeyRequest = { method: "GET" };
173
+ if (c.req.method === "QUERY") {
174
+ const digest = await createQueryDigest(c, maxQueryBodySize);
175
+ if (digest === void 0) {
176
+ await next();
177
+ return;
178
+ }
179
+ cacheKeyRequest = { method: "QUERY", digest };
180
+ }
88
181
  let key = c.req.url;
89
182
  if (options.keyGenerator) {
90
183
  key = await options.keyGenerator(c);
91
184
  }
185
+ const varyHeaders = [];
92
186
  if (varyDirectives) {
93
187
  for (const directive of varyDirectives) {
94
188
  const value = c.req.raw.headers.get(directive) ?? "";
95
- key += `::${directive}=${encodeURIComponent(value)}`;
189
+ varyHeaders.push([directive, value]);
96
190
  }
97
191
  }
192
+ key = createCacheKey(key, c.req.url, cacheKeyRequest, varyHeaders);
98
193
  const cacheName = typeof options.cacheName === "function" ? await options.cacheName(c) : options.cacheName;
99
194
  const cache3 = await caches.open(cacheName);
100
195
  const response = await cache3.match(key);
@@ -43,6 +43,7 @@ const selectEncoding = (header, candidates) => {
43
43
  }
44
44
  return best?.encoding;
45
45
  };
46
+ const varyAcceptEncodingRegExp = /(?:^|,)\s*accept-encoding\s*(?:,|$)/i;
46
47
  const compress = (options) => {
47
48
  const threshold = options?.threshold ?? 1024;
48
49
  const candidates = options?.encoding ? [options.encoding] : ENCODING_TYPES;
@@ -66,6 +67,10 @@ const compress = (options) => {
66
67
  !shouldTransform(ctx.res)) {
67
68
  return;
68
69
  }
70
+ const current = ctx.res.headers.get("Vary");
71
+ if (current !== "*" && !(current && varyAcceptEncodingRegExp.test(current))) {
72
+ ctx.header("Vary", current ? `${current}, Accept-Encoding` : "Accept-Encoding");
73
+ }
69
74
  const accepted = ctx.req.header("Accept-Encoding");
70
75
  const encoding = selectEncoding(accepted, candidates);
71
76
  if (!encoding || !ctx.res.body) {
@@ -23,7 +23,7 @@ module.exports = __toCommonJS(cors_exports);
23
23
  const cors = (options) => {
24
24
  const opts = {
25
25
  origin: "*",
26
- allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"],
26
+ allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH", "QUERY"],
27
27
  allowHeaders: [],
28
28
  exposeHeaders: [],
29
29
  ...options
@@ -79,7 +79,7 @@ const cors = (options) => {
79
79
  if (!headers?.length) {
80
80
  const requestHeaders = c.req.header("Access-Control-Request-Headers");
81
81
  if (requestHeaders) {
82
- headers = requestHeaders.split(/\s*,\s*/);
82
+ headers = requestHeaders.split(",").map((h) => h.trim());
83
83
  }
84
84
  }
85
85
  if (headers?.length) {
@@ -70,7 +70,7 @@ const etag = (options) => {
70
70
  }
71
71
  etag3 = weak ? `W/"${hash}"` : `"${hash}"`;
72
72
  }
73
- const matched = ifNoneMatch === "*" ? (c.req.method === "GET" || c.req.method === "HEAD") && res.ok : etagMatches(etag3, ifNoneMatch);
73
+ const matched = ifNoneMatch === "*" ? (c.req.method === "GET" || c.req.method === "HEAD" || c.req.method === "QUERY") && res.ok : etagMatches(etag3, ifNoneMatch);
74
74
  if (matched) {
75
75
  c.res = new Response(null, {
76
76
  status: 304,
@@ -45,7 +45,8 @@ const jwk = (options, init) => {
45
45
  res: unauthorizedResponse({
46
46
  ctx,
47
47
  error: "invalid_request",
48
- errDescription
48
+ errDescription,
49
+ realm: options.realm
49
50
  })
50
51
  });
51
52
  } else {
@@ -83,7 +84,8 @@ const jwk = (options, init) => {
83
84
  res: unauthorizedResponse({
84
85
  ctx,
85
86
  error: "invalid_request",
86
- errDescription
87
+ errDescription,
88
+ realm: options.realm
87
89
  })
88
90
  });
89
91
  }
@@ -110,7 +112,8 @@ const jwk = (options, init) => {
110
112
  ctx,
111
113
  error: "invalid_token",
112
114
  statusText: "Unauthorized",
113
- errDescription: "token verification failure"
115
+ errDescription: "token verification failure",
116
+ realm: options.realm
114
117
  }),
115
118
  cause
116
119
  });
@@ -120,11 +123,13 @@ const jwk = (options, init) => {
120
123
  };
121
124
  };
122
125
  function unauthorizedResponse(opts) {
126
+ const realm = (opts.realm ?? opts.ctx.req.url).replace(/"/g, '\\"');
127
+ const errDescription = opts.errDescription.replace(/"/g, '\\"');
123
128
  return new Response("Unauthorized", {
124
129
  status: 401,
125
130
  statusText: opts.statusText,
126
131
  headers: {
127
- "WWW-Authenticate": `Bearer realm="${opts.ctx.req.url}",error="${opts.error}",error_description="${opts.errDescription}"`
132
+ "WWW-Authenticate": `Bearer realm="${realm}",error="${opts.error}",error_description="${errDescription}"`
128
133
  }
129
134
  });
130
135
  }
@@ -52,7 +52,8 @@ const jwt = (options) => {
52
52
  res: unauthorizedResponse({
53
53
  ctx,
54
54
  error: "invalid_request",
55
- errDescription
55
+ errDescription,
56
+ realm: options.realm
56
57
  })
57
58
  });
58
59
  } else {
@@ -87,7 +88,8 @@ const jwt = (options) => {
87
88
  res: unauthorizedResponse({
88
89
  ctx,
89
90
  error: "invalid_request",
90
- errDescription
91
+ errDescription,
92
+ realm: options.realm
91
93
  })
92
94
  });
93
95
  }
@@ -108,7 +110,8 @@ const jwt = (options) => {
108
110
  ctx,
109
111
  error: "invalid_token",
110
112
  statusText: "Unauthorized",
111
- errDescription: "token verification failure"
113
+ errDescription: "token verification failure",
114
+ realm: options.realm
112
115
  }),
113
116
  cause
114
117
  });
@@ -118,11 +121,13 @@ const jwt = (options) => {
118
121
  };
119
122
  };
120
123
  function unauthorizedResponse(opts) {
124
+ const realm = (opts.realm ?? opts.ctx.req.url).replace(/"/g, '\\"');
125
+ const errDescription = opts.errDescription.replace(/"/g, '\\"');
121
126
  return new Response("Unauthorized", {
122
127
  status: 401,
123
128
  statusText: opts.statusText,
124
129
  headers: {
125
- "WWW-Authenticate": `Bearer realm="${opts.ctx.req.url}",error="${opts.error}",error_description="${opts.errDescription}"`
130
+ "WWW-Authenticate": `Bearer realm="${realm}",error="${opts.error}",error_description="${errDescription}"`
126
131
  }
127
132
  });
128
133
  }
@@ -69,14 +69,18 @@ const normalizeLanguage = (lang, options) => {
69
69
  if (exactIndex !== -1) {
70
70
  return options.supportedLanguages[exactIndex];
71
71
  }
72
- const parts = compLang.split("-");
73
- for (let i = parts.length - 1; i > 0; i--) {
74
- const candidate = parts.slice(0, i).join("-");
75
- const prefixIndex = compSupported.indexOf(candidate);
76
- if (prefixIndex !== -1) {
77
- return options.supportedLanguages[prefixIndex];
72
+ let longestMatchIndex = -1;
73
+ let longestMatchLength = -1;
74
+ for (let i = 0; i < compSupported.length; i++) {
75
+ const candidate = compSupported[i];
76
+ if (candidate.length < compLang.length && candidate.length > longestMatchLength && compLang.startsWith(candidate) && compLang[candidate.length] === "-") {
77
+ longestMatchIndex = i;
78
+ longestMatchLength = candidate.length;
78
79
  }
79
80
  }
81
+ if (longestMatchIndex !== -1) {
82
+ return options.supportedLanguages[longestMatchIndex];
83
+ }
80
84
  return void 0;
81
85
  } catch {
82
86
  return void 0;
@@ -0,0 +1,90 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+ var method_not_allowed_exports = {};
19
+ __export(method_not_allowed_exports, {
20
+ methodNotAllowed: () => methodNotAllowed
21
+ });
22
+ module.exports = __toCommonJS(method_not_allowed_exports);
23
+ var import_route = require("../../helper/route");
24
+ var import_router = require("../../router");
25
+ var import_trie_router = require("../../router/trie-router");
26
+ const methodNotAllowed = (options) => {
27
+ let methodRouter;
28
+ return async function methodNotAllowed2(c, next) {
29
+ const routeIndex = c.req.routeIndex;
30
+ await next();
31
+ if (c.res.status !== 404) {
32
+ return;
33
+ }
34
+ if (c.error) {
35
+ return;
36
+ }
37
+ if (!methodRouter) {
38
+ const methodsByPath = /* @__PURE__ */ new Map();
39
+ for (const route of options.app.routes) {
40
+ if (route.method === import_router.METHOD_NAME_ALL || route.method === "HEAD") {
41
+ continue;
42
+ }
43
+ const methods2 = methodsByPath.get(route.path) ?? /* @__PURE__ */ new Set();
44
+ methods2.add(route.method);
45
+ if (route.method === "GET") {
46
+ methods2.add("HEAD");
47
+ }
48
+ methodsByPath.set(route.path, methods2);
49
+ }
50
+ methodRouter = new import_trie_router.TrieRouter();
51
+ for (const [path, methods2] of methodsByPath) {
52
+ methodRouter.add(import_router.METHOD_NAME_ALL, path, [...methods2]);
53
+ }
54
+ }
55
+ let requestPath = c.req.path;
56
+ const routes = (0, import_route.matchedRoutes)(c);
57
+ const currentRoute = routes[routeIndex];
58
+ const sourceRoute = options.app.routes.find((route) => route.handler === methodNotAllowed2);
59
+ if (currentRoute && sourceRoute) {
60
+ const currentBasePathParts = (0, import_route.basePath)(c, routeIndex).split("/").filter(Boolean);
61
+ const sourceBasePathLength = sourceRoute.basePath.split("/").filter(Boolean).length;
62
+ const mountBasePathParts = currentBasePathParts.slice(
63
+ 0,
64
+ currentBasePathParts.length - sourceBasePathLength
65
+ );
66
+ if (mountBasePathParts.length > 0) {
67
+ const mountBasePath = `/${mountBasePathParts.join("/")}`;
68
+ requestPath = c.req.path.slice(mountBasePath.length) || "/";
69
+ }
70
+ }
71
+ const allowedMethods = /* @__PURE__ */ new Set();
72
+ for (const [methods2] of methodRouter.match(import_router.METHOD_NAME_ALL, requestPath)[0]) {
73
+ for (const method of methods2) {
74
+ allowedMethods.add(method);
75
+ }
76
+ }
77
+ if (allowedMethods.size === 0 || allowedMethods.has(c.req.method)) {
78
+ return;
79
+ }
80
+ c.res.headers.delete("Allow");
81
+ c.res.headers.delete("Content-Length");
82
+ const methods = [...allowedMethods];
83
+ const allow = methods.join(", ");
84
+ c.res = options.onMethodNotAllowed ? await options.onMethodNotAllowed(c, methods) : c.text("Method Not Allowed", 405, { Allow: allow });
85
+ };
86
+ };
87
+ // Annotate the CommonJS export names for ESM import in node:
88
+ 0 && (module.exports = {
89
+ methodNotAllowed
90
+ });
@@ -71,14 +71,20 @@ const secureHeaders = (customOptions) => {
71
71
  const headersToSet = getFilteredHeaders(options);
72
72
  const callbacks = [];
73
73
  if (options.contentSecurityPolicy) {
74
- const [callback, value] = getCSPDirectives(options.contentSecurityPolicy);
74
+ const [callback, value] = getCSPDirectives(
75
+ options.contentSecurityPolicy,
76
+ "Content-Security-Policy"
77
+ );
75
78
  if (callback) {
76
79
  callbacks.push(callback);
77
80
  }
78
81
  headersToSet.push(["Content-Security-Policy", value]);
79
82
  }
80
83
  if (options.contentSecurityPolicyReportOnly) {
81
- const [callback, value] = getCSPDirectives(options.contentSecurityPolicyReportOnly);
84
+ const [callback, value] = getCSPDirectives(
85
+ options.contentSecurityPolicyReportOnly,
86
+ "Content-Security-Policy-Report-Only"
87
+ );
82
88
  if (callback) {
83
89
  callbacks.push(callback);
84
90
  }
@@ -111,7 +117,7 @@ function getFilteredHeaders(options) {
111
117
  return typeof overrideValue === "string" ? [defaultValue[0], overrideValue] : defaultValue;
112
118
  });
113
119
  }
114
- function getCSPDirectives(contentSecurityPolicy) {
120
+ function getCSPDirectives(contentSecurityPolicy, headerName) {
115
121
  const callbacks = [];
116
122
  const resultValues = [];
117
123
  for (const [directive, value] of Object.entries(contentSecurityPolicy)) {
@@ -136,7 +142,7 @@ function getCSPDirectives(contentSecurityPolicy) {
136
142
  resultValues.pop();
137
143
  return callbacks.length === 0 ? [void 0, resultValues.join("")] : [
138
144
  (ctx, headersToSet) => headersToSet.map((values) => {
139
- if (values[0] === "Content-Security-Policy" || values[0] === "Content-Security-Policy-Report-Only") {
145
+ if (values[0] === headerName) {
140
146
  const clone = values[1].slice();
141
147
  callbacks.forEach((cb) => {
142
148
  cb(ctx, clone);
@@ -25,7 +25,6 @@ var import_http_exception = require("./http-exception");
25
25
  var import_constants = require("./request/constants");
26
26
  var import_body = require("./utils/body");
27
27
  var import_url = require("./utils/url");
28
- const tryDecodeURIComponent = (str) => (0, import_url.tryDecode)(str, import_url.decodeURIComponent_);
29
28
  class HonoRequest {
30
29
  /**
31
30
  * `.raw` can get the raw Request object.
@@ -64,7 +63,6 @@ class HonoRequest {
64
63
  this.raw = request;
65
64
  this.path = path;
66
65
  this.#matchResult = matchResult;
67
- this.#validatedData = {};
68
66
  }
69
67
  param(key) {
70
68
  return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
@@ -72,7 +70,7 @@ class HonoRequest {
72
70
  #getDecodedParam(key) {
73
71
  const paramKey = this.#matchResult[0][this.routeIndex][1][key];
74
72
  const param = this.#getParamValue(paramKey);
75
- return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
73
+ return param && (0, import_url.tryDecodeURIComponent)(param);
76
74
  }
77
75
  #getAllDecodedParams() {
78
76
  const decoded = {};
@@ -80,7 +78,7 @@ class HonoRequest {
80
78
  for (const key of keys) {
81
79
  const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
82
80
  if (value !== void 0) {
83
- decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
81
+ decoded[key] = (0, import_url.tryDecodeURIComponent)(value);
84
82
  }
85
83
  }
86
84
  return decoded;
@@ -98,7 +96,7 @@ class HonoRequest {
98
96
  if (name) {
99
97
  return this.raw.headers.get(name) ?? void 0;
100
98
  }
101
- const headerData = {};
99
+ const headerData = /* @__PURE__ */ Object.create(null);
102
100
  this.raw.headers.forEach((value, key) => {
103
101
  headerData[key] = value;
104
102
  });
@@ -113,8 +111,7 @@ class HonoRequest {
113
111
  if (cachedBody) {
114
112
  return cachedBody;
115
113
  }
116
- const anyCachedKey = Object.keys(bodyCache)[0];
117
- if (anyCachedKey) {
114
+ for (const anyCachedKey in bodyCache) {
118
115
  return bodyCache[anyCachedKey].then((body) => {
119
116
  if (anyCachedKey === "json") {
120
117
  body = JSON.stringify(body);
@@ -217,10 +214,11 @@ class HonoRequest {
217
214
  * @param data - The validated data to add.
218
215
  */
219
216
  addValidatedData(target, data) {
220
- this.#validatedData[target] = data;
217
+ ;
218
+ (this.#validatedData ??= {})[target] = data;
221
219
  }
222
220
  valid(target) {
223
- return this.#validatedData[target];
221
+ return this.#validatedData?.[target];
224
222
  }
225
223
  /**
226
224
  * `.url()` can get the request url strings.