@statsmcp/core 0.4.1 → 0.6.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/node.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { i as SnapshotReader } from "./snapshot-DwtIVsqx.js";
1
+ import { i as SnapshotReader } from "./snapshot-BCJSa_1e.js";
2
2
  export declare const DEFAULT_INDEX_URL = "https://statsmcp.dev";
3
3
  export interface NodeTableSnapshotsOptions {
4
4
  userAgent?: string;
package/dist/node.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as snapshotKey, i as readSnapshot, o as urlSnapshotReader, r as firstSnapshot } from "./snapshot-CT_ItdeR.js";
1
+ import { a as snapshotKey, i as readSnapshot, o as urlSnapshotReader, r as firstSnapshot } from "./snapshot-CMstGbu-.js";
2
2
  import { readFile } from "node:fs/promises";
3
3
  // src/node.ts
4
4
  const DEFAULT_INDEX_URL = "https://statsmcp.dev";
@@ -15,6 +15,7 @@ declare const snapshotSchema: z.ZodObject<{
15
15
  lastPeriod: z.ZodOptional<z.ZodString>;
16
16
  discontinued: z.ZodOptional<z.ZodBoolean>;
17
17
  }, z.core.$strip>>;
18
+ searchIndex: z.ZodOptional<z.ZodUnknown>;
18
19
  }, z.core.$strip>;
19
20
  /** A source's table catalogue in one language, as the crawler stores it. */
20
21
  type Snapshot = z.infer<typeof snapshotSchema>;
@@ -0,0 +1,635 @@
1
+ import { z } from "zod";
2
+ import MiniSearch from "minisearch";
3
+ // src/search-ranking.ts
4
+ const CLOSED_RANGE = /(\d{4})(?:[MQH]\d{1,2})?\s*-\s*(\d{4})(?:[MQH]\d{1,2})?\s*$/;
5
+ const CLOSED_SERIES = /closed series|avslutta serie|avsluttet serie/i;
6
+ const HISTORICAL_PENALTY = 1;
7
+ const RECENCY_WEIGHT$1 = .15;
8
+ const RECENCY_YEARS$1 = 4;
9
+ const POSITION_COST = .03;
10
+ function isHistorical(title, currentYear) {
11
+ if (CLOSED_SERIES.test(title)) return true;
12
+ const match = CLOSED_RANGE.exec(title);
13
+ return match !== null && Number(match[2]) < currentYear - 1;
14
+ }
15
+ function recency$1(published, currentYear) {
16
+ const year = Number(published?.slice(0, 4));
17
+ if (!Number.isFinite(year)) return 0;
18
+ const age = currentYear - year;
19
+ return Math.max(0, Math.min(1, (RECENCY_YEARS$1 - age) / RECENCY_YEARS$1));
20
+ }
21
+ /** The API's relevance order stays the base score; age and closed ranges adjust it. */
22
+ function rankSearchHits(hits, currentYear) {
23
+ return hits.map((hit, index) => {
24
+ let score = -index * POSITION_COST;
25
+ if (hit.archived || isHistorical(hit.title, currentYear)) score -= HISTORICAL_PENALTY;
26
+ score += RECENCY_WEIGHT$1 * recency$1(hit.published, currentYear);
27
+ return {
28
+ hit,
29
+ score,
30
+ index
31
+ };
32
+ }).toSorted((a, b) => b.score - a.score || a.index - b.index).map((entry) => entry.hit);
33
+ }
34
+ // src/text.ts
35
+ /** Letters that Unicode does not decompose into a base letter and a mark. */
36
+ const FOLDED_LETTERS = {
37
+ ø: "o",
38
+ æ: "ae",
39
+ œ: "oe",
40
+ ß: "ss",
41
+ đ: "d",
42
+ ð: "d",
43
+ ł: "l",
44
+ þ: "th"
45
+ };
46
+ /** Lower case without diacritics, so "Plača" matches "placa" and "Købekraft" matches "kobekraft". */
47
+ function normalize(text, lang) {
48
+ return text.toLocaleLowerCase(lang).normalize("NFD").replace(/\p{M}/gu, "").replace(/[øæœßđðłþ]/gu, (letter) => FOLDED_LETTERS[letter] ?? letter);
49
+ }
50
+ /** True when `term` starts a word in `text`, so "price" matches "prices" but "wage" does not match "sewage". */
51
+ function startsWord(text, term) {
52
+ let index = text.indexOf(term);
53
+ while (index >= 0) {
54
+ if (!/\p{L}/u.test(text[index - 1] ?? " ")) return true;
55
+ index = text.indexOf(term, index + 1);
56
+ }
57
+ return false;
58
+ }
59
+ // src/title-search.ts
60
+ const MIN_TERM_LENGTH$1 = 2;
61
+ function termsOf(query, lang) {
62
+ return [...new Set(normalize(query, lang).split(/[^\p{L}\p{N}]+/u).filter((term) => term.length >= MIN_TERM_LENGTH$1))];
63
+ }
64
+ /**
65
+ * Keyword search over a local list of tables, for APIs without a working search.
66
+ * A table matches when at least half of the query words start a word in its title
67
+ * or equal its id, so a short word such as "for" alone does not match every table.
68
+ * Tables that match more words come first; ties keep the list order.
69
+ */
70
+ function searchTitles(tables, query, lang) {
71
+ const terms = termsOf(query, lang);
72
+ if (terms.length === 0) return [];
73
+ const needed = Math.ceil(terms.length / 2);
74
+ return tables.map((table, index) => {
75
+ const title = normalize(table.title, lang);
76
+ const id = normalize(table.tableId, lang);
77
+ return {
78
+ table,
79
+ matches: terms.filter((term) => id === term || startsWord(title, term)).length,
80
+ index
81
+ };
82
+ }).filter((entry) => entry.matches >= needed).toSorted((a, b) => b.matches - a.matches || a.index - b.index).map((entry) => entry.table);
83
+ }
84
+ // src/table-index.ts
85
+ /** Norwegian written standards share one stop-word list. */
86
+ const LANGUAGE_FAMILY = {
87
+ nb: "no",
88
+ nn: "no"
89
+ };
90
+ const FIELD_BOOST = {
91
+ title: 3,
92
+ path: 1
93
+ };
94
+ const PREFIX_MIN_LENGTH = 4;
95
+ const FUZZY_MIN_LENGTH = 6;
96
+ const FUZZY_DISTANCE = .2;
97
+ const MIN_TERM_LENGTH = 2;
98
+ const RECENCY_WEIGHT = .15;
99
+ const RECENCY_YEARS = 4;
100
+ const CLOSED_FACTOR = .5;
101
+ /** BM25 length normalisation; the MiniSearch default, kept after the golden-set evaluation. */
102
+ const LENGTH_NORMALIZATION = .75;
103
+ /** Rank constant of reciprocal rank fusion; small values trust the top ranks more. */
104
+ const FUSION_K = 10;
105
+ /** Function words of two or more letters (shorter words are never indexed). */
106
+ const STOP_WORDS = {
107
+ en: [
108
+ "an",
109
+ "and",
110
+ "at",
111
+ "by",
112
+ "for",
113
+ "from",
114
+ "in",
115
+ "of",
116
+ "on",
117
+ "or",
118
+ "per",
119
+ "the",
120
+ "to",
121
+ "with"
122
+ ],
123
+ da: [
124
+ "af",
125
+ "den",
126
+ "det",
127
+ "efter",
128
+ "for",
129
+ "fordelt",
130
+ "med",
131
+ "og",
132
+ "pa",
133
+ "til"
134
+ ],
135
+ de: [
136
+ "das",
137
+ "der",
138
+ "die",
139
+ "fur",
140
+ "im",
141
+ "in",
142
+ "je",
143
+ "mit",
144
+ "nach",
145
+ "und",
146
+ "von"
147
+ ],
148
+ et: ["ja", "ning"],
149
+ fi: ["ja"],
150
+ fo: ["og"],
151
+ hr: [
152
+ "do",
153
+ "i",
154
+ "iz",
155
+ "ili",
156
+ "na",
157
+ "od",
158
+ "po",
159
+ "prema",
160
+ "sa",
161
+ "te",
162
+ "za"
163
+ ],
164
+ is: [
165
+ "af",
166
+ "eftir",
167
+ "fra",
168
+ "med",
169
+ "og",
170
+ "til",
171
+ "um",
172
+ "vid"
173
+ ],
174
+ fr: [
175
+ "au",
176
+ "aux",
177
+ "de",
178
+ "des",
179
+ "du",
180
+ "en",
181
+ "et",
182
+ "la",
183
+ "le",
184
+ "les",
185
+ "par",
186
+ "pour",
187
+ "un",
188
+ "une"
189
+ ],
190
+ nl: [
191
+ "de",
192
+ "een",
193
+ "en",
194
+ "het",
195
+ "in",
196
+ "met",
197
+ "naar",
198
+ "op",
199
+ "per",
200
+ "van",
201
+ "voor"
202
+ ],
203
+ no: [
204
+ "av",
205
+ "etter",
206
+ "for",
207
+ "med",
208
+ "og",
209
+ "pa",
210
+ "til"
211
+ ],
212
+ es: [
213
+ "al",
214
+ "con",
215
+ "de",
216
+ "del",
217
+ "el",
218
+ "en",
219
+ "la",
220
+ "las",
221
+ "los",
222
+ "para",
223
+ "por",
224
+ "segun",
225
+ "un",
226
+ "una"
227
+ ],
228
+ pt: [
229
+ "ao",
230
+ "aos",
231
+ "as",
232
+ "com",
233
+ "da",
234
+ "das",
235
+ "de",
236
+ "do",
237
+ "dos",
238
+ "em",
239
+ "na",
240
+ "nas",
241
+ "no",
242
+ "nos",
243
+ "os",
244
+ "ou",
245
+ "pela",
246
+ "pelas",
247
+ "pelo",
248
+ "pelos",
249
+ "por",
250
+ "um",
251
+ "uma"
252
+ ],
253
+ sl: [
254
+ "in",
255
+ "na",
256
+ "po",
257
+ "ter",
258
+ "za"
259
+ ],
260
+ sv: [
261
+ "av",
262
+ "efter",
263
+ "for",
264
+ "med",
265
+ "och",
266
+ "pa",
267
+ "till"
268
+ ]
269
+ };
270
+ function extractField(doc, field) {
271
+ if (field === "path") return (doc.path ?? []).join(" ");
272
+ if (field === "id") return doc.id;
273
+ return doc.title;
274
+ }
275
+ const PX_FILE = /\.px$/i;
276
+ /** Docs by key, leaving out keys that more than one doc shares. */
277
+ function uniqueBy(docs, key) {
278
+ const byKey = /* @__PURE__ */ new Map();
279
+ for (const doc of docs) {
280
+ const value = key(doc);
281
+ if (value === void 0) continue;
282
+ byKey.set(value, byKey.has(value) ? void 0 : doc);
283
+ }
284
+ return new Map([...byKey].filter((entry) => entry[1] !== void 0));
285
+ }
286
+ /** Path ids ("db/folder/MAN00101.px") also match by a file name that only one table has. */
287
+ function uniqueFileNames(docs, lang) {
288
+ return uniqueBy(docs, (doc) => doc.id.includes("/") ? normalize(doc.id.split("/").at(-1) ?? "", lang).replace(PX_FILE, "") : void 0);
289
+ }
290
+ function recency(updated, currentYear) {
291
+ const year = Number(updated?.slice(0, 4));
292
+ if (!Number.isFinite(year)) return 0;
293
+ return Math.max(0, Math.min(1, (RECENCY_YEARS - (currentYear - year)) / RECENCY_YEARS));
294
+ }
295
+ function toHit(doc) {
296
+ return {
297
+ tableId: doc.id,
298
+ title: doc.title,
299
+ published: doc.updated,
300
+ ...doc.discontinued ? { archived: true } : {}
301
+ };
302
+ }
303
+ /**
304
+ * Reciprocal rank fusion (Cormack et al. 2009): each list adds 1 / (k + rank),
305
+ * so a table that ranks well in both lists comes first.
306
+ */
307
+ function fuseRankings(lists, k) {
308
+ const scores = /* @__PURE__ */ new Map();
309
+ for (const list of lists) list.forEach((id, rank) => {
310
+ scores.set(id, (scores.get(id) ?? 0) + 1 / (k + rank + 1));
311
+ });
312
+ return [...scores.entries()].toSorted((a, b) => b[1] - a[1]).map(([id]) => id);
313
+ }
314
+ /** True when the last period lies in the current or the previous year. */
315
+ function hasCurrentData(lastPeriod, currentYear) {
316
+ const year = Number(/(\d{4})/.exec(lastPeriod ?? "")?.[1]);
317
+ return Number.isFinite(year) && year >= currentYear - 1;
318
+ }
319
+ /** Bump when the index fields or the MiniSearch version change; term processing is checked by its fingerprint. */
320
+ const SEARCH_INDEX_VERSION = 1;
321
+ /** The prebuilt index stored in a snapshot, if it has the expected shape. */
322
+ function asPrebuiltIndex(value) {
323
+ if (typeof value !== "object" || value === null) return void 0;
324
+ if (!("version" in value) || typeof value.version !== "number") return void 0;
325
+ if (!("index" in value) || !isPlainIndex(value.index)) return void 0;
326
+ const terms = "terms" in value && typeof value.terms === "string" ? value.terms : void 0;
327
+ return {
328
+ version: value.version,
329
+ ...terms && { terms },
330
+ index: value.index
331
+ };
332
+ }
333
+ function isPlainIndex(value) {
334
+ return typeof value === "object" && value !== null && "documentCount" in value && typeof value.documentCount === "number" && "index" in value && Array.isArray(value.index) && "serializationVersion" in value && typeof value.serializationVersion === "number";
335
+ }
336
+ const prebuiltIndexes = /* @__PURE__ */ new WeakMap();
337
+ /** Lets createTableIndex load this prebuilt index instead of building one for these docs. */
338
+ function attachSearchIndex(docs, prebuilt) {
339
+ prebuiltIndexes.set(docs, prebuilt);
340
+ }
341
+ function miniSearchOptions(lang) {
342
+ const stopWords = new Set(STOP_WORDS[LANGUAGE_FAMILY[lang] ?? lang] ?? []);
343
+ return {
344
+ idField: "id",
345
+ fields: ["title", "path"],
346
+ extractField,
347
+ processTerm: (term) => {
348
+ const value = normalize(term, lang);
349
+ return value.length < MIN_TERM_LENGTH || stopWords.has(value) ? null : value;
350
+ }
351
+ };
352
+ }
353
+ const TERM_PROBE = "Ætt Øl Ål Ää Öö Üü Ññ Çç Šš Žž Čč Ćć Đđ Łł Ðð Þþ ß IJ ı İ Ş Ţ Ș Ț Ё Ђ Ѓ Ќ ќ 2026 1,5 e-mail";
354
+ function termFingerprint(lang) {
355
+ const { processTerm } = miniSearchOptions(lang);
356
+ const stopWords = STOP_WORDS[LANGUAGE_FAMILY[lang] ?? lang] ?? [];
357
+ return [
358
+ ...TERM_PROBE.split(" ").map((term) => processTerm(term) ?? "-"),
359
+ "|",
360
+ ...stopWords
361
+ ].join(" ");
362
+ }
363
+ function uniqueDocs(docs) {
364
+ return [...new Map(docs.map((doc) => [doc.id, doc])).values()];
365
+ }
366
+ /** Builds the search index of a table list, to store with the list. */
367
+ function buildSearchIndex(docs, lang) {
368
+ const index = new MiniSearch(miniSearchOptions(lang));
369
+ index.addAll(uniqueDocs(docs));
370
+ return {
371
+ version: 1,
372
+ terms: termFingerprint(lang),
373
+ index: index.toJSON()
374
+ };
375
+ }
376
+ function loadIndex(docs, unique, lang, options) {
377
+ const prebuilt = prebuiltIndexes.get(docs);
378
+ prebuiltIndexes.delete(docs);
379
+ if (prebuilt?.version === 1 && prebuilt.terms === termFingerprint(lang)) try {
380
+ const loaded = MiniSearch.loadJS(prebuilt.index, options);
381
+ if (loaded.documentCount === unique.length) return loaded;
382
+ } catch {}
383
+ const index = new MiniSearch(options);
384
+ index.addAll(unique);
385
+ return index;
386
+ }
387
+ /**
388
+ * Keyword search over a source's table catalogue, for APIs whose own search is
389
+ * missing, broken or weak. It fuses two rankings: BM25 over titles (three times)
390
+ * and subject folders, and word-start matches in the office's own catalogue order,
391
+ * where offices list their main tables first.
392
+ */
393
+ function createTableIndex(docs, lang, options = {}) {
394
+ const currentYear = options.currentYear ?? (/* @__PURE__ */ new Date()).getUTCFullYear();
395
+ const indexOptions = miniSearchOptions(lang);
396
+ const processTerm = indexOptions.processTerm;
397
+ const byId = new Map(docs.map((doc) => [doc.id, doc]));
398
+ const byNormalizedId = uniqueBy(docs, (doc) => normalize(doc.id, lang));
399
+ const byFileName = uniqueFileNames(docs, lang);
400
+ const factor = new Map(docs.map((doc) => {
401
+ const closed = doc.discontinued || isHistorical(doc.title, currentYear);
402
+ const current = hasCurrentData(doc.lastPeriod, currentYear);
403
+ const boost = (closed ? CLOSED_FACTOR : 1) * (1 + RECENCY_WEIGHT * recency(doc.updated, currentYear)) * (current ? 1.3 : 1);
404
+ return [doc.id, boost];
405
+ }));
406
+ const index = loadIndex(docs, [...byId.values()], lang, indexOptions);
407
+ const base = {
408
+ boost: FIELD_BOOST,
409
+ prefix: (term) => term.length >= PREFIX_MIN_LENGTH,
410
+ boostDocument: (id) => factor.get(id) ?? 1,
411
+ bm25: {
412
+ k: 1.2,
413
+ b: LENGTH_NORMALIZATION,
414
+ d: .5
415
+ }
416
+ };
417
+ const hits = [...byId.values()].map(toHit);
418
+ return {
419
+ size: byId.size,
420
+ search(query, searchOptions = {}) {
421
+ const wanted = normalize(query.trim(), lang);
422
+ const exact = byId.get(query.trim()) ?? byNormalizedId.get(wanted) ?? byFileName.get(wanted.replace(PX_FILE, ""));
423
+ let ids = [...index.search(query, {
424
+ ...base,
425
+ combineWith: "AND"
426
+ }), ...index.search(query, {
427
+ ...base,
428
+ combineWith: "OR"
429
+ })].map((result) => String(result.id));
430
+ if (ids.length === 0) ids = index.search(query, {
431
+ ...base,
432
+ combineWith: "OR",
433
+ fuzzy: (term) => term.length >= FUZZY_MIN_LENGTH ? FUZZY_DISTANCE : false
434
+ }).map((result) => String(result.id));
435
+ const visible = (id) => searchOptions.includeArchived || !byId.get(id)?.discontinued;
436
+ const bm25 = [...new Set(ids)].filter(visible);
437
+ const keywords = query.split(/[^\p{L}\p{N}]+/u).filter((term) => processTerm(term) !== null).join(" ");
438
+ const fused = fuseRankings([bm25, rankSearchHits(searchTitles(hits, keywords, lang), currentYear).map((hit) => hit.tableId).filter(visible)], FUSION_K);
439
+ return [.../* @__PURE__ */ new Set([...exact ? [exact.id] : [], ...fused])].map((id) => byId.get(id)).filter((doc) => doc !== void 0).map(toHit);
440
+ }
441
+ };
442
+ }
443
+ /** Loads the crawled list when it has tables, else the live list. */
444
+ function preferCrawled(load, crawled) {
445
+ if (!crawled) return load;
446
+ return async (lang) => {
447
+ const docs = await crawled(lang).catch(() => void 0);
448
+ return docs && docs.length > 0 ? docs : load(lang);
449
+ };
450
+ }
451
+ const DEFAULT_RETRY_SECONDS = 300;
452
+ const PENDING_TIMEOUT_MS = 3e4;
453
+ /**
454
+ * Keeps one built index per language. Parallel searches share a build, an index
455
+ * is rebuilt after `ttlSeconds`, and a failed refresh keeps serving the old one.
456
+ */
457
+ function createTableIndexLoader(load, options) {
458
+ const built = /* @__PURE__ */ new Map();
459
+ const loading = /* @__PURE__ */ new Map();
460
+ const ttlMs = options.ttlSeconds * 1e3;
461
+ const retryMs = (options.retrySeconds ?? DEFAULT_RETRY_SECONDS) * 1e3;
462
+ const build = (docs, lang) => createTableIndex(docs, lang, { currentYear: options.currentYear?.() ?? (/* @__PURE__ */ new Date()).getUTCFullYear() });
463
+ async function fallbackIndex(lang) {
464
+ try {
465
+ const docs = await options.fallback?.(lang);
466
+ return docs && docs.length > 0 ? build(docs, lang) : void 0;
467
+ } catch {
468
+ return;
469
+ }
470
+ }
471
+ function start(lang) {
472
+ const current = built.get(lang);
473
+ const isCurrent = () => loading.get(lang)?.promise === promise;
474
+ const promise = load(lang).then((docs) => {
475
+ const index = build(docs, lang);
476
+ if (isCurrent()) built.set(lang, {
477
+ at: Date.now(),
478
+ index
479
+ });
480
+ return index;
481
+ }).catch(async (err) => {
482
+ const index = current?.index ?? await fallbackIndex(lang);
483
+ if (!index) throw err;
484
+ if (isCurrent()) built.set(lang, {
485
+ at: Date.now() - ttlMs + retryMs,
486
+ index
487
+ });
488
+ return index;
489
+ }).finally(() => {
490
+ if (isCurrent()) loading.delete(lang);
491
+ });
492
+ loading.set(lang, {
493
+ at: Date.now(),
494
+ promise
495
+ });
496
+ return promise;
497
+ }
498
+ return (lang) => {
499
+ const current = built.get(lang);
500
+ if (current && Date.now() - current.at < ttlMs) return Promise.resolve(current.index);
501
+ const pending = loading.get(lang);
502
+ if (!pending || Date.now() - pending.at > PENDING_TIMEOUT_MS) return start(lang);
503
+ return pending.promise.catch((err) => {
504
+ const now = loading.get(lang);
505
+ if (now && now !== pending) return now.promise;
506
+ if (!now) {
507
+ const fresh = built.get(lang);
508
+ if (fresh && fresh !== current) return fresh.index;
509
+ throw err;
510
+ }
511
+ loading.delete(lang);
512
+ return start(lang);
513
+ });
514
+ };
515
+ }
516
+ // src/table-doc.ts
517
+ /** One table in a source's catalogue, as the index and the snapshots store it. */
518
+ const tableDocSchema = z.object({
519
+ id: z.string().min(1),
520
+ title: z.string(),
521
+ /** Subject folders from the top, for example ["Economy", "Prices"]. */
522
+ path: z.array(z.string()).readonly().optional(),
523
+ /** ISO date of the last data update. */
524
+ updated: z.string().optional(),
525
+ /** Last period with data, for example "2026M09", "2026-Q3" or "2025". */
526
+ lastPeriod: z.string().optional(),
527
+ discontinued: z.boolean().optional()
528
+ });
529
+ // src/snapshot.ts
530
+ /** Format version of a table snapshot; readers reject other versions. */
531
+ const SNAPSHOT_VERSION = 1;
532
+ const MAX_SNAPSHOT_BYTES = 20971520;
533
+ const DEFAULT_TIMEOUT_MS = 15e3;
534
+ const KEY_PART = /^[A-Za-z0-9_-]+$/;
535
+ const GZIP_MAGIC = [31, 139];
536
+ const snapshotSchema = z.object({
537
+ version: z.literal(1),
538
+ source: z.string().min(1),
539
+ lang: z.string().min(1),
540
+ builtAt: z.iso.datetime(),
541
+ count: z.number().int().nonnegative(),
542
+ docs: z.array(tableDocSchema),
543
+ searchIndex: z.unknown().optional()
544
+ }).refine((snapshot) => snapshot.count === snapshot.docs.length, { message: "count does not match the number of tables" });
545
+ /** Object key and URL path of a snapshot: `index/<source>/<lang>.json.gz`. */
546
+ function snapshotKey(source, lang) {
547
+ if (!KEY_PART.test(source) || !KEY_PART.test(lang)) throw new Error(`Invalid snapshot source "${source}" or language "${lang}".`);
548
+ return `index/${source}/${lang}.json.gz`;
549
+ }
550
+ async function readBytes(stream) {
551
+ const reader = stream.getReader();
552
+ const chunks = [];
553
+ let size = 0;
554
+ for (;;) {
555
+ const { done, value } = await reader.read();
556
+ if (done) break;
557
+ size += value.byteLength;
558
+ if (size > MAX_SNAPSHOT_BYTES) {
559
+ await reader.cancel();
560
+ throw new Error("Snapshot is too large.");
561
+ }
562
+ chunks.push(value);
563
+ }
564
+ const bytes = new Uint8Array(size);
565
+ let offset = 0;
566
+ for (const chunk of chunks) {
567
+ bytes.set(chunk, offset);
568
+ offset += chunk.byteLength;
569
+ }
570
+ return bytes;
571
+ }
572
+ /**
573
+ * Reads gzip or plain JSON: hosts that send `Content-Encoding: gzip` let fetch
574
+ * decompress the body already. Both sizes are capped.
575
+ */
576
+ async function readSnapshotText(stream) {
577
+ const raw = await readBytes(stream);
578
+ const text = raw[0] === GZIP_MAGIC[0] && raw[1] === GZIP_MAGIC[1] ? await readBytes(new Blob([raw]).stream().pipeThrough(new DecompressionStream("gzip"))) : raw;
579
+ return new TextDecoder().decode(text);
580
+ }
581
+ /** Decompresses and validates a gzip snapshot for the expected source and language. */
582
+ async function readSnapshot(body, source, lang) {
583
+ const snapshot = snapshotSchema.parse(JSON.parse(await readSnapshotText(body)));
584
+ if (snapshot.source !== source || snapshot.lang !== lang) throw new Error(`Snapshot is for ${snapshot.source}/${snapshot.lang}, not ${source}/${lang}.`);
585
+ const searchIndex = asPrebuiltIndex(snapshot.searchIndex);
586
+ if (searchIndex) attachSearchIndex(snapshot.docs, searchIndex);
587
+ return snapshot;
588
+ }
589
+ /** Serialises and gzips a snapshot, for the crawler and for bundling. */
590
+ async function writeSnapshot(snapshot) {
591
+ const stream = new Blob([JSON.stringify(snapshotSchema.parse(snapshot))]).stream().pipeThrough(new CompressionStream("gzip"));
592
+ return new Uint8Array(await new Response(stream).arrayBuffer());
593
+ }
594
+ /** Reads snapshots over HTTP(S), for example from https://statsmcp.dev. */
595
+ function urlSnapshotReader(baseUrl, options = {}) {
596
+ const root = baseUrl.replace(/\/+$/, "");
597
+ const doFetch = options.fetch ?? fetch;
598
+ return async (source, lang) => {
599
+ const response = await doFetch(`${root}/${snapshotKey(source, lang)}`, {
600
+ headers: options.userAgent ? { "user-agent": options.userAgent } : {},
601
+ signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS)
602
+ });
603
+ if (response.status === 404) {
604
+ await response.body?.cancel();
605
+ return;
606
+ }
607
+ if (!response.ok || !response.body) {
608
+ await response.body?.cancel();
609
+ throw new Error(`Snapshot request returned HTTP ${response.status}.`);
610
+ }
611
+ return readSnapshot(response.body, source, lang);
612
+ };
613
+ }
614
+ /** Reads snapshots from an R2 bucket binding in the Worker. */
615
+ function bucketSnapshotReader(bucket) {
616
+ return async (source, lang) => {
617
+ const object = await bucket.get(snapshotKey(source, lang));
618
+ return object ? readSnapshot(object.body, source, lang) : void 0;
619
+ };
620
+ }
621
+ /**
622
+ * Tries the readers in order and returns the first snapshot found. A reader that
623
+ * fails counts as "no snapshot", so a broken mirror falls through to the next one.
624
+ */
625
+ function firstSnapshot(readers, options = {}) {
626
+ return async (source, lang) => {
627
+ for (const [position, read] of readers.entries()) try {
628
+ const snapshot = await read(source, lang);
629
+ if (snapshot) return snapshot;
630
+ } catch (err) {
631
+ options.onError?.(err, position);
632
+ }
633
+ };
634
+ }
635
+ export { startsWord as _, snapshotKey as a, tableDocSchema as c, buildSearchIndex as d, createTableIndex as f, normalize as g, searchTitles as h, readSnapshot as i, SEARCH_INDEX_VERSION as l, preferCrawled as m, bucketSnapshotReader as n, urlSnapshotReader as o, createTableIndexLoader as p, firstSnapshot as r, writeSnapshot as s, SNAPSHOT_VERSION as t, asPrebuiltIndex as u, rankSearchHits as v };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@statsmcp/core",
3
- "version": "0.4.1",
3
+ "version": "0.6.0",
4
4
  "description": "MCP server toolkit for statistics APIs: PxWeb v1 and v2, StatBank Denmark, CBS OData, PxStat, SDMX, Eurostat, Statistics Canada and SingStat",
5
5
  "license": "MIT",
6
6
  "author": "Tadej Polajnar",
@@ -48,8 +48,8 @@
48
48
  },
49
49
  "devDependencies": {
50
50
  "@modelcontextprotocol/server": "^2.4.0",
51
- "@types/node": "26.6.5",
52
- "tsdown": "0.23.2",
51
+ "@types/node": "26.6.6",
52
+ "tsdown": "0.23.4",
53
53
  "typescript": "7.0.2",
54
54
  "vitest": "5.0.5"
55
55
  },