@statsmcp/core 0.4.0 → 0.5.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.
@@ -1,118 +0,0 @@
1
- import { z } from "zod";
2
- // src/table-doc.ts
3
- /** One table in a source's catalogue, as the index and the snapshots store it. */
4
- const tableDocSchema = z.object({
5
- id: z.string().min(1),
6
- title: z.string(),
7
- /** Subject folders from the top, for example ["Economy", "Prices"]. */
8
- path: z.array(z.string()).readonly().optional(),
9
- /** ISO date of the last data update. */
10
- updated: z.string().optional(),
11
- /** Last period with data, for example "2026M09", "2026-Q3" or "2025". */
12
- lastPeriod: z.string().optional(),
13
- discontinued: z.boolean().optional()
14
- });
15
- // src/snapshot.ts
16
- /** Format version of a table snapshot; readers reject other versions. */
17
- const SNAPSHOT_VERSION = 1;
18
- const MAX_SNAPSHOT_BYTES = 20971520;
19
- const DEFAULT_TIMEOUT_MS = 15e3;
20
- const KEY_PART = /^[A-Za-z0-9_-]+$/;
21
- const GZIP_MAGIC = [31, 139];
22
- const snapshotSchema = z.object({
23
- version: z.literal(1),
24
- source: z.string().min(1),
25
- lang: z.string().min(1),
26
- builtAt: z.iso.datetime(),
27
- count: z.number().int().nonnegative(),
28
- docs: z.array(tableDocSchema)
29
- }).refine((snapshot) => snapshot.count === snapshot.docs.length, { message: "count does not match the number of tables" });
30
- /** Object key and URL path of a snapshot: `index/<source>/<lang>.json.gz`. */
31
- function snapshotKey(source, lang) {
32
- if (!KEY_PART.test(source) || !KEY_PART.test(lang)) throw new Error(`Invalid snapshot source "${source}" or language "${lang}".`);
33
- return `index/${source}/${lang}.json.gz`;
34
- }
35
- async function readBytes(stream) {
36
- const reader = stream.getReader();
37
- const chunks = [];
38
- let size = 0;
39
- for (;;) {
40
- const { done, value } = await reader.read();
41
- if (done) break;
42
- size += value.byteLength;
43
- if (size > MAX_SNAPSHOT_BYTES) {
44
- await reader.cancel();
45
- throw new Error("Snapshot is too large.");
46
- }
47
- chunks.push(value);
48
- }
49
- const bytes = new Uint8Array(size);
50
- let offset = 0;
51
- for (const chunk of chunks) {
52
- bytes.set(chunk, offset);
53
- offset += chunk.byteLength;
54
- }
55
- return bytes;
56
- }
57
- /**
58
- * Reads gzip or plain JSON: hosts that send `Content-Encoding: gzip` let fetch
59
- * decompress the body already. Both sizes are capped.
60
- */
61
- async function readSnapshotText(stream) {
62
- const raw = await readBytes(stream);
63
- const text = raw[0] === GZIP_MAGIC[0] && raw[1] === GZIP_MAGIC[1] ? await readBytes(new Blob([raw]).stream().pipeThrough(new DecompressionStream("gzip"))) : raw;
64
- return new TextDecoder().decode(text);
65
- }
66
- /** Decompresses and validates a gzip snapshot for the expected source and language. */
67
- async function readSnapshot(body, source, lang) {
68
- const snapshot = snapshotSchema.parse(JSON.parse(await readSnapshotText(body)));
69
- if (snapshot.source !== source || snapshot.lang !== lang) throw new Error(`Snapshot is for ${snapshot.source}/${snapshot.lang}, not ${source}/${lang}.`);
70
- return snapshot;
71
- }
72
- /** Serialises and gzips a snapshot, for the crawler and for bundling. */
73
- async function writeSnapshot(snapshot) {
74
- const stream = new Blob([JSON.stringify(snapshotSchema.parse(snapshot))]).stream().pipeThrough(new CompressionStream("gzip"));
75
- return new Uint8Array(await new Response(stream).arrayBuffer());
76
- }
77
- /** Reads snapshots over HTTP(S), for example from https://statsmcp.dev. */
78
- function urlSnapshotReader(baseUrl, options = {}) {
79
- const root = baseUrl.replace(/\/+$/, "");
80
- const doFetch = options.fetch ?? fetch;
81
- return async (source, lang) => {
82
- const response = await doFetch(`${root}/${snapshotKey(source, lang)}`, {
83
- headers: options.userAgent ? { "user-agent": options.userAgent } : {},
84
- signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS)
85
- });
86
- if (response.status === 404) {
87
- await response.body?.cancel();
88
- return;
89
- }
90
- if (!response.ok || !response.body) {
91
- await response.body?.cancel();
92
- throw new Error(`Snapshot request returned HTTP ${response.status}.`);
93
- }
94
- return readSnapshot(response.body, source, lang);
95
- };
96
- }
97
- /** Reads snapshots from an R2 bucket binding in the Worker. */
98
- function bucketSnapshotReader(bucket) {
99
- return async (source, lang) => {
100
- const object = await bucket.get(snapshotKey(source, lang));
101
- return object ? readSnapshot(object.body, source, lang) : void 0;
102
- };
103
- }
104
- /**
105
- * Tries the readers in order and returns the first snapshot found. A reader that
106
- * fails counts as "no snapshot", so a broken mirror falls through to the next one.
107
- */
108
- function firstSnapshot(readers, options = {}) {
109
- return async (source, lang) => {
110
- for (const [position, read] of readers.entries()) try {
111
- const snapshot = await read(source, lang);
112
- if (snapshot) return snapshot;
113
- } catch (err) {
114
- options.onError?.(err, position);
115
- }
116
- };
117
- }
118
- export { snapshotKey as a, tableDocSchema as c, readSnapshot as i, bucketSnapshotReader as n, urlSnapshotReader as o, firstSnapshot as r, writeSnapshot as s, SNAPSHOT_VERSION as t };