@busca-agentes/core 0.1.1 → 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.
package/dist/index.d.cts CHANGED
@@ -89,16 +89,41 @@ declare function parseSearchMarkdown(markdown: string): {
89
89
  }>;
90
90
  };
91
91
 
92
+ declare const MISSING_QUERY_CODE = "missing_query";
93
+ declare const MISSING_QUERY_HOW_TO_FIX = "GET /.well-known/search?q=<text> or QUERY with text/plain body or JSON {\"q\":\"...\"}";
94
+ type SearchErrorCode = "missing_query" | "unsupported_media_type" | "method_not_allowed" | "payload_too_large";
95
+ type SearchQueryFailure = {
96
+ ok: false;
97
+ status: number;
98
+ code: SearchErrorCode;
99
+ message: string;
100
+ };
101
+ type SearchErrorDocument = {
102
+ error: {
103
+ code: string;
104
+ message: string;
105
+ how_to_fix: string;
106
+ examples: string[];
107
+ documentation: string;
108
+ };
109
+ };
110
+ declare function requestOrigin(request: Request): string;
111
+ /** True when Accept lists application/json as the preferred concrete type. */
112
+ declare function acceptPrefersJson(accept: string | null): boolean;
113
+ declare function missingQueryFailure(): SearchQueryFailure;
114
+ declare function searchErrorDocument(request: Request, failure: SearchQueryFailure): SearchErrorDocument;
115
+ declare function searchErrorMarkdown(doc: SearchErrorDocument): string;
116
+ declare function describedByLink(docsUrl?: string): string;
117
+ declare function searchErrorResponse(request: Request, failure: SearchQueryFailure): Response;
118
+ declare function searchErrorHead(request: Request, failure: SearchQueryFailure): Response;
119
+
92
120
  type ParsedQuery = {
93
121
  ok: true;
94
122
  q: string;
95
123
  method: "GET" | "QUERY" | "HEAD";
96
- } | {
97
- ok: false;
98
- status: number;
99
- body: string;
100
- contentType: string;
101
- };
124
+ } | SearchQueryFailure;
125
+ /** q wins when present; query= and question= are fallbacks. Whitespace-only is empty. */
126
+ declare function firstQueryAlias(getter: (name: string) => string | null, has?: (name: string) => boolean): string;
102
127
  /**
103
128
  * Extract the search text from a GET, HEAD, or QUERY request.
104
129
  *
@@ -107,10 +132,12 @@ type ParsedQuery = {
107
132
  * - QUERY + `text/plain`: raw UTF-8 body
108
133
  * - QUERY + `application/json`: `{ "q": "..." }`
109
134
  *
135
+ * Aliases `query` and `question` are accepted as fallbacks when `q` is absent.
136
+ * Empty or whitespace-only `q` is `missing_query` (HTTP 400).
137
+ *
110
138
  * Decision (curl-friendly, not in the written spec): QUERY without a
111
139
  * Content-Type, and `application/x-www-form-urlencoded` bodies, are treated
112
140
  * as plain text. `curl -X QUERY --data '...'` sends urlencoded by default.
113
- * Empty or missing `q` returns HTTP 400 with body `Missing query parameter: ?q=`.
114
141
  */
115
142
  declare function parseSearchQuery(request: Request): Promise<ParsedQuery>;
116
143
 
@@ -122,7 +149,11 @@ declare function methodNotAllowed(): Response;
122
149
  declare function quotaExceededResponse(): Response;
123
150
 
124
151
  declare function monthKey(date?: Date): string;
125
- declare function decideQuota(input: {
152
+ /**
153
+ * Usage is counted, never blocked. Billing and prepaid credit were removed.
154
+ * `credits` is ignored; the field remains so existing stores keep compiling.
155
+ */
156
+ declare function decideQuota(_input: {
126
157
  usedFree: number;
127
158
  credits: number;
128
159
  freeLimit?: number;
@@ -156,4 +187,4 @@ declare function agentDiscovery(options: {
156
187
  declare function agentMetaTags(discovery: AgentDiscovery): string;
157
188
  declare function agentYamlFrontMatter(discovery: AgentDiscovery): string;
158
189
 
159
- export { ACCEPT_QUERY, ALLOW_METHODS, type AgentDiscovery, DEFAULT_CHUNK_OVERLAP_RATIO, DEFAULT_CHUNK_TOKENS, DEFAULT_DOCUMENTATION, DEFAULT_EMBEDDING_DIMENSION, DEFAULT_INSTRUCTIONS, DEFAULT_MATCH_THRESHOLD, DEFAULT_MAX_RESULTS, FREE_QUERIES_PER_MONTH, MARKDOWN_CONTENT_TYPE, MISSING_QUERY_BODY, PLAIN_CONTENT_TYPE, PREPAID_USD_PER_1000, type QuotaBucket, type QuotaDecision, type QuotaExhausted, type QuotaResult, type QuotaStore, RRF_K, SEARCH_PATH, type SearchBackend, type SearchHandlerOptions, type SearchHit, agentDiscovery, agentMetaTags, agentYamlFrontMatter, createMemoryQuotaStore, decideQuota, emptyHead, formatSearchMarkdown, handleSearchRequest, markdownResponse, methodNotAllowed, monthKey, normalizeScores, parseSearchMarkdown, parseSearchQuery, plainResponse, prepaidQueriesForUsd, quotaExceededResponse, reciprocalRankFusion, searchResponseHeaders, usdForPrepaidQueries };
190
+ export { ACCEPT_QUERY, ALLOW_METHODS, type AgentDiscovery, DEFAULT_CHUNK_OVERLAP_RATIO, DEFAULT_CHUNK_TOKENS, DEFAULT_DOCUMENTATION, DEFAULT_EMBEDDING_DIMENSION, DEFAULT_INSTRUCTIONS, DEFAULT_MATCH_THRESHOLD, DEFAULT_MAX_RESULTS, FREE_QUERIES_PER_MONTH, MARKDOWN_CONTENT_TYPE, MISSING_QUERY_BODY, MISSING_QUERY_CODE, MISSING_QUERY_HOW_TO_FIX, PLAIN_CONTENT_TYPE, PREPAID_USD_PER_1000, type QuotaBucket, type QuotaDecision, type QuotaExhausted, type QuotaResult, type QuotaStore, RRF_K, SEARCH_PATH, type SearchBackend, type SearchErrorCode, type SearchErrorDocument, type SearchHandlerOptions, type SearchHit, type SearchQueryFailure, acceptPrefersJson, agentDiscovery, agentMetaTags, agentYamlFrontMatter, createMemoryQuotaStore, decideQuota, describedByLink, emptyHead, firstQueryAlias, formatSearchMarkdown, handleSearchRequest, markdownResponse, methodNotAllowed, missingQueryFailure, monthKey, normalizeScores, parseSearchMarkdown, parseSearchQuery, plainResponse, prepaidQueriesForUsd, quotaExceededResponse, reciprocalRankFusion, requestOrigin, searchErrorDocument, searchErrorHead, searchErrorMarkdown, searchErrorResponse, searchResponseHeaders, usdForPrepaidQueries };
package/dist/index.d.ts CHANGED
@@ -89,16 +89,41 @@ declare function parseSearchMarkdown(markdown: string): {
89
89
  }>;
90
90
  };
91
91
 
92
+ declare const MISSING_QUERY_CODE = "missing_query";
93
+ declare const MISSING_QUERY_HOW_TO_FIX = "GET /.well-known/search?q=<text> or QUERY with text/plain body or JSON {\"q\":\"...\"}";
94
+ type SearchErrorCode = "missing_query" | "unsupported_media_type" | "method_not_allowed" | "payload_too_large";
95
+ type SearchQueryFailure = {
96
+ ok: false;
97
+ status: number;
98
+ code: SearchErrorCode;
99
+ message: string;
100
+ };
101
+ type SearchErrorDocument = {
102
+ error: {
103
+ code: string;
104
+ message: string;
105
+ how_to_fix: string;
106
+ examples: string[];
107
+ documentation: string;
108
+ };
109
+ };
110
+ declare function requestOrigin(request: Request): string;
111
+ /** True when Accept lists application/json as the preferred concrete type. */
112
+ declare function acceptPrefersJson(accept: string | null): boolean;
113
+ declare function missingQueryFailure(): SearchQueryFailure;
114
+ declare function searchErrorDocument(request: Request, failure: SearchQueryFailure): SearchErrorDocument;
115
+ declare function searchErrorMarkdown(doc: SearchErrorDocument): string;
116
+ declare function describedByLink(docsUrl?: string): string;
117
+ declare function searchErrorResponse(request: Request, failure: SearchQueryFailure): Response;
118
+ declare function searchErrorHead(request: Request, failure: SearchQueryFailure): Response;
119
+
92
120
  type ParsedQuery = {
93
121
  ok: true;
94
122
  q: string;
95
123
  method: "GET" | "QUERY" | "HEAD";
96
- } | {
97
- ok: false;
98
- status: number;
99
- body: string;
100
- contentType: string;
101
- };
124
+ } | SearchQueryFailure;
125
+ /** q wins when present; query= and question= are fallbacks. Whitespace-only is empty. */
126
+ declare function firstQueryAlias(getter: (name: string) => string | null, has?: (name: string) => boolean): string;
102
127
  /**
103
128
  * Extract the search text from a GET, HEAD, or QUERY request.
104
129
  *
@@ -107,10 +132,12 @@ type ParsedQuery = {
107
132
  * - QUERY + `text/plain`: raw UTF-8 body
108
133
  * - QUERY + `application/json`: `{ "q": "..." }`
109
134
  *
135
+ * Aliases `query` and `question` are accepted as fallbacks when `q` is absent.
136
+ * Empty or whitespace-only `q` is `missing_query` (HTTP 400).
137
+ *
110
138
  * Decision (curl-friendly, not in the written spec): QUERY without a
111
139
  * Content-Type, and `application/x-www-form-urlencoded` bodies, are treated
112
140
  * as plain text. `curl -X QUERY --data '...'` sends urlencoded by default.
113
- * Empty or missing `q` returns HTTP 400 with body `Missing query parameter: ?q=`.
114
141
  */
115
142
  declare function parseSearchQuery(request: Request): Promise<ParsedQuery>;
116
143
 
@@ -122,7 +149,11 @@ declare function methodNotAllowed(): Response;
122
149
  declare function quotaExceededResponse(): Response;
123
150
 
124
151
  declare function monthKey(date?: Date): string;
125
- declare function decideQuota(input: {
152
+ /**
153
+ * Usage is counted, never blocked. Billing and prepaid credit were removed.
154
+ * `credits` is ignored; the field remains so existing stores keep compiling.
155
+ */
156
+ declare function decideQuota(_input: {
126
157
  usedFree: number;
127
158
  credits: number;
128
159
  freeLimit?: number;
@@ -156,4 +187,4 @@ declare function agentDiscovery(options: {
156
187
  declare function agentMetaTags(discovery: AgentDiscovery): string;
157
188
  declare function agentYamlFrontMatter(discovery: AgentDiscovery): string;
158
189
 
159
- export { ACCEPT_QUERY, ALLOW_METHODS, type AgentDiscovery, DEFAULT_CHUNK_OVERLAP_RATIO, DEFAULT_CHUNK_TOKENS, DEFAULT_DOCUMENTATION, DEFAULT_EMBEDDING_DIMENSION, DEFAULT_INSTRUCTIONS, DEFAULT_MATCH_THRESHOLD, DEFAULT_MAX_RESULTS, FREE_QUERIES_PER_MONTH, MARKDOWN_CONTENT_TYPE, MISSING_QUERY_BODY, PLAIN_CONTENT_TYPE, PREPAID_USD_PER_1000, type QuotaBucket, type QuotaDecision, type QuotaExhausted, type QuotaResult, type QuotaStore, RRF_K, SEARCH_PATH, type SearchBackend, type SearchHandlerOptions, type SearchHit, agentDiscovery, agentMetaTags, agentYamlFrontMatter, createMemoryQuotaStore, decideQuota, emptyHead, formatSearchMarkdown, handleSearchRequest, markdownResponse, methodNotAllowed, monthKey, normalizeScores, parseSearchMarkdown, parseSearchQuery, plainResponse, prepaidQueriesForUsd, quotaExceededResponse, reciprocalRankFusion, searchResponseHeaders, usdForPrepaidQueries };
190
+ export { ACCEPT_QUERY, ALLOW_METHODS, type AgentDiscovery, DEFAULT_CHUNK_OVERLAP_RATIO, DEFAULT_CHUNK_TOKENS, DEFAULT_DOCUMENTATION, DEFAULT_EMBEDDING_DIMENSION, DEFAULT_INSTRUCTIONS, DEFAULT_MATCH_THRESHOLD, DEFAULT_MAX_RESULTS, FREE_QUERIES_PER_MONTH, MARKDOWN_CONTENT_TYPE, MISSING_QUERY_BODY, MISSING_QUERY_CODE, MISSING_QUERY_HOW_TO_FIX, PLAIN_CONTENT_TYPE, PREPAID_USD_PER_1000, type QuotaBucket, type QuotaDecision, type QuotaExhausted, type QuotaResult, type QuotaStore, RRF_K, SEARCH_PATH, type SearchBackend, type SearchErrorCode, type SearchErrorDocument, type SearchHandlerOptions, type SearchHit, type SearchQueryFailure, acceptPrefersJson, agentDiscovery, agentMetaTags, agentYamlFrontMatter, createMemoryQuotaStore, decideQuota, describedByLink, emptyHead, firstQueryAlias, formatSearchMarkdown, handleSearchRequest, markdownResponse, methodNotAllowed, missingQueryFailure, monthKey, normalizeScores, parseSearchMarkdown, parseSearchQuery, plainResponse, prepaidQueriesForUsd, quotaExceededResponse, reciprocalRankFusion, requestOrigin, searchErrorDocument, searchErrorHead, searchErrorMarkdown, searchErrorResponse, searchResponseHeaders, usdForPrepaidQueries };
package/dist/index.js CHANGED
@@ -80,6 +80,162 @@ function parseSearchMarkdown(markdown) {
80
80
  return { query, hits };
81
81
  }
82
82
 
83
+ // src/headers.ts
84
+ function searchResponseHeaders(extra) {
85
+ const headers = new Headers({
86
+ Allow: ALLOW_METHODS,
87
+ "Accept-Query": ACCEPT_QUERY,
88
+ "X-Content-Type-Options": "nosniff",
89
+ ...extra
90
+ });
91
+ return headers;
92
+ }
93
+ function markdownResponse(body, status = 200) {
94
+ return new Response(body, {
95
+ status,
96
+ headers: searchResponseHeaders({
97
+ "Content-Type": MARKDOWN_CONTENT_TYPE
98
+ })
99
+ });
100
+ }
101
+ function plainResponse(body, status) {
102
+ return new Response(body, {
103
+ status,
104
+ headers: searchResponseHeaders({
105
+ "Content-Type": PLAIN_CONTENT_TYPE
106
+ })
107
+ });
108
+ }
109
+ function emptyHead(status, markdown) {
110
+ return new Response(null, {
111
+ status,
112
+ headers: searchResponseHeaders({
113
+ "Content-Type": markdown ? MARKDOWN_CONTENT_TYPE : PLAIN_CONTENT_TYPE
114
+ })
115
+ });
116
+ }
117
+ function methodNotAllowed() {
118
+ return plainResponse("Method Not Allowed", 405);
119
+ }
120
+ function quotaExceededResponse() {
121
+ return plainResponse("Too many requests. Retry shortly.", 429);
122
+ }
123
+
124
+ // src/errors.ts
125
+ var MISSING_QUERY_CODE = "missing_query";
126
+ var MISSING_QUERY_HOW_TO_FIX = 'GET /.well-known/search?q=<text> or QUERY with text/plain body or JSON {"q":"..."}';
127
+ var MAX_MARKDOWN_BYTES = 800;
128
+ function requestOrigin(request) {
129
+ try {
130
+ return new URL(request.url).origin;
131
+ } catch {
132
+ return "";
133
+ }
134
+ }
135
+ function acceptPrefersJson(accept) {
136
+ if (!accept) return false;
137
+ let jsonQ = -1;
138
+ let otherQ = -1;
139
+ for (const part of accept.split(",")) {
140
+ const bits = part.split(";").map((s) => s.trim());
141
+ const type = (bits[0] ?? "").toLowerCase();
142
+ if (!type) continue;
143
+ let q = 1;
144
+ for (const param of bits.slice(1)) {
145
+ const match = /^q=([0-9]*\.?[0-9]+)$/i.exec(param);
146
+ if (match) {
147
+ const n = Number(match[1]);
148
+ q = Number.isFinite(n) ? n : 0;
149
+ }
150
+ }
151
+ if (type === "application/json") {
152
+ jsonQ = Math.max(jsonQ, q);
153
+ } else if (type === "text/markdown" || type === "text/plain" || type === "text/*") {
154
+ otherQ = Math.max(otherQ, q);
155
+ }
156
+ }
157
+ return jsonQ > 0 && jsonQ >= otherQ;
158
+ }
159
+ function missingQueryFailure() {
160
+ return {
161
+ ok: false,
162
+ status: 400,
163
+ code: MISSING_QUERY_CODE,
164
+ message: MISSING_QUERY_BODY
165
+ };
166
+ }
167
+ function searchErrorDocument(request, failure) {
168
+ const origin = requestOrigin(request);
169
+ const howToFix = failure.code === MISSING_QUERY_CODE ? MISSING_QUERY_HOW_TO_FIX : failure.code === "unsupported_media_type" ? 'Retry QUERY with Content-Type: text/plain (raw query) or application/json {"q":"..."}.' : failure.code === "method_not_allowed" ? "Use GET, HEAD, or QUERY on /.well-known/search (Allow: GET, HEAD, QUERY)." : "Send a smaller QUERY body.";
170
+ const examples = origin ? [
171
+ `${origin}${SEARCH_PATH}?q=example`,
172
+ `${origin}${SEARCH_PATH}?q=free+shipping`
173
+ ] : [`${SEARCH_PATH}?q=example`];
174
+ return {
175
+ error: {
176
+ code: failure.code,
177
+ message: failure.message,
178
+ how_to_fix: howToFix,
179
+ examples,
180
+ documentation: DEFAULT_DOCUMENTATION
181
+ }
182
+ };
183
+ }
184
+ function searchErrorMarkdown(doc) {
185
+ const { error } = doc;
186
+ const body = [
187
+ `# ${error.code}`,
188
+ "",
189
+ error.message,
190
+ "",
191
+ `how_to_fix: ${error.how_to_fix}`,
192
+ "",
193
+ "examples:",
194
+ ...error.examples.map((url) => `- ${url}`),
195
+ "",
196
+ `documentation: ${error.documentation}`,
197
+ ""
198
+ ].join("\n");
199
+ if (new TextEncoder().encode(body).length > MAX_MARKDOWN_BYTES) {
200
+ return body.slice(0, MAX_MARKDOWN_BYTES);
201
+ }
202
+ return body;
203
+ }
204
+ function describedByLink(docsUrl = DEFAULT_DOCUMENTATION) {
205
+ return `<${docsUrl}>; rel="describedby"`;
206
+ }
207
+ function searchErrorResponse(request, failure) {
208
+ const doc = searchErrorDocument(request, failure);
209
+ const asJson = acceptPrefersJson(request.headers.get("accept"));
210
+ const extra = {
211
+ Link: describedByLink()
212
+ };
213
+ if (asJson) {
214
+ extra["Content-Type"] = "application/json; charset=utf-8";
215
+ return new Response(JSON.stringify(doc), {
216
+ status: failure.status,
217
+ headers: searchResponseHeaders(extra)
218
+ });
219
+ }
220
+ extra["Content-Type"] = MARKDOWN_CONTENT_TYPE;
221
+ return new Response(searchErrorMarkdown(doc), {
222
+ status: failure.status,
223
+ headers: searchResponseHeaders(extra)
224
+ });
225
+ }
226
+ function searchErrorHead(request, failure) {
227
+ const asJson = acceptPrefersJson(request.headers.get("accept"));
228
+ return new Response(null, {
229
+ status: failure.status,
230
+ headers: searchResponseHeaders({
231
+ Link: describedByLink(),
232
+ "Content-Type": asJson ? "application/json; charset=utf-8" : MARKDOWN_CONTENT_TYPE,
233
+ Allow: ALLOW_METHODS,
234
+ "Accept-Query": ACCEPT_QUERY
235
+ })
236
+ });
237
+ }
238
+
83
239
  // src/query.ts
84
240
  function isJsonContentType(value) {
85
241
  if (!value) return false;
@@ -90,20 +246,37 @@ function isPlainText(value) {
90
246
  const v = value.toLowerCase();
91
247
  return v.includes("text/plain") || v.includes("text/markdown") || v.includes("application/x-www-form-urlencoded");
92
248
  }
249
+ function firstQueryAlias(getter, has) {
250
+ const present = has ?? ((name) => getter(name) !== null);
251
+ if (present("q")) return (getter("q") ?? "").trim();
252
+ if (present("query")) return (getter("query") ?? "").trim();
253
+ if (present("question")) return (getter("question") ?? "").trim();
254
+ return "";
255
+ }
256
+ function fromSearchParams(params) {
257
+ return firstQueryAlias(
258
+ (name) => params.get(name),
259
+ (name) => params.has(name)
260
+ );
261
+ }
262
+ function fromJsonObject(value) {
263
+ if (!value || typeof value !== "object") return "";
264
+ const obj = value;
265
+ return firstQueryAlias(
266
+ (name) => {
267
+ const v = obj[name];
268
+ return typeof v === "string" ? v : "";
269
+ },
270
+ (name) => Object.prototype.hasOwnProperty.call(obj, name)
271
+ );
272
+ }
93
273
  async function parseSearchQuery(request) {
94
274
  const method = request.method.toUpperCase();
95
275
  const url = new URL(request.url);
96
276
  const headerQ = request.headers.get("x-agent-search-q");
97
277
  if (method === "GET" || method === "HEAD") {
98
- const q = (headerQ ?? url.searchParams.get("q") ?? "").trim();
99
- if (!q) {
100
- return {
101
- ok: false,
102
- status: 400,
103
- body: MISSING_QUERY_BODY,
104
- contentType: "text/plain; charset=utf-8"
105
- };
106
- }
278
+ const q = (headerQ?.trim() || fromSearchParams(url.searchParams)).trim();
279
+ if (!q) return missingQueryFailure();
107
280
  return { ok: true, q, method: method === "HEAD" ? "HEAD" : "GET" };
108
281
  }
109
282
  if (method === "QUERY") {
@@ -112,12 +285,12 @@ async function parseSearchQuery(request) {
112
285
  try {
113
286
  if (isJsonContentType(contentType)) {
114
287
  const json = await request.json();
115
- q = typeof json?.q === "string" ? json.q : "";
288
+ q = fromJsonObject(json);
116
289
  } else if (isPlainText(contentType)) {
117
290
  const raw = await request.text();
118
291
  if (contentType && contentType.toLowerCase().includes("application/x-www-form-urlencoded")) {
119
292
  const params = new URLSearchParams(raw);
120
- q = (params.get("q") ?? raw).trim();
293
+ q = fromSearchParams(params) || raw.trim();
121
294
  } else {
122
295
  q = raw.trim();
123
296
  }
@@ -125,102 +298,33 @@ async function parseSearchQuery(request) {
125
298
  return {
126
299
  ok: false,
127
300
  status: 415,
128
- body: "Unsupported QUERY content type. Use text/plain or application/json.",
129
- contentType: "text/plain; charset=utf-8"
301
+ code: "unsupported_media_type",
302
+ message: "Unsupported QUERY content type. Use text/plain or application/json."
130
303
  };
131
304
  }
132
305
  } catch {
133
- return {
134
- ok: false,
135
- status: 400,
136
- body: MISSING_QUERY_BODY,
137
- contentType: "text/plain; charset=utf-8"
138
- };
306
+ return missingQueryFailure();
139
307
  }
140
308
  q = q.trim();
141
- if (!q) {
142
- return {
143
- ok: false,
144
- status: 400,
145
- body: MISSING_QUERY_BODY,
146
- contentType: "text/plain; charset=utf-8"
147
- };
148
- }
309
+ if (!q) return missingQueryFailure();
149
310
  return { ok: true, q, method: "QUERY" };
150
311
  }
151
312
  return {
152
313
  ok: false,
153
314
  status: 405,
154
- body: "Method Not Allowed",
155
- contentType: "text/plain; charset=utf-8"
315
+ code: "method_not_allowed",
316
+ message: "Method Not Allowed"
156
317
  };
157
318
  }
158
319
 
159
- // src/headers.ts
160
- function searchResponseHeaders(extra) {
161
- const headers = new Headers({
162
- Allow: ALLOW_METHODS,
163
- "Accept-Query": ACCEPT_QUERY,
164
- "X-Content-Type-Options": "nosniff",
165
- ...extra
166
- });
167
- return headers;
168
- }
169
- function markdownResponse(body, status = 200) {
170
- return new Response(body, {
171
- status,
172
- headers: searchResponseHeaders({
173
- "Content-Type": MARKDOWN_CONTENT_TYPE
174
- })
175
- });
176
- }
177
- function plainResponse(body, status) {
178
- return new Response(body, {
179
- status,
180
- headers: searchResponseHeaders({
181
- "Content-Type": PLAIN_CONTENT_TYPE
182
- })
183
- });
184
- }
185
- function emptyHead(status, markdown) {
186
- return new Response(null, {
187
- status,
188
- headers: searchResponseHeaders({
189
- "Content-Type": markdown ? MARKDOWN_CONTENT_TYPE : PLAIN_CONTENT_TYPE
190
- })
191
- });
192
- }
193
- function methodNotAllowed() {
194
- return plainResponse("Method Not Allowed", 405);
195
- }
196
- function quotaExceededResponse() {
197
- return plainResponse(
198
- "Query quota exceeded. This site has used its included 1000 queries this month and has no prepaid credit.",
199
- 429
200
- );
201
- }
202
-
203
320
  // src/quota.ts
204
321
  function monthKey(date = /* @__PURE__ */ new Date()) {
205
322
  const year = date.getUTCFullYear();
206
323
  const month = String(date.getUTCMonth() + 1).padStart(2, "0");
207
324
  return `${year}-${month}`;
208
325
  }
209
- function decideQuota(input) {
210
- const freeLimit = input.freeLimit ?? FREE_QUERIES_PER_MONTH;
211
- if (input.usedFree < freeLimit) {
212
- return { ok: true, bucket: "free" };
213
- }
214
- if (input.credits > 0) {
215
- return { ok: true, bucket: "credit" };
216
- }
217
- return {
218
- ok: false,
219
- reason: "exhausted",
220
- usedFree: input.usedFree,
221
- credits: input.credits,
222
- freeLimit
223
- };
326
+ function decideQuota(_input) {
327
+ return { ok: true, bucket: "free" };
224
328
  }
225
329
  function prepaidQueriesForUsd(usd) {
226
330
  return Math.round(usd / 0.75 * 1e3);
@@ -240,18 +344,12 @@ function createMemoryQuotaStore(options) {
240
344
  const key = `${siteId}:${currentMonth()}`;
241
345
  const usedFree = used.get(key) ?? 0;
242
346
  const remainingCredits = credits.get(siteId) ?? 0;
243
- const decision = decideQuota({
347
+ used.set(key, usedFree + 1);
348
+ return decideQuota({
244
349
  usedFree,
245
350
  credits: remainingCredits,
246
351
  freeLimit
247
352
  });
248
- if (!decision.ok) return decision;
249
- if (decision.bucket === "free") {
250
- used.set(key, usedFree + 1);
251
- } else {
252
- credits.set(siteId, remainingCredits - 1);
253
- }
254
- return decision;
255
353
  },
256
354
  snapshot(siteId) {
257
355
  return {
@@ -295,14 +393,27 @@ async function handleSearchRequest(request, options) {
295
393
  });
296
394
  }
297
395
  if (!["GET", "HEAD", "QUERY"].includes(method)) {
298
- return methodNotAllowed();
396
+ if (method === "HEAD") {
397
+ return searchErrorHead(request, {
398
+ ok: false,
399
+ status: 405,
400
+ code: "method_not_allowed",
401
+ message: "Method Not Allowed"
402
+ });
403
+ }
404
+ return searchErrorResponse(request, {
405
+ ok: false,
406
+ status: 405,
407
+ code: "method_not_allowed",
408
+ message: "Method Not Allowed"
409
+ });
299
410
  }
300
411
  const parsed = await parseSearchQuery(request);
301
412
  if (!parsed.ok) {
302
413
  if (method === "HEAD") {
303
- return emptyHead(parsed.status, false);
414
+ return searchErrorHead(request, parsed);
304
415
  }
305
- return plainResponse(parsed.body, parsed.status);
416
+ return searchErrorResponse(request, parsed);
306
417
  }
307
418
  if (options.quota && options.siteId) {
308
419
  const quota = await options.quota.consume(options.siteId);
@@ -368,20 +479,26 @@ export {
368
479
  FREE_QUERIES_PER_MONTH,
369
480
  MARKDOWN_CONTENT_TYPE,
370
481
  MISSING_QUERY_BODY,
482
+ MISSING_QUERY_CODE,
483
+ MISSING_QUERY_HOW_TO_FIX,
371
484
  PLAIN_CONTENT_TYPE,
372
485
  PREPAID_USD_PER_1000,
373
486
  RRF_K,
374
487
  SEARCH_PATH,
488
+ acceptPrefersJson,
375
489
  agentDiscovery,
376
490
  agentMetaTags,
377
491
  agentYamlFrontMatter,
378
492
  createMemoryQuotaStore,
379
493
  decideQuota,
494
+ describedByLink,
380
495
  emptyHead,
496
+ firstQueryAlias,
381
497
  formatSearchMarkdown,
382
498
  handleSearchRequest,
383
499
  markdownResponse,
384
500
  methodNotAllowed,
501
+ missingQueryFailure,
385
502
  monthKey,
386
503
  normalizeScores,
387
504
  parseSearchMarkdown,
@@ -390,6 +507,11 @@ export {
390
507
  prepaidQueriesForUsd,
391
508
  quotaExceededResponse,
392
509
  reciprocalRankFusion,
510
+ requestOrigin,
511
+ searchErrorDocument,
512
+ searchErrorHead,
513
+ searchErrorMarkdown,
514
+ searchErrorResponse,
393
515
  searchResponseHeaders,
394
516
  usdForPrepaidQueries
395
517
  };