@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.
- package/dist/index.d.ts +227 -5
- package/dist/index.js +2963 -532
- package/dist/node.d.ts +1 -1
- package/dist/node.js +1 -1
- package/dist/{snapshot-DwtIVsqx.d.ts → snapshot-BCJSa_1e.d.ts} +1 -0
- package/dist/snapshot-BqwC4tjq.js +594 -0
- package/package.json +4 -4
- package/dist/snapshot-CT_ItdeR.js +0 -118
package/dist/index.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { a as snapshotKey, c as tableDocSchema, i as readSnapshot, n as bucketSnapshotReader, o as urlSnapshotReader, r as firstSnapshot, s as writeSnapshot, t as SNAPSHOT_VERSION } from "./snapshot-
|
|
1
|
+
import { _ as startsWord, a as snapshotKey, c as tableDocSchema, d as buildSearchIndex, f as createTableIndex, g as normalize, h as searchTitles, i as readSnapshot, l as SEARCH_INDEX_VERSION, m as preferCrawled, n as bucketSnapshotReader, o as urlSnapshotReader, p as createTableIndexLoader, r as firstSnapshot, s as writeSnapshot, t as SNAPSHOT_VERSION, u as asPrebuiltIndex, v as rankSearchHits } from "./snapshot-BqwC4tjq.js";
|
|
2
2
|
import { McpServer } from "@modelcontextprotocol/server";
|
|
3
3
|
import { z } from "zod";
|
|
4
|
-
import MiniSearch from "minisearch";
|
|
5
4
|
// src/cache.ts
|
|
6
5
|
const DEFAULT_MAX_ENTRIES = 500;
|
|
7
6
|
const DEFAULT_MAX_CHARS = 8388608;
|
|
@@ -44,7 +43,7 @@ function createMemoryCache(options = {}) {
|
|
|
44
43
|
};
|
|
45
44
|
}
|
|
46
45
|
// src/json-stat.ts
|
|
47
|
-
const categorySchema$
|
|
46
|
+
const categorySchema$2 = z.object({
|
|
48
47
|
index: z.union([z.record(z.string(), z.number()), z.array(z.string())]),
|
|
49
48
|
label: z.record(z.string(), z.string()).optional()
|
|
50
49
|
});
|
|
@@ -56,7 +55,7 @@ const jsonStatDatasetSchema = z.object({
|
|
|
56
55
|
size: z.array(z.number()),
|
|
57
56
|
dimension: z.record(z.string(), z.object({
|
|
58
57
|
label: z.string().optional(),
|
|
59
|
-
category: categorySchema$
|
|
58
|
+
category: categorySchema$2
|
|
60
59
|
})),
|
|
61
60
|
value: z.union([z.array(z.number().nullable()), z.record(z.string(), z.number().nullable())])
|
|
62
61
|
});
|
|
@@ -110,7 +109,7 @@ const SEARCH_TTL_SECONDS = 3600;
|
|
|
110
109
|
const METADATA_TTL_SECONDS = 86400;
|
|
111
110
|
const DATA_TTL_SECONDS = 3600;
|
|
112
111
|
const ERROR_BODY_MAX_CHARS = 300;
|
|
113
|
-
const DEFAULT_TIMEOUT_MS = 3e4;
|
|
112
|
+
const DEFAULT_TIMEOUT_MS$1 = 3e4;
|
|
114
113
|
const MAX_RESPONSE_BYTES = 20971520;
|
|
115
114
|
var PxwebError = class extends Error {
|
|
116
115
|
status;
|
|
@@ -120,7 +119,7 @@ var PxwebError = class extends Error {
|
|
|
120
119
|
this.name = "PxwebError";
|
|
121
120
|
}
|
|
122
121
|
};
|
|
123
|
-
async function readCappedText(response) {
|
|
122
|
+
async function readCappedText(response, maxBytes = MAX_RESPONSE_BYTES) {
|
|
124
123
|
if (!response.body) return "";
|
|
125
124
|
const reader = response.body.getReader();
|
|
126
125
|
const decoder = new TextDecoder();
|
|
@@ -131,7 +130,7 @@ async function readCappedText(response) {
|
|
|
131
130
|
const { done, value } = await reader.read();
|
|
132
131
|
if (done) break;
|
|
133
132
|
size += value.byteLength;
|
|
134
|
-
if (size >
|
|
133
|
+
if (size > maxBytes) {
|
|
135
134
|
await reader.cancel().catch(() => void 0);
|
|
136
135
|
throw new PxwebError("PxWeb response is too large.", 502);
|
|
137
136
|
}
|
|
@@ -143,7 +142,7 @@ async function readCappedText(response) {
|
|
|
143
142
|
}
|
|
144
143
|
return text + decoder.decode();
|
|
145
144
|
}
|
|
146
|
-
function toFlatTable$
|
|
145
|
+
function toFlatTable$2(dataset) {
|
|
147
146
|
try {
|
|
148
147
|
return flattenJsonStat(dataset);
|
|
149
148
|
} catch {
|
|
@@ -163,7 +162,7 @@ function parseBody(body, schema) {
|
|
|
163
162
|
}
|
|
164
163
|
function createFetcher(options) {
|
|
165
164
|
const doFetch = options.fetch ?? fetch;
|
|
166
|
-
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
165
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS$1;
|
|
167
166
|
const headers = { accept: "application/json" };
|
|
168
167
|
if (options.userAgent) headers["user-agent"] = options.userAgent;
|
|
169
168
|
async function fetchBody(url, init) {
|
|
@@ -214,392 +213,8 @@ function createTextRequester(options) {
|
|
|
214
213
|
return result;
|
|
215
214
|
};
|
|
216
215
|
}
|
|
217
|
-
// src/search-ranking.ts
|
|
218
|
-
const CLOSED_RANGE = /(\d{4})(?:[MQH]\d{1,2})?\s*-\s*(\d{4})(?:[MQH]\d{1,2})?\s*$/;
|
|
219
|
-
const CLOSED_SERIES = /closed series|avslutta serie|avsluttet serie/i;
|
|
220
|
-
const HISTORICAL_PENALTY = 1;
|
|
221
|
-
const RECENCY_WEIGHT$1 = .15;
|
|
222
|
-
const RECENCY_YEARS$1 = 4;
|
|
223
|
-
const POSITION_COST = .03;
|
|
224
|
-
function isHistorical(title, currentYear) {
|
|
225
|
-
if (CLOSED_SERIES.test(title)) return true;
|
|
226
|
-
const match = CLOSED_RANGE.exec(title);
|
|
227
|
-
return match !== null && Number(match[2]) < currentYear - 1;
|
|
228
|
-
}
|
|
229
|
-
function recency$1(published, currentYear) {
|
|
230
|
-
const year = Number(published?.slice(0, 4));
|
|
231
|
-
if (!Number.isFinite(year)) return 0;
|
|
232
|
-
const age = currentYear - year;
|
|
233
|
-
return Math.max(0, Math.min(1, (RECENCY_YEARS$1 - age) / RECENCY_YEARS$1));
|
|
234
|
-
}
|
|
235
|
-
/** The API's relevance order stays the base score; age and closed ranges adjust it. */
|
|
236
|
-
function rankSearchHits(hits, currentYear) {
|
|
237
|
-
return hits.map((hit, index) => {
|
|
238
|
-
let score = -index * POSITION_COST;
|
|
239
|
-
if (hit.archived || isHistorical(hit.title, currentYear)) score -= HISTORICAL_PENALTY;
|
|
240
|
-
score += RECENCY_WEIGHT$1 * recency$1(hit.published, currentYear);
|
|
241
|
-
return {
|
|
242
|
-
hit,
|
|
243
|
-
score,
|
|
244
|
-
index
|
|
245
|
-
};
|
|
246
|
-
}).toSorted((a, b) => b.score - a.score || a.index - b.index).map((entry) => entry.hit);
|
|
247
|
-
}
|
|
248
|
-
// src/text.ts
|
|
249
|
-
/** Letters that Unicode does not decompose into a base letter and a mark. */
|
|
250
|
-
const FOLDED_LETTERS = {
|
|
251
|
-
ø: "o",
|
|
252
|
-
æ: "ae",
|
|
253
|
-
œ: "oe",
|
|
254
|
-
ß: "ss",
|
|
255
|
-
đ: "d",
|
|
256
|
-
ð: "d",
|
|
257
|
-
ł: "l",
|
|
258
|
-
þ: "th"
|
|
259
|
-
};
|
|
260
|
-
/** Lower case without diacritics, so "Plača" matches "placa" and "Købekraft" matches "kobekraft". */
|
|
261
|
-
function normalize(text, lang) {
|
|
262
|
-
return text.toLocaleLowerCase(lang).normalize("NFD").replace(/\p{M}/gu, "").replace(/[øæœßđðłþ]/gu, (letter) => FOLDED_LETTERS[letter] ?? letter);
|
|
263
|
-
}
|
|
264
|
-
/** True when `term` starts a word in `text`, so "price" matches "prices" but "wage" does not match "sewage". */
|
|
265
|
-
function startsWord(text, term) {
|
|
266
|
-
let index = text.indexOf(term);
|
|
267
|
-
while (index >= 0) {
|
|
268
|
-
if (!/\p{L}/u.test(text[index - 1] ?? " ")) return true;
|
|
269
|
-
index = text.indexOf(term, index + 1);
|
|
270
|
-
}
|
|
271
|
-
return false;
|
|
272
|
-
}
|
|
273
|
-
// src/title-search.ts
|
|
274
|
-
const MIN_TERM_LENGTH$1 = 2;
|
|
275
|
-
function termsOf(query, lang) {
|
|
276
|
-
return [...new Set(normalize(query, lang).split(/[^\p{L}\p{N}]+/u).filter((term) => term.length >= MIN_TERM_LENGTH$1))];
|
|
277
|
-
}
|
|
278
|
-
/**
|
|
279
|
-
* Keyword search over a local list of tables, for APIs without a working search.
|
|
280
|
-
* A table matches when at least half of the query words start a word in its title
|
|
281
|
-
* or equal its id, so a short word such as "for" alone does not match every table.
|
|
282
|
-
* Tables that match more words come first; ties keep the list order.
|
|
283
|
-
*/
|
|
284
|
-
function searchTitles(tables, query, lang) {
|
|
285
|
-
const terms = termsOf(query, lang);
|
|
286
|
-
if (terms.length === 0) return [];
|
|
287
|
-
const needed = Math.ceil(terms.length / 2);
|
|
288
|
-
return tables.map((table, index) => {
|
|
289
|
-
const title = normalize(table.title, lang);
|
|
290
|
-
const id = normalize(table.tableId, lang);
|
|
291
|
-
return {
|
|
292
|
-
table,
|
|
293
|
-
matches: terms.filter((term) => id === term || startsWord(title, term)).length,
|
|
294
|
-
index
|
|
295
|
-
};
|
|
296
|
-
}).filter((entry) => entry.matches >= needed).toSorted((a, b) => b.matches - a.matches || a.index - b.index).map((entry) => entry.table);
|
|
297
|
-
}
|
|
298
|
-
// src/table-index.ts
|
|
299
|
-
/** Norwegian written standards share one stop-word list. */
|
|
300
|
-
const LANGUAGE_FAMILY = {
|
|
301
|
-
nb: "no",
|
|
302
|
-
nn: "no"
|
|
303
|
-
};
|
|
304
|
-
const FIELD_BOOST = {
|
|
305
|
-
title: 3,
|
|
306
|
-
path: 1
|
|
307
|
-
};
|
|
308
|
-
const PREFIX_MIN_LENGTH = 4;
|
|
309
|
-
const FUZZY_MIN_LENGTH = 6;
|
|
310
|
-
const FUZZY_DISTANCE = .2;
|
|
311
|
-
const MIN_TERM_LENGTH = 2;
|
|
312
|
-
const RECENCY_WEIGHT = .15;
|
|
313
|
-
const RECENCY_YEARS = 4;
|
|
314
|
-
const CLOSED_FACTOR = .5;
|
|
315
|
-
/** BM25 length normalisation; the MiniSearch default, kept after the golden-set evaluation. */
|
|
316
|
-
const LENGTH_NORMALIZATION = .75;
|
|
317
|
-
/** Rank constant of reciprocal rank fusion; small values trust the top ranks more. */
|
|
318
|
-
const FUSION_K = 10;
|
|
319
|
-
/** Function words of two or more letters (shorter words are never indexed). */
|
|
320
|
-
const STOP_WORDS = {
|
|
321
|
-
en: [
|
|
322
|
-
"an",
|
|
323
|
-
"and",
|
|
324
|
-
"at",
|
|
325
|
-
"by",
|
|
326
|
-
"for",
|
|
327
|
-
"from",
|
|
328
|
-
"in",
|
|
329
|
-
"of",
|
|
330
|
-
"on",
|
|
331
|
-
"or",
|
|
332
|
-
"per",
|
|
333
|
-
"the",
|
|
334
|
-
"to",
|
|
335
|
-
"with"
|
|
336
|
-
],
|
|
337
|
-
da: [
|
|
338
|
-
"af",
|
|
339
|
-
"den",
|
|
340
|
-
"det",
|
|
341
|
-
"efter",
|
|
342
|
-
"for",
|
|
343
|
-
"fordelt",
|
|
344
|
-
"med",
|
|
345
|
-
"og",
|
|
346
|
-
"pa",
|
|
347
|
-
"til"
|
|
348
|
-
],
|
|
349
|
-
de: [
|
|
350
|
-
"das",
|
|
351
|
-
"der",
|
|
352
|
-
"die",
|
|
353
|
-
"fur",
|
|
354
|
-
"im",
|
|
355
|
-
"in",
|
|
356
|
-
"je",
|
|
357
|
-
"mit",
|
|
358
|
-
"nach",
|
|
359
|
-
"und",
|
|
360
|
-
"von"
|
|
361
|
-
],
|
|
362
|
-
et: ["ja", "ning"],
|
|
363
|
-
fi: ["ja"],
|
|
364
|
-
fo: ["og"],
|
|
365
|
-
hr: [
|
|
366
|
-
"do",
|
|
367
|
-
"i",
|
|
368
|
-
"iz",
|
|
369
|
-
"ili",
|
|
370
|
-
"na",
|
|
371
|
-
"od",
|
|
372
|
-
"po",
|
|
373
|
-
"prema",
|
|
374
|
-
"sa",
|
|
375
|
-
"te",
|
|
376
|
-
"za"
|
|
377
|
-
],
|
|
378
|
-
is: [
|
|
379
|
-
"af",
|
|
380
|
-
"eftir",
|
|
381
|
-
"fra",
|
|
382
|
-
"med",
|
|
383
|
-
"og",
|
|
384
|
-
"til",
|
|
385
|
-
"um",
|
|
386
|
-
"vid"
|
|
387
|
-
],
|
|
388
|
-
fr: [
|
|
389
|
-
"au",
|
|
390
|
-
"aux",
|
|
391
|
-
"de",
|
|
392
|
-
"des",
|
|
393
|
-
"du",
|
|
394
|
-
"en",
|
|
395
|
-
"et",
|
|
396
|
-
"la",
|
|
397
|
-
"le",
|
|
398
|
-
"les",
|
|
399
|
-
"par",
|
|
400
|
-
"pour",
|
|
401
|
-
"un",
|
|
402
|
-
"une"
|
|
403
|
-
],
|
|
404
|
-
nl: [
|
|
405
|
-
"de",
|
|
406
|
-
"een",
|
|
407
|
-
"en",
|
|
408
|
-
"het",
|
|
409
|
-
"in",
|
|
410
|
-
"met",
|
|
411
|
-
"naar",
|
|
412
|
-
"op",
|
|
413
|
-
"per",
|
|
414
|
-
"van",
|
|
415
|
-
"voor"
|
|
416
|
-
],
|
|
417
|
-
no: [
|
|
418
|
-
"av",
|
|
419
|
-
"etter",
|
|
420
|
-
"for",
|
|
421
|
-
"med",
|
|
422
|
-
"og",
|
|
423
|
-
"pa",
|
|
424
|
-
"til"
|
|
425
|
-
],
|
|
426
|
-
sl: [
|
|
427
|
-
"in",
|
|
428
|
-
"na",
|
|
429
|
-
"po",
|
|
430
|
-
"ter",
|
|
431
|
-
"za"
|
|
432
|
-
],
|
|
433
|
-
sv: [
|
|
434
|
-
"av",
|
|
435
|
-
"efter",
|
|
436
|
-
"for",
|
|
437
|
-
"med",
|
|
438
|
-
"och",
|
|
439
|
-
"pa",
|
|
440
|
-
"till"
|
|
441
|
-
]
|
|
442
|
-
};
|
|
443
|
-
function extractField(doc, field) {
|
|
444
|
-
if (field === "path") return (doc.path ?? []).join(" ");
|
|
445
|
-
if (field === "id") return doc.id;
|
|
446
|
-
return doc.title;
|
|
447
|
-
}
|
|
448
|
-
const PX_FILE = /\.px$/i;
|
|
449
|
-
/** Docs by key, leaving out keys that more than one doc shares. */
|
|
450
|
-
function uniqueBy(docs, key) {
|
|
451
|
-
const byKey = /* @__PURE__ */ new Map();
|
|
452
|
-
for (const doc of docs) {
|
|
453
|
-
const value = key(doc);
|
|
454
|
-
if (value === void 0) continue;
|
|
455
|
-
byKey.set(value, byKey.has(value) ? void 0 : doc);
|
|
456
|
-
}
|
|
457
|
-
return new Map([...byKey].filter((entry) => entry[1] !== void 0));
|
|
458
|
-
}
|
|
459
|
-
/** Path ids ("db/folder/MAN00101.px") also match by a file name that only one table has. */
|
|
460
|
-
function uniqueFileNames(docs, lang) {
|
|
461
|
-
return uniqueBy(docs, (doc) => doc.id.includes("/") ? normalize(doc.id.split("/").at(-1) ?? "", lang).replace(PX_FILE, "") : void 0);
|
|
462
|
-
}
|
|
463
|
-
function recency(updated, currentYear) {
|
|
464
|
-
const year = Number(updated?.slice(0, 4));
|
|
465
|
-
if (!Number.isFinite(year)) return 0;
|
|
466
|
-
return Math.max(0, Math.min(1, (RECENCY_YEARS - (currentYear - year)) / RECENCY_YEARS));
|
|
467
|
-
}
|
|
468
|
-
function toHit(doc) {
|
|
469
|
-
return {
|
|
470
|
-
tableId: doc.id,
|
|
471
|
-
title: doc.title,
|
|
472
|
-
published: doc.updated,
|
|
473
|
-
...doc.discontinued ? { archived: true } : {}
|
|
474
|
-
};
|
|
475
|
-
}
|
|
476
|
-
/**
|
|
477
|
-
* Reciprocal rank fusion (Cormack et al. 2009): each list adds 1 / (k + rank),
|
|
478
|
-
* so a table that ranks well in both lists comes first.
|
|
479
|
-
*/
|
|
480
|
-
function fuseRankings(lists, k) {
|
|
481
|
-
const scores = /* @__PURE__ */ new Map();
|
|
482
|
-
for (const list of lists) list.forEach((id, rank) => {
|
|
483
|
-
scores.set(id, (scores.get(id) ?? 0) + 1 / (k + rank + 1));
|
|
484
|
-
});
|
|
485
|
-
return [...scores.entries()].toSorted((a, b) => b[1] - a[1]).map(([id]) => id);
|
|
486
|
-
}
|
|
487
|
-
/** True when the last period lies in the current or the previous year. */
|
|
488
|
-
function hasCurrentData(lastPeriod, currentYear) {
|
|
489
|
-
const year = Number(/(\d{4})/.exec(lastPeriod ?? "")?.[1]);
|
|
490
|
-
return Number.isFinite(year) && year >= currentYear - 1;
|
|
491
|
-
}
|
|
492
|
-
/**
|
|
493
|
-
* Keyword search over a source's table catalogue, for APIs whose own search is
|
|
494
|
-
* missing, broken or weak. It fuses two rankings: BM25 over titles (three times)
|
|
495
|
-
* and subject folders, and word-start matches in the office's own catalogue order,
|
|
496
|
-
* where offices list their main tables first.
|
|
497
|
-
*/
|
|
498
|
-
function createTableIndex(docs, lang, options = {}) {
|
|
499
|
-
const currentYear = options.currentYear ?? (/* @__PURE__ */ new Date()).getUTCFullYear();
|
|
500
|
-
const stopWords = new Set(STOP_WORDS[LANGUAGE_FAMILY[lang] ?? lang] ?? []);
|
|
501
|
-
const processTerm = (term) => {
|
|
502
|
-
const value = normalize(term, lang);
|
|
503
|
-
return value.length < MIN_TERM_LENGTH || stopWords.has(value) ? null : value;
|
|
504
|
-
};
|
|
505
|
-
const byId = new Map(docs.map((doc) => [doc.id, doc]));
|
|
506
|
-
const byNormalizedId = uniqueBy(docs, (doc) => normalize(doc.id, lang));
|
|
507
|
-
const byFileName = uniqueFileNames(docs, lang);
|
|
508
|
-
const factor = new Map(docs.map((doc) => {
|
|
509
|
-
const closed = doc.discontinued || isHistorical(doc.title, currentYear);
|
|
510
|
-
const current = hasCurrentData(doc.lastPeriod, currentYear);
|
|
511
|
-
const boost = (closed ? CLOSED_FACTOR : 1) * (1 + RECENCY_WEIGHT * recency(doc.updated, currentYear)) * (current ? 1.3 : 1);
|
|
512
|
-
return [doc.id, boost];
|
|
513
|
-
}));
|
|
514
|
-
const index = new MiniSearch({
|
|
515
|
-
idField: "id",
|
|
516
|
-
fields: ["title", "path"],
|
|
517
|
-
extractField,
|
|
518
|
-
processTerm
|
|
519
|
-
});
|
|
520
|
-
index.addAll([...byId.values()]);
|
|
521
|
-
const base = {
|
|
522
|
-
boost: FIELD_BOOST,
|
|
523
|
-
prefix: (term) => term.length >= PREFIX_MIN_LENGTH,
|
|
524
|
-
boostDocument: (id) => factor.get(id) ?? 1,
|
|
525
|
-
bm25: {
|
|
526
|
-
k: 1.2,
|
|
527
|
-
b: LENGTH_NORMALIZATION,
|
|
528
|
-
d: .5
|
|
529
|
-
}
|
|
530
|
-
};
|
|
531
|
-
const hits = [...byId.values()].map(toHit);
|
|
532
|
-
return {
|
|
533
|
-
size: byId.size,
|
|
534
|
-
search(query, searchOptions = {}) {
|
|
535
|
-
const wanted = normalize(query.trim(), lang);
|
|
536
|
-
const exact = byId.get(query.trim()) ?? byNormalizedId.get(wanted) ?? byFileName.get(wanted.replace(PX_FILE, ""));
|
|
537
|
-
let ids = [...index.search(query, {
|
|
538
|
-
...base,
|
|
539
|
-
combineWith: "AND"
|
|
540
|
-
}), ...index.search(query, {
|
|
541
|
-
...base,
|
|
542
|
-
combineWith: "OR"
|
|
543
|
-
})].map((result) => String(result.id));
|
|
544
|
-
if (ids.length === 0) ids = index.search(query, {
|
|
545
|
-
...base,
|
|
546
|
-
combineWith: "OR",
|
|
547
|
-
fuzzy: (term) => term.length >= FUZZY_MIN_LENGTH ? FUZZY_DISTANCE : false
|
|
548
|
-
}).map((result) => String(result.id));
|
|
549
|
-
const visible = (id) => searchOptions.includeArchived || !byId.get(id)?.discontinued;
|
|
550
|
-
const bm25 = [...new Set(ids)].filter(visible);
|
|
551
|
-
const keywords = query.split(/[^\p{L}\p{N}]+/u).filter((term) => processTerm(term) !== null).join(" ");
|
|
552
|
-
const fused = fuseRankings([bm25, rankSearchHits(searchTitles(hits, keywords, lang), currentYear).map((hit) => hit.tableId).filter(visible)], FUSION_K);
|
|
553
|
-
return [.../* @__PURE__ */ new Set([...exact ? [exact.id] : [], ...fused])].map((id) => byId.get(id)).filter((doc) => doc !== void 0).map(toHit);
|
|
554
|
-
}
|
|
555
|
-
};
|
|
556
|
-
}
|
|
557
|
-
const DEFAULT_RETRY_SECONDS = 300;
|
|
558
|
-
/**
|
|
559
|
-
* Keeps one built index per language. Parallel searches share a build, an index
|
|
560
|
-
* is rebuilt after `ttlSeconds`, and a failed refresh keeps serving the old one.
|
|
561
|
-
*/
|
|
562
|
-
function createTableIndexLoader(load, options) {
|
|
563
|
-
const built = /* @__PURE__ */ new Map();
|
|
564
|
-
const loading = /* @__PURE__ */ new Map();
|
|
565
|
-
const ttlMs = options.ttlSeconds * 1e3;
|
|
566
|
-
const retryMs = (options.retrySeconds ?? DEFAULT_RETRY_SECONDS) * 1e3;
|
|
567
|
-
const build = (docs, lang) => createTableIndex(docs, lang, { currentYear: options.currentYear?.() ?? (/* @__PURE__ */ new Date()).getUTCFullYear() });
|
|
568
|
-
async function fallbackIndex(lang) {
|
|
569
|
-
try {
|
|
570
|
-
const docs = await options.fallback?.(lang);
|
|
571
|
-
return docs && docs.length > 0 ? build(docs, lang) : void 0;
|
|
572
|
-
} catch {
|
|
573
|
-
return;
|
|
574
|
-
}
|
|
575
|
-
}
|
|
576
|
-
return (lang) => {
|
|
577
|
-
const current = built.get(lang);
|
|
578
|
-
if (current && Date.now() - current.at < ttlMs) return Promise.resolve(current.index);
|
|
579
|
-
const pending = loading.get(lang);
|
|
580
|
-
if (pending) return pending;
|
|
581
|
-
const promise = load(lang).then((docs) => {
|
|
582
|
-
const index = build(docs, lang);
|
|
583
|
-
built.set(lang, {
|
|
584
|
-
at: Date.now(),
|
|
585
|
-
index
|
|
586
|
-
});
|
|
587
|
-
return index;
|
|
588
|
-
}).catch(async (err) => {
|
|
589
|
-
const index = current?.index ?? await fallbackIndex(lang);
|
|
590
|
-
if (!index) throw err;
|
|
591
|
-
built.set(lang, {
|
|
592
|
-
at: Date.now() - ttlMs + retryMs,
|
|
593
|
-
index
|
|
594
|
-
});
|
|
595
|
-
return index;
|
|
596
|
-
}).finally(() => loading.delete(lang));
|
|
597
|
-
loading.set(lang, promise);
|
|
598
|
-
return promise;
|
|
599
|
-
};
|
|
600
|
-
}
|
|
601
216
|
// src/cbs-odata-client.ts
|
|
602
|
-
const TABLE_ID_PATTERN$
|
|
217
|
+
const TABLE_ID_PATTERN$9 = /^[A-Za-z0-9]+$/;
|
|
603
218
|
const NOT_FOUND_STATUSES$4 = /* @__PURE__ */ new Set([400, 404]);
|
|
604
219
|
const DISCONTINUED = /* @__PURE__ */ new Set(["Gediscontinueerd", "Discontinued"]);
|
|
605
220
|
const DIMENSION_TYPES = /* @__PURE__ */ new Set([
|
|
@@ -609,7 +224,7 @@ const DIMENSION_TYPES = /* @__PURE__ */ new Set([
|
|
|
609
224
|
]);
|
|
610
225
|
/** Code of the synthetic variable that holds the measures (OData columns). */
|
|
611
226
|
const TOPICS_CODE = "Topics";
|
|
612
|
-
const catalogueSchema = z.object({ value: z.array(z.object({
|
|
227
|
+
const catalogueSchema$2 = z.object({ value: z.array(z.object({
|
|
613
228
|
Identifier: z.string(),
|
|
614
229
|
Title: z.string(),
|
|
615
230
|
Language: z.string(),
|
|
@@ -667,7 +282,19 @@ const DEFAULT_DATASETS_URL = "https://datasets.cbs.nl/odata/v1/CBS";
|
|
|
667
282
|
function isNotFound(err) {
|
|
668
283
|
return err instanceof PxwebError && NOT_FOUND_STATUSES$4.has(err.status);
|
|
669
284
|
}
|
|
670
|
-
function
|
|
285
|
+
function isTransient(err) {
|
|
286
|
+
if (!(err instanceof PxwebError)) return true;
|
|
287
|
+
return err.status === 429 || err.status >= 500;
|
|
288
|
+
}
|
|
289
|
+
function sameOriginLink(next, current) {
|
|
290
|
+
if (!next) return void 0;
|
|
291
|
+
try {
|
|
292
|
+
return new URL(next).origin === new URL(current).origin ? next : void 0;
|
|
293
|
+
} catch {
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
function notFound$13(tableId) {
|
|
671
298
|
return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
672
299
|
}
|
|
673
300
|
function tooLarge() {
|
|
@@ -682,8 +309,8 @@ function odataUrl(base, params) {
|
|
|
682
309
|
...params
|
|
683
310
|
}).map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join("&")}`;
|
|
684
311
|
}
|
|
685
|
-
function checkTableId$
|
|
686
|
-
if (!TABLE_ID_PATTERN$
|
|
312
|
+
function checkTableId$5(tableId) {
|
|
313
|
+
if (!TABLE_ID_PATTERN$9.test(tableId)) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it.`, 400);
|
|
687
314
|
}
|
|
688
315
|
function selectedCodes$2(variable, selection) {
|
|
689
316
|
if (!selection || selection.selection.filter === "all") return variable.values;
|
|
@@ -732,7 +359,7 @@ function createCbsODataClient(options) {
|
|
|
732
359
|
});
|
|
733
360
|
/** One download serves both languages and parallel searches. */
|
|
734
361
|
function catalogue() {
|
|
735
|
-
loadingCatalogue ??= request(odataUrl(`${baseUrl}/ODataCatalog/Tables`, { $select: "Identifier,Title,Language,Modified,OutputStatus,Period" }), get, catalogueSchema, (data) => data.value, SEARCH_TTL_SECONDS, `catalogue:${baseUrl}`).finally(() => {
|
|
362
|
+
loadingCatalogue ??= request(odataUrl(`${baseUrl}/ODataCatalog/Tables`, { $select: "Identifier,Title,Language,Modified,OutputStatus,Period" }), get, catalogueSchema$2, (data) => data.value, SEARCH_TTL_SECONDS, `catalogue:${baseUrl}`).finally(() => {
|
|
736
363
|
loadingCatalogue = void 0;
|
|
737
364
|
});
|
|
738
365
|
return loadingCatalogue;
|
|
@@ -744,7 +371,7 @@ function createCbsODataClient(options) {
|
|
|
744
371
|
for (let page = 0; url && page < MAX_KEY_PAGES; page++) {
|
|
745
372
|
const data = await request(url, get, keysSchema, (parsed) => parsed, METADATA_TTL_SECONDS, `meta:${url}`);
|
|
746
373
|
keys.push(...data.value);
|
|
747
|
-
url = data["odata.nextLink"];
|
|
374
|
+
url = sameOriginLink(data["odata.nextLink"], firstUrl);
|
|
748
375
|
}
|
|
749
376
|
return keys;
|
|
750
377
|
}
|
|
@@ -789,7 +416,7 @@ function createCbsODataClient(options) {
|
|
|
789
416
|
for (let page = 0; url && page < MAX_KEY_PAGES; page++) {
|
|
790
417
|
const data = await request(url, get, v4CodesSchema, (parsed) => parsed, METADATA_TTL_SECONDS, `meta:${url}`);
|
|
791
418
|
codes.push(...data.value);
|
|
792
|
-
url = data["@odata.nextLink"];
|
|
419
|
+
url = sameOriginLink(data["@odata.nextLink"], firstUrl);
|
|
793
420
|
}
|
|
794
421
|
return codes;
|
|
795
422
|
}
|
|
@@ -799,7 +426,7 @@ function createCbsODataClient(options) {
|
|
|
799
426
|
* Dutch twin, with Dutch labels.
|
|
800
427
|
*/
|
|
801
428
|
async function loadV4Table(tableId) {
|
|
802
|
-
const datasetId = tableId.replace(/
|
|
429
|
+
const datasetId = tableId.replace(/eng$/i, (suffix) => suffix === "eng" ? "ned" : "NED");
|
|
803
430
|
const tableBase = `${datasetsUrl}/${datasetId}`;
|
|
804
431
|
const [title, dimensions, measures] = await Promise.all([
|
|
805
432
|
request(`${tableBase}/Properties`, get, v4PropertiesSchema, (data) => data.Title, METADATA_TTL_SECONDS, `meta:${tableBase}/Properties`),
|
|
@@ -838,15 +465,15 @@ function createCbsODataClient(options) {
|
|
|
838
465
|
};
|
|
839
466
|
}
|
|
840
467
|
async function table(tableId) {
|
|
841
|
-
checkTableId$
|
|
468
|
+
checkTableId$5(tableId);
|
|
842
469
|
try {
|
|
843
470
|
return await loadTable(tableId);
|
|
844
471
|
} catch (err) {
|
|
845
|
-
if (isNotFound(err)) throw notFound$
|
|
472
|
+
if (isNotFound(err)) throw notFound$13(tableId);
|
|
846
473
|
try {
|
|
847
474
|
return await loadV4Table(tableId);
|
|
848
475
|
} catch (v4Err) {
|
|
849
|
-
if (isNotFound(v4Err)) throw notFound$
|
|
476
|
+
if (isNotFound(v4Err)) throw isTransient(err) ? err : notFound$13(tableId);
|
|
850
477
|
throw v4Err;
|
|
851
478
|
}
|
|
852
479
|
}
|
|
@@ -933,10 +560,294 @@ function createCbsODataClient(options) {
|
|
|
933
560
|
}
|
|
934
561
|
};
|
|
935
562
|
}
|
|
563
|
+
// src/czso-client.ts
|
|
564
|
+
const TABLE_ID_PATTERN$8 = /^[A-Za-z0-9_]{1,40}$/;
|
|
565
|
+
const LANGUAGES$4 = /* @__PURE__ */ new Set(["cs", "en"]);
|
|
566
|
+
const INDICATOR_CODE = "IndicatorType";
|
|
567
|
+
const INDICATOR_LABELS = {
|
|
568
|
+
cs: "Ukazatel",
|
|
569
|
+
en: "Indicator"
|
|
570
|
+
};
|
|
571
|
+
const TIME_TYPE = "REF_CAS";
|
|
572
|
+
const DEFAULT_LEVEL = "#DEFAULT";
|
|
573
|
+
const DEFAULT_MAX_CELLS$5 = 5e3;
|
|
574
|
+
const MAX_CACHED_TABLES$4 = 8;
|
|
575
|
+
const catalogueSchema$1 = z.array(z.object({
|
|
576
|
+
kod: z.string(),
|
|
577
|
+
verze: z.string(),
|
|
578
|
+
nazev: z.string(),
|
|
579
|
+
casZmenyDefinice: z.string().nullish()
|
|
580
|
+
}));
|
|
581
|
+
const contentListSchema = z.array(z.object({
|
|
582
|
+
sadaKod: z.string(),
|
|
583
|
+
verzeKod: z.string(),
|
|
584
|
+
metadata: z.object({
|
|
585
|
+
casZmeny: z.string().nullish(),
|
|
586
|
+
casovaDimenzeDo: z.string().nullish()
|
|
587
|
+
}).nullish()
|
|
588
|
+
}));
|
|
589
|
+
const variantSchema = z.object({
|
|
590
|
+
kod: z.string(),
|
|
591
|
+
verze: z.string(),
|
|
592
|
+
typDimenzeKod: z.string(),
|
|
593
|
+
nazev: z.string(),
|
|
594
|
+
vychoziVariantaDimenze: z.boolean().nullish(),
|
|
595
|
+
urovneDimenze: z.array(z.object({ pocetPolozek: z.number().nullish() })).default([])
|
|
596
|
+
});
|
|
597
|
+
const datasetSchema = z.object({
|
|
598
|
+
verze: z.string(),
|
|
599
|
+
nazev: z.string(),
|
|
600
|
+
ukazatele: z.array(z.object({
|
|
601
|
+
kod: z.string(),
|
|
602
|
+
nazev: z.string(),
|
|
603
|
+
mericiJednotka: z.object({ nazev: z.string() }).nullish()
|
|
604
|
+
})).default([]),
|
|
605
|
+
variantyDimenze: z.array(variantSchema).default([])
|
|
606
|
+
});
|
|
607
|
+
const itemsSchema = z.array(z.object({
|
|
608
|
+
kod: z.string(),
|
|
609
|
+
nazev: z.string(),
|
|
610
|
+
kodUrovne: z.string().nullish(),
|
|
611
|
+
poradi: z.number(),
|
|
612
|
+
agregacniPolozka: z.boolean().nullish()
|
|
613
|
+
}));
|
|
614
|
+
const contentSchema = z.object({ dimenze: z.array(z.object({
|
|
615
|
+
kod: z.string(),
|
|
616
|
+
rozsahHodnot: z.array(z.object({
|
|
617
|
+
kodUrovne: z.string(),
|
|
618
|
+
poradiPolozkyOd: z.number().nullish(),
|
|
619
|
+
poradiPolozkyDo: z.number().nullish()
|
|
620
|
+
})).default([])
|
|
621
|
+
})).nullish() });
|
|
622
|
+
function notFound$12(tableId) {
|
|
623
|
+
return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
624
|
+
}
|
|
625
|
+
function checkLanguage$5(lang) {
|
|
626
|
+
if (!LANGUAGES$4.has(lang)) throw new PxwebError(`Language "${lang}" is not supported.`, 400);
|
|
627
|
+
}
|
|
628
|
+
function upstreamError$2(err) {
|
|
629
|
+
if (err instanceof PxwebError && err.status >= 500) return new PxwebError(`DataStat could not answer (HTTP ${err.status}). Try again later.`, 502);
|
|
630
|
+
return err;
|
|
631
|
+
}
|
|
632
|
+
function variantRank(variant) {
|
|
633
|
+
return [
|
|
634
|
+
variant.vychoziVariantaDimenze ? 1 : 0,
|
|
635
|
+
variant.urovneDimenze.length,
|
|
636
|
+
variant.urovneDimenze.reduce((sum, level) => sum + (level.pocetPolozek ?? 0), 0)
|
|
637
|
+
];
|
|
638
|
+
}
|
|
639
|
+
function outranks(a, b) {
|
|
640
|
+
const rankB = variantRank(b);
|
|
641
|
+
for (const [index, value] of variantRank(a).entries()) {
|
|
642
|
+
const difference = value - (rankB[index] ?? 0);
|
|
643
|
+
if (difference !== 0) return difference > 0;
|
|
644
|
+
}
|
|
645
|
+
return false;
|
|
646
|
+
}
|
|
647
|
+
/** A dataset offers alternative variants of one dimension type; one query can use only one. */
|
|
648
|
+
function oneVariantPerType(variants) {
|
|
649
|
+
const byType = /* @__PURE__ */ new Map();
|
|
650
|
+
for (const variant of variants) {
|
|
651
|
+
const current = byType.get(variant.typDimenzeKod);
|
|
652
|
+
if (!current || outranks(variant, current)) byType.set(variant.typDimenzeKod, variant);
|
|
653
|
+
}
|
|
654
|
+
return [...byType.values()];
|
|
655
|
+
}
|
|
656
|
+
/** Time dimensions list every period of the code list; keep those inside the data range. */
|
|
657
|
+
function periodsWithData(variant, items, content) {
|
|
658
|
+
const ranges = content?.dimenze?.find((dimension) => dimension.kod === variant.kod)?.rozsahHodnot;
|
|
659
|
+
if (!ranges) return items;
|
|
660
|
+
return items.filter((item) => {
|
|
661
|
+
const range = ranges.find((entry) => entry.kodUrovne === (item.kodUrovne ?? DEFAULT_LEVEL));
|
|
662
|
+
return range?.poradiPolozkyOd != null && range.poradiPolozkyDo != null && item.poradi >= range.poradiPolozkyOd && item.poradi <= range.poradiPolozkyDo;
|
|
663
|
+
});
|
|
664
|
+
}
|
|
665
|
+
function toVariable$1(variant, items, isTime) {
|
|
666
|
+
const unique = [...new Map(items.toSorted((a, b) => a.poradi - b.poradi).map((item) => [item.kod, item])).values()];
|
|
667
|
+
return {
|
|
668
|
+
code: variant.kod,
|
|
669
|
+
label: variant.nazev.trim(),
|
|
670
|
+
values: unique.map((item) => item.kod),
|
|
671
|
+
valueLabels: unique.map((item) => item.nazev.trim()),
|
|
672
|
+
eliminable: !isTime && unique.some((item) => item.agregacniPolozka),
|
|
673
|
+
isTime
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
function indicatorLabel(name, unit) {
|
|
677
|
+
const label = name.trim();
|
|
678
|
+
return unit && !label.endsWith(")") ? `${label} (${unit})` : label;
|
|
679
|
+
}
|
|
680
|
+
/** `latest` picks the newest periods of each level, so a years-and-quarters dimension gives both. */
|
|
681
|
+
function newestPerLevel(codes, levels, count) {
|
|
682
|
+
const byLevel = /* @__PURE__ */ new Map();
|
|
683
|
+
for (const code of codes) {
|
|
684
|
+
const level = levels.get(code) ?? DEFAULT_LEVEL;
|
|
685
|
+
byLevel.set(level, [...byLevel.get(level) ?? [], code]);
|
|
686
|
+
}
|
|
687
|
+
const newest = new Set([...byLevel.values()].flatMap((list) => list.slice(-count)));
|
|
688
|
+
return codes.filter((code) => newest.has(code));
|
|
689
|
+
}
|
|
690
|
+
function chosenCodes$5(variable, selection, timeLevels) {
|
|
691
|
+
if (!selection || selection.selection.filter === "all") return [];
|
|
692
|
+
const { filter, values } = selection.selection;
|
|
693
|
+
if (filter === "item") return values;
|
|
694
|
+
const count = Math.max(1, Number(values[0]) || 1);
|
|
695
|
+
if (variable.isTime) return newestPerLevel(variable.values, timeLevels, count);
|
|
696
|
+
return variable.values.slice(-count);
|
|
697
|
+
}
|
|
698
|
+
/**
|
|
699
|
+
* Client for DataStat, the CZSO (Czech Statistical Office) API, in Czech and English.
|
|
700
|
+
*
|
|
701
|
+
* - Table id: the dataset code (`kod`, for example "CEN0101H").
|
|
702
|
+
* - Search: a local index over the live catalogue (`katalog/v1/sady`, per language) and
|
|
703
|
+
* the content list (`dotaz/v1/metadata/sady/seznam`, for the data update date and
|
|
704
|
+
* last period), both cached for an hour. No crawled snapshot is needed; `listFallback`
|
|
705
|
+
* is used when the live catalogue fails.
|
|
706
|
+
* - Metadata: the dataset detail gives the indicators and the dimension variants. A
|
|
707
|
+
* dataset can have several variants of one dimension type (years, quarters, or years
|
|
708
|
+
* and quarters; regions or districts), and a query can use only one, so each type
|
|
709
|
+
* exposes its default variant, else the one with the most levels, then the most items.
|
|
710
|
+
* Items come from the variant's code list; time items are cut to the data range of the
|
|
711
|
+
* dataset content metadata and ordered by the code list order. A dimension with a
|
|
712
|
+
* total item is eliminable: DataStat returns the total when it is left out.
|
|
713
|
+
* - Query: one GET custom selection (`data/sady/{kod}/vlastni`, JSON-stat 2.0) with one
|
|
714
|
+
* parameter per selected dimension. `latest` gives the newest periods of each time level.
|
|
715
|
+
* The cell limit is checked before the request. Predefined selections (`data/vybery`)
|
|
716
|
+
* are not used: they cover one variant each and cost the same single request.
|
|
717
|
+
* - Caching: catalogue and code lists in the shared cache; the parsed table in memory for
|
|
718
|
+
* an hour, so new periods appear soon after a release.
|
|
719
|
+
*/
|
|
720
|
+
function createCzsoClient(options) {
|
|
721
|
+
const root = options.baseUrl.replace(/\/+$/, "");
|
|
722
|
+
const maxCells = options.maxCells ?? DEFAULT_MAX_CELLS$5;
|
|
723
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
724
|
+
const request = createRequester(options);
|
|
725
|
+
function get(lang, path, schema, ttlSeconds) {
|
|
726
|
+
const url = `${root}/${path}`;
|
|
727
|
+
return request(url, {
|
|
728
|
+
method: "GET",
|
|
729
|
+
...lang && { headers: { "accept-language": lang } }
|
|
730
|
+
}, schema, (data) => data, ttlSeconds, `${lang ?? "*"}:${url}`);
|
|
731
|
+
}
|
|
732
|
+
async function listTables(lang) {
|
|
733
|
+
checkLanguage$5(lang);
|
|
734
|
+
const [datasets, contents] = await Promise.all([get(lang, "katalog/v1/sady", catalogueSchema$1, SEARCH_TTL_SECONDS), get(void 0, "dotaz/v1/metadata/sady/seznam", contentListSchema, SEARCH_TTL_SECONDS).catch(() => [])]);
|
|
735
|
+
const contentOf = new Map(contents.map((entry) => [`${entry.sadaKod}:${entry.verzeKod}`, entry.metadata]));
|
|
736
|
+
return datasets.map((dataset) => {
|
|
737
|
+
const content = contentOf.get(`${dataset.kod}:${dataset.verze}`);
|
|
738
|
+
const updated = (content?.casZmeny ?? dataset.casZmenyDefinice)?.slice(0, 10);
|
|
739
|
+
const lastPeriod = content?.casovaDimenzeDo?.slice(0, 4);
|
|
740
|
+
return {
|
|
741
|
+
id: dataset.kod,
|
|
742
|
+
title: dataset.nazev.trim(),
|
|
743
|
+
...updated && { updated },
|
|
744
|
+
...lastPeriod && { lastPeriod }
|
|
745
|
+
};
|
|
746
|
+
});
|
|
747
|
+
}
|
|
748
|
+
const tableIndex = createTableIndexLoader(listTables, {
|
|
749
|
+
fallback: options.listFallback,
|
|
750
|
+
ttlSeconds: SEARCH_TTL_SECONDS,
|
|
751
|
+
currentYear: () => now().getUTCFullYear()
|
|
752
|
+
});
|
|
753
|
+
async function loadTable(lang, tableId) {
|
|
754
|
+
checkLanguage$5(lang);
|
|
755
|
+
if (!TABLE_ID_PATTERN$8.test(tableId)) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it.`, 400);
|
|
756
|
+
const dataset = await get(lang, `katalog/v1/sady/${tableId}`, datasetSchema, METADATA_TTL_SECONDS).catch((err) => {
|
|
757
|
+
if (err instanceof PxwebError && err.status === 404) throw notFound$12(tableId);
|
|
758
|
+
throw upstreamError$2(err);
|
|
759
|
+
});
|
|
760
|
+
const variants = oneVariantPerType(dataset.variantyDimenze);
|
|
761
|
+
const hasTime = variants.some((variant) => variant.typDimenzeKod === TIME_TYPE);
|
|
762
|
+
const [content, ...itemLists] = await Promise.all([hasTime ? get(void 0, `dotaz/v1/metadata/sady/${tableId}?verze=${encodeURIComponent(dataset.verze)}`, contentSchema, DATA_TTL_SECONDS) : void 0, ...variants.map((variant) => get(lang, `katalog/v1/dimenze/${encodeURIComponent(variant.kod)}/polozky?verze=${encodeURIComponent(variant.verze)}`, itemsSchema, METADATA_TTL_SECONDS))]).catch((err) => {
|
|
763
|
+
throw upstreamError$2(err);
|
|
764
|
+
});
|
|
765
|
+
const timeLevels = /* @__PURE__ */ new Map();
|
|
766
|
+
const dimensions = variants.map((variant, index) => {
|
|
767
|
+
const isTime = variant.typDimenzeKod === TIME_TYPE;
|
|
768
|
+
const items = itemLists[index] ?? [];
|
|
769
|
+
if (!isTime) return toVariable$1(variant, items, false);
|
|
770
|
+
const periods = periodsWithData(variant, items, content);
|
|
771
|
+
for (const item of periods) timeLevels.set(item.kod, item.kodUrovne ?? DEFAULT_LEVEL);
|
|
772
|
+
return toVariable$1(variant, periods, true);
|
|
773
|
+
});
|
|
774
|
+
const indicator = {
|
|
775
|
+
code: INDICATOR_CODE,
|
|
776
|
+
label: INDICATOR_LABELS[lang] ?? INDICATOR_CODE,
|
|
777
|
+
values: dataset.ukazatele.map((item) => item.kod),
|
|
778
|
+
valueLabels: dataset.ukazatele.map((item) => indicatorLabel(item.nazev, item.mericiJednotka?.nazev)),
|
|
779
|
+
eliminable: false,
|
|
780
|
+
isTime: false
|
|
781
|
+
};
|
|
782
|
+
return {
|
|
783
|
+
metadata: {
|
|
784
|
+
title: dataset.nazev.trim(),
|
|
785
|
+
variables: [
|
|
786
|
+
indicator,
|
|
787
|
+
...dimensions.filter((variable) => !variable.isTime),
|
|
788
|
+
...dimensions.filter((variable) => variable.isTime)
|
|
789
|
+
]
|
|
790
|
+
},
|
|
791
|
+
timeLevels
|
|
792
|
+
};
|
|
793
|
+
}
|
|
794
|
+
const tables = /* @__PURE__ */ new Map();
|
|
795
|
+
async function cachedTable(lang, tableId) {
|
|
796
|
+
const key = `${lang}:${tableId}`;
|
|
797
|
+
const cached = tables.get(key);
|
|
798
|
+
if (cached && cached.expires > Date.now()) return cached.table;
|
|
799
|
+
const table = await loadTable(lang, tableId);
|
|
800
|
+
tables.delete(key);
|
|
801
|
+
tables.set(key, {
|
|
802
|
+
expires: Date.now() + DATA_TTL_SECONDS * 1e3,
|
|
803
|
+
table
|
|
804
|
+
});
|
|
805
|
+
const oldest = tables.keys().next().value;
|
|
806
|
+
if (tables.size > MAX_CACHED_TABLES$4 && oldest !== void 0) tables.delete(oldest);
|
|
807
|
+
return table;
|
|
808
|
+
}
|
|
809
|
+
return {
|
|
810
|
+
listTables,
|
|
811
|
+
async search(lang, query, searchOptions) {
|
|
812
|
+
checkLanguage$5(lang);
|
|
813
|
+
return (await tableIndex(lang)).search(query, searchOptions);
|
|
814
|
+
},
|
|
815
|
+
async getMetadata(lang, tableId) {
|
|
816
|
+
return (await cachedTable(lang, tableId)).metadata;
|
|
817
|
+
},
|
|
818
|
+
async query(lang, tableId, selections) {
|
|
819
|
+
const table = await cachedTable(lang, tableId);
|
|
820
|
+
const byCode = new Map(selections.map((selection) => [selection.code, selection]));
|
|
821
|
+
const params = ["format=JSON_STAT"];
|
|
822
|
+
let cells = 1;
|
|
823
|
+
for (const variable of table.metadata.variables) {
|
|
824
|
+
const selection = byCode.get(variable.code);
|
|
825
|
+
if (!selection && variable.eliminable) continue;
|
|
826
|
+
const codes = chosenCodes$5(variable, selection, table.timeLevels);
|
|
827
|
+
cells *= codes.length || variable.values.length;
|
|
828
|
+
const value = codes.length > 0 ? codes.map(encodeURIComponent).join(",") : "*";
|
|
829
|
+
params.push(`${encodeURIComponent(variable.code)}=${value}`);
|
|
830
|
+
}
|
|
831
|
+
if (cells > maxCells) throw new PxwebError(`The query could return ${cells} cells, above the limit of ${maxCells}. Select fewer values.`, 400);
|
|
832
|
+
return get(lang, `dotaz/v1/data/sady/${tableId}/vlastni?${params.join("&")}`, jsonStatDatasetSchema, DATA_TTL_SECONDS).then((dataset) => {
|
|
833
|
+
const flat = toFlatTable$2(dataset);
|
|
834
|
+
return {
|
|
835
|
+
label: table.metadata.title,
|
|
836
|
+
columns: flat.columns.map((column) => column.trim()),
|
|
837
|
+
rows: flat.rows.map((row) => row.map((cell) => typeof cell === "string" ? cell.trim() : cell))
|
|
838
|
+
};
|
|
839
|
+
}).catch((err) => {
|
|
840
|
+
if (err instanceof PxwebError && err.status === 404) throw notFound$12(tableId);
|
|
841
|
+
if (err instanceof PxwebError && err.status === 400) throw new PxwebError(`DataStat refused this selection: ${err.message.replace(/^PxWeb returned HTTP 400: /, "")}. Check the value codes with get_table_metadata.`, 400);
|
|
842
|
+
throw upstreamError$2(err);
|
|
843
|
+
});
|
|
844
|
+
}
|
|
845
|
+
};
|
|
846
|
+
}
|
|
936
847
|
// src/eurostat-client.ts
|
|
937
|
-
const CODE_PATTERN = /^[A-Za-z0-9_$.-]+$/;
|
|
938
|
-
const CLOSED_TITLE = /\(\d{4}\s*-\s*\d{4}\)\s*$/;
|
|
939
|
-
const TIME_CODE$
|
|
848
|
+
const CODE_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9_$.-]+$/;
|
|
849
|
+
const CLOSED_TITLE$1 = /\(\d{4}\s*-\s*\d{4}\)\s*$/;
|
|
850
|
+
const TIME_CODE$6 = "time";
|
|
940
851
|
const NOT_FOUND_STATUSES$3 = /* @__PURE__ */ new Set([400, 404]);
|
|
941
852
|
const TEXT = {
|
|
942
853
|
method: "GET",
|
|
@@ -953,42 +864,42 @@ const XML_ENTITIES = {
|
|
|
953
864
|
quot: "\"",
|
|
954
865
|
apos: "'"
|
|
955
866
|
};
|
|
956
|
-
const MAX_CODE_POINT = 1114111;
|
|
957
|
-
function decodeXml(text) {
|
|
867
|
+
const MAX_CODE_POINT$1 = 1114111;
|
|
868
|
+
function decodeXml$1(text) {
|
|
958
869
|
return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (entity, name) => {
|
|
959
870
|
if (!name.startsWith("#")) return Object.hasOwn(XML_ENTITIES, name) ? XML_ENTITIES[name] ?? entity : entity;
|
|
960
871
|
const point = name[1]?.toLowerCase() === "x" ? Number.parseInt(name.slice(2), 16) : Number(name.slice(1));
|
|
961
|
-
return point <= MAX_CODE_POINT ? String.fromCodePoint(point) : entity;
|
|
872
|
+
return point <= MAX_CODE_POINT$1 ? String.fromCodePoint(point) : entity;
|
|
962
873
|
});
|
|
963
874
|
}
|
|
964
875
|
/** Turns `<s:Code id="X"/>` into `<s:Code id="X"></s:Code>`, so one pattern reads both forms. */
|
|
965
876
|
function expandSelfClosing(xml) {
|
|
966
877
|
return xml.replace(/<(s:(?:Concept|Codelist|Code|Dimension))\b([^>]*?)\/>/g, "<$1$2></$1>");
|
|
967
878
|
}
|
|
968
|
-
function attribute(tag, name) {
|
|
879
|
+
function attribute$1(tag, name) {
|
|
969
880
|
return new RegExp(`\\b${name}="([^"]*)"`).exec(tag)?.[1];
|
|
970
881
|
}
|
|
971
882
|
/** Name in the asked language, else English, else the code. */
|
|
972
883
|
function nameIn(block, lang) {
|
|
973
884
|
const names = [...block.matchAll(/<c:Name xml:lang="([a-z]+)">([^<]*)<\/c:Name>/g)];
|
|
974
885
|
const match = names.find((name) => name[1] === lang) ?? names.find((name) => name[1] === "en");
|
|
975
|
-
return match?.[2] === void 0 ? void 0 : decodeXml(match[2]);
|
|
886
|
+
return match?.[2] === void 0 ? void 0 : decodeXml$1(match[2]);
|
|
976
887
|
}
|
|
977
888
|
/** Dimension order and codes from an SDMX-ML 2.1 structure message. */
|
|
978
|
-
function parseStructure(xml, lang) {
|
|
889
|
+
function parseStructure$1(xml, lang) {
|
|
979
890
|
xml = expandSelfClosing(xml);
|
|
980
891
|
const concepts = /* @__PURE__ */ new Map();
|
|
981
892
|
for (const concept of xml.matchAll(/<s:Concept\b([^>]*)>([\s\S]*?)<\/s:Concept>/g)) {
|
|
982
|
-
const id = attribute(concept[1] ?? "", "id");
|
|
893
|
+
const id = attribute$1(concept[1] ?? "", "id");
|
|
983
894
|
const name = nameIn(concept[2] ?? "", lang);
|
|
984
895
|
if (id && name) concepts.set(id, name);
|
|
985
896
|
}
|
|
986
897
|
const codelists = /* @__PURE__ */ new Map();
|
|
987
898
|
for (const list of xml.matchAll(/<s:Codelist\b([^>]*)>([\s\S]*?)<\/s:Codelist>/g)) {
|
|
988
|
-
const id = attribute(list[1] ?? "", "id");
|
|
899
|
+
const id = attribute$1(list[1] ?? "", "id");
|
|
989
900
|
if (!id) continue;
|
|
990
901
|
const codes = [...(list[2] ?? "").matchAll(/<s:Code\b([^>]*)>([\s\S]*?)<\/s:Code>/g)].map((code) => {
|
|
991
|
-
const codeId = decodeXml(attribute(code[1] ?? "", "id") ?? "");
|
|
902
|
+
const codeId = decodeXml$1(attribute$1(code[1] ?? "", "id") ?? "");
|
|
992
903
|
return {
|
|
993
904
|
id: codeId,
|
|
994
905
|
label: nameIn(code[2] ?? "", lang) ?? codeId
|
|
@@ -999,9 +910,9 @@ function parseStructure(xml, lang) {
|
|
|
999
910
|
return { dimensions: [...xml.matchAll(/<s:Dimension\b([^>]*)>([\s\S]*?)<\/s:Dimension>/g)].map((dimension) => {
|
|
1000
911
|
const reference = /<Ref\b[^>]*\bclass="Codelist"[^>]*>/.exec(dimension[2] ?? "")?.[0] ?? "";
|
|
1001
912
|
return {
|
|
1002
|
-
id: attribute(dimension[1] ?? "", "id") ?? "",
|
|
1003
|
-
position: Number(attribute(dimension[1] ?? "", "position") ?? 0),
|
|
1004
|
-
codes: codelists.get(attribute(reference, "id") ?? "") ?? []
|
|
913
|
+
id: attribute$1(dimension[1] ?? "", "id") ?? "",
|
|
914
|
+
position: Number(attribute$1(dimension[1] ?? "", "position") ?? 0),
|
|
915
|
+
codes: codelists.get(attribute$1(reference, "id") ?? "") ?? []
|
|
1005
916
|
};
|
|
1006
917
|
}).filter((dimension) => dimension.id).toSorted((a, b) => a.position - b.position).map(({ id, codes }) => ({
|
|
1007
918
|
id,
|
|
@@ -1083,7 +994,7 @@ function uniqueByCode(entries) {
|
|
|
1083
994
|
return true;
|
|
1084
995
|
});
|
|
1085
996
|
}
|
|
1086
|
-
function notFound$
|
|
997
|
+
function notFound$11(code) {
|
|
1087
998
|
return new PxwebError(`Table "${code}" was not found. Use search_tables to find a table id.`, 404);
|
|
1088
999
|
}
|
|
1089
1000
|
function checkCode(code) {
|
|
@@ -1127,7 +1038,7 @@ function createEurostatClient(options) {
|
|
|
1127
1038
|
path: entry.path,
|
|
1128
1039
|
...entry.updated ? { updated: entry.updated } : {},
|
|
1129
1040
|
...entry.end ? { lastPeriod: entry.end } : {},
|
|
1130
|
-
...CLOSED_TITLE.test(entry.title) ? { discontinued: true } : {}
|
|
1041
|
+
...CLOSED_TITLE$1.test(entry.title) ? { discontinued: true } : {}
|
|
1131
1042
|
}));
|
|
1132
1043
|
const tableIndex = createTableIndexLoader(listTables, {
|
|
1133
1044
|
fallback: options.listFallback,
|
|
@@ -1136,14 +1047,14 @@ function createEurostatClient(options) {
|
|
|
1136
1047
|
});
|
|
1137
1048
|
async function metadata(lang, code) {
|
|
1138
1049
|
const entry = (await toc(lang)).find((item) => item.code === code);
|
|
1139
|
-
if (!entry) throw notFound$
|
|
1050
|
+
if (!entry) throw notFound$11(code);
|
|
1140
1051
|
const url = `${baseUrl}/sdmx/2.1/dataflow/ESTAT/${encodeURIComponent(code)}/latest?references=descendants&detail=referencepartial`;
|
|
1141
1052
|
const variables = (await requestText(url, TEXT, (xml) => {
|
|
1142
|
-
const result = parseStructure(xml, lang);
|
|
1053
|
+
const result = parseStructure$1(xml, lang);
|
|
1143
1054
|
if (result.dimensions.length === 0) throw new PxwebError("Eurostat returned a structure without dimensions.", 502);
|
|
1144
1055
|
return result;
|
|
1145
1056
|
}, METADATA_TTL_SECONDS, `meta:${url}:${lang}`).catch((err) => {
|
|
1146
|
-
if (err instanceof PxwebError && NOT_FOUND_STATUSES$3.has(err.status)) throw notFound$
|
|
1057
|
+
if (err instanceof PxwebError && NOT_FOUND_STATUSES$3.has(err.status)) throw notFound$11(code);
|
|
1147
1058
|
throw err;
|
|
1148
1059
|
})).dimensions.map((dimension) => ({
|
|
1149
1060
|
code: dimension.id,
|
|
@@ -1154,53 +1065,2032 @@ function createEurostatClient(options) {
|
|
|
1154
1065
|
isTime: false
|
|
1155
1066
|
}));
|
|
1156
1067
|
const periods = periodsBetween(entry.start, entry.end);
|
|
1068
|
+
const incomplete = stepOf(entry.end) === void 0 || !periodParts(entry.start) || !periodParts(entry.end);
|
|
1157
1069
|
variables.push({
|
|
1158
|
-
code: TIME_CODE$
|
|
1159
|
-
label: TIME_CODE$
|
|
1070
|
+
code: TIME_CODE$6,
|
|
1071
|
+
label: TIME_CODE$6,
|
|
1160
1072
|
values: periods,
|
|
1161
1073
|
valueLabels: periods,
|
|
1162
1074
|
eliminable: false,
|
|
1163
|
-
isTime: true
|
|
1075
|
+
isTime: true,
|
|
1076
|
+
...incomplete && { periodsIncomplete: true }
|
|
1077
|
+
});
|
|
1078
|
+
return {
|
|
1079
|
+
title: entry.title,
|
|
1080
|
+
variables
|
|
1081
|
+
};
|
|
1082
|
+
}
|
|
1083
|
+
return {
|
|
1084
|
+
listTables,
|
|
1085
|
+
async search(lang, query, searchOptions) {
|
|
1086
|
+
return (await tableIndex(lang)).search(query, searchOptions);
|
|
1087
|
+
},
|
|
1088
|
+
async getMetadata(lang, code) {
|
|
1089
|
+
checkCode(code);
|
|
1090
|
+
return metadata(lang, code);
|
|
1091
|
+
},
|
|
1092
|
+
async query(lang, code, selections) {
|
|
1093
|
+
checkCode(code);
|
|
1094
|
+
const params = new URLSearchParams({ lang });
|
|
1095
|
+
const known = selections.some((selection) => selection.selection.filter === "top" && selection.code !== TIME_CODE$6) ? await metadata(lang, code) : void 0;
|
|
1096
|
+
for (const selection of selections) {
|
|
1097
|
+
const { filter, values } = selection.selection;
|
|
1098
|
+
if (filter === "all") continue;
|
|
1099
|
+
const count = Math.max(1, Number(values[0]) || 1);
|
|
1100
|
+
if (filter === "top" && selection.code === TIME_CODE$6) {
|
|
1101
|
+
params.append("lastTimePeriod", String(count));
|
|
1102
|
+
continue;
|
|
1103
|
+
}
|
|
1104
|
+
let codes = values;
|
|
1105
|
+
if (filter === "top") {
|
|
1106
|
+
const variable = known?.variables.find((item) => item.code === selection.code);
|
|
1107
|
+
if (!variable) throw new PxwebError(`Table "${code}" has no variable "${selection.code}". Call get_table_metadata to see its variables.`, 400);
|
|
1108
|
+
codes = variable.values.slice(-count);
|
|
1109
|
+
}
|
|
1110
|
+
for (const value of codes) params.append(selection.code, value);
|
|
1111
|
+
}
|
|
1112
|
+
const url = `${baseUrl}/statistics/1.0/data/${encodeURIComponent(code)}?${params.toString()}`;
|
|
1113
|
+
return request(url, { method: "GET" }, jsonStatDatasetSchema, toFlatTable$2, DATA_TTL_SECONDS, `data:${url}`).catch((err) => {
|
|
1114
|
+
if (err instanceof PxwebError && err.status === 404) throw notFound$11(code);
|
|
1115
|
+
throw err;
|
|
1116
|
+
});
|
|
1117
|
+
}
|
|
1118
|
+
};
|
|
1119
|
+
}
|
|
1120
|
+
// src/ibge-client.ts
|
|
1121
|
+
const TABLE_ID_PATTERN$7 = /^\d{1,7}$/;
|
|
1122
|
+
const LANGUAGE = "pt";
|
|
1123
|
+
const DEFAULT_SIDRA_URL = "https://apisidra.ibge.gov.br/values";
|
|
1124
|
+
const DEFAULT_MAX_CELLS$4 = 5e3;
|
|
1125
|
+
const MAX_CACHED_TABLES$3 = 8;
|
|
1126
|
+
const VARIABLE_CODE = "variavel";
|
|
1127
|
+
const LOCALITY_CODE = "localidade";
|
|
1128
|
+
const PERIOD_CODE = "periodo";
|
|
1129
|
+
const COUNTRY_LEVEL = "N1";
|
|
1130
|
+
/**
|
|
1131
|
+
* Brazil, major regions, states and municipalities. The localities endpoint answers
|
|
1132
|
+
* an empty list for metropolitan regions (N7) and some other levels, and one empty
|
|
1133
|
+
* level empties the whole answer, so only these are asked for.
|
|
1134
|
+
*/
|
|
1135
|
+
const LOCALITY_LEVELS = [
|
|
1136
|
+
"N1",
|
|
1137
|
+
"N2",
|
|
1138
|
+
"N3",
|
|
1139
|
+
"N6"
|
|
1140
|
+
];
|
|
1141
|
+
const LOCALITY_PATTERN = /^N(\d+):(\d+)$/;
|
|
1142
|
+
/** "(série encerrada em 2021)", or a closed range such as "(de janeiro/2012 até dezembro/2019)". */
|
|
1143
|
+
const CLOSED_TITLE = /s[ée]rie (encerrada|descontinuada|suspensa)|até (\p{L}+\/)?\d{4}\)\s*$/iu;
|
|
1144
|
+
/**
|
|
1145
|
+
* Survey groups whose aggregates all ended long ago (checked on 2026-11-27):
|
|
1146
|
+
* PME (ended 2016-02), PNAD (2015), PIMES (2015-12), PIM Dados Gerais (2001),
|
|
1147
|
+
* the old PIA (1995), IPC-r (1995), IRSM and INPC-E (1994).
|
|
1148
|
+
*/
|
|
1149
|
+
const DISCONTINUED_GROUPS = /* @__PURE__ */ new Set([
|
|
1150
|
+
"PE",
|
|
1151
|
+
"PD",
|
|
1152
|
+
"XY",
|
|
1153
|
+
"DG",
|
|
1154
|
+
"PI",
|
|
1155
|
+
"IL",
|
|
1156
|
+
"IJ",
|
|
1157
|
+
"PG"
|
|
1158
|
+
]);
|
|
1159
|
+
const catalogueSchema = z.array(z.object({
|
|
1160
|
+
id: z.string(),
|
|
1161
|
+
nome: z.string(),
|
|
1162
|
+
agregados: z.array(z.object({
|
|
1163
|
+
id: z.string(),
|
|
1164
|
+
nome: z.string()
|
|
1165
|
+
}))
|
|
1166
|
+
}));
|
|
1167
|
+
const metadataSchema$5 = z.object({
|
|
1168
|
+
nome: z.string(),
|
|
1169
|
+
nivelTerritorial: z.record(z.string(), z.array(z.string())),
|
|
1170
|
+
variaveis: z.array(z.object({
|
|
1171
|
+
id: z.number(),
|
|
1172
|
+
nome: z.string(),
|
|
1173
|
+
unidade: z.string().nullish()
|
|
1174
|
+
})),
|
|
1175
|
+
classificacoes: z.array(z.object({
|
|
1176
|
+
id: z.number(),
|
|
1177
|
+
nome: z.string(),
|
|
1178
|
+
sumarizacao: z.object({ status: z.boolean() }),
|
|
1179
|
+
categorias: z.array(z.object({
|
|
1180
|
+
id: z.number(),
|
|
1181
|
+
nome: z.string()
|
|
1182
|
+
}))
|
|
1183
|
+
})).default([])
|
|
1184
|
+
});
|
|
1185
|
+
const periodsSchema = z.array(z.object({
|
|
1186
|
+
id: z.string(),
|
|
1187
|
+
literals: z.array(z.string())
|
|
1188
|
+
}));
|
|
1189
|
+
const localitiesSchema = z.array(z.object({
|
|
1190
|
+
id: z.string(),
|
|
1191
|
+
nome: z.string(),
|
|
1192
|
+
nivel: z.object({ id: z.string() })
|
|
1193
|
+
}));
|
|
1194
|
+
/** The first row holds the column titles; the rest are cells. */
|
|
1195
|
+
const valuesSchema$1 = z.array(z.record(z.string(), z.string()));
|
|
1196
|
+
function notFound$10(tableId) {
|
|
1197
|
+
return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
1198
|
+
}
|
|
1199
|
+
function checkLanguage$4(lang) {
|
|
1200
|
+
if (lang !== LANGUAGE) throw new PxwebError(`Language "${lang}" is not supported.`, 400);
|
|
1201
|
+
}
|
|
1202
|
+
function upstreamError$1(err) {
|
|
1203
|
+
if (err instanceof PxwebError && err.status >= 500) return new PxwebError(`IBGE could not answer (HTTP ${err.status}). Try again later.`, 502);
|
|
1204
|
+
return err;
|
|
1205
|
+
}
|
|
1206
|
+
function withUnit(name, unit) {
|
|
1207
|
+
const label = name.trim();
|
|
1208
|
+
if (!unit || unit === "Nenhuma" || label.endsWith(")")) return label;
|
|
1209
|
+
return `${label} (${unit})`;
|
|
1210
|
+
}
|
|
1211
|
+
/** IBGE writes "-" for a true zero and "..", "..." or "X" for missing or withheld data. */
|
|
1212
|
+
function toNumber$1(value) {
|
|
1213
|
+
if (value === "-") return 0;
|
|
1214
|
+
const number = Number(value);
|
|
1215
|
+
return value && Number.isFinite(number) ? number : null;
|
|
1216
|
+
}
|
|
1217
|
+
function chosenCodes$4(variable, selection) {
|
|
1218
|
+
if (!selection || selection.selection.filter === "all") return void 0;
|
|
1219
|
+
const { filter, values } = selection.selection;
|
|
1220
|
+
if (filter === "item") return values;
|
|
1221
|
+
return variable.values.slice(-Math.max(1, Number(values[0]) || 1));
|
|
1222
|
+
}
|
|
1223
|
+
function localitySegments(codes) {
|
|
1224
|
+
const byLevel = /* @__PURE__ */ new Map();
|
|
1225
|
+
for (const code of codes) {
|
|
1226
|
+
const match = LOCALITY_PATTERN.exec(code);
|
|
1227
|
+
if (!match) throw new PxwebError(`Unknown locality "${code}". Use the codes from get_table_metadata.`, 400);
|
|
1228
|
+
const level = `n${match[1]}`;
|
|
1229
|
+
byLevel.set(level, [...byLevel.get(level) ?? [], match[2] ?? ""]);
|
|
1230
|
+
}
|
|
1231
|
+
return [...byLevel].map(([level, ids]) => `${level}/${ids.join(",")}`).join("/");
|
|
1232
|
+
}
|
|
1233
|
+
function allLevels(variable) {
|
|
1234
|
+
return [...new Set(variable.values.map((code) => code.split(":")[0]?.toLowerCase()))].map((level) => `${level}/all`).join("/");
|
|
1235
|
+
}
|
|
1236
|
+
/**
|
|
1237
|
+
* Client for IBGE (Instituto Brasileiro de Geografia e Estatística), in Portuguese.
|
|
1238
|
+
*
|
|
1239
|
+
* - Table id: the aggregate id, which is also the SIDRA table number (for example "1737").
|
|
1240
|
+
* - Search: a local index over the aggregates catalogue (`/agregados`, one 2 MB call
|
|
1241
|
+
* cached for an hour); the survey group is the path. The catalogue has no dates, so
|
|
1242
|
+
* there is no recency ranking. Aggregates are marked discontinued when the title
|
|
1243
|
+
* says "série encerrada" (or "descontinuada", "suspensa"), ends with a closed range
|
|
1244
|
+
* ("… até dezembro/2019)") or the survey ended long ago (`DISCONTINUED_GROUPS`).
|
|
1245
|
+
* - Metadata: `/agregados/{id}/metadados`, `/periodos` and `/localidades/{levels}`.
|
|
1246
|
+
* Variables: `variavel` (the IBGE variables, with the unit in the label), one `c{id}`
|
|
1247
|
+
* per classification (eliminable when IBGE sums it, which gives the total category
|
|
1248
|
+
* when it is left out), `localidade` (codes "N1:1", "N3:35", "N6:3550308"; levels
|
|
1249
|
+
* Brazil, regions, states and municipalities; eliminable when Brazil is offered) and
|
|
1250
|
+
* `periodo` (ordered oldest first).
|
|
1251
|
+
* - Query: one SIDRA values request (`/t/{id}/n…/v/…/p/…/c…`), because SIDRA answers a
|
|
1252
|
+
* refused selection with HTTP 400 and a message, where the aggregates API answers 500.
|
|
1253
|
+
* The cell limit is checked first. SIDRA orders the columns as the request does
|
|
1254
|
+
* (locality, variable, period, then classifications) and adds the left-out
|
|
1255
|
+
* classifications after them, so only the requested ones become columns.
|
|
1256
|
+
* - Not found: the aggregates API answers HTTP 500 for an unknown id, so a failed
|
|
1257
|
+
* metadata call is checked against the catalogue.
|
|
1258
|
+
* - Caching: catalogue, metadata and localities in the shared cache; the parsed table in
|
|
1259
|
+
* memory for an hour.
|
|
1260
|
+
*/
|
|
1261
|
+
function createIbgeClient(options) {
|
|
1262
|
+
const root = options.baseUrl.replace(/\/+$/, "");
|
|
1263
|
+
const sidraRoot = (options.sidraUrl ?? DEFAULT_SIDRA_URL).replace(/\/+$/, "");
|
|
1264
|
+
const maxCells = options.maxCells ?? DEFAULT_MAX_CELLS$4;
|
|
1265
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
1266
|
+
const request = createRequester(options);
|
|
1267
|
+
function get(url, schema, ttlSeconds) {
|
|
1268
|
+
return request(url, { method: "GET" }, schema, (data) => data, ttlSeconds, url);
|
|
1269
|
+
}
|
|
1270
|
+
async function listTables(lang) {
|
|
1271
|
+
checkLanguage$4(lang);
|
|
1272
|
+
const groups = await get(root, catalogueSchema, SEARCH_TTL_SECONDS);
|
|
1273
|
+
const docs = /* @__PURE__ */ new Map();
|
|
1274
|
+
for (const group of groups) for (const aggregate of group.agregados) {
|
|
1275
|
+
if (docs.has(aggregate.id)) continue;
|
|
1276
|
+
docs.set(aggregate.id, {
|
|
1277
|
+
id: aggregate.id,
|
|
1278
|
+
title: aggregate.nome.trim(),
|
|
1279
|
+
path: [group.nome.trim()],
|
|
1280
|
+
...(DISCONTINUED_GROUPS.has(group.id) || CLOSED_TITLE.test(aggregate.nome)) && { discontinued: true }
|
|
1281
|
+
});
|
|
1282
|
+
}
|
|
1283
|
+
return [...docs.values()];
|
|
1284
|
+
}
|
|
1285
|
+
const tableIndex = createTableIndexLoader(preferCrawled(listTables, options.crawledList), {
|
|
1286
|
+
fallback: options.listFallback,
|
|
1287
|
+
ttlSeconds: SEARCH_TTL_SECONDS,
|
|
1288
|
+
currentYear: () => now().getUTCFullYear()
|
|
1289
|
+
});
|
|
1290
|
+
async function missingOrUpstream(tableId, err) {
|
|
1291
|
+
if (!(err instanceof PxwebError)) return err;
|
|
1292
|
+
const tables = await listTables(LANGUAGE).catch(() => void 0);
|
|
1293
|
+
if (tables && !tables.some((table) => table.id === tableId)) return notFound$10(tableId);
|
|
1294
|
+
return upstreamError$1(err);
|
|
1295
|
+
}
|
|
1296
|
+
async function loadTable(tableId) {
|
|
1297
|
+
const base = `${root}/${tableId}`;
|
|
1298
|
+
const metadata = await get(`${base}/metadados`, metadataSchema$5, METADATA_TTL_SECONDS).catch(async (err) => {
|
|
1299
|
+
throw await missingOrUpstream(tableId, err);
|
|
1300
|
+
});
|
|
1301
|
+
const offered = Object.values(metadata.nivelTerritorial).flat();
|
|
1302
|
+
const preferred = LOCALITY_LEVELS.filter((level) => offered.includes(level));
|
|
1303
|
+
const levels = preferred.length > 0 ? preferred : offered;
|
|
1304
|
+
const [periods, localities] = await Promise.all([get(`${base}/periodos`, periodsSchema, DATA_TTL_SECONDS), levels.length > 0 ? get(`${base}/localidades/${levels.join("|")}`, localitiesSchema, METADATA_TTL_SECONDS) : []]).catch((err) => {
|
|
1305
|
+
throw upstreamError$1(err);
|
|
1306
|
+
});
|
|
1307
|
+
const orderedPeriods = periods.toSorted((a, b) => a.id.localeCompare(b.id, "en", { numeric: true }));
|
|
1308
|
+
const orderedLocalities = levels.flatMap((level) => localities.filter((locality) => locality.nivel.id === level));
|
|
1309
|
+
return {
|
|
1310
|
+
title: metadata.nome.trim(),
|
|
1311
|
+
variables: [
|
|
1312
|
+
{
|
|
1313
|
+
code: VARIABLE_CODE,
|
|
1314
|
+
label: "Variável",
|
|
1315
|
+
values: metadata.variaveis.map((variable) => String(variable.id)),
|
|
1316
|
+
valueLabels: metadata.variaveis.map((variable) => withUnit(variable.nome, variable.unidade)),
|
|
1317
|
+
eliminable: false,
|
|
1318
|
+
isTime: false
|
|
1319
|
+
},
|
|
1320
|
+
...metadata.classificacoes.map((classification) => ({
|
|
1321
|
+
code: `c${classification.id}`,
|
|
1322
|
+
label: classification.nome.trim(),
|
|
1323
|
+
values: classification.categorias.map((category) => String(category.id)),
|
|
1324
|
+
valueLabels: classification.categorias.map((category) => category.nome.trim()),
|
|
1325
|
+
eliminable: classification.sumarizacao.status,
|
|
1326
|
+
isTime: false
|
|
1327
|
+
})),
|
|
1328
|
+
{
|
|
1329
|
+
code: LOCALITY_CODE,
|
|
1330
|
+
label: "Localidade",
|
|
1331
|
+
values: orderedLocalities.map((locality) => `${locality.nivel.id}:${locality.id}`),
|
|
1332
|
+
valueLabels: orderedLocalities.map((locality) => locality.nome.trim()),
|
|
1333
|
+
eliminable: levels.includes(COUNTRY_LEVEL),
|
|
1334
|
+
isTime: false
|
|
1335
|
+
},
|
|
1336
|
+
{
|
|
1337
|
+
code: PERIOD_CODE,
|
|
1338
|
+
label: "Período",
|
|
1339
|
+
values: orderedPeriods.map((period) => period.id),
|
|
1340
|
+
valueLabels: orderedPeriods.map((period) => period.literals[0] ?? period.id),
|
|
1341
|
+
eliminable: false,
|
|
1342
|
+
isTime: true
|
|
1343
|
+
}
|
|
1344
|
+
]
|
|
1345
|
+
};
|
|
1346
|
+
}
|
|
1347
|
+
const tables = /* @__PURE__ */ new Map();
|
|
1348
|
+
async function cachedTable(lang, tableId) {
|
|
1349
|
+
checkLanguage$4(lang);
|
|
1350
|
+
if (!TABLE_ID_PATTERN$7.test(tableId)) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it.`, 400);
|
|
1351
|
+
const cached = tables.get(tableId);
|
|
1352
|
+
if (cached && cached.expires > Date.now()) return cached.table;
|
|
1353
|
+
const table = await loadTable(tableId);
|
|
1354
|
+
tables.delete(tableId);
|
|
1355
|
+
tables.set(tableId, {
|
|
1356
|
+
expires: Date.now() + DATA_TTL_SECONDS * 1e3,
|
|
1357
|
+
table
|
|
1358
|
+
});
|
|
1359
|
+
const oldest = tables.keys().next().value;
|
|
1360
|
+
if (tables.size > MAX_CACHED_TABLES$3 && oldest !== void 0) tables.delete(oldest);
|
|
1361
|
+
return table;
|
|
1362
|
+
}
|
|
1363
|
+
return {
|
|
1364
|
+
listTables,
|
|
1365
|
+
async search(lang, query, searchOptions) {
|
|
1366
|
+
checkLanguage$4(lang);
|
|
1367
|
+
return (await tableIndex(lang)).search(query, searchOptions);
|
|
1368
|
+
},
|
|
1369
|
+
async getMetadata(lang, tableId) {
|
|
1370
|
+
return cachedTable(lang, tableId);
|
|
1371
|
+
},
|
|
1372
|
+
async query(lang, tableId, selections) {
|
|
1373
|
+
const table = await cachedTable(lang, tableId);
|
|
1374
|
+
const byCode = new Map(selections.map((selection) => [selection.code, selection]));
|
|
1375
|
+
let locality = `${COUNTRY_LEVEL.toLowerCase()}/all`;
|
|
1376
|
+
let variables = "v/all";
|
|
1377
|
+
let periods = "p/all";
|
|
1378
|
+
const classificationPaths = [];
|
|
1379
|
+
const classifications = [];
|
|
1380
|
+
let cells = 1;
|
|
1381
|
+
for (const variable of table.variables) {
|
|
1382
|
+
const selection = byCode.get(variable.code);
|
|
1383
|
+
if (!selection && variable.eliminable) continue;
|
|
1384
|
+
const codes = chosenCodes$4(variable, selection);
|
|
1385
|
+
cells *= codes?.length ?? variable.values.length;
|
|
1386
|
+
const list = codes?.map(encodeURIComponent).join(",") ?? "all";
|
|
1387
|
+
if (variable.code === LOCALITY_CODE) locality = codes ? localitySegments(codes) : allLevels(variable);
|
|
1388
|
+
else if (variable.code === VARIABLE_CODE) variables = `v/${list}`;
|
|
1389
|
+
else if (variable.code === PERIOD_CODE) periods = `p/${list}`;
|
|
1390
|
+
else {
|
|
1391
|
+
classifications.push(variable);
|
|
1392
|
+
classificationPaths.push(`${variable.code}/${list}`);
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
1395
|
+
if (cells > maxCells) throw new PxwebError(`The query could return ${cells} cells, above the limit of ${maxCells}. Select fewer values.`, 400);
|
|
1396
|
+
const path = [
|
|
1397
|
+
`t/${tableId}`,
|
|
1398
|
+
locality,
|
|
1399
|
+
variables,
|
|
1400
|
+
periods,
|
|
1401
|
+
...classificationPaths
|
|
1402
|
+
].join("/");
|
|
1403
|
+
const rows = await get(`${sidraRoot}/${path}`, valuesSchema$1, DATA_TTL_SECONDS).catch((err) => {
|
|
1404
|
+
if (err instanceof PxwebError && err.status === 400) throw new PxwebError(`SIDRA refused this selection: ${err.message.replace(/^.*?HTTP 400:\s*/, "")}. Check the value codes with get_table_metadata.`, 400);
|
|
1405
|
+
throw upstreamError$1(err);
|
|
1406
|
+
});
|
|
1407
|
+
const variable = table.variables.find((entry) => entry.code === VARIABLE_CODE);
|
|
1408
|
+
const variableLabels = new Map(variable?.values.map((code, index) => [code, variable.valueLabels[index] ?? code]));
|
|
1409
|
+
return {
|
|
1410
|
+
label: table.title,
|
|
1411
|
+
columns: [
|
|
1412
|
+
"Localidade",
|
|
1413
|
+
"Variável",
|
|
1414
|
+
...classifications.map((entry) => entry.label),
|
|
1415
|
+
"Período",
|
|
1416
|
+
"Valor"
|
|
1417
|
+
],
|
|
1418
|
+
rows: rows.slice(1).map((row) => [
|
|
1419
|
+
row.D1N ?? null,
|
|
1420
|
+
variableLabels.get(row.D2C ?? "") ?? row.D2N ?? null,
|
|
1421
|
+
...classifications.map((_, index) => row[`D${index + 4}N`] ?? null),
|
|
1422
|
+
row.D3N ?? null,
|
|
1423
|
+
toNumber$1(row.V)
|
|
1424
|
+
])
|
|
1425
|
+
};
|
|
1426
|
+
}
|
|
1427
|
+
};
|
|
1428
|
+
}
|
|
1429
|
+
// src/ine-es-client.ts
|
|
1430
|
+
const TABLE_ID_PATTERN$6 = /^\d+$/;
|
|
1431
|
+
const LANGUAGES$3 = {
|
|
1432
|
+
es: "ES",
|
|
1433
|
+
en: "EN"
|
|
1434
|
+
};
|
|
1435
|
+
const TIME_CODE$5 = "period";
|
|
1436
|
+
const TIME_LABELS = {
|
|
1437
|
+
es: "Periodo",
|
|
1438
|
+
en: "Period"
|
|
1439
|
+
};
|
|
1440
|
+
const VALUE_LABELS$1 = {
|
|
1441
|
+
es: "Valor",
|
|
1442
|
+
en: "Value"
|
|
1443
|
+
};
|
|
1444
|
+
/** The INE licence asks reusers to give the date of the last update. */
|
|
1445
|
+
const UPDATED_LABELS$1 = {
|
|
1446
|
+
es: "última actualización",
|
|
1447
|
+
en: "last update"
|
|
1448
|
+
};
|
|
1449
|
+
/** DATOS_TABLA without nult or date sends the full history of every series. */
|
|
1450
|
+
const PROBE_PERIODS = 1e4;
|
|
1451
|
+
const MONTHS$2 = [
|
|
1452
|
+
"Jan",
|
|
1453
|
+
"Feb",
|
|
1454
|
+
"Mar",
|
|
1455
|
+
"Apr",
|
|
1456
|
+
"May",
|
|
1457
|
+
"Jun",
|
|
1458
|
+
"Jul",
|
|
1459
|
+
"Aug",
|
|
1460
|
+
"Sep",
|
|
1461
|
+
"Oct",
|
|
1462
|
+
"Nov",
|
|
1463
|
+
"Dec"
|
|
1464
|
+
];
|
|
1465
|
+
const operationsSchema = z.array(z.object({
|
|
1466
|
+
Id: z.number(),
|
|
1467
|
+
Nombre: z.string()
|
|
1468
|
+
}));
|
|
1469
|
+
const tablesSchema = z.array(z.object({
|
|
1470
|
+
Id: z.number(),
|
|
1471
|
+
Nombre: z.string(),
|
|
1472
|
+
Ultima_Modificacion: z.string().optional(),
|
|
1473
|
+
FK_Periodo_fin: z.number().optional(),
|
|
1474
|
+
Anyo_Periodo_fin: z.string().optional()
|
|
1475
|
+
}));
|
|
1476
|
+
const groupsSchema = z.array(z.object({
|
|
1477
|
+
Id: z.number(),
|
|
1478
|
+
Nombre: z.string()
|
|
1479
|
+
}));
|
|
1480
|
+
const valuesSchema = z.array(z.object({
|
|
1481
|
+
Id: z.number(),
|
|
1482
|
+
FK_Variable: z.number(),
|
|
1483
|
+
Nombre: z.string()
|
|
1484
|
+
}));
|
|
1485
|
+
const seriesSchema$1 = z.array(z.object({
|
|
1486
|
+
MetaData: z.array(z.object({ Id: z.number() })).default([]),
|
|
1487
|
+
Data: z.array(z.object({
|
|
1488
|
+
Fecha: z.number(),
|
|
1489
|
+
FK_Periodo: z.number(),
|
|
1490
|
+
Anyo: z.number(),
|
|
1491
|
+
Valor: z.number().nullish(),
|
|
1492
|
+
Secreto: z.boolean().optional()
|
|
1493
|
+
}))
|
|
1494
|
+
}));
|
|
1495
|
+
function periodCode$2(year, period) {
|
|
1496
|
+
if (period >= 1 && period <= 12) return `${year}M${String(period).padStart(2, "0")}`;
|
|
1497
|
+
if (period >= 19 && period <= 22) return `${year}Q${period - 18}`;
|
|
1498
|
+
if (period === 28) return String(year);
|
|
1499
|
+
}
|
|
1500
|
+
/** Fecha is midnight in Madrid; noon UTC of the same instant keeps its calendar day. */
|
|
1501
|
+
function madridDate(fecha) {
|
|
1502
|
+
return new Date(fecha + 432e5).toISOString().slice(0, 10);
|
|
1503
|
+
}
|
|
1504
|
+
function pointCode(point) {
|
|
1505
|
+
return periodCode$2(point.Anyo, point.FK_Periodo) ?? madridDate(point.Fecha);
|
|
1506
|
+
}
|
|
1507
|
+
/** "Fri Nov 13 09:00:00 CET 2026" → "2026-11-13". */
|
|
1508
|
+
function isoDate$2(text) {
|
|
1509
|
+
const match = /^\w{3} (\w{3}) (\d{2}) \S+ \S+ (\d{4})$/.exec(text ?? "");
|
|
1510
|
+
const month = MONTHS$2.indexOf(match?.[1] ?? "");
|
|
1511
|
+
if (!match || month < 0) return void 0;
|
|
1512
|
+
return `${match[3]}-${String(month + 1).padStart(2, "0")}-${match[2]}`;
|
|
1513
|
+
}
|
|
1514
|
+
function notFound$9(tableId) {
|
|
1515
|
+
return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
1516
|
+
}
|
|
1517
|
+
function pathLanguage(lang) {
|
|
1518
|
+
const code = LANGUAGES$3[lang];
|
|
1519
|
+
if (!code) throw new PxwebError(`Language "${lang}" is not supported.`, 400);
|
|
1520
|
+
return code;
|
|
1521
|
+
}
|
|
1522
|
+
function chosenCodes$3(variable, selection) {
|
|
1523
|
+
if (!selection || selection.selection.filter === "all") return [];
|
|
1524
|
+
const { filter, values } = selection.selection;
|
|
1525
|
+
if (filter === "top") return variable.values.slice(-Math.max(1, Number(values[0]) || 1));
|
|
1526
|
+
return values;
|
|
1527
|
+
}
|
|
1528
|
+
function timeParams(table, selection) {
|
|
1529
|
+
const periods = table.periodDates.size;
|
|
1530
|
+
if (!selection || selection.selection.filter === "all") {
|
|
1531
|
+
if (periods === 0) throw new PxwebError(`The periods of this table are not known. Use latest on "${TIME_CODE$5}".`, 400);
|
|
1532
|
+
return { params: [`nult=${periods}`] };
|
|
1533
|
+
}
|
|
1534
|
+
const { filter, values } = selection.selection;
|
|
1535
|
+
if (filter === "top") return { params: [`nult=${Math.max(1, Number(values[0]) || 1)}`] };
|
|
1536
|
+
const dates = values.map((code) => table.periodDates.get(code)).filter((date) => date !== void 0).toSorted();
|
|
1537
|
+
const [first] = dates;
|
|
1538
|
+
const last = dates.at(-1);
|
|
1539
|
+
if (!first || !last) throw new PxwebError(`Unknown periods ${values.join(", ")}. Call get_table_metadata to see valid periods.`, 400);
|
|
1540
|
+
return {
|
|
1541
|
+
params: [`date=${first}:${last}`],
|
|
1542
|
+
keep: new Set(values)
|
|
1543
|
+
};
|
|
1544
|
+
}
|
|
1545
|
+
function createIneEsClient(options) {
|
|
1546
|
+
const root = options.baseUrl.replace(/\/+$/, "");
|
|
1547
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
1548
|
+
const request = createRequester(options);
|
|
1549
|
+
const tableIndex = createTableIndexLoader(async (lang) => {
|
|
1550
|
+
if (!options.tableList) throw new PxwebError("The table list is not available now.", 503);
|
|
1551
|
+
return options.tableList(lang);
|
|
1552
|
+
}, {
|
|
1553
|
+
ttlSeconds: SEARCH_TTL_SECONDS,
|
|
1554
|
+
currentYear: () => now().getUTCFullYear()
|
|
1555
|
+
});
|
|
1556
|
+
function get(url, schema, map, ttlSeconds) {
|
|
1557
|
+
return request(url, { method: "GET" }, schema, map, ttlSeconds, url);
|
|
1558
|
+
}
|
|
1559
|
+
async function titleOf(lang, tableId) {
|
|
1560
|
+
const hit = await tableIndex(lang).then((index) => index.search(tableId)[0]).catch(() => void 0);
|
|
1561
|
+
if (hit?.tableId !== tableId) return `INE ${tableId}`;
|
|
1562
|
+
if (!hit.published) return hit.title;
|
|
1563
|
+
return `${hit.title} (${UPDATED_LABELS$1[lang] ?? UPDATED_LABELS$1.en}: ${hit.published})`;
|
|
1564
|
+
}
|
|
1565
|
+
async function loadTable(lang, tableId) {
|
|
1566
|
+
if (!TABLE_ID_PATTERN$6.test(tableId)) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it.`, 400);
|
|
1567
|
+
const base = `${root}/${pathLanguage(lang)}`;
|
|
1568
|
+
const groups = await get(`${base}/GRUPOS_TABLA/${tableId}`, groupsSchema, (data) => data, METADATA_TTL_SECONDS).catch((err) => {
|
|
1569
|
+
if (err instanceof PxwebError && err.status === 404) throw notFound$9(tableId);
|
|
1570
|
+
throw err;
|
|
1571
|
+
});
|
|
1572
|
+
if (groups.length === 0) throw notFound$9(tableId);
|
|
1573
|
+
const groupValues = await Promise.all(groups.map((group) => get(`${base}/VALORES_GRUPOSTABLA/${tableId}/${group.Id}`, valuesSchema, (data) => data, METADATA_TTL_SECONDS)));
|
|
1574
|
+
const variableOf = /* @__PURE__ */ new Map();
|
|
1575
|
+
const variables = groups.map((group, index) => {
|
|
1576
|
+
const values = groupValues[index] ?? [];
|
|
1577
|
+
for (const value of values) if (!variableOf.has(String(value.Id))) variableOf.set(String(value.Id), value.FK_Variable);
|
|
1578
|
+
return {
|
|
1579
|
+
code: String(group.Id),
|
|
1580
|
+
label: group.Nombre.trim(),
|
|
1581
|
+
values: values.map((value) => String(value.Id)),
|
|
1582
|
+
valueLabels: values.map((value) => value.Nombre.trim()),
|
|
1583
|
+
eliminable: false,
|
|
1584
|
+
isTime: false
|
|
1585
|
+
};
|
|
1586
|
+
});
|
|
1587
|
+
const [series] = await get(`${base}/DATOS_TABLA/${tableId}?${[
|
|
1588
|
+
...groupValues.map((values) => values[0]).filter((value) => value !== void 0).map((value) => `tv=${value.FK_Variable}:${value.Id}`),
|
|
1589
|
+
`nult=${PROBE_PERIODS}`,
|
|
1590
|
+
"tip=M"
|
|
1591
|
+
].join("&")}`, seriesSchema$1, (data) => data, DATA_TTL_SECONDS).catch(() => []);
|
|
1592
|
+
const periodDates = new Map((series?.Data ?? []).toSorted((a, b) => a.Fecha - b.Fecha).map((point) => [pointCode(point), madridDate(point.Fecha).replaceAll("-", "")]));
|
|
1593
|
+
const periods = [...periodDates.keys()];
|
|
1594
|
+
variables.push({
|
|
1595
|
+
code: TIME_CODE$5,
|
|
1596
|
+
label: TIME_LABELS[lang] ?? TIME_CODE$5,
|
|
1597
|
+
values: periods,
|
|
1598
|
+
valueLabels: periods,
|
|
1599
|
+
eliminable: false,
|
|
1600
|
+
isTime: true,
|
|
1601
|
+
...periods.length === 0 && { periodsIncomplete: true }
|
|
1602
|
+
});
|
|
1603
|
+
return {
|
|
1604
|
+
metadata: {
|
|
1605
|
+
title: await titleOf(lang, tableId),
|
|
1606
|
+
variables
|
|
1607
|
+
},
|
|
1608
|
+
variableOf,
|
|
1609
|
+
periodDates
|
|
1610
|
+
};
|
|
1611
|
+
}
|
|
1612
|
+
async function listTables(lang) {
|
|
1613
|
+
const base = `${root}/${pathLanguage(lang)}`;
|
|
1614
|
+
const operations = await get(`${base}/OPERACIONES_DISPONIBLES`, operationsSchema, (data) => data, SEARCH_TTL_SECONDS);
|
|
1615
|
+
const docs = /* @__PURE__ */ new Map();
|
|
1616
|
+
for (const operation of operations) {
|
|
1617
|
+
const tables = await get(`${base}/TABLAS_OPERACION/${operation.Id}`, tablesSchema, (data) => data, SEARCH_TTL_SECONDS);
|
|
1618
|
+
for (const table of tables) {
|
|
1619
|
+
const id = String(table.Id);
|
|
1620
|
+
if (docs.has(id)) continue;
|
|
1621
|
+
const updated = isoDate$2(table.Ultima_Modificacion);
|
|
1622
|
+
const endYear = table.Anyo_Periodo_fin;
|
|
1623
|
+
const lastPeriod = endYear && (periodCode$2(Number(endYear), table.FK_Periodo_fin ?? 0) ?? endYear);
|
|
1624
|
+
docs.set(id, {
|
|
1625
|
+
id,
|
|
1626
|
+
title: table.Nombre.trim(),
|
|
1627
|
+
path: [operation.Nombre.trim()],
|
|
1628
|
+
...updated && { updated },
|
|
1629
|
+
...lastPeriod && { lastPeriod }
|
|
1630
|
+
});
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
return [...docs.values()];
|
|
1634
|
+
}
|
|
1635
|
+
return {
|
|
1636
|
+
listTables,
|
|
1637
|
+
async search(lang, query, searchOptions) {
|
|
1638
|
+
pathLanguage(lang);
|
|
1639
|
+
return (await tableIndex(lang)).search(query, searchOptions);
|
|
1640
|
+
},
|
|
1641
|
+
async getMetadata(lang, tableId) {
|
|
1642
|
+
return (await loadTable(lang, tableId)).metadata;
|
|
1643
|
+
},
|
|
1644
|
+
async query(lang, tableId, selections) {
|
|
1645
|
+
const table = await loadTable(lang, tableId);
|
|
1646
|
+
const byCode = new Map(selections.map((selection) => [selection.code, selection]));
|
|
1647
|
+
const groups = table.metadata.variables.filter((variable) => !variable.isTime);
|
|
1648
|
+
const filters = groups.flatMap((variable) => chosenCodes$3(variable, byCode.get(variable.code)).map((code) => {
|
|
1649
|
+
const variableId = table.variableOf.get(code);
|
|
1650
|
+
if (variableId === void 0) throw new PxwebError(`Variable "${variable.code}" has no value ${code}. Call get_table_metadata to see valid value codes.`, 400);
|
|
1651
|
+
return `tv=${variableId}:${code}`;
|
|
1652
|
+
}));
|
|
1653
|
+
const time = timeParams(table, byCode.get(TIME_CODE$5));
|
|
1654
|
+
const url = `${root}/${pathLanguage(lang)}/DATOS_TABLA/${tableId}?${[
|
|
1655
|
+
...filters,
|
|
1656
|
+
...time.params,
|
|
1657
|
+
"tip=M"
|
|
1658
|
+
].join("&")}`;
|
|
1659
|
+
const labels = groups.map((variable) => new Map(variable.values.map((value, index) => [Number(value), variable.valueLabels[index] ?? value])));
|
|
1660
|
+
return get(url, seriesSchema$1, (series) => ({
|
|
1661
|
+
label: table.metadata.title,
|
|
1662
|
+
columns: [
|
|
1663
|
+
...groups.map((variable) => variable.label),
|
|
1664
|
+
TIME_LABELS[lang] ?? TIME_CODE$5,
|
|
1665
|
+
VALUE_LABELS$1[lang] ?? "Value"
|
|
1666
|
+
],
|
|
1667
|
+
rows: series.flatMap((item) => {
|
|
1668
|
+
const cells = labels.map((byId) => item.MetaData.map((meta) => byId.get(meta.Id)).find((label) => label !== void 0) ?? null);
|
|
1669
|
+
return item.Data.toSorted((a, b) => a.Fecha - b.Fecha).map((point) => ({
|
|
1670
|
+
point,
|
|
1671
|
+
code: pointCode(point)
|
|
1672
|
+
})).filter(({ code }) => !time.keep || time.keep.has(code)).map(({ point, code }) => [
|
|
1673
|
+
...cells,
|
|
1674
|
+
code,
|
|
1675
|
+
point.Secreto ? null : point.Valor ?? null
|
|
1676
|
+
]);
|
|
1677
|
+
})
|
|
1678
|
+
}), DATA_TTL_SECONDS).catch((err) => {
|
|
1679
|
+
if (err instanceof PxwebError && err.status >= 500) throw new PxwebError(`INE could not answer this selection (HTTP ${err.status}). Check the value codes with get_table_metadata, or select fewer values.`, 502);
|
|
1680
|
+
throw err;
|
|
1681
|
+
});
|
|
1682
|
+
}
|
|
1683
|
+
};
|
|
1684
|
+
}
|
|
1685
|
+
// src/ine-pt-client.ts
|
|
1686
|
+
const INDICATOR_PATTERN = /^\d{7}$/;
|
|
1687
|
+
const TIME_DIMENSION = "1";
|
|
1688
|
+
const GEOGRAPHY_DIMENSION = "2";
|
|
1689
|
+
const NOT_FOUND_CODE = "1";
|
|
1690
|
+
/** INE refuses requests above 1,000,000 rows. */
|
|
1691
|
+
const API_MAX_CELLS = 1e6;
|
|
1692
|
+
/** The full catalogue is about 21 MB of XML; downloads have taken from 30 s to more than 120 s. */
|
|
1693
|
+
const CATALOGUE_MAX_BYTES = 67108864;
|
|
1694
|
+
const CATALOGUE_TIMEOUT_MS = 3e5;
|
|
1695
|
+
const failureSchema = z.object({ Sucesso: z.object({ Falso: z.array(z.object({
|
|
1696
|
+
Msg: z.string().optional(),
|
|
1697
|
+
Cod: z.string().optional()
|
|
1698
|
+
})) }) });
|
|
1699
|
+
const categorySchema$1 = z.object({
|
|
1700
|
+
dim_num: z.string(),
|
|
1701
|
+
cat_id: z.string(),
|
|
1702
|
+
categ_dsg: z.string(),
|
|
1703
|
+
categ_ord: z.string().optional()
|
|
1704
|
+
});
|
|
1705
|
+
const indicatorSchema = z.object({
|
|
1706
|
+
IndicadorNome: z.string(),
|
|
1707
|
+
Dimensoes: z.object({
|
|
1708
|
+
Descricao_Dim: z.array(z.object({
|
|
1709
|
+
dim_num: z.string(),
|
|
1710
|
+
abrv: z.string()
|
|
1711
|
+
})),
|
|
1712
|
+
Categoria_Dim: z.array(z.record(z.string(), z.array(categorySchema$1)))
|
|
1713
|
+
})
|
|
1714
|
+
});
|
|
1715
|
+
const dataSetSchema = z.object({ Dados: z.record(z.string(), z.array(z.record(z.string(), z.unknown()))) });
|
|
1716
|
+
const metadataSchema$4 = z.tuple([z.union([indicatorSchema, failureSchema])], z.unknown());
|
|
1717
|
+
const dataSchema$3 = z.tuple([z.union([dataSetSchema, failureSchema])], z.unknown());
|
|
1718
|
+
function notFound$8(tableId) {
|
|
1719
|
+
return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
1720
|
+
}
|
|
1721
|
+
function checkTableId$4(tableId) {
|
|
1722
|
+
if (!INDICATOR_PATTERN.test(tableId)) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it.`, 400);
|
|
1723
|
+
}
|
|
1724
|
+
/** INE answers errors with HTTP 200 and a bilingual message: "(PT) … / (EN) …". */
|
|
1725
|
+
function failure(tableId, data) {
|
|
1726
|
+
const first = data.Sucesso.Falso[0];
|
|
1727
|
+
if (first?.Cod === NOT_FOUND_CODE) return notFound$8(tableId);
|
|
1728
|
+
return new PxwebError(`INE refused the request: ${first?.Msg?.split("(EN)").at(-1)?.trim() || "unknown error"}`, 400);
|
|
1729
|
+
}
|
|
1730
|
+
function toMetadata(tableId, [indicator]) {
|
|
1731
|
+
if (!("IndicadorNome" in indicator)) throw failure(tableId, indicator);
|
|
1732
|
+
const categories = Object.values(indicator.Dimensoes.Categoria_Dim[0] ?? {}).flatMap((entries) => entries.slice(0, 1));
|
|
1733
|
+
return {
|
|
1734
|
+
title: indicator.IndicadorNome,
|
|
1735
|
+
variables: indicator.Dimensoes.Descricao_Dim.map((dimension) => {
|
|
1736
|
+
const own = categories.filter((category) => category.dim_num === dimension.dim_num).toSorted((a, b) => Number(a.categ_ord ?? 0) - Number(b.categ_ord ?? 0));
|
|
1737
|
+
return {
|
|
1738
|
+
code: `Dim${dimension.dim_num}`,
|
|
1739
|
+
label: dimension.abrv,
|
|
1740
|
+
values: own.map((category) => category.cat_id),
|
|
1741
|
+
valueLabels: own.map((category) => category.categ_dsg),
|
|
1742
|
+
eliminable: false,
|
|
1743
|
+
isTime: dimension.dim_num === TIME_DIMENSION
|
|
1744
|
+
};
|
|
1745
|
+
})
|
|
1746
|
+
};
|
|
1747
|
+
}
|
|
1748
|
+
/** Codes to request, or undefined to leave the dimension out (INE then returns all of it). */
|
|
1749
|
+
function requestedCodes$1(variable, selection) {
|
|
1750
|
+
const filter = selection?.selection.filter ?? "all";
|
|
1751
|
+
if (filter === "top") {
|
|
1752
|
+
const count = Math.max(1, Number(selection?.selection.values[0]) || 1);
|
|
1753
|
+
return variable.values.slice(-count);
|
|
1754
|
+
}
|
|
1755
|
+
if (filter === "item") return selection?.selection.values ?? [];
|
|
1756
|
+
return variable.isTime ? variable.values : void 0;
|
|
1757
|
+
}
|
|
1758
|
+
function rowCode(row, variable) {
|
|
1759
|
+
const number = variable.slice(3);
|
|
1760
|
+
return String(number === GEOGRAPHY_DIMENSION ? row.geocod : row[`dim_${number}`]);
|
|
1761
|
+
}
|
|
1762
|
+
function numberOrNull$1(value) {
|
|
1763
|
+
if (typeof value !== "string" || value.trim() === "") return null;
|
|
1764
|
+
const parsed = Number(value);
|
|
1765
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
1766
|
+
}
|
|
1767
|
+
const compareOrder = (a, b) => a.reduce((result, value, i) => result || value - (b[i] ?? 0), 0);
|
|
1768
|
+
const apiLang = (lang) => encodeURIComponent(lang.toUpperCase());
|
|
1769
|
+
const positions = (keys) => new Map(keys.map((key, index) => [key, index]));
|
|
1770
|
+
/** Data comes grouped by period label in no useful order, so rows are sorted like the metadata. */
|
|
1771
|
+
function toFlatTable$1(metadata, dados) {
|
|
1772
|
+
const time = metadata.variables.find((variable) => variable.isTime);
|
|
1773
|
+
const others = metadata.variables.filter((variable) => !variable.isTime);
|
|
1774
|
+
const periodIndex = positions(time?.valueLabels ?? []);
|
|
1775
|
+
const indexes = others.map((variable) => positions(variable.values));
|
|
1776
|
+
const rows = Object.entries(dados).flatMap(([period, entries]) => entries.map((entry) => {
|
|
1777
|
+
const codes = others.map((variable) => rowCode(entry, variable.code));
|
|
1778
|
+
const order = codes.map((code, d) => indexes[d]?.get(code) ?? -1);
|
|
1779
|
+
const labels = codes.map((code, d) => others[d]?.valueLabels[order[d] ?? -1] ?? code);
|
|
1780
|
+
return {
|
|
1781
|
+
order: [periodIndex.get(period) ?? -1, ...order],
|
|
1782
|
+
cells: [
|
|
1783
|
+
period,
|
|
1784
|
+
...labels,
|
|
1785
|
+
numberOrNull$1(entry.valor)
|
|
1786
|
+
]
|
|
1787
|
+
};
|
|
1788
|
+
}));
|
|
1789
|
+
return {
|
|
1790
|
+
label: metadata.title,
|
|
1791
|
+
columns: [
|
|
1792
|
+
...time ? [time.label] : [],
|
|
1793
|
+
...others.map((variable) => variable.label),
|
|
1794
|
+
"Value"
|
|
1795
|
+
],
|
|
1796
|
+
rows: rows.toSorted((a, b) => compareOrder(a.order, b.order)).map((row) => row.cells)
|
|
1797
|
+
};
|
|
1798
|
+
}
|
|
1799
|
+
const field = (block, name) => new RegExp(`<${name}>\\s*(?:<!\\[CDATA\\[([\\s\\S]*?)\\]\\]>|([^<]*))\\s*</${name}>`).exec(block)?.slice(1).find((value) => value !== void 0)?.trim() || void 0;
|
|
1800
|
+
function isoDate$1(day) {
|
|
1801
|
+
const match = /^(\d{2})-(\d{2})-(\d{4})$/.exec(day ?? "");
|
|
1802
|
+
return match ? `${match[3]}-${match[2]}-${match[1]}` : void 0;
|
|
1803
|
+
}
|
|
1804
|
+
/**
|
|
1805
|
+
* Many indicators share a short title ("Resident population (No.)"), so the
|
|
1806
|
+
* title is the description, which adds the dimensions and the source. The
|
|
1807
|
+
* catalogue has no meaningful order, so the most recently updated go first
|
|
1808
|
+
* (sorting by last period would put projections to 2100 first).
|
|
1809
|
+
*/
|
|
1810
|
+
function parseCatalogue(xml) {
|
|
1811
|
+
return [...xml.matchAll(/<indicator id="(\d{7})">([\s\S]*?)<\/indicator>/g)].flatMap(([, id = "", block = ""]) => {
|
|
1812
|
+
const title = field(block, "description") ?? field(block, "title");
|
|
1813
|
+
if (!title) return [];
|
|
1814
|
+
const path = [field(block, "theme"), field(block, "subtheme")].filter((part) => part !== void 0);
|
|
1815
|
+
const updated = isoDate$1(field(block, "last_update"));
|
|
1816
|
+
const lastPeriod = field(block, "last_period_available")?.replace(/^S?\d+A/, "");
|
|
1817
|
+
return [{
|
|
1818
|
+
id,
|
|
1819
|
+
title,
|
|
1820
|
+
...path.length ? { path } : {},
|
|
1821
|
+
...updated ? { updated } : {},
|
|
1822
|
+
...lastPeriod ? { lastPeriod } : {}
|
|
1823
|
+
}];
|
|
1824
|
+
}).toSorted((a, b) => (b.updated ?? "").localeCompare(a.updated ?? "") || a.id.localeCompare(b.id));
|
|
1825
|
+
}
|
|
1826
|
+
function createInePtClient(options) {
|
|
1827
|
+
const root = options.baseUrl.replace(/\/+$/, "");
|
|
1828
|
+
const maxCells = options.maxCells ?? API_MAX_CELLS;
|
|
1829
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
1830
|
+
const request = createRequester(options);
|
|
1831
|
+
const doFetch = options.fetch ?? fetch;
|
|
1832
|
+
const tableIndex = createTableIndexLoader(async (lang) => {
|
|
1833
|
+
if (!options.tableList) throw new PxwebError("The table list is not available now.", 503);
|
|
1834
|
+
return options.tableList(lang);
|
|
1835
|
+
}, {
|
|
1836
|
+
ttlSeconds: SEARCH_TTL_SECONDS,
|
|
1837
|
+
currentYear: () => now().getUTCFullYear()
|
|
1838
|
+
});
|
|
1839
|
+
async function getMetadata(lang, tableId) {
|
|
1840
|
+
checkTableId$4(tableId);
|
|
1841
|
+
const url = `${root}/json_indicador/pindicaMeta.jsp?varcd=${tableId}&lang=${apiLang(lang)}`;
|
|
1842
|
+
return request(url, { method: "GET" }, metadataSchema$4, (data) => toMetadata(tableId, data), METADATA_TTL_SECONDS, `meta:${url}`);
|
|
1843
|
+
}
|
|
1844
|
+
return {
|
|
1845
|
+
async search(lang, query, searchOptions) {
|
|
1846
|
+
return (await tableIndex(lang)).search(query, searchOptions);
|
|
1847
|
+
},
|
|
1848
|
+
getMetadata,
|
|
1849
|
+
async listTables(lang) {
|
|
1850
|
+
const url = `${root}/xml_indic.jsp?opc=2&lang=${apiLang(lang)}`;
|
|
1851
|
+
const response = await doFetch(url, {
|
|
1852
|
+
headers: options.userAgent ? { "user-agent": options.userAgent } : {},
|
|
1853
|
+
signal: AbortSignal.timeout(CATALOGUE_TIMEOUT_MS)
|
|
1854
|
+
}).catch((err) => {
|
|
1855
|
+
throw new PxwebError(`INE catalogue request failed: ${err instanceof Error ? err.message : String(err)}`, 502);
|
|
1856
|
+
});
|
|
1857
|
+
const xml = await readCappedText(response, CATALOGUE_MAX_BYTES);
|
|
1858
|
+
if (!response.ok) throw new PxwebError(`INE catalogue returned HTTP ${response.status}.`, response.status);
|
|
1859
|
+
if (!/<\/catalog>\s*$/.test(xml)) throw new PxwebError("INE returned an incomplete catalogue.", 502);
|
|
1860
|
+
const docs = parseCatalogue(xml);
|
|
1861
|
+
if (docs.length === 0) throw new PxwebError("INE returned an empty catalogue.", 502);
|
|
1862
|
+
return docs;
|
|
1863
|
+
},
|
|
1864
|
+
async query(lang, tableId, selections) {
|
|
1865
|
+
const metadata = await getMetadata(lang, tableId);
|
|
1866
|
+
const byCode = new Map(selections.map((selection) => [selection.code, selection]));
|
|
1867
|
+
let cells = 1;
|
|
1868
|
+
const params = [`op=2`, `varcd=${tableId}`];
|
|
1869
|
+
for (const variable of metadata.variables) {
|
|
1870
|
+
const codes = requestedCodes$1(variable, byCode.get(variable.code));
|
|
1871
|
+
cells *= codes?.length ?? variable.values.length;
|
|
1872
|
+
if (codes) params.push(`${variable.code}=${codes.map(encodeURIComponent).join(",")}`);
|
|
1873
|
+
}
|
|
1874
|
+
if (cells > maxCells) throw new PxwebError(`The query would return ${cells} cells, above the limit of ${maxCells}. Select fewer values.`, 400);
|
|
1875
|
+
params.push(`lang=${apiLang(lang)}`);
|
|
1876
|
+
const url = `${root}/json_indicador/pindica.jsp?${params.join("&")}`;
|
|
1877
|
+
return request(url, { method: "GET" }, dataSchema$3, ([data]) => {
|
|
1878
|
+
if (!("Dados" in data)) throw failure(tableId, data);
|
|
1879
|
+
return toFlatTable$1(metadata, data.Dados);
|
|
1880
|
+
}, DATA_TTL_SECONDS, `data:${url}`);
|
|
1881
|
+
}
|
|
1882
|
+
};
|
|
1883
|
+
}
|
|
1884
|
+
// src/insee-client.ts
|
|
1885
|
+
const TABLE_ID_PATTERN$5 = /^[A-Z][A-Z0-9_]{0,99}$/;
|
|
1886
|
+
const LANGUAGES$2 = /* @__PURE__ */ new Set(["fr", "en"]);
|
|
1887
|
+
const TIME_CODE$4 = "TIME_PERIOD";
|
|
1888
|
+
/** Data answers name a territory with its vintage ("2025-DEP-976"); filters take "DEP-976". */
|
|
1889
|
+
const GEO_VINTAGE = /^\d{4}-/;
|
|
1890
|
+
const DEFAULT_MAX_CELLS$3 = 1e5;
|
|
1891
|
+
const MAX_CACHED_TABLES$2 = 20;
|
|
1892
|
+
const VALUE_LABELS = {
|
|
1893
|
+
fr: "Valeur",
|
|
1894
|
+
en: "Value"
|
|
1895
|
+
};
|
|
1896
|
+
/** Licence Ouverte asks reusers to give the date of the last update. */
|
|
1897
|
+
const UPDATED_LABELS = {
|
|
1898
|
+
fr: "dernière mise à jour",
|
|
1899
|
+
en: "last update"
|
|
1900
|
+
};
|
|
1901
|
+
const labelsSchema = z.record(z.string(), z.string()).optional();
|
|
1902
|
+
const textsSchema = z.array(z.object({
|
|
1903
|
+
content: z.string().optional(),
|
|
1904
|
+
lang: z.string()
|
|
1905
|
+
})).nullish();
|
|
1906
|
+
const rangeSchema = z.object({
|
|
1907
|
+
label: labelsSchema,
|
|
1908
|
+
range: z.array(z.object({
|
|
1909
|
+
concept: z.object({
|
|
1910
|
+
code: z.string(),
|
|
1911
|
+
label: labelsSchema
|
|
1912
|
+
}),
|
|
1913
|
+
type: z.string(),
|
|
1914
|
+
values: z.array(z.object({
|
|
1915
|
+
code: z.string(),
|
|
1916
|
+
id: z.string().optional(),
|
|
1917
|
+
label: labelsSchema
|
|
1918
|
+
})).nullish()
|
|
1919
|
+
}))
|
|
1920
|
+
});
|
|
1921
|
+
const dataSchema$2 = z.object({ observations: z.array(z.object({
|
|
1922
|
+
dimensions: z.record(z.string(), z.string().nullable()),
|
|
1923
|
+
measures: z.record(z.string(), z.object({ value: z.unknown().optional() }).nullable()).optional()
|
|
1924
|
+
})) });
|
|
1925
|
+
const catalogSchema = z.array(z.object({
|
|
1926
|
+
identifier: z.string(),
|
|
1927
|
+
title: textsSchema,
|
|
1928
|
+
modified: z.string().nullish(),
|
|
1929
|
+
numObservations: z.number().nullish(),
|
|
1930
|
+
temporal: z.object({ endPeriod: z.string().optional() }).nullish(),
|
|
1931
|
+
theme: z.array(z.object({
|
|
1932
|
+
label: textsSchema,
|
|
1933
|
+
themeTaxonomy: z.string()
|
|
1934
|
+
})).nullish()
|
|
1935
|
+
}));
|
|
1936
|
+
function text(texts, lang) {
|
|
1937
|
+
const pick = (wanted) => texts?.find((item) => item.lang === wanted)?.content?.trim();
|
|
1938
|
+
return pick(lang) || pick("fr");
|
|
1939
|
+
}
|
|
1940
|
+
function label$1(labels, lang, fallback) {
|
|
1941
|
+
return (labels?.[lang] ?? labels?.fr ?? fallback).trim();
|
|
1942
|
+
}
|
|
1943
|
+
function byPeriod(a, b) {
|
|
1944
|
+
return a.localeCompare(b, "en", { numeric: true });
|
|
1945
|
+
}
|
|
1946
|
+
/** "2026", "2026-09" and "2026-Q3" have different shapes: one per frequency. */
|
|
1947
|
+
function periodShape(code) {
|
|
1948
|
+
return code.replace(/\d/g, "9");
|
|
1949
|
+
}
|
|
1950
|
+
/** `latest` picks the newest periods of each frequency, so annual and monthly series both get data. */
|
|
1951
|
+
function newestPerFrequency$1(codes, count) {
|
|
1952
|
+
const byShape = /* @__PURE__ */ new Map();
|
|
1953
|
+
for (const code of codes) {
|
|
1954
|
+
const shape = periodShape(code);
|
|
1955
|
+
byShape.set(shape, [...byShape.get(shape) ?? [], code]);
|
|
1956
|
+
}
|
|
1957
|
+
return [...byShape.values()].flatMap((list) => list.slice(-count));
|
|
1958
|
+
}
|
|
1959
|
+
function chosenCodes$2(variable, selection) {
|
|
1960
|
+
if (!selection || selection.selection.filter === "all") return [];
|
|
1961
|
+
const { filter, values } = selection.selection;
|
|
1962
|
+
if (filter === "item") return values;
|
|
1963
|
+
const count = Math.max(1, Number(values[0]) || 1);
|
|
1964
|
+
if (variable.isTime) return newestPerFrequency$1(variable.values, count);
|
|
1965
|
+
return variable.values.slice(-count);
|
|
1966
|
+
}
|
|
1967
|
+
function compareKeys$1(a, b) {
|
|
1968
|
+
for (const [index, value] of a.entries()) {
|
|
1969
|
+
const difference = value - (b[index] ?? 0);
|
|
1970
|
+
if (difference !== 0) return difference;
|
|
1971
|
+
}
|
|
1972
|
+
return 0;
|
|
1973
|
+
}
|
|
1974
|
+
function notFound$7(tableId) {
|
|
1975
|
+
return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
1976
|
+
}
|
|
1977
|
+
function checkLanguage$3(lang) {
|
|
1978
|
+
if (!LANGUAGES$2.has(lang)) throw new PxwebError(`Language "${lang}" is not supported.`, 400);
|
|
1979
|
+
}
|
|
1980
|
+
function toVariables(range, dimensions, lang) {
|
|
1981
|
+
const variables = range.range.filter((entry) => dimensions.has(entry.concept.code)).map((entry) => {
|
|
1982
|
+
const values = (entry.values ?? []).map((value) => ({
|
|
1983
|
+
code: entry.type === "geo" && value.id ? value.id.replace(GEO_VINTAGE, "") : value.code,
|
|
1984
|
+
label: label$1(value.label, lang, value.code)
|
|
1985
|
+
}));
|
|
1986
|
+
const isTime = entry.concept.code === TIME_CODE$4;
|
|
1987
|
+
if (isTime) values.sort((a, b) => byPeriod(a.code, b.code));
|
|
1988
|
+
return {
|
|
1989
|
+
code: entry.concept.code,
|
|
1990
|
+
label: label$1(entry.concept.label, lang, entry.concept.code),
|
|
1991
|
+
values: values.map((value) => value.code),
|
|
1992
|
+
valueLabels: values.map((value) => value.label),
|
|
1993
|
+
eliminable: false,
|
|
1994
|
+
isTime
|
|
1995
|
+
};
|
|
1996
|
+
});
|
|
1997
|
+
return [...variables.filter((variable) => !variable.isTime), ...variables.filter((variable) => variable.isTime)];
|
|
1998
|
+
}
|
|
1999
|
+
function measureValue(observation) {
|
|
2000
|
+
const value = Object.values(observation.measures ?? {})[0]?.value;
|
|
2001
|
+
return typeof value === "number" ? value : null;
|
|
2002
|
+
}
|
|
2003
|
+
function createInseeClient(options) {
|
|
2004
|
+
const root = options.baseUrl.replace(/\/+$/, "");
|
|
2005
|
+
const maxCells = options.maxCells ?? DEFAULT_MAX_CELLS$3;
|
|
2006
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
2007
|
+
const request = createRequester(options);
|
|
2008
|
+
const tableIndex = createTableIndexLoader(async (lang) => {
|
|
2009
|
+
if (!options.tableList) throw new PxwebError("The table list is not available now.", 503);
|
|
2010
|
+
return options.tableList(lang);
|
|
2011
|
+
}, {
|
|
2012
|
+
ttlSeconds: SEARCH_TTL_SECONDS,
|
|
2013
|
+
currentYear: () => now().getUTCFullYear()
|
|
2014
|
+
});
|
|
2015
|
+
function get(url, schema, map, ttlSeconds) {
|
|
2016
|
+
return request(url, {
|
|
2017
|
+
method: "GET",
|
|
2018
|
+
headers: { "accept-encoding": "gzip" }
|
|
2019
|
+
}, schema, map, ttlSeconds, url);
|
|
2020
|
+
}
|
|
2021
|
+
async function titleOf(lang, tableId, title) {
|
|
2022
|
+
const hit = await tableIndex(lang).then((index) => index.search(tableId)[0]).catch(() => void 0);
|
|
2023
|
+
if (hit?.tableId !== tableId || !hit.published) return title;
|
|
2024
|
+
return `${title} (${UPDATED_LABELS[lang] ?? UPDATED_LABELS.en}: ${hit.published})`;
|
|
2025
|
+
}
|
|
2026
|
+
const tables = /* @__PURE__ */ new Map();
|
|
2027
|
+
async function cachedTable(lang, tableId) {
|
|
2028
|
+
const key = `${lang}:${tableId}`;
|
|
2029
|
+
const cached = tables.get(key);
|
|
2030
|
+
if (cached && cached.expires > Date.now()) return cached.table;
|
|
2031
|
+
const table = await loadTable(lang, tableId);
|
|
2032
|
+
tables.delete(key);
|
|
2033
|
+
tables.set(key, {
|
|
2034
|
+
expires: Date.now() + METADATA_TTL_SECONDS * 1e3,
|
|
2035
|
+
table
|
|
2036
|
+
});
|
|
2037
|
+
const oldest = tables.keys().next().value;
|
|
2038
|
+
if (tables.size > MAX_CACHED_TABLES$2 && oldest !== void 0) tables.delete(oldest);
|
|
2039
|
+
return table;
|
|
2040
|
+
}
|
|
2041
|
+
async function loadTable(lang, tableId) {
|
|
2042
|
+
checkLanguage$3(lang);
|
|
2043
|
+
if (!TABLE_ID_PATTERN$5.test(tableId)) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it.`, 400);
|
|
2044
|
+
const [range, probe] = await Promise.all([get(`${root}/range/${tableId}`, rangeSchema, (data) => data, METADATA_TTL_SECONDS), get(`${root}/data/${tableId}?maxResult=1`, dataSchema$2, (data) => data.observations[0], METADATA_TTL_SECONDS)]).catch((err) => {
|
|
2045
|
+
if (err instanceof PxwebError && (err.status === 400 || err.status === 404)) throw notFound$7(tableId);
|
|
2046
|
+
throw err;
|
|
2047
|
+
});
|
|
2048
|
+
if (!probe) throw new PxwebError(`Dataset "${tableId}" has no data. Use search_tables to find a current dataset.`, 404);
|
|
2049
|
+
const variables = toVariables(range, new Set(Object.keys(probe.dimensions)), lang);
|
|
2050
|
+
const geoCodes = new Set(range.range.filter((entry) => entry.type === "geo").map((entry) => entry.concept.code));
|
|
2051
|
+
return {
|
|
2052
|
+
metadata: {
|
|
2053
|
+
title: await titleOf(lang, tableId, label$1(range.label, lang, tableId)),
|
|
2054
|
+
variables
|
|
2055
|
+
},
|
|
2056
|
+
geoCodes
|
|
2057
|
+
};
|
|
2058
|
+
}
|
|
2059
|
+
async function listTables(lang) {
|
|
2060
|
+
checkLanguage$3(lang);
|
|
2061
|
+
return get(`${root}/catalog/all`, catalogSchema, (datasets) => datasets.map((dataset) => {
|
|
2062
|
+
const theme = dataset.theme?.find((item) => item.themeTaxonomy === "inseeTheme");
|
|
2063
|
+
const folder = theme && text(theme.label, lang);
|
|
2064
|
+
const updated = dataset.modified?.slice(0, 10);
|
|
2065
|
+
const lastPeriod = dataset.temporal?.endPeriod?.slice(0, 4);
|
|
2066
|
+
return {
|
|
2067
|
+
id: dataset.identifier,
|
|
2068
|
+
title: text(dataset.title, lang) ?? dataset.identifier,
|
|
2069
|
+
...folder && { path: [folder] },
|
|
2070
|
+
...updated && { updated },
|
|
2071
|
+
...lastPeriod && { lastPeriod },
|
|
2072
|
+
...!dataset.numObservations && { discontinued: true }
|
|
2073
|
+
};
|
|
2074
|
+
}), SEARCH_TTL_SECONDS);
|
|
2075
|
+
}
|
|
2076
|
+
return {
|
|
2077
|
+
listTables,
|
|
2078
|
+
async search(lang, query, searchOptions) {
|
|
2079
|
+
checkLanguage$3(lang);
|
|
2080
|
+
return (await tableIndex(lang)).search(query, searchOptions);
|
|
2081
|
+
},
|
|
2082
|
+
async getMetadata(lang, tableId) {
|
|
2083
|
+
return (await cachedTable(lang, tableId)).metadata;
|
|
2084
|
+
},
|
|
2085
|
+
async query(lang, tableId, selections) {
|
|
2086
|
+
const table = await cachedTable(lang, tableId);
|
|
2087
|
+
const { variables } = table.metadata;
|
|
2088
|
+
const byCode = new Map(selections.map((selection) => [selection.code, selection]));
|
|
2089
|
+
const params = [];
|
|
2090
|
+
let cells = 1;
|
|
2091
|
+
let periods;
|
|
2092
|
+
for (const variable of variables) {
|
|
2093
|
+
const codes = chosenCodes$2(variable, byCode.get(variable.code));
|
|
2094
|
+
cells *= codes.length || variable.values.length;
|
|
2095
|
+
if (variable.isTime && codes.length > 0) periods = new Set(codes);
|
|
2096
|
+
for (const code of codes) params.push(`${encodeURIComponent(variable.code)}=${encodeURIComponent(code)}`);
|
|
2097
|
+
}
|
|
2098
|
+
if (cells > maxCells) throw new PxwebError(`The query could return ${cells} cells, above the limit of ${maxCells}. Select fewer values.`, 400);
|
|
2099
|
+
const timeIndex = variables.findIndex((variable) => variable.isTime);
|
|
2100
|
+
const frequencies = new Set(variables[timeIndex]?.values.map(periodShape)).size || 1;
|
|
2101
|
+
const url = `${root}/data/${tableId}?${[...params, `maxResult=${Math.max(1, cells * frequencies)}`].join("&")}`;
|
|
2102
|
+
const positions = variables.map((variable) => new Map(variable.values.map((value, index) => [value, index])));
|
|
2103
|
+
const toRow = (observation) => {
|
|
2104
|
+
const codes = variables.map((variable) => {
|
|
2105
|
+
const raw = observation.dimensions[variable.code] ?? "";
|
|
2106
|
+
return table.geoCodes.has(variable.code) ? raw.replace(GEO_VINTAGE, "") : raw;
|
|
2107
|
+
});
|
|
2108
|
+
return {
|
|
2109
|
+
codes,
|
|
2110
|
+
key: codes.map((code, index) => positions[index]?.get(code) ?? Number.MAX_SAFE_INTEGER),
|
|
2111
|
+
value: measureValue(observation)
|
|
2112
|
+
};
|
|
2113
|
+
};
|
|
2114
|
+
return get(url, dataSchema$2, (data) => ({
|
|
2115
|
+
label: table.metadata.title,
|
|
2116
|
+
columns: [...variables.map((variable) => variable.label), VALUE_LABELS[lang] ?? "Value"],
|
|
2117
|
+
rows: data.observations.map(toRow).filter(({ codes }) => !periods || periods.has(codes[timeIndex] ?? "")).toSorted((a, b) => compareKeys$1(a.key, b.key)).map(({ codes, key, value }) => [...codes.map((code, index) => variables[index]?.valueLabels[key[index] ?? -1] ?? code), value])
|
|
2118
|
+
}), DATA_TTL_SECONDS).catch((err) => {
|
|
2119
|
+
if (err instanceof PxwebError && err.status === 400) throw new PxwebError(`INSEE refused this selection: ${err.message.replace(/^PxWeb returned HTTP 400: /, "")}. Check the value codes with get_table_metadata.`, 400);
|
|
2120
|
+
if (err instanceof PxwebError && err.status >= 500) throw new PxwebError(`INSEE could not answer this selection (HTTP ${err.status}). Select fewer values or try again later.`, 502);
|
|
2121
|
+
throw err;
|
|
2122
|
+
});
|
|
2123
|
+
}
|
|
2124
|
+
};
|
|
2125
|
+
}
|
|
2126
|
+
// src/ons-client.ts
|
|
2127
|
+
const ONS_SITE = "https://www.ons.gov.uk";
|
|
2128
|
+
const TABLE_ID_PATTERN$4 = /^([A-Z0-9]{1,20})\/([A-Z0-9]{1,20})$/i;
|
|
2129
|
+
const FREQUENCY_CODE = "frequency";
|
|
2130
|
+
const FREQUENCY_LABEL = "Frequency";
|
|
2131
|
+
const TIME_CODE$3 = "period";
|
|
2132
|
+
const TIME_LABEL$1 = "Period";
|
|
2133
|
+
const SEARCH_LIMIT = 50;
|
|
2134
|
+
const DEFAULT_MAX_CELLS$2 = 5e3;
|
|
2135
|
+
const MAX_KNOWN_URIS = 1e3;
|
|
2136
|
+
const FREQUENCIES = [
|
|
2137
|
+
{
|
|
2138
|
+
key: "years",
|
|
2139
|
+
code: "A",
|
|
2140
|
+
label: "Annual"
|
|
2141
|
+
},
|
|
2142
|
+
{
|
|
2143
|
+
key: "quarters",
|
|
2144
|
+
code: "Q",
|
|
2145
|
+
label: "Quarterly"
|
|
2146
|
+
},
|
|
2147
|
+
{
|
|
2148
|
+
key: "months",
|
|
2149
|
+
code: "M",
|
|
2150
|
+
label: "Monthly"
|
|
2151
|
+
}
|
|
2152
|
+
];
|
|
2153
|
+
const MONTHS$1 = [
|
|
2154
|
+
"JAN",
|
|
2155
|
+
"FEB",
|
|
2156
|
+
"MAR",
|
|
2157
|
+
"APR",
|
|
2158
|
+
"MAY",
|
|
2159
|
+
"JUN",
|
|
2160
|
+
"JUL",
|
|
2161
|
+
"AUG",
|
|
2162
|
+
"SEP",
|
|
2163
|
+
"OCT",
|
|
2164
|
+
"NOV",
|
|
2165
|
+
"DEC"
|
|
2166
|
+
];
|
|
2167
|
+
const searchSchema$1 = z.object({ items: z.array(z.object({
|
|
2168
|
+
cdid: z.string().nullish(),
|
|
2169
|
+
dataset_id: z.string().nullish(),
|
|
2170
|
+
release_date: z.string().nullish(),
|
|
2171
|
+
title: z.string(),
|
|
2172
|
+
uri: z.string()
|
|
2173
|
+
})) });
|
|
2174
|
+
const pointsSchema = z.array(z.object({
|
|
2175
|
+
date: z.string(),
|
|
2176
|
+
value: z.string(),
|
|
2177
|
+
label: z.string().nullish()
|
|
2178
|
+
})).nullish();
|
|
2179
|
+
const seriesSchema = z.object({
|
|
2180
|
+
description: z.object({
|
|
2181
|
+
title: z.string(),
|
|
2182
|
+
unit: z.string().nullish(),
|
|
2183
|
+
preUnit: z.string().nullish(),
|
|
2184
|
+
datasetId: z.string(),
|
|
2185
|
+
releaseDate: z.string().nullish(),
|
|
2186
|
+
nextRelease: z.string().nullish()
|
|
2187
|
+
}),
|
|
2188
|
+
years: pointsSchema,
|
|
2189
|
+
quarters: pointsSchema,
|
|
2190
|
+
months: pointsSchema
|
|
2191
|
+
});
|
|
2192
|
+
const knownUris = /* @__PURE__ */ new Map();
|
|
2193
|
+
function rememberUri(tableId, uri) {
|
|
2194
|
+
knownUris.delete(tableId);
|
|
2195
|
+
knownUris.set(tableId, uri);
|
|
2196
|
+
const oldest = knownUris.keys().next().value;
|
|
2197
|
+
if (knownUris.size > MAX_KNOWN_URIS && oldest !== void 0) knownUris.delete(oldest);
|
|
2198
|
+
}
|
|
2199
|
+
/** The series page after this process resolved the id, otherwise an ONS search for its CDID. */
|
|
2200
|
+
function onsTableUrl(tableId) {
|
|
2201
|
+
const id = tableId.trim().toUpperCase();
|
|
2202
|
+
const uri = knownUris.get(id);
|
|
2203
|
+
if (uri) return `${ONS_SITE}${uri}`;
|
|
2204
|
+
const cdid = id.split("/").at(-1) ?? id;
|
|
2205
|
+
return `${ONS_SITE}/search?q=${encodeURIComponent(cdid)}&filter=time_series`;
|
|
2206
|
+
}
|
|
2207
|
+
function hitId(item) {
|
|
2208
|
+
if (!item.cdid || !item.dataset_id || !item.uri.startsWith("/")) return;
|
|
2209
|
+
const id = `${item.dataset_id}/${item.cdid}`.toUpperCase();
|
|
2210
|
+
return TABLE_ID_PATTERN$4.test(id) ? id : void 0;
|
|
2211
|
+
}
|
|
2212
|
+
/** ONS writes UK midnight as UTC ("2026-09-29T23:00Z" is 30 September); noon keeps the UK day. */
|
|
2213
|
+
function ukDate(timestamp) {
|
|
2214
|
+
const time = Date.parse(timestamp ?? "");
|
|
2215
|
+
if (Number.isNaN(time)) return void 0;
|
|
2216
|
+
return new Date(time + 432e5).toISOString().slice(0, 10);
|
|
2217
|
+
}
|
|
2218
|
+
/** "2025" → "2025", "2026 Q3" → "2026-Q3", "2026 OCT" → "2026-10". */
|
|
2219
|
+
function periodCode$1(date) {
|
|
2220
|
+
const [year, part] = date.trim().split(/\s+/);
|
|
2221
|
+
if (!part) return date.trim();
|
|
2222
|
+
const month = MONTHS$1.indexOf(part.toUpperCase());
|
|
2223
|
+
if (month >= 0) return `${year}-${String(month + 1).padStart(2, "0")}`;
|
|
2224
|
+
return `${year}-${part}`;
|
|
2225
|
+
}
|
|
2226
|
+
function numeric(value) {
|
|
2227
|
+
const number = Number(value);
|
|
2228
|
+
return value.trim() === "" || !Number.isFinite(number) ? null : number;
|
|
2229
|
+
}
|
|
2230
|
+
function seriesTitle(tableId, series) {
|
|
2231
|
+
const { description } = series;
|
|
2232
|
+
const unit = `${description.preUnit ?? ""}${description.unit ?? ""}`.trim();
|
|
2233
|
+
const released = ukDate(description.releaseDate);
|
|
2234
|
+
const notes = [
|
|
2235
|
+
`dataset ${description.datasetId.toUpperCase()}`,
|
|
2236
|
+
unit && `unit: ${unit}`,
|
|
2237
|
+
released && `last update: ${released}`,
|
|
2238
|
+
description.nextRelease && `next release: ${description.nextRelease}`
|
|
2239
|
+
].filter(Boolean);
|
|
2240
|
+
return `${description.title.trim() || tableId} (${notes.join("; ")})`;
|
|
2241
|
+
}
|
|
2242
|
+
function toTable$2(tableId, series) {
|
|
2243
|
+
const points = /* @__PURE__ */ new Map();
|
|
2244
|
+
for (const frequency of FREQUENCIES) {
|
|
2245
|
+
const list = (series[frequency.key] ?? []).map((point) => ({
|
|
2246
|
+
code: periodCode$1(point.date),
|
|
2247
|
+
label: point.label?.trim() || point.date.trim(),
|
|
2248
|
+
value: numeric(point.value)
|
|
2249
|
+
}));
|
|
2250
|
+
if (list.length > 0) points.set(frequency.code, list);
|
|
2251
|
+
}
|
|
2252
|
+
const present = FREQUENCIES.filter((frequency) => points.has(frequency.code));
|
|
2253
|
+
const periods = [...points.values()].flat();
|
|
2254
|
+
return {
|
|
2255
|
+
metadata: {
|
|
2256
|
+
title: seriesTitle(tableId, series),
|
|
2257
|
+
variables: [{
|
|
2258
|
+
code: FREQUENCY_CODE,
|
|
2259
|
+
label: FREQUENCY_LABEL,
|
|
2260
|
+
values: present.map((frequency) => frequency.code),
|
|
2261
|
+
valueLabels: present.map((frequency) => frequency.label),
|
|
2262
|
+
eliminable: false,
|
|
2263
|
+
isTime: false
|
|
2264
|
+
}, {
|
|
2265
|
+
code: TIME_CODE$3,
|
|
2266
|
+
label: TIME_LABEL$1,
|
|
2267
|
+
values: periods.map((point) => point.code),
|
|
2268
|
+
valueLabels: periods.map((point) => point.label),
|
|
2269
|
+
eliminable: false,
|
|
2270
|
+
isTime: true
|
|
2271
|
+
}]
|
|
2272
|
+
},
|
|
2273
|
+
points
|
|
2274
|
+
};
|
|
2275
|
+
}
|
|
2276
|
+
function chosenFrequencies(variable, selection) {
|
|
2277
|
+
const codes = variable?.values ?? [];
|
|
2278
|
+
if (!selection || selection.selection.filter === "all") return codes;
|
|
2279
|
+
const { filter, values } = selection.selection;
|
|
2280
|
+
if (filter === "item") return values;
|
|
2281
|
+
return codes.slice(-Math.max(1, Number(values[0]) || 1));
|
|
2282
|
+
}
|
|
2283
|
+
function chosenPoints(points, selection) {
|
|
2284
|
+
if (!selection || selection.selection.filter === "all") return points;
|
|
2285
|
+
const { filter, values } = selection.selection;
|
|
2286
|
+
if (filter === "top") return points.slice(-Math.max(1, Number(values[0]) || 1));
|
|
2287
|
+
const wanted = new Set(values);
|
|
2288
|
+
return points.filter((point) => wanted.has(point.code));
|
|
2289
|
+
}
|
|
2290
|
+
function notFound$6(tableId) {
|
|
2291
|
+
return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
2292
|
+
}
|
|
2293
|
+
function checkLanguage$2(lang) {
|
|
2294
|
+
if (lang !== "en") throw new PxwebError(`Language "${lang}" is not supported.`, 400);
|
|
2295
|
+
}
|
|
2296
|
+
/**
|
|
2297
|
+
* ONS time series client. One table is one time series, with the id
|
|
2298
|
+
* `<DATASET>/<CDID>` in upper case, for example "MM23/D7G7" (CPI annual rate).
|
|
2299
|
+
* Lower case input is accepted.
|
|
2300
|
+
*
|
|
2301
|
+
* - Search uses the live search API (`/search?content_type=timeseries`); there is
|
|
2302
|
+
* no crawled index. Hits keep the API order, adjusted for release recency.
|
|
2303
|
+
* - An id resolves to its page uri through a search for the CDID; the hit must
|
|
2304
|
+
* match both the CDID and the dataset. The requester cache keeps the answer.
|
|
2305
|
+
* - Metadata and data come from one request, `https://www.ons.gov.uk/<uri>/data`.
|
|
2306
|
+
* The variables are "frequency" (A, Q, M; only those that the series has) and
|
|
2307
|
+
* "period" (codes "2025", "2026-Q3", "2026-10"; labels as ONS gives them, for
|
|
2308
|
+
* example "2026 JUL-SEP" for a rolling quarter). The title gives the dataset,
|
|
2309
|
+
* the unit, the release date and the next release.
|
|
2310
|
+
* - `latest` on "period" gives the newest N periods of each selected frequency.
|
|
2311
|
+
* - The beta dataset API (`/v1/datasets`) is not used: it is out of date.
|
|
2312
|
+
*/
|
|
2313
|
+
function createOnsClient(options) {
|
|
2314
|
+
const root = options.baseUrl.replace(/\/+$/, "");
|
|
2315
|
+
const maxCells = options.maxCells ?? DEFAULT_MAX_CELLS$2;
|
|
2316
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
2317
|
+
const request = createRequester(options);
|
|
2318
|
+
async function get(url, schema, ttlSeconds, tableId) {
|
|
2319
|
+
try {
|
|
2320
|
+
return await request(url, { method: "GET" }, schema, (data) => data, ttlSeconds, url);
|
|
2321
|
+
} catch (err) {
|
|
2322
|
+
if (!(err instanceof PxwebError)) throw err;
|
|
2323
|
+
if (tableId && err.status === 404) throw notFound$6(tableId);
|
|
2324
|
+
if (err.status >= 400 && err.status < 500) throw new PxwebError(`ONS refused the request (HTTP ${err.status}). Change the query and try again.`, 400);
|
|
2325
|
+
throw new PxwebError(`ONS could not answer (HTTP ${err.status}). Try again later.`, 502);
|
|
2326
|
+
}
|
|
2327
|
+
}
|
|
2328
|
+
function searchUrl(query) {
|
|
2329
|
+
return `${root}/search?q=${encodeURIComponent(query)}&content_type=timeseries&limit=${SEARCH_LIMIT}`;
|
|
2330
|
+
}
|
|
2331
|
+
async function loadTable(lang, tableId) {
|
|
2332
|
+
checkLanguage$2(lang);
|
|
2333
|
+
const id = tableId.trim().toUpperCase();
|
|
2334
|
+
const match = TABLE_ID_PATTERN$4.exec(id);
|
|
2335
|
+
if (!match?.[2]) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it, for example "MM23/D7G7".`, 400);
|
|
2336
|
+
const { items } = await get(searchUrl(match[2]), searchSchema$1, METADATA_TTL_SECONDS);
|
|
2337
|
+
const uri = items.find((item) => hitId(item) === id)?.uri;
|
|
2338
|
+
if (!uri) throw notFound$6(tableId);
|
|
2339
|
+
rememberUri(id, uri);
|
|
2340
|
+
return toTable$2(id, await get(`${ONS_SITE}${uri}/data`, seriesSchema, DATA_TTL_SECONDS, tableId));
|
|
2341
|
+
}
|
|
2342
|
+
return {
|
|
2343
|
+
async search(lang, query) {
|
|
2344
|
+
checkLanguage$2(lang);
|
|
2345
|
+
const { items } = await get(searchUrl(query), searchSchema$1, SEARCH_TTL_SECONDS);
|
|
2346
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2347
|
+
const hits = items.flatMap((item) => {
|
|
2348
|
+
const tableId = hitId(item);
|
|
2349
|
+
if (!tableId || seen.has(tableId)) return [];
|
|
2350
|
+
seen.add(tableId);
|
|
2351
|
+
const dataset = tableId.split("/")[0];
|
|
2352
|
+
return [{
|
|
2353
|
+
tableId,
|
|
2354
|
+
title: `${item.title.trim()} (dataset ${dataset})`,
|
|
2355
|
+
published: ukDate(item.release_date)
|
|
2356
|
+
}];
|
|
2357
|
+
});
|
|
2358
|
+
return rankSearchHits(hits, now().getUTCFullYear());
|
|
2359
|
+
},
|
|
2360
|
+
async getMetadata(lang, tableId) {
|
|
2361
|
+
return (await loadTable(lang, tableId)).metadata;
|
|
2362
|
+
},
|
|
2363
|
+
async query(lang, tableId, selections) {
|
|
2364
|
+
const table = await loadTable(lang, tableId);
|
|
2365
|
+
const [frequency] = table.metadata.variables;
|
|
2366
|
+
const byCode = new Map(selections.map((selection) => [selection.code, selection]));
|
|
2367
|
+
const wanted = new Set(chosenFrequencies(frequency, byCode.get(FREQUENCY_CODE)));
|
|
2368
|
+
const rows = FREQUENCIES.filter((item) => wanted.has(item.code)).flatMap((item) => chosenPoints(table.points.get(item.code) ?? [], byCode.get(TIME_CODE$3)).map((point) => [
|
|
2369
|
+
item.label,
|
|
2370
|
+
point.label,
|
|
2371
|
+
point.value
|
|
2372
|
+
]));
|
|
2373
|
+
if (rows.length > maxCells) throw new PxwebError(`The query would return ${rows.length} cells, above the limit of ${maxCells}. Select fewer values.`, 400);
|
|
2374
|
+
return {
|
|
2375
|
+
label: table.metadata.title,
|
|
2376
|
+
columns: [
|
|
2377
|
+
FREQUENCY_LABEL,
|
|
2378
|
+
TIME_LABEL$1,
|
|
2379
|
+
"Value"
|
|
2380
|
+
],
|
|
2381
|
+
rows
|
|
2382
|
+
};
|
|
2383
|
+
}
|
|
2384
|
+
};
|
|
2385
|
+
}
|
|
2386
|
+
// src/sdmx-ml.ts
|
|
2387
|
+
const ENTITIES = {
|
|
2388
|
+
amp: "&",
|
|
2389
|
+
lt: "<",
|
|
2390
|
+
gt: ">",
|
|
2391
|
+
quot: "\"",
|
|
2392
|
+
apos: "'"
|
|
2393
|
+
};
|
|
2394
|
+
const MAX_CODE_POINT = 1114111;
|
|
2395
|
+
function decodeOnce(text) {
|
|
2396
|
+
return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (entity, name) => {
|
|
2397
|
+
if (!name.startsWith("#")) return Object.hasOwn(ENTITIES, name) ? ENTITIES[name] ?? entity : entity;
|
|
2398
|
+
const point = name[1]?.toLowerCase() === "x" ? Number.parseInt(name.slice(2), 16) : Number(name.slice(1));
|
|
2399
|
+
return point <= MAX_CODE_POINT ? String.fromCodePoint(point) : entity;
|
|
2400
|
+
});
|
|
2401
|
+
}
|
|
2402
|
+
/** Some OSP labels are escaped twice ("&apos;"), so a second pass is needed. */
|
|
2403
|
+
function decodeXml(text) {
|
|
2404
|
+
return decodeOnce(decodeOnce(text)).replace(/\s+/g, " ").trim();
|
|
2405
|
+
}
|
|
2406
|
+
function attribute(tag, name) {
|
|
2407
|
+
const value = new RegExp(`\\b${name}="([^"]*)"`).exec(tag)?.[1];
|
|
2408
|
+
return value === void 0 ? void 0 : decodeOnce(value);
|
|
2409
|
+
}
|
|
2410
|
+
const localizedPatterns = /* @__PURE__ */ new Map();
|
|
2411
|
+
function localizedPattern(element) {
|
|
2412
|
+
let pattern = localizedPatterns.get(element);
|
|
2413
|
+
if (!pattern) {
|
|
2414
|
+
pattern = new RegExp(`<${element} xml:lang="([a-z-]+)">([^<]*)</${element}>`, "g");
|
|
2415
|
+
localizedPatterns.set(element, pattern);
|
|
2416
|
+
}
|
|
2417
|
+
return pattern;
|
|
2418
|
+
}
|
|
2419
|
+
function localized(block, element) {
|
|
2420
|
+
const texts = /* @__PURE__ */ new Map();
|
|
2421
|
+
const pattern = localizedPattern(element);
|
|
2422
|
+
for (const [, lang, text] of block.matchAll(pattern)) if (lang && text !== void 0) texts.set(lang, decodeXml(text));
|
|
2423
|
+
return texts;
|
|
2424
|
+
}
|
|
2425
|
+
/** The text in `lang`, else in English, else in any language that has one. */
|
|
2426
|
+
function textIn(texts, lang) {
|
|
2427
|
+
if (!texts) return void 0;
|
|
2428
|
+
return [
|
|
2429
|
+
texts.get(lang),
|
|
2430
|
+
texts.get("en"),
|
|
2431
|
+
...texts.values()
|
|
2432
|
+
].find((text) => text !== void 0 && text !== "");
|
|
2433
|
+
}
|
|
2434
|
+
function expectRoot(xml, root) {
|
|
2435
|
+
if (!xml.includes(`<${root}`) || !xml.trimEnd().endsWith(`</${root}>`)) throw new PxwebError("Statistics Lithuania returned an incomplete or unexpected response.", 502);
|
|
2436
|
+
}
|
|
2437
|
+
/** The error that OSP puts in the footer of an HTTP 200 answer, if any. */
|
|
2438
|
+
function footerMessage(xml) {
|
|
2439
|
+
const match = /<footer:Message\b([^>]*)>([\s\S]*?)<\/footer:Message>/.exec(xml);
|
|
2440
|
+
if (!match) return void 0;
|
|
2441
|
+
return {
|
|
2442
|
+
code: attribute(match[1] ?? "", "code") ?? "",
|
|
2443
|
+
texts: localized(match[2] ?? "", "com:Text")
|
|
2444
|
+
};
|
|
2445
|
+
}
|
|
2446
|
+
function parseDataflows(xml) {
|
|
2447
|
+
expectRoot(xml, "mes:Structure");
|
|
2448
|
+
return [...xml.matchAll(/<str:Dataflow\b([^>]*)>([\s\S]*?)<\/str:Dataflow>/g)].flatMap(([, tag = "", body = ""]) => {
|
|
2449
|
+
const id = attribute(tag, "id");
|
|
2450
|
+
if (!id) return [];
|
|
2451
|
+
const reference = /<str:Structure>\s*<Ref\b([^>]*)>/.exec(body)?.[1];
|
|
2452
|
+
return [{
|
|
2453
|
+
id,
|
|
2454
|
+
names: localized(body, "com:Name"),
|
|
2455
|
+
descriptions: localized(body, "com:Description"),
|
|
2456
|
+
structureId: reference ? attribute(reference, "id") : void 0
|
|
2457
|
+
}];
|
|
2458
|
+
});
|
|
2459
|
+
}
|
|
2460
|
+
function parseCodes(body) {
|
|
2461
|
+
return [...body.matchAll(/<str:Code\b([^>]*?)(?:\/>|>([\s\S]*?)<\/str:Code>)/g)].flatMap(([, tag = "", content = ""]) => {
|
|
2462
|
+
const id = attribute(tag, "id");
|
|
2463
|
+
return id ? [{
|
|
2464
|
+
id,
|
|
2465
|
+
names: localized(content, "com:Name")
|
|
2466
|
+
}] : [];
|
|
2467
|
+
});
|
|
2468
|
+
}
|
|
2469
|
+
function parseStructure(xml) {
|
|
2470
|
+
expectRoot(xml, "mes:Structure");
|
|
2471
|
+
const codelists = /* @__PURE__ */ new Map();
|
|
2472
|
+
for (const [, tag = "", body = ""] of xml.matchAll(/<str:Codelist\b([^>]*)>([\s\S]*?)<\/str:Codelist>/g)) {
|
|
2473
|
+
const id = attribute(tag, "id");
|
|
2474
|
+
if (id) codelists.set(id, parseCodes(body));
|
|
2475
|
+
}
|
|
2476
|
+
const concepts = /* @__PURE__ */ new Map();
|
|
2477
|
+
for (const [, tag = "", body = ""] of xml.matchAll(/<str:Concept\b([^>]*)>([\s\S]*?)<\/str:Concept>/g)) {
|
|
2478
|
+
const id = attribute(tag, "id");
|
|
2479
|
+
if (id) concepts.set(id, localized(body, "com:Name"));
|
|
2480
|
+
}
|
|
2481
|
+
const dimensions = [...xml.matchAll(/<str:(Dimension|MeasureDimension|TimeDimension)\b([^>]*)>([\s\S]*?)<\/str:\1>/g)].flatMap(([, kind, tag = "", body = ""]) => {
|
|
2482
|
+
const id = attribute(tag, "id");
|
|
2483
|
+
if (!id) return [];
|
|
2484
|
+
const reference = /<str:Enumeration>\s*<Ref\b([^>]*)>/.exec(body)?.[1];
|
|
2485
|
+
return [{
|
|
2486
|
+
id,
|
|
2487
|
+
position: Number(attribute(tag, "position") ?? 0),
|
|
2488
|
+
isTime: kind === "TimeDimension",
|
|
2489
|
+
codelistId: reference ? attribute(reference, "id") : void 0
|
|
2490
|
+
}];
|
|
2491
|
+
}).toSorted((a, b) => a.position - b.position);
|
|
2492
|
+
if (dimensions.length === 0) throw new PxwebError("Statistics Lithuania returned a data structure without dimensions.", 502);
|
|
2493
|
+
return {
|
|
2494
|
+
dimensions,
|
|
2495
|
+
concepts,
|
|
2496
|
+
codelists
|
|
2497
|
+
};
|
|
2498
|
+
}
|
|
2499
|
+
function values(block) {
|
|
2500
|
+
const found = /* @__PURE__ */ new Map();
|
|
2501
|
+
for (const [, tag = ""] of block.matchAll(/<g:Value\b([^>]*?)\/?>/g)) {
|
|
2502
|
+
const id = attribute(tag, "id");
|
|
2503
|
+
const value = attribute(tag, "value");
|
|
2504
|
+
if (id && value !== void 0) found.set(id, value);
|
|
2505
|
+
}
|
|
2506
|
+
return found;
|
|
2507
|
+
}
|
|
2508
|
+
const OBS_OPEN = "<g:Obs>";
|
|
2509
|
+
const OBS_CLOSE = "</g:Obs>";
|
|
2510
|
+
function parseObservation(body) {
|
|
2511
|
+
const key = /<g:ObsKey>([\s\S]*?)<\/g:ObsKey>/.exec(body)?.[1] ?? "";
|
|
2512
|
+
const valueTag = /<g:ObsValue\b([^>]*)>/.exec(body)?.[1];
|
|
2513
|
+
const attributes = /<g:Attributes>([\s\S]*?)<\/g:Attributes>/.exec(body)?.[1] ?? "";
|
|
2514
|
+
return {
|
|
2515
|
+
key: values(key),
|
|
2516
|
+
value: valueTag ? attribute(valueTag, "value") : void 0,
|
|
2517
|
+
attributes: values(attributes)
|
|
2518
|
+
};
|
|
2519
|
+
}
|
|
2520
|
+
/**
|
|
2521
|
+
* Reads SDMX-ML 2.1 generic data (all dimensions at the observation level) in
|
|
2522
|
+
* chunks, so a large message is never held in memory as a whole.
|
|
2523
|
+
*/
|
|
2524
|
+
function createGenericDataReader(onObservation) {
|
|
2525
|
+
let head;
|
|
2526
|
+
let buffer = "";
|
|
2527
|
+
return {
|
|
2528
|
+
push(text) {
|
|
2529
|
+
buffer += text;
|
|
2530
|
+
let offset = 0;
|
|
2531
|
+
for (;;) {
|
|
2532
|
+
const start = buffer.indexOf(OBS_OPEN, offset);
|
|
2533
|
+
const end = start < 0 ? -1 : buffer.indexOf(OBS_CLOSE, start);
|
|
2534
|
+
if (end < 0) break;
|
|
2535
|
+
head ??= buffer.slice(0, start);
|
|
2536
|
+
onObservation(parseObservation(buffer.slice(start + 7, end)));
|
|
2537
|
+
offset = end + 8;
|
|
2538
|
+
}
|
|
2539
|
+
buffer = buffer.slice(offset);
|
|
2540
|
+
},
|
|
2541
|
+
finish() {
|
|
2542
|
+
const header = head ?? buffer;
|
|
2543
|
+
expectRoot((head ?? "") + buffer, "mes:GenericData");
|
|
2544
|
+
const dataSet = header.slice(Math.max(0, header.indexOf("<mes:DataSet")));
|
|
2545
|
+
return {
|
|
2546
|
+
prepared: /<mes:Prepared>([^<]*)<\/mes:Prepared>/.exec(header)?.[1],
|
|
2547
|
+
attributes: values(/<g:Attributes>([\s\S]*?)<\/g:Attributes>/.exec(dataSet)?.[1] ?? ""),
|
|
2548
|
+
footer: footerMessage(buffer)
|
|
2549
|
+
};
|
|
2550
|
+
}
|
|
2551
|
+
};
|
|
2552
|
+
}
|
|
2553
|
+
// src/osp-client.ts
|
|
2554
|
+
const AGENCY = "LSD";
|
|
2555
|
+
const LANGUAGES$1 = ["lt", "en"];
|
|
2556
|
+
const TABLE_ID_PATTERN$3 = /^(?!\.{1,2}$)[\w.-](?:[\w. -]{0,62}[\w.-])?$/;
|
|
2557
|
+
const DEFAULT_MAX_CELLS$1 = 5e3;
|
|
2558
|
+
/**
|
|
2559
|
+
* OSP cannot filter by dimension, so every code of every dimension is downloaded:
|
|
2560
|
+
* about 400 bytes and 0.3 ms per observation, streamed and filtered here.
|
|
2561
|
+
*/
|
|
2562
|
+
const DEFAULT_MAX_DOWNLOAD_OBSERVATIONS = 6e4;
|
|
2563
|
+
const MAX_DATA_BYTES = 67108864;
|
|
2564
|
+
const MAX_CACHED_TABLES$1 = 8;
|
|
2565
|
+
/** Separate period runs are fetched one request each, up to this many. */
|
|
2566
|
+
const MAX_PERIOD_RANGES = 4;
|
|
2567
|
+
const NO_DATA_MESSAGE = /did not return the data/i;
|
|
2568
|
+
const MAX_LISTED_PERIODS = 5e3;
|
|
2569
|
+
const DEFAULT_TIMEOUT_MS = 3e4;
|
|
2570
|
+
const XML_ACCEPT = "application/xml";
|
|
2571
|
+
const STATUS_CONCEPT = "OBS_STATUS";
|
|
2572
|
+
const TOTAL_LABEL = /^(?:total|total by .+|all-items|males and females|republic of lithuania|urban and rural areas|miestas ir kaimas|iš viso|iš viso pagal .+|vyrai ir moterys|lietuvos respublika)$/i;
|
|
2573
|
+
const TEXTS$1 = {
|
|
2574
|
+
lt: {
|
|
2575
|
+
value: "Reikšmė",
|
|
2576
|
+
status: "Sutartinis simbolis",
|
|
2577
|
+
updated: "atnaujinta",
|
|
2578
|
+
retrieved: "gauta",
|
|
2579
|
+
noData: "Pasirinktais laikotarpiais duomenų nėra."
|
|
2580
|
+
},
|
|
2581
|
+
en: {
|
|
2582
|
+
value: "Value",
|
|
2583
|
+
status: "Status",
|
|
2584
|
+
updated: "last update",
|
|
2585
|
+
retrieved: "retrieved",
|
|
2586
|
+
noData: "No data for the selected periods."
|
|
2587
|
+
}
|
|
2588
|
+
};
|
|
2589
|
+
const flatTableSchema = z.object({
|
|
2590
|
+
label: z.string(),
|
|
2591
|
+
columns: z.array(z.string()),
|
|
2592
|
+
rows: z.array(z.array(z.union([
|
|
2593
|
+
z.string(),
|
|
2594
|
+
z.number(),
|
|
2595
|
+
z.null()
|
|
2596
|
+
])))
|
|
2597
|
+
});
|
|
2598
|
+
function isLanguage(lang) {
|
|
2599
|
+
return LANGUAGES$1.some((language) => language === lang);
|
|
2600
|
+
}
|
|
2601
|
+
function checkLanguage$1(lang) {
|
|
2602
|
+
if (!isLanguage(lang)) throw new PxwebError(`Language "${lang}" is not supported.`, 400);
|
|
2603
|
+
return lang;
|
|
2604
|
+
}
|
|
2605
|
+
function notFound$5(tableId) {
|
|
2606
|
+
return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
2607
|
+
}
|
|
2608
|
+
function upstreamError(err) {
|
|
2609
|
+
if (err instanceof PxwebError && ![
|
|
2610
|
+
400,
|
|
2611
|
+
404,
|
|
2612
|
+
502
|
|
2613
|
+
].includes(err.status)) return new PxwebError(`Statistics Lithuania could not answer (HTTP ${err.status}). Try again later.`, 502);
|
|
2614
|
+
return err;
|
|
2615
|
+
}
|
|
2616
|
+
function parseCached(text) {
|
|
2617
|
+
if (text === void 0) return void 0;
|
|
2618
|
+
try {
|
|
2619
|
+
return JSON.parse(text);
|
|
2620
|
+
} catch {
|
|
2621
|
+
return;
|
|
2622
|
+
}
|
|
2623
|
+
}
|
|
2624
|
+
/** "Sex | Age (1996 - 2026) (Was renewed: 2026-05-07)" or "… (Not be renewed)". */
|
|
2625
|
+
function parseDescription(text) {
|
|
2626
|
+
let rest = text;
|
|
2627
|
+
let updated;
|
|
2628
|
+
let discontinued = false;
|
|
2629
|
+
const status = /\(([^()]*)\)$/.exec(rest);
|
|
2630
|
+
if (status && !/^\S+ - \S+$/.test(status[1] ?? "")) {
|
|
2631
|
+
updated = /\d{4}-\d{2}-\d{2}/.exec(status[1] ?? "")?.[0];
|
|
2632
|
+
discontinued = updated === void 0;
|
|
2633
|
+
rest = rest.slice(0, status.index).trim();
|
|
2634
|
+
}
|
|
2635
|
+
const range = /\((\S+) - (\S+)\)$/.exec(rest);
|
|
2636
|
+
if (range) rest = rest.slice(0, range.index).trim();
|
|
2637
|
+
return {
|
|
2638
|
+
dimensions: rest,
|
|
2639
|
+
first: range?.[1],
|
|
2640
|
+
last: range?.[2],
|
|
2641
|
+
updated,
|
|
2642
|
+
discontinued
|
|
2643
|
+
};
|
|
2644
|
+
}
|
|
2645
|
+
function flowTitle(name, description) {
|
|
2646
|
+
const title = description.dimensions ? `${name}: ${description.dimensions}` : name;
|
|
2647
|
+
return description.first && description.last ? `${title} (${description.first} - ${description.last})` : title;
|
|
2648
|
+
}
|
|
2649
|
+
function toTableDoc(flow, lang) {
|
|
2650
|
+
const description = parseDescription(textIn(flow.descriptions, lang) ?? "");
|
|
2651
|
+
return {
|
|
2652
|
+
id: flow.id,
|
|
2653
|
+
title: flowTitle(textIn(flow.names, lang) ?? flow.id, description),
|
|
2654
|
+
...description.updated && { updated: description.updated },
|
|
2655
|
+
...description.last && { lastPeriod: description.last },
|
|
2656
|
+
...description.discontinued && { discontinued: true }
|
|
2657
|
+
};
|
|
2658
|
+
}
|
|
2659
|
+
const PERIOD_FORMATS = [
|
|
2660
|
+
{
|
|
2661
|
+
pattern: /^(\d{4})$/,
|
|
2662
|
+
perYear: 1,
|
|
2663
|
+
code: (year) => String(year),
|
|
2664
|
+
api: (match) => match[1] ?? ""
|
|
2665
|
+
},
|
|
2666
|
+
{
|
|
2667
|
+
pattern: /^(\d{4})P([12])$/,
|
|
2668
|
+
perYear: 2,
|
|
2669
|
+
code: (year, index) => `${year}P${index + 1}`,
|
|
2670
|
+
api: (match) => `${match[1]}-S${match[2]}`
|
|
2671
|
+
},
|
|
2672
|
+
{
|
|
2673
|
+
pattern: /^(\d{4})K([1-4])$/,
|
|
2674
|
+
perYear: 4,
|
|
2675
|
+
code: (year, index) => `${year}K${index + 1}`,
|
|
2676
|
+
api: (match) => `${match[1]}-Q${match[2]}`
|
|
2677
|
+
},
|
|
2678
|
+
{
|
|
2679
|
+
pattern: /^(\d{4})M(0[1-9]|1[0-2])$/,
|
|
2680
|
+
perYear: 12,
|
|
2681
|
+
code: (year, index) => `${year}M${String(index + 1).padStart(2, "0")}`,
|
|
2682
|
+
api: (match) => `${match[1]}-${match[2]}`
|
|
2683
|
+
},
|
|
2684
|
+
{
|
|
2685
|
+
pattern: /^(\d{4})-(\d{4})$/,
|
|
2686
|
+
perYear: 1,
|
|
2687
|
+
code: (year) => `${year}-${year + 1}`,
|
|
2688
|
+
api: (match, edge) => (edge === "start" ? match[1] : match[2]) ?? ""
|
|
2689
|
+
}
|
|
2690
|
+
];
|
|
2691
|
+
function matchPeriod(code) {
|
|
2692
|
+
for (const format of PERIOD_FORMATS) {
|
|
2693
|
+
const match = format.pattern.exec(code);
|
|
2694
|
+
if (match) return {
|
|
2695
|
+
format,
|
|
2696
|
+
match
|
|
2697
|
+
};
|
|
2698
|
+
}
|
|
2699
|
+
}
|
|
2700
|
+
/** Position of a period on its format's scale; undefined for multi-year spans. */
|
|
2701
|
+
function periodStep(format, match) {
|
|
2702
|
+
const year = Number(match[1]);
|
|
2703
|
+
if (format.perYear === 1) return match[2] === void 0 || Number(match[2]) === year + 1 ? year : void 0;
|
|
2704
|
+
return year * format.perYear + Number(match[2]) - 1;
|
|
2705
|
+
}
|
|
2706
|
+
/**
|
|
2707
|
+
* The API lists no periods, so they come from the range in the dataflow description.
|
|
2708
|
+
* Multi-year spans ("2008-2010 - 2022-2024") and mixed ranges have gaps that cannot
|
|
2709
|
+
* be known, so only their first and last periods are listed.
|
|
2710
|
+
*/
|
|
2711
|
+
function periodList(first, last) {
|
|
2712
|
+
const start = matchPeriod(first);
|
|
2713
|
+
const end = matchPeriod(last);
|
|
2714
|
+
const from = start && periodStep(start.format, start.match);
|
|
2715
|
+
const to = end && periodStep(end.format, end.match);
|
|
2716
|
+
if (!start || start.format !== end?.format || from === void 0 || to === void 0 || to < from || to - from >= MAX_LISTED_PERIODS) return [.../* @__PURE__ */ new Set([first, last])];
|
|
2717
|
+
const { format } = start;
|
|
2718
|
+
const codes = [];
|
|
2719
|
+
for (let step = from; step <= to; step++) codes.push(format.code(Math.floor(step / format.perYear), step % format.perYear));
|
|
2720
|
+
return codes;
|
|
2721
|
+
}
|
|
2722
|
+
function apiPeriod(code, edge) {
|
|
2723
|
+
const found = matchPeriod(code);
|
|
2724
|
+
if (found) return found.format.api(found.match, edge);
|
|
2725
|
+
const years = code.match(/\d{4}/g) ?? [];
|
|
2726
|
+
return (edge === "start" ? years[0] : years.at(-1)) ?? code;
|
|
2727
|
+
}
|
|
2728
|
+
function compareCodes(a, b) {
|
|
2729
|
+
const numericA = /^\d+$/.test(a);
|
|
2730
|
+
const numericB = /^\d+$/.test(b);
|
|
2731
|
+
if (numericA && numericB) return Number(a) - Number(b) || a.length - b.length;
|
|
2732
|
+
if (numericA !== numericB) return numericA ? -1 : 1;
|
|
2733
|
+
if (a === b) return 0;
|
|
2734
|
+
return a < b ? -1 : 1;
|
|
2735
|
+
}
|
|
2736
|
+
function totalCode(codes) {
|
|
2737
|
+
const totals = codes.filter((code) => [...code.names.values()].some((name) => TOTAL_LABEL.test(name)));
|
|
2738
|
+
return totals.length === 1 ? totals[0]?.id : void 0;
|
|
2739
|
+
}
|
|
2740
|
+
function buildTable(flow, structure, lang) {
|
|
2741
|
+
const description = parseDescription(textIn(flow.descriptions, lang) ?? "");
|
|
2742
|
+
const totals = /* @__PURE__ */ new Map();
|
|
2743
|
+
const dimensions = [];
|
|
2744
|
+
let time;
|
|
2745
|
+
for (const dimension of structure.dimensions) {
|
|
2746
|
+
const label = textIn(structure.concepts.get(dimension.id), lang) ?? dimension.id;
|
|
2747
|
+
if (dimension.isTime) {
|
|
2748
|
+
const periods = description.first && description.last ? periodList(description.first, description.last) : [];
|
|
2749
|
+
time = {
|
|
2750
|
+
code: dimension.id,
|
|
2751
|
+
label,
|
|
2752
|
+
values: periods,
|
|
2753
|
+
valueLabels: periods,
|
|
2754
|
+
eliminable: false,
|
|
2755
|
+
isTime: true
|
|
2756
|
+
};
|
|
2757
|
+
continue;
|
|
2758
|
+
}
|
|
2759
|
+
const codes = structure.codelists.get(dimension.codelistId ?? "") ?? [];
|
|
2760
|
+
const total = codes.length > 1 ? totalCode(codes) : void 0;
|
|
2761
|
+
if (total !== void 0) totals.set(dimension.id, total);
|
|
2762
|
+
const ordered = codes.toSorted((a, b) => {
|
|
2763
|
+
if (a.id === total) return -1;
|
|
2764
|
+
if (b.id === total) return 1;
|
|
2765
|
+
return compareCodes(a.id, b.id);
|
|
2766
|
+
});
|
|
2767
|
+
dimensions.push({
|
|
2768
|
+
code: dimension.id,
|
|
2769
|
+
label,
|
|
2770
|
+
values: ordered.map((code) => code.id),
|
|
2771
|
+
valueLabels: ordered.map((code) => textIn(code.names, lang) ?? code.id),
|
|
2772
|
+
eliminable: total !== void 0,
|
|
2773
|
+
isTime: false
|
|
2774
|
+
});
|
|
2775
|
+
}
|
|
2776
|
+
if (!time) throw new PxwebError(`Table "${flow.id}" has no time dimension in its data structure.`, 502);
|
|
2777
|
+
const statuses = structure.codelists.get(STATUS_CONCEPT) ?? [];
|
|
2778
|
+
return {
|
|
2779
|
+
flowId: flow.id,
|
|
2780
|
+
metadata: {
|
|
2781
|
+
title: flowTitle(textIn(flow.names, lang) ?? flow.id, description),
|
|
2782
|
+
variables: [...dimensions, time]
|
|
2783
|
+
},
|
|
2784
|
+
totals,
|
|
2785
|
+
statusTexts: new Map(statuses.map((code) => [code.id, textIn(code.names, lang) ?? code.id]))
|
|
2786
|
+
};
|
|
2787
|
+
}
|
|
2788
|
+
/**
|
|
2789
|
+
* Index ranges of the chosen periods: one per adjacent run, or one span over all
|
|
2790
|
+
* of them when there are many runs.
|
|
2791
|
+
*/
|
|
2792
|
+
function periodRanges(periods, chosen) {
|
|
2793
|
+
const runs = [];
|
|
2794
|
+
periods.forEach((period, index) => {
|
|
2795
|
+
if (!chosen.has(period)) return;
|
|
2796
|
+
const last = runs.at(-1);
|
|
2797
|
+
if (last && last[1] === index - 1) last[1] = index;
|
|
2798
|
+
else runs.push([index, index]);
|
|
2799
|
+
});
|
|
2800
|
+
const first = runs[0];
|
|
2801
|
+
const end = runs.at(-1);
|
|
2802
|
+
if (runs.length <= MAX_PERIOD_RANGES || !first || !end) return runs;
|
|
2803
|
+
return [[first[0], end[1]]];
|
|
2804
|
+
}
|
|
2805
|
+
function chosenCodes$1(variable, selection) {
|
|
2806
|
+
if (!selection || selection.selection.filter === "all") return variable.values;
|
|
2807
|
+
const { filter, values } = selection.selection;
|
|
2808
|
+
if (filter === "top") {
|
|
2809
|
+
const count = Math.max(1, Number(values[0]) || 1);
|
|
2810
|
+
return variable.values.slice(-count);
|
|
2811
|
+
}
|
|
2812
|
+
const known = new Set(variable.values);
|
|
2813
|
+
const unknown = values.filter((value) => !known.has(value));
|
|
2814
|
+
if (unknown.length > 0) throw new PxwebError(`Variable "${variable.code}" has no values ${unknown.join(", ")}. Call get_table_metadata to see valid value codes.`, 400);
|
|
2815
|
+
return values;
|
|
2816
|
+
}
|
|
2817
|
+
function toNumber(value) {
|
|
2818
|
+
if (value === void 0 || value.trim() === "") return null;
|
|
2819
|
+
const number = Number(value);
|
|
2820
|
+
return Number.isFinite(number) ? number : null;
|
|
2821
|
+
}
|
|
2822
|
+
function selectCodes(table, selections, maxCells) {
|
|
2823
|
+
const byCode = new Map(selections.map((selection) => [selection.code, selection]));
|
|
2824
|
+
const chosen = /* @__PURE__ */ new Map();
|
|
2825
|
+
const hidden = /* @__PURE__ */ new Set();
|
|
2826
|
+
let cells = 1;
|
|
2827
|
+
let perPeriod = 1;
|
|
2828
|
+
for (const variable of table.metadata.variables) {
|
|
2829
|
+
const selection = byCode.get(variable.code);
|
|
2830
|
+
const total = table.totals.get(variable.code);
|
|
2831
|
+
if (!variable.isTime) perPeriod *= Math.max(1, variable.values.length);
|
|
2832
|
+
if (!selection && total !== void 0) {
|
|
2833
|
+
chosen.set(variable.code, /* @__PURE__ */ new Set([total]));
|
|
2834
|
+
hidden.add(variable.code);
|
|
2835
|
+
continue;
|
|
2836
|
+
}
|
|
2837
|
+
const codes = chosenCodes$1(variable, selection);
|
|
2838
|
+
chosen.set(variable.code, new Set(codes));
|
|
2839
|
+
cells *= codes.length;
|
|
2840
|
+
}
|
|
2841
|
+
if (cells > maxCells) throw new PxwebError(`The query could return ${cells} cells, above the limit of ${maxCells}. Select fewer values.`, 400);
|
|
2842
|
+
return {
|
|
2843
|
+
chosen,
|
|
2844
|
+
hidden,
|
|
2845
|
+
perPeriod
|
|
2846
|
+
};
|
|
2847
|
+
}
|
|
2848
|
+
function collectRows(table, filter, lang) {
|
|
2849
|
+
const variables = table.metadata.variables;
|
|
2850
|
+
const shown = variables.filter((variable) => !filter.hidden.has(variable.code));
|
|
2851
|
+
const timeCode = variables.at(-1)?.code ?? "";
|
|
2852
|
+
const dimensionCodes = new Set(variables.filter((variable) => !variable.isTime).map((v) => v.code));
|
|
2853
|
+
const positions = new Map(variables.map((variable) => [variable.code, new Map(variable.values.map((value, index) => [value, index]))]));
|
|
2854
|
+
const found = [];
|
|
2855
|
+
let hasStatus = false;
|
|
2856
|
+
return {
|
|
2857
|
+
add(observation) {
|
|
2858
|
+
const codes = /* @__PURE__ */ new Map();
|
|
2859
|
+
for (const [id, code] of observation.key) codes.set(dimensionCodes.has(id) ? id : timeCode, code);
|
|
2860
|
+
if (!variables.every((variable) => {
|
|
2861
|
+
const code = codes.get(variable.code);
|
|
2862
|
+
return code !== void 0 && filter.chosen.get(variable.code)?.has(code);
|
|
2863
|
+
})) return;
|
|
2864
|
+
const status = observation.attributes.get(STATUS_CONCEPT);
|
|
2865
|
+
if (status) hasStatus = true;
|
|
2866
|
+
const order = shown.map((variable) => positions.get(variable.code)?.get(codes.get(variable.code) ?? "") ?? 0);
|
|
2867
|
+
found.push({
|
|
2868
|
+
order,
|
|
2869
|
+
cells: [
|
|
2870
|
+
...shown.map((variable, index) => variable.valueLabels[order[index] ?? -1] ?? codes.get(variable.code) ?? ""),
|
|
2871
|
+
toNumber(observation.value),
|
|
2872
|
+
status ? table.statusTexts.get(status) ?? status : null
|
|
2873
|
+
]
|
|
2874
|
+
});
|
|
2875
|
+
},
|
|
2876
|
+
build(headers) {
|
|
2877
|
+
const header = headers.find((entry) => entry.attributes.size > 0) ?? headers[0];
|
|
2878
|
+
found.sort((a, b) => {
|
|
2879
|
+
for (const [index, value] of a.order.entries()) {
|
|
2880
|
+
const difference = value - (b.order[index] ?? 0);
|
|
2881
|
+
if (difference !== 0) return difference;
|
|
2882
|
+
}
|
|
2883
|
+
return 0;
|
|
2884
|
+
});
|
|
2885
|
+
const texts = TEXTS$1[lang];
|
|
2886
|
+
const updated = header?.attributes.get("DS_LAST_UPDATE");
|
|
2887
|
+
const retrieved = header?.prepared?.slice(0, 10);
|
|
2888
|
+
const dates = [updated && `${texts.updated}: ${updated}`, retrieved && `${texts.retrieved}: ${retrieved}`].filter(Boolean);
|
|
2889
|
+
const title = dates.length ? `${table.metadata.title} (${dates.join("; ")})` : table.metadata.title;
|
|
2890
|
+
return {
|
|
2891
|
+
label: found.length ? title : `${title}. ${texts.noData}`,
|
|
2892
|
+
columns: [
|
|
2893
|
+
...shown.map((variable) => variable.label),
|
|
2894
|
+
texts.value,
|
|
2895
|
+
...hasStatus ? [texts.status] : []
|
|
2896
|
+
],
|
|
2897
|
+
rows: found.map((row) => hasStatus ? row.cells : row.cells.slice(0, -1))
|
|
2898
|
+
};
|
|
2899
|
+
}
|
|
2900
|
+
};
|
|
2901
|
+
}
|
|
2902
|
+
/**
|
|
2903
|
+
* Client for the Official Statistics Portal (OSP) of Statistics Lithuania (State
|
|
2904
|
+
* Data Agency), an SDMX 2.1 REST service that answers only SDMX-ML, in Lithuanian
|
|
2905
|
+
* and English (every message carries both).
|
|
2906
|
+
*
|
|
2907
|
+
* - Table id: the dataflow id, for example "S7R121_M2020103_1". One indicator
|
|
2908
|
+
* ("S7R121") has one dataflow per breakdown, so the title adds the dimensions
|
|
2909
|
+
* and the period range from the dataflow description.
|
|
2910
|
+
* - Search: a local index over the full dataflow list (`dataflow/`, 7 MB, one call
|
|
2911
|
+
* for both languages). The parsed list is kept in memory for an hour; it is too
|
|
2912
|
+
* large for the shared cache. The description gives the update date, the last
|
|
2913
|
+
* period and "not renewed" (discontinued) dataflows.
|
|
2914
|
+
* - Metadata: `dataflow/LSD/{id}` and `datastructure/LSD/{dsd}` (code lists and
|
|
2915
|
+
* concept names). Code lists come unordered and are sorted by code. A dimension is
|
|
2916
|
+
* eliminable only when exactly one code is labelled as a total ("Total by age",
|
|
2917
|
+
* "Republic of Lithuania", "Males and females" …); left out, it is filtered to that
|
|
2918
|
+
* code. The structure lists no periods, so they are expanded from the range in the
|
|
2919
|
+
* dataflow description.
|
|
2920
|
+
* - Query: OSP supports only `startPeriod` and `endPeriod` (no key, no
|
|
2921
|
+
* `lastNObservations`, so URLs stay far below its 1,000-character limit). Each
|
|
2922
|
+
* run of adjacent chosen periods is one request (more than four runs become one
|
|
2923
|
+
* span) with every code of every dimension; the message is streamed and filtered
|
|
2924
|
+
* here, never held whole. `latest` picks the newest listed periods. The cell
|
|
2925
|
+
* limit applies to the result, and a separate limit (60,000 observations, about
|
|
2926
|
+
* 20 s) to the download. Errors and "no data" come as HTTP 200 with a footer.
|
|
2927
|
+
* - Caching: dataflow and structure messages in the shared cache; the parsed table
|
|
2928
|
+
* in memory for an hour (finished values only); the filtered result in the shared
|
|
2929
|
+
* cache for an hour. Titles of results carry the data update and retrieval dates.
|
|
2930
|
+
*/
|
|
2931
|
+
function createOspClient(options) {
|
|
2932
|
+
const root = options.baseUrl.replace(/\/+$/, "");
|
|
2933
|
+
const maxCells = options.maxCells ?? DEFAULT_MAX_CELLS$1;
|
|
2934
|
+
const maxDownload = options.maxDownloadObservations ?? DEFAULT_MAX_DOWNLOAD_OBSERVATIONS;
|
|
2935
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
2936
|
+
const cache = options.cache ?? createMemoryCache();
|
|
2937
|
+
const doFetch = options.fetch ?? fetch;
|
|
2938
|
+
const request = createTextRequester({
|
|
2939
|
+
...options,
|
|
2940
|
+
cache
|
|
2941
|
+
});
|
|
2942
|
+
const xmlGet = {
|
|
2943
|
+
method: "GET",
|
|
2944
|
+
headers: { accept: XML_ACCEPT }
|
|
2945
|
+
};
|
|
2946
|
+
async function open(url) {
|
|
2947
|
+
const response = await doFetch(url, {
|
|
2948
|
+
headers: {
|
|
2949
|
+
accept: XML_ACCEPT,
|
|
2950
|
+
...options.userAgent && { "user-agent": options.userAgent }
|
|
2951
|
+
},
|
|
2952
|
+
signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS)
|
|
2953
|
+
}).catch((err) => {
|
|
2954
|
+
throw new PxwebError(`Statistics Lithuania request failed: ${err instanceof Error ? err.message : String(err)}`, 502);
|
|
2955
|
+
});
|
|
2956
|
+
if (!response.ok) {
|
|
2957
|
+
await response.body?.cancel().catch(() => void 0);
|
|
2958
|
+
throw upstreamError(new PxwebError(`Statistics Lithuania returned HTTP ${response.status}.`, response.status));
|
|
2959
|
+
}
|
|
2960
|
+
return response;
|
|
2961
|
+
}
|
|
2962
|
+
async function streamData(url, onObservation) {
|
|
2963
|
+
const response = await open(url);
|
|
2964
|
+
const reader = createGenericDataReader(onObservation);
|
|
2965
|
+
const decoder = new TextDecoder();
|
|
2966
|
+
const body = response.body?.getReader();
|
|
2967
|
+
let size = 0;
|
|
2968
|
+
try {
|
|
2969
|
+
for (;;) {
|
|
2970
|
+
const chunk = await body?.read();
|
|
2971
|
+
if (!chunk || chunk.done) break;
|
|
2972
|
+
size += chunk.value.byteLength;
|
|
2973
|
+
if (size > MAX_DATA_BYTES) {
|
|
2974
|
+
await body?.cancel().catch(() => void 0);
|
|
2975
|
+
throw new PxwebError("Statistics Lithuania response is too large.", 502);
|
|
2976
|
+
}
|
|
2977
|
+
reader.push(decoder.decode(chunk.value, { stream: true }));
|
|
2978
|
+
}
|
|
2979
|
+
} catch (err) {
|
|
2980
|
+
await body?.cancel().catch(() => void 0);
|
|
2981
|
+
if (err instanceof PxwebError) throw err;
|
|
2982
|
+
throw new PxwebError(`Statistics Lithuania response could not be read: ${err instanceof Error ? err.message : String(err)}`, 502);
|
|
2983
|
+
}
|
|
2984
|
+
reader.push(decoder.decode());
|
|
2985
|
+
return reader.finish();
|
|
2986
|
+
}
|
|
2987
|
+
let catalogue;
|
|
2988
|
+
async function listTables(lang) {
|
|
2989
|
+
const language = checkLanguage$1(lang);
|
|
2990
|
+
if (!catalogue || catalogue.expires <= Date.now()) {
|
|
2991
|
+
const flows = parseDataflows(await readCappedText(await open(`${root}/dataflow/`)));
|
|
2992
|
+
if (flows.length === 0) throw new PxwebError("Statistics Lithuania returned no dataflows.", 502);
|
|
2993
|
+
catalogue = {
|
|
2994
|
+
expires: Date.now() + SEARCH_TTL_SECONDS * 1e3,
|
|
2995
|
+
flows
|
|
2996
|
+
};
|
|
2997
|
+
}
|
|
2998
|
+
return catalogue.flows.map((flow) => toTableDoc(flow, language));
|
|
2999
|
+
}
|
|
3000
|
+
const tableIndex = createTableIndexLoader(preferCrawled(listTables, options.crawledList), {
|
|
3001
|
+
fallback: options.listFallback,
|
|
3002
|
+
ttlSeconds: SEARCH_TTL_SECONDS,
|
|
3003
|
+
currentYear: () => now().getUTCFullYear()
|
|
3004
|
+
});
|
|
3005
|
+
function getStructure(path, ttlSeconds, parse) {
|
|
3006
|
+
const url = `${root}/${path}`;
|
|
3007
|
+
return request(url, xmlGet, parse, ttlSeconds, `osp:${url}`).catch((err) => {
|
|
3008
|
+
throw upstreamError(err);
|
|
1164
3009
|
});
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
}
|
|
3010
|
+
}
|
|
3011
|
+
async function loadTable(lang, tableId) {
|
|
3012
|
+
if (!TABLE_ID_PATTERN$3.test(tableId)) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it.`, 400);
|
|
3013
|
+
const flow = await getStructure(`dataflow/${AGENCY}/${encodeURIComponent(tableId)}`, SEARCH_TTL_SECONDS, (xml) => {
|
|
3014
|
+
const [found] = parseDataflows(xml);
|
|
3015
|
+
if (found?.id !== tableId || !found.structureId) throw notFound$5(tableId);
|
|
3016
|
+
return {
|
|
3017
|
+
...found,
|
|
3018
|
+
structureId: found.structureId
|
|
3019
|
+
};
|
|
3020
|
+
});
|
|
3021
|
+
return buildTable(flow, await getStructure(`datastructure/${AGENCY}/${encodeURIComponent(flow.structureId)}`, METADATA_TTL_SECONDS, (xml) => {
|
|
3022
|
+
const footer = footerMessage(xml);
|
|
3023
|
+
if (footer) throw new PxwebError(`Statistics Lithuania has no data structure for table "${tableId}": ${textIn(footer.texts, lang) ?? footer.code}`, 502);
|
|
3024
|
+
return parseStructure(xml);
|
|
3025
|
+
}), lang);
|
|
3026
|
+
}
|
|
3027
|
+
const tables = /* @__PURE__ */ new Map();
|
|
3028
|
+
async function cachedTable(lang, tableId) {
|
|
3029
|
+
const language = checkLanguage$1(lang);
|
|
3030
|
+
const key = `${language}:${tableId}`;
|
|
3031
|
+
const cached = tables.get(key);
|
|
3032
|
+
if (cached && cached.expires > Date.now()) return cached.table;
|
|
3033
|
+
const table = await loadTable(language, tableId);
|
|
3034
|
+
tables.delete(key);
|
|
3035
|
+
tables.set(key, {
|
|
3036
|
+
expires: Date.now() + DATA_TTL_SECONDS * 1e3,
|
|
3037
|
+
table
|
|
3038
|
+
});
|
|
3039
|
+
const oldest = tables.keys().next().value;
|
|
3040
|
+
if (tables.size > MAX_CACHED_TABLES$1 && oldest !== void 0) tables.delete(oldest);
|
|
3041
|
+
return table;
|
|
1169
3042
|
}
|
|
1170
3043
|
return {
|
|
1171
3044
|
listTables,
|
|
1172
3045
|
async search(lang, query, searchOptions) {
|
|
3046
|
+
checkLanguage$1(lang);
|
|
1173
3047
|
return (await tableIndex(lang)).search(query, searchOptions);
|
|
1174
3048
|
},
|
|
1175
|
-
async getMetadata(lang,
|
|
1176
|
-
|
|
1177
|
-
return metadata(lang, code);
|
|
3049
|
+
async getMetadata(lang, tableId) {
|
|
3050
|
+
return (await cachedTable(lang, tableId)).metadata;
|
|
1178
3051
|
},
|
|
1179
|
-
async query(lang,
|
|
1180
|
-
|
|
1181
|
-
const
|
|
1182
|
-
const
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
}
|
|
1191
|
-
let codes = values;
|
|
1192
|
-
if (filter === "top") {
|
|
1193
|
-
const variable = known?.variables.find((item) => item.code === selection.code);
|
|
1194
|
-
if (!variable) throw new PxwebError(`Table "${code}" has no variable "${selection.code}". Call get_table_metadata to see its variables.`, 400);
|
|
1195
|
-
codes = variable.values.slice(-count);
|
|
1196
|
-
}
|
|
1197
|
-
for (const value of codes) params.append(selection.code, value);
|
|
3052
|
+
async query(lang, tableId, selections) {
|
|
3053
|
+
const language = checkLanguage$1(lang);
|
|
3054
|
+
const table = await cachedTable(language, tableId);
|
|
3055
|
+
const { chosen, hidden, perPeriod } = selectCodes(table, selections, maxCells);
|
|
3056
|
+
const time = table.metadata.variables.at(-1);
|
|
3057
|
+
const ranges = periodRanges(time?.values ?? [], chosen.get(time?.code ?? "") ?? /* @__PURE__ */ new Set());
|
|
3058
|
+
const periods = ranges.reduce((sum, [from, to]) => sum + to - from + 1, 0);
|
|
3059
|
+
if (periods === 0 || !time) throw new PxwebError(`Table "${tableId}" lists no periods.`, 400);
|
|
3060
|
+
const download = perPeriod * periods;
|
|
3061
|
+
if (download > maxDownload) {
|
|
3062
|
+
const fit = Math.floor(maxDownload / perPeriod);
|
|
3063
|
+
throw new PxwebError(fit > 0 ? `Statistics Lithuania sends every value of every dimension, so these periods mean about ${download} observations, above the limit of ${maxDownload}. Select at most ${fit} periods.` : `Statistics Lithuania sends every value of every dimension, about ${perPeriod} observations per period, above the limit of ${maxDownload}. Use a table with fewer dimensions.`, 400);
|
|
1198
3064
|
}
|
|
1199
|
-
const
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
3065
|
+
const urls = ranges.map(([from, to]) => `${root}/data/${encodeURIComponent(table.flowId)}?startPeriod=${apiPeriod(time.values[from] ?? "", "start")}&endPeriod=${apiPeriod(time.values[to] ?? "", "end")}`);
|
|
3066
|
+
const signature = [...chosen].map(([code, values]) => `${code}=${[...values].join(",")}`).join("&");
|
|
3067
|
+
const cacheKey = `osp:rows:${language}:${urls.join(" ")}:${signature}`;
|
|
3068
|
+
const cached = await cache.get(cacheKey);
|
|
3069
|
+
const parsed = flatTableSchema.safeParse(parseCached(cached));
|
|
3070
|
+
if (parsed.success) return parsed.data;
|
|
3071
|
+
const rows = collectRows(table, {
|
|
3072
|
+
chosen,
|
|
3073
|
+
hidden
|
|
3074
|
+
}, language);
|
|
3075
|
+
let observations = 0;
|
|
3076
|
+
const countObservation = (observation) => {
|
|
3077
|
+
observations += 1;
|
|
3078
|
+
if (observations > maxDownload) throw new PxwebError(`Statistics Lithuania sent more than ${maxDownload} observations for these periods. Select fewer periods.`, 400);
|
|
3079
|
+
rows.add(observation);
|
|
3080
|
+
};
|
|
3081
|
+
const headers = [];
|
|
3082
|
+
for (const url of urls) {
|
|
3083
|
+
const header = await streamData(url, countObservation).catch((err) => {
|
|
3084
|
+
if (err instanceof PxwebError && err.status === 404) throw notFound$5(tableId);
|
|
3085
|
+
throw err;
|
|
3086
|
+
});
|
|
3087
|
+
const footer = header.footer;
|
|
3088
|
+
if (footer && !NO_DATA_MESSAGE.test(footer.texts.get("en") ?? "")) throw new PxwebError(`Statistics Lithuania refused the request for table "${tableId}": ${textIn(footer.texts, language) ?? footer.code}`, 502);
|
|
3089
|
+
headers.push(header);
|
|
3090
|
+
}
|
|
3091
|
+
const result = rows.build(headers);
|
|
3092
|
+
await cache.set(cacheKey, JSON.stringify(result), DATA_TTL_SECONDS);
|
|
3093
|
+
return result;
|
|
1204
3094
|
}
|
|
1205
3095
|
};
|
|
1206
3096
|
}
|
|
@@ -1227,7 +3117,7 @@ function categoryCodes(index) {
|
|
|
1227
3117
|
if (Array.isArray(index)) return index;
|
|
1228
3118
|
return Object.entries(index).toSorted((a, b) => a[1] - b[1]).map(([code]) => code);
|
|
1229
3119
|
}
|
|
1230
|
-
function toTable(data) {
|
|
3120
|
+
function toTable$1(data) {
|
|
1231
3121
|
const elimination = Object.fromEntries(Object.entries(data.extension?.elimination ?? {}).filter((entry) => entry[1] !== null));
|
|
1232
3122
|
const timeCodes = new Set(data.role?.time ?? []);
|
|
1233
3123
|
return {
|
|
@@ -1249,10 +3139,10 @@ function toTable(data) {
|
|
|
1249
3139
|
}
|
|
1250
3140
|
};
|
|
1251
3141
|
}
|
|
1252
|
-
function notFound$
|
|
3142
|
+
function notFound$4(tableId) {
|
|
1253
3143
|
return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
1254
3144
|
}
|
|
1255
|
-
function checkTableId$
|
|
3145
|
+
function checkTableId$3(tableId) {
|
|
1256
3146
|
if (!MATRIX_PATTERN.test(tableId)) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it.`, 400);
|
|
1257
3147
|
}
|
|
1258
3148
|
function requestedCodes(values, selection, total) {
|
|
@@ -1274,12 +3164,12 @@ function createPxstatClient(options) {
|
|
|
1274
3164
|
currentYear: () => now().getUTCFullYear()
|
|
1275
3165
|
});
|
|
1276
3166
|
async function loadTable(lang, tableId) {
|
|
1277
|
-
checkTableId$
|
|
3167
|
+
checkTableId$3(tableId);
|
|
1278
3168
|
const url = `${root}/api.restful/PxStat.Data.Cube_API.ReadMetadata/${tableId}/JSON-stat/2.0/${encodeURIComponent(lang)}`;
|
|
1279
3169
|
try {
|
|
1280
|
-
return await request(url, { method: "GET" }, metadataSchema$3, toTable, METADATA_TTL_SECONDS, `meta:${url}`);
|
|
3170
|
+
return await request(url, { method: "GET" }, metadataSchema$3, toTable$1, METADATA_TTL_SECONDS, `meta:${url}`);
|
|
1281
3171
|
} catch (err) {
|
|
1282
|
-
if (err instanceof PxwebError && err.status === 404) throw notFound$
|
|
3172
|
+
if (err instanceof PxwebError && err.status === 404) throw notFound$4(tableId);
|
|
1283
3173
|
throw err;
|
|
1284
3174
|
}
|
|
1285
3175
|
}
|
|
@@ -1325,8 +3215,8 @@ function createPxstatClient(options) {
|
|
|
1325
3215
|
headers: { "content-type": "application/json" }
|
|
1326
3216
|
}, rpcSchema, (data) => {
|
|
1327
3217
|
if (data.error) throw new PxwebError(`PxStat refused the query: ${data.error.message ?? "unknown error"}`, 400);
|
|
1328
|
-
if (!data.result) throw notFound$
|
|
1329
|
-
return toFlatTable$
|
|
3218
|
+
if (!data.result) throw notFound$4(tableId);
|
|
3219
|
+
return toFlatTable$2(data.result);
|
|
1330
3220
|
}, DATA_TTL_SECONDS, `data:${url}:${body}`);
|
|
1331
3221
|
}
|
|
1332
3222
|
};
|
|
@@ -1339,7 +3229,7 @@ const NOT_FOUND_STATUSES$2 = /* @__PURE__ */ new Set([400, 404]);
|
|
|
1339
3229
|
* dashes and diacritics; "." and ".." and URL syntax characters are refused.
|
|
1340
3230
|
*/
|
|
1341
3231
|
const SEGMENT_PATTERN = /^(?!\.{1,2}$)[^\s/\\?#%\p{Cc}\p{Cs}](?:[^/\\?#%\p{Cc}\p{Cs}]*[^\s/\\?#%\p{Cc}\p{Cs}])?$/u;
|
|
1342
|
-
const MAX_TABLE_ID_LENGTH = 400;
|
|
3232
|
+
const MAX_TABLE_ID_LENGTH$1 = 400;
|
|
1343
3233
|
const searchHitSchema = z.object({
|
|
1344
3234
|
id: z.string(),
|
|
1345
3235
|
path: z.string().optional(),
|
|
@@ -1371,7 +3261,7 @@ const metadataSchema$2 = z.object({
|
|
|
1371
3261
|
variables: z.array(variableSchema)
|
|
1372
3262
|
});
|
|
1373
3263
|
function isValidTableId(tableId) {
|
|
1374
|
-
return tableId.length <= MAX_TABLE_ID_LENGTH && tableId.split("/").every((segment) => SEGMENT_PATTERN.test(segment));
|
|
3264
|
+
return tableId.length <= MAX_TABLE_ID_LENGTH$1 && tableId.split("/").every((segment) => SEGMENT_PATTERN.test(segment));
|
|
1375
3265
|
}
|
|
1376
3266
|
const encodePath = (path) => path.split("/").map(encodeURIComponent).join("/");
|
|
1377
3267
|
function rootForLanguage(baseUrl, lang) {
|
|
@@ -1427,21 +3317,26 @@ function createPxwebClient(options) {
|
|
|
1427
3317
|
const failure = results.find((result) => result.status === "rejected");
|
|
1428
3318
|
if (found.length === 0 && failure) throw failure.reason;
|
|
1429
3319
|
const merged = found.flat();
|
|
1430
|
-
|
|
3320
|
+
const hits = (multiDatabase ? merged.toSorted((a, b) => b.score - a.score) : merged).map(({ score: _score, ...hit }) => hit);
|
|
3321
|
+
return rankSearchHits(uniqueByTableId(hits), now().getUTCFullYear());
|
|
1431
3322
|
},
|
|
1432
3323
|
async getMetadata(lang, tableId) {
|
|
1433
3324
|
const url = tableUrl(lang, tableId);
|
|
1434
3325
|
try {
|
|
1435
3326
|
return await request(url, { method: "GET" }, metadataSchema$2, (parsed) => ({
|
|
1436
3327
|
title: parsed.title,
|
|
1437
|
-
variables: parsed.variables.map((variable) =>
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
3328
|
+
variables: parsed.variables.map((variable) => {
|
|
3329
|
+
const namedTime = variable.time !== true && (options.timeVariables?.includes(variable.code) ?? false);
|
|
3330
|
+
return {
|
|
3331
|
+
code: variable.code,
|
|
3332
|
+
label: variable.text,
|
|
3333
|
+
values: variable.values,
|
|
3334
|
+
valueLabels: variable.valueTexts,
|
|
3335
|
+
eliminable: variable.elimination ?? false,
|
|
3336
|
+
isTime: variable.time === true || namedTime,
|
|
3337
|
+
...namedTime && { latestByCode: true }
|
|
3338
|
+
};
|
|
3339
|
+
})
|
|
1445
3340
|
}), METADATA_TTL_SECONDS, `meta:${url}`);
|
|
1446
3341
|
} catch (err) {
|
|
1447
3342
|
if (err instanceof PxwebError && NOT_FOUND_STATUSES$2.has(err.status)) throw new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
@@ -1458,7 +3353,7 @@ function createPxwebClient(options) {
|
|
|
1458
3353
|
method: "POST",
|
|
1459
3354
|
body,
|
|
1460
3355
|
headers: { "content-type": "application/json" }
|
|
1461
|
-
}, jsonStatDatasetSchema, toFlatTable$
|
|
3356
|
+
}, jsonStatDatasetSchema, toFlatTable$2, DATA_TTL_SECONDS, `data:${url}:${body}`);
|
|
1462
3357
|
}
|
|
1463
3358
|
};
|
|
1464
3359
|
}
|
|
@@ -1571,7 +3466,7 @@ function createPxwebV2Client(options) {
|
|
|
1571
3466
|
pageSize: String(SEARCH_PAGE_SIZE)
|
|
1572
3467
|
});
|
|
1573
3468
|
const url = `${baseUrl}/tables?${params.toString()}`;
|
|
1574
|
-
|
|
3469
|
+
const hits = await request(url, { method: "GET" }, tableListSchema$1, ({ tables }) => tables.map((table) => {
|
|
1575
3470
|
const hit = {
|
|
1576
3471
|
id: table.id,
|
|
1577
3472
|
title: table.label,
|
|
@@ -1584,7 +3479,8 @@ function createPxwebV2Client(options) {
|
|
|
1584
3479
|
published: hit.published,
|
|
1585
3480
|
...archived ? { archived: true } : {}
|
|
1586
3481
|
};
|
|
1587
|
-
}), SEARCH_TTL_SECONDS, `search:${url}`)
|
|
3482
|
+
}), SEARCH_TTL_SECONDS, `search:${url}`);
|
|
3483
|
+
return rankSearchHits(hits, now().getUTCFullYear());
|
|
1588
3484
|
},
|
|
1589
3485
|
async getMetadata(lang, tableId) {
|
|
1590
3486
|
const url = `${tablePath(tableId)}/metadata?${new URLSearchParams({ lang }).toString()}`;
|
|
@@ -1609,7 +3505,7 @@ function createPxwebV2Client(options) {
|
|
|
1609
3505
|
method: "POST",
|
|
1610
3506
|
body,
|
|
1611
3507
|
headers: { "content-type": "application/json" }
|
|
1612
|
-
}, jsonStatDatasetSchema, toFlatTable$
|
|
3508
|
+
}, jsonStatDatasetSchema, toFlatTable$2, DATA_TTL_SECONDS, `data:${url}:${body}`);
|
|
1613
3509
|
}
|
|
1614
3510
|
};
|
|
1615
3511
|
}
|
|
@@ -1673,7 +3569,7 @@ function periodCodes(freq, start, end) {
|
|
|
1673
3569
|
for (let step = first; step <= last; step++) codes.push(periodCode(freq, Math.floor(step / perYear), step % perYear));
|
|
1674
3570
|
return codes;
|
|
1675
3571
|
}
|
|
1676
|
-
function parsePeriod(code) {
|
|
3572
|
+
function parsePeriod$1(code) {
|
|
1677
3573
|
for (const { freq, pattern } of PERIOD_PATTERNS) {
|
|
1678
3574
|
const match = pattern.exec(code);
|
|
1679
3575
|
if (!match) continue;
|
|
@@ -1687,8 +3583,8 @@ function parsePeriod(code) {
|
|
|
1687
3583
|
}
|
|
1688
3584
|
/** Sorts by start date, then year before half-year, quarter and month; unknown codes last. */
|
|
1689
3585
|
function comparePeriods(a, b) {
|
|
1690
|
-
const left = parsePeriod(a);
|
|
1691
|
-
const right = parsePeriod(b);
|
|
3586
|
+
const left = parsePeriod$1(a);
|
|
3587
|
+
const right = parsePeriod$1(b);
|
|
1692
3588
|
if (!left || !right) {
|
|
1693
3589
|
if (left) return -1;
|
|
1694
3590
|
if (right) return 1;
|
|
@@ -1841,7 +3737,8 @@ function toTableStructure(structure, availability, lang) {
|
|
|
1841
3737
|
values: periods,
|
|
1842
3738
|
valueLabels: periods,
|
|
1843
3739
|
eliminable: false,
|
|
1844
|
-
isTime: true
|
|
3740
|
+
isTime: true,
|
|
3741
|
+
...periods.length === 0 && { periodsIncomplete: true }
|
|
1845
3742
|
});
|
|
1846
3743
|
return {
|
|
1847
3744
|
metadata: {
|
|
@@ -1938,7 +3835,7 @@ const STRUCTURE_ACCEPT = "application/vnd.sdmx.structure+json;version=1.0";
|
|
|
1938
3835
|
const DATA_ACCEPT = "application/vnd.sdmx.data+json;version=1.0";
|
|
1939
3836
|
const MAX_URL_LENGTH = 4e3;
|
|
1940
3837
|
const NO_DATA_NOTE = "No data for these periods. This table may have data only for some years; use latest.";
|
|
1941
|
-
function notFound$
|
|
3838
|
+
function notFound$3(tableId) {
|
|
1942
3839
|
return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
1943
3840
|
}
|
|
1944
3841
|
function unknownValues(code, values) {
|
|
@@ -1974,13 +3871,20 @@ function createSdmxClient(options) {
|
|
|
1974
3871
|
const { agency } = options;
|
|
1975
3872
|
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
1976
3873
|
const request = createRequester(options);
|
|
3874
|
+
const language = options.languages?.length ? { "accept-language": options.languages.join(",") } : {};
|
|
1977
3875
|
const structureGet = {
|
|
1978
3876
|
method: "GET",
|
|
1979
|
-
headers: {
|
|
3877
|
+
headers: {
|
|
3878
|
+
accept: STRUCTURE_ACCEPT,
|
|
3879
|
+
...language
|
|
3880
|
+
}
|
|
1980
3881
|
};
|
|
1981
3882
|
const dataGet = {
|
|
1982
3883
|
method: "GET",
|
|
1983
|
-
headers: {
|
|
3884
|
+
headers: {
|
|
3885
|
+
accept: DATA_ACCEPT,
|
|
3886
|
+
...language
|
|
3887
|
+
}
|
|
1984
3888
|
};
|
|
1985
3889
|
let loadingCatalogue;
|
|
1986
3890
|
function busy(promise) {
|
|
@@ -2024,14 +3928,14 @@ function createSdmxClient(options) {
|
|
|
2024
3928
|
} catch (err) {
|
|
2025
3929
|
const upper = tableId.toUpperCase();
|
|
2026
3930
|
if (!(err instanceof PxwebError && err.status === 404)) throw err;
|
|
2027
|
-
if (upper === tableId) throw notFound$
|
|
3931
|
+
if (upper === tableId) throw notFound$3(tableId);
|
|
2028
3932
|
try {
|
|
2029
3933
|
return {
|
|
2030
3934
|
flowId: upper,
|
|
2031
3935
|
data: await structure(upper)
|
|
2032
3936
|
};
|
|
2033
3937
|
} catch (retryErr) {
|
|
2034
|
-
if (retryErr instanceof PxwebError && retryErr.status === 404) throw notFound$
|
|
3938
|
+
if (retryErr instanceof PxwebError && retryErr.status === 404) throw notFound$3(tableId);
|
|
2035
3939
|
throw retryErr;
|
|
2036
3940
|
}
|
|
2037
3941
|
}
|
|
@@ -2107,7 +4011,7 @@ function createSdmxClient(options) {
|
|
|
2107
4011
|
// src/singstat-client.ts
|
|
2108
4012
|
const TABLE_ID_PATTERN$1 = /^[A-Za-z0-9]+$/;
|
|
2109
4013
|
const SERIES_CODE = "series";
|
|
2110
|
-
const TIME_CODE$
|
|
4014
|
+
const TIME_CODE$2 = "time";
|
|
2111
4015
|
const TIME_SERIES = "time series";
|
|
2112
4016
|
const searchSchema = z.object({
|
|
2113
4017
|
StatusCode: z.number().nullish(),
|
|
@@ -2149,10 +4053,10 @@ function unwrap(envelope) {
|
|
|
2149
4053
|
if (status !== 200 || !envelope.Data) throw new PxwebError(`SingStat returned ${status}: ${envelope.Message ?? "no data"}`, status === 200 ? 502 : status);
|
|
2150
4054
|
return envelope.Data;
|
|
2151
4055
|
}
|
|
2152
|
-
function checkTableId$
|
|
4056
|
+
function checkTableId$2(tableId) {
|
|
2153
4057
|
if (!TABLE_ID_PATTERN$1.test(tableId)) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it.`, 400);
|
|
2154
4058
|
}
|
|
2155
|
-
function notFound$
|
|
4059
|
+
function notFound$2(tableId) {
|
|
2156
4060
|
return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
2157
4061
|
}
|
|
2158
4062
|
function numberOrNull(value) {
|
|
@@ -2178,11 +4082,11 @@ function createSingstatClient(options) {
|
|
|
2178
4082
|
async function metadata(tableId) {
|
|
2179
4083
|
const url = `${baseUrl}/metadata/${tableId}`;
|
|
2180
4084
|
const records = await request(url, get, metadataSchema, (data) => unwrap(data).records, METADATA_TTL_SECONDS, `meta:${url}`).catch((err) => {
|
|
2181
|
-
if (err instanceof PxwebError && err.status === 404) throw notFound$
|
|
4085
|
+
if (err instanceof PxwebError && err.status === 404) throw notFound$2(tableId);
|
|
2182
4086
|
throw err;
|
|
2183
4087
|
});
|
|
2184
4088
|
const first = records.row[0];
|
|
2185
|
-
if (!first) throw notFound$
|
|
4089
|
+
if (!first) throw notFound$2(tableId);
|
|
2186
4090
|
const periodsUrl = `${baseUrl}/tabledata/${tableId}?seriesNoORrowNo=${encodeURIComponent(first.seriesNo)}`;
|
|
2187
4091
|
const periods = await request(periodsUrl, get, dataSchema$1, (data) => unwrap(data).row[0]?.columns.map((column) => column.key) ?? [], METADATA_TTL_SECONDS, `meta:${periodsUrl}`);
|
|
2188
4092
|
return {
|
|
@@ -2195,7 +4099,7 @@ function createSingstatClient(options) {
|
|
|
2195
4099
|
eliminable: false,
|
|
2196
4100
|
isTime: false
|
|
2197
4101
|
}, {
|
|
2198
|
-
code: TIME_CODE$
|
|
4102
|
+
code: TIME_CODE$2,
|
|
2199
4103
|
label: "Period",
|
|
2200
4104
|
values: periods,
|
|
2201
4105
|
valueLabels: periods,
|
|
@@ -2221,16 +4125,16 @@ function createSingstatClient(options) {
|
|
|
2221
4125
|
return rankSearchHits([...inTitle, ...hits.filter((hit) => !titled.has(hit.tableId))], now().getUTCFullYear());
|
|
2222
4126
|
},
|
|
2223
4127
|
async getMetadata(_lang, tableId) {
|
|
2224
|
-
checkTableId$
|
|
4128
|
+
checkTableId$2(tableId);
|
|
2225
4129
|
return metadata(tableId);
|
|
2226
4130
|
},
|
|
2227
4131
|
async query(_lang, tableId, selections) {
|
|
2228
|
-
checkTableId$
|
|
4132
|
+
checkTableId$2(tableId);
|
|
2229
4133
|
const table = await metadata(tableId);
|
|
2230
4134
|
const byCode = new Map(selections.map((selection) => [selection.code, selection]));
|
|
2231
4135
|
const [seriesVariable, timeVariable] = table.variables;
|
|
2232
4136
|
const series = selected(seriesVariable?.values ?? [], byCode.get(SERIES_CODE));
|
|
2233
|
-
const periods = selected(timeVariable?.values ?? [], byCode.get(TIME_CODE$
|
|
4137
|
+
const periods = selected(timeVariable?.values ?? [], byCode.get(TIME_CODE$2));
|
|
2234
4138
|
if (series?.length === 0 || periods?.length === 0) throw new PxwebError("Select at least one value for every variable.", 400);
|
|
2235
4139
|
const params = [];
|
|
2236
4140
|
if (series) params.push(`seriesNoORrowNo=${encodeURIComponent(series.join(","))}`);
|
|
@@ -2338,7 +4242,7 @@ function valueCodes(selection) {
|
|
|
2338
4242
|
if (filter === "all") return ["*"];
|
|
2339
4243
|
return values;
|
|
2340
4244
|
}
|
|
2341
|
-
function checkTableId(tableId) {
|
|
4245
|
+
function checkTableId$1(tableId) {
|
|
2342
4246
|
if (!TABLE_ID_PATTERN.test(tableId)) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it.`, 400);
|
|
2343
4247
|
}
|
|
2344
4248
|
function post$1(body) {
|
|
@@ -2377,7 +4281,7 @@ function createStatbankDkClient(options) {
|
|
|
2377
4281
|
return (await tableIndex(lang)).search(query, searchOptions);
|
|
2378
4282
|
},
|
|
2379
4283
|
async getMetadata(lang, tableId) {
|
|
2380
|
-
checkTableId(tableId);
|
|
4284
|
+
checkTableId$1(tableId);
|
|
2381
4285
|
const url = `${baseUrl}/tableinfo/${encodeURIComponent(tableId)}?${new URLSearchParams({ lang }).toString()}`;
|
|
2382
4286
|
try {
|
|
2383
4287
|
return await request(url, { method: "GET" }, tableInfoSchema, toTableMetadata, METADATA_TTL_SECONDS, `meta:${url}`);
|
|
@@ -2387,7 +4291,7 @@ function createStatbankDkClient(options) {
|
|
|
2387
4291
|
}
|
|
2388
4292
|
},
|
|
2389
4293
|
async query(lang, tableId, selections) {
|
|
2390
|
-
checkTableId(tableId);
|
|
4294
|
+
checkTableId$1(tableId);
|
|
2391
4295
|
const url = `${baseUrl}/data`;
|
|
2392
4296
|
const body = {
|
|
2393
4297
|
table: tableId,
|
|
@@ -2398,7 +4302,435 @@ function createStatbankDkClient(options) {
|
|
|
2398
4302
|
values: valueCodes(selection)
|
|
2399
4303
|
}))
|
|
2400
4304
|
};
|
|
2401
|
-
return request(url, post$1(body), jsonStat1Schema, (raw) => toFlatTable$
|
|
4305
|
+
return request(url, post$1(body), jsonStat1Schema, (raw) => toFlatTable$2(toJsonStat2(raw)), DATA_TTL_SECONDS, `data:${url}:${JSON.stringify(body)}`);
|
|
4306
|
+
}
|
|
4307
|
+
};
|
|
4308
|
+
}
|
|
4309
|
+
// src/statbel-client.ts
|
|
4310
|
+
const VIEW_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
4311
|
+
const LANGUAGES = /* @__PURE__ */ new Set([
|
|
4312
|
+
"nl",
|
|
4313
|
+
"fr",
|
|
4314
|
+
"en",
|
|
4315
|
+
"de"
|
|
4316
|
+
]);
|
|
4317
|
+
const DEFAULT_MAX_CELLS = 5e3;
|
|
4318
|
+
const MAX_CACHED_TABLES = 20;
|
|
4319
|
+
const TIME_CODE$1 = "period";
|
|
4320
|
+
const MEASURE_CODE = "indicator";
|
|
4321
|
+
/** Code of the row that a view writes with an empty (null) cell: the total over that column. */
|
|
4322
|
+
const TOTAL_CODE = "_T";
|
|
4323
|
+
/** Measures carry float noise, for example 100.75000000000036. */
|
|
4324
|
+
const SIGNIFICANT_DIGITS = 12;
|
|
4325
|
+
const EN_TEXTS = {
|
|
4326
|
+
period: "Period",
|
|
4327
|
+
measure: "Indicator",
|
|
4328
|
+
value: "Value",
|
|
4329
|
+
total: "Total",
|
|
4330
|
+
updated: "last update"
|
|
4331
|
+
};
|
|
4332
|
+
const TEXTS = {
|
|
4333
|
+
en: EN_TEXTS,
|
|
4334
|
+
nl: {
|
|
4335
|
+
period: "Periode",
|
|
4336
|
+
measure: "Indicator",
|
|
4337
|
+
value: "Waarde",
|
|
4338
|
+
total: "Totaal",
|
|
4339
|
+
updated: "laatst bijgewerkt"
|
|
4340
|
+
},
|
|
4341
|
+
fr: {
|
|
4342
|
+
period: "Période",
|
|
4343
|
+
measure: "Indicateur",
|
|
4344
|
+
value: "Valeur",
|
|
4345
|
+
total: "Total",
|
|
4346
|
+
updated: "dernière mise à jour"
|
|
4347
|
+
},
|
|
4348
|
+
de: {
|
|
4349
|
+
period: "Zeitraum",
|
|
4350
|
+
measure: "Indikator",
|
|
4351
|
+
value: "Wert",
|
|
4352
|
+
total: "Insgesamt",
|
|
4353
|
+
updated: "letzte Aktualisierung"
|
|
4354
|
+
}
|
|
4355
|
+
};
|
|
4356
|
+
const REFERENCE = "(?:reference ?|referentie|referenz)?";
|
|
4357
|
+
const TIME_COLUMNS = [
|
|
4358
|
+
["month", new RegExp(`^${REFERENCE}(?:month|maand|mois|monat)$`)],
|
|
4359
|
+
["quarter", /^(?:quarter|kwartaal|trimester|trimestre|quartal)$/],
|
|
4360
|
+
["half", /^(?:semester|semestre|halbjahr)$/],
|
|
4361
|
+
["year", new RegExp(`^${REFERENCE}(?:year|jaar|annee|jahr)$`)]
|
|
4362
|
+
];
|
|
4363
|
+
const PERIOD_LETTERS = {
|
|
4364
|
+
month: "M",
|
|
4365
|
+
quarter: "Q",
|
|
4366
|
+
half: "S",
|
|
4367
|
+
year: ""
|
|
4368
|
+
};
|
|
4369
|
+
const PERIOD_MAX = {
|
|
4370
|
+
month: 12,
|
|
4371
|
+
quarter: 4,
|
|
4372
|
+
half: 2,
|
|
4373
|
+
year: 0
|
|
4374
|
+
};
|
|
4375
|
+
const MONTHS = new Map([
|
|
4376
|
+
[
|
|
4377
|
+
"january",
|
|
4378
|
+
"januari",
|
|
4379
|
+
"janvier",
|
|
4380
|
+
"januar"
|
|
4381
|
+
],
|
|
4382
|
+
[
|
|
4383
|
+
"february",
|
|
4384
|
+
"februari",
|
|
4385
|
+
"fevrier",
|
|
4386
|
+
"februar"
|
|
4387
|
+
],
|
|
4388
|
+
[
|
|
4389
|
+
"march",
|
|
4390
|
+
"maart",
|
|
4391
|
+
"mars",
|
|
4392
|
+
"marz"
|
|
4393
|
+
],
|
|
4394
|
+
["april", "avril"],
|
|
4395
|
+
[
|
|
4396
|
+
"may",
|
|
4397
|
+
"mei",
|
|
4398
|
+
"mai"
|
|
4399
|
+
],
|
|
4400
|
+
[
|
|
4401
|
+
"june",
|
|
4402
|
+
"juni",
|
|
4403
|
+
"juin"
|
|
4404
|
+
],
|
|
4405
|
+
[
|
|
4406
|
+
"july",
|
|
4407
|
+
"juli",
|
|
4408
|
+
"juillet"
|
|
4409
|
+
],
|
|
4410
|
+
[
|
|
4411
|
+
"august",
|
|
4412
|
+
"augustus",
|
|
4413
|
+
"aout"
|
|
4414
|
+
],
|
|
4415
|
+
["september", "septembre"],
|
|
4416
|
+
[
|
|
4417
|
+
"october",
|
|
4418
|
+
"oktober",
|
|
4419
|
+
"octobre"
|
|
4420
|
+
],
|
|
4421
|
+
["november", "novembre"],
|
|
4422
|
+
[
|
|
4423
|
+
"december",
|
|
4424
|
+
"decembre",
|
|
4425
|
+
"dezember"
|
|
4426
|
+
]
|
|
4427
|
+
].flatMap((names, index) => names.map((name) => [name, index + 1])));
|
|
4428
|
+
const viewSchema = z.object({
|
|
4429
|
+
id: z.string(),
|
|
4430
|
+
name: z.string(),
|
|
4431
|
+
locale: z.string(),
|
|
4432
|
+
dataSourceId: z.string().nullish(),
|
|
4433
|
+
lastPublishDate: z.number().nullish(),
|
|
4434
|
+
inapplicable: z.boolean().nullish()
|
|
4435
|
+
});
|
|
4436
|
+
const dataSourceSchema = z.object({
|
|
4437
|
+
id: z.string(),
|
|
4438
|
+
descriptions: z.record(z.string(), z.string().nullable()).nullish(),
|
|
4439
|
+
lastDataUpdateDate: z.number().nullish()
|
|
4440
|
+
});
|
|
4441
|
+
const resultSchema = z.object({ facts: z.array(z.record(z.string(), z.union([
|
|
4442
|
+
z.string(),
|
|
4443
|
+
z.number(),
|
|
4444
|
+
z.null()
|
|
4445
|
+
]))) });
|
|
4446
|
+
function parseJson(text, schema) {
|
|
4447
|
+
let json;
|
|
4448
|
+
try {
|
|
4449
|
+
json = JSON.parse(text);
|
|
4450
|
+
} catch {
|
|
4451
|
+
throw new PxwebError("Statbel returned a response that is not JSON.", 502);
|
|
4452
|
+
}
|
|
4453
|
+
const result = schema.safeParse(json);
|
|
4454
|
+
if (!result.success) throw new PxwebError("Statbel returned an unexpected response shape.", 502);
|
|
4455
|
+
return result.data;
|
|
4456
|
+
}
|
|
4457
|
+
function isoDate(ms) {
|
|
4458
|
+
return ms ? new Date(ms).toISOString().slice(0, 10) : void 0;
|
|
4459
|
+
}
|
|
4460
|
+
function checkLanguage(lang) {
|
|
4461
|
+
if (!LANGUAGES.has(lang)) throw new PxwebError(`Language "${lang}" is not supported.`, 400);
|
|
4462
|
+
}
|
|
4463
|
+
function notFound$1(tableId) {
|
|
4464
|
+
return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
4465
|
+
}
|
|
4466
|
+
function timeKind(column) {
|
|
4467
|
+
const name = normalize(column.trim(), "en");
|
|
4468
|
+
return TIME_COLUMNS.find(([, pattern]) => pattern.test(name))?.[0];
|
|
4469
|
+
}
|
|
4470
|
+
/** "October 2025", "Octobre 2025", " 1", "3rd quarter 2025", "1ste kwartaal 2024", "2026". */
|
|
4471
|
+
function parsePeriod(kind, text) {
|
|
4472
|
+
const year = /(?<!\d)(\d{4})(?!\d)/.exec(text)?.[1];
|
|
4473
|
+
if (kind === "year") return /^\d{4}$/.test(text) ? { year: text } : void 0;
|
|
4474
|
+
const rest = normalize(text.replace(year ?? "", ""), "en").trim();
|
|
4475
|
+
const part = kind === "month" && !/^\d+$/.test(rest) ? MONTHS.get(rest) : Number(/^(\d{1,2})(?!\d)/.exec(rest)?.[1]);
|
|
4476
|
+
if (!part || part > PERIOD_MAX[kind]) return void 0;
|
|
4477
|
+
return {
|
|
4478
|
+
...year && { year },
|
|
4479
|
+
part
|
|
4480
|
+
};
|
|
4481
|
+
}
|
|
4482
|
+
/** The finest period of a row: null when every time cell is empty (a total), undefined when one does not parse. */
|
|
4483
|
+
function rowPeriod(fact, columns) {
|
|
4484
|
+
let year;
|
|
4485
|
+
let finest;
|
|
4486
|
+
for (const [column, kind] of columns) {
|
|
4487
|
+
const cell = fact[column];
|
|
4488
|
+
if (typeof cell !== "string") continue;
|
|
4489
|
+
const label = cell.trim();
|
|
4490
|
+
const parsed = parsePeriod(kind, label);
|
|
4491
|
+
if (!parsed) return void 0;
|
|
4492
|
+
year ??= parsed.year;
|
|
4493
|
+
if (parsed.part && (!finest || PERIOD_MAX[kind] > PERIOD_MAX[finest.kind])) finest = {
|
|
4494
|
+
kind,
|
|
4495
|
+
part: parsed.part,
|
|
4496
|
+
label
|
|
4497
|
+
};
|
|
4498
|
+
}
|
|
4499
|
+
if (!year && !finest) return null;
|
|
4500
|
+
if (!year) return void 0;
|
|
4501
|
+
if (!finest) return {
|
|
4502
|
+
code: year,
|
|
4503
|
+
label: year
|
|
4504
|
+
};
|
|
4505
|
+
const width = finest.kind === "month" ? 2 : 1;
|
|
4506
|
+
const code = `${year}${PERIOD_LETTERS[finest.kind]}${String(finest.part).padStart(width, "0")}`;
|
|
4507
|
+
return {
|
|
4508
|
+
code,
|
|
4509
|
+
label: finest.label.includes(year) ? finest.label : code
|
|
4510
|
+
};
|
|
4511
|
+
}
|
|
4512
|
+
/** `latest` picks the newest periods of each frequency, so annual and monthly rows both get data. */
|
|
4513
|
+
function newestPerFrequency(codes, count) {
|
|
4514
|
+
const byShape = /* @__PURE__ */ new Map();
|
|
4515
|
+
for (const code of codes) {
|
|
4516
|
+
if (code === TOTAL_CODE) continue;
|
|
4517
|
+
const shape = code.replace(/\d/g, "9");
|
|
4518
|
+
byShape.set(shape, [...byShape.get(shape) ?? [], code]);
|
|
4519
|
+
}
|
|
4520
|
+
return [...byShape.values()].flatMap((list) => list.slice(-count));
|
|
4521
|
+
}
|
|
4522
|
+
function chosenCodes(variable, selection) {
|
|
4523
|
+
if (!selection || selection.selection.filter === "all") return void 0;
|
|
4524
|
+
const { filter, values } = selection.selection;
|
|
4525
|
+
if (filter === "top") {
|
|
4526
|
+
const count = Math.max(1, Number(values[0]) || 1);
|
|
4527
|
+
if (variable.isTime) return newestPerFrequency(variable.values, count);
|
|
4528
|
+
return variable.values.slice(-count);
|
|
4529
|
+
}
|
|
4530
|
+
const known = new Set(variable.values);
|
|
4531
|
+
const unknown = values.filter((value) => !known.has(value));
|
|
4532
|
+
if (unknown.length > 0) throw new PxwebError(`Variable "${variable.code}" has no values ${unknown.join(", ")}. Call get_table_metadata to see valid value codes.`, 400);
|
|
4533
|
+
return values;
|
|
4534
|
+
}
|
|
4535
|
+
/** The total, when the column has one, comes first. */
|
|
4536
|
+
function toVariable(code, label, labels, total, isTime) {
|
|
4537
|
+
const entries = [...total === void 0 ? [] : [[TOTAL_CODE, total]], ...labels];
|
|
4538
|
+
return {
|
|
4539
|
+
code,
|
|
4540
|
+
label,
|
|
4541
|
+
values: entries.map(([value]) => value),
|
|
4542
|
+
valueLabels: entries.map(([, text]) => text),
|
|
4543
|
+
eliminable: total !== void 0,
|
|
4544
|
+
isTime
|
|
4545
|
+
};
|
|
4546
|
+
}
|
|
4547
|
+
function round(value) {
|
|
4548
|
+
return typeof value === "number" ? Number(value.toPrecision(SIGNIFICANT_DIGITS)) : null;
|
|
4549
|
+
}
|
|
4550
|
+
function compareKeys(a, b) {
|
|
4551
|
+
for (const [index, value] of a.entries()) {
|
|
4552
|
+
const difference = value - (b[index] ?? 0);
|
|
4553
|
+
if (difference !== 0) return difference;
|
|
4554
|
+
}
|
|
4555
|
+
return 0;
|
|
4556
|
+
}
|
|
4557
|
+
function toTable(facts, title, texts) {
|
|
4558
|
+
const kinds = /* @__PURE__ */ new Map();
|
|
4559
|
+
for (const fact of facts) for (const [column, cell] of Object.entries(fact)) if (typeof cell === "string") kinds.set(column, "dimension");
|
|
4560
|
+
else if (typeof cell === "number" && !kinds.has(column)) kinds.set(column, "measure");
|
|
4561
|
+
const columnsOf = (kind) => [...kinds].filter(([, value]) => value === kind).map(([column]) => column);
|
|
4562
|
+
const measures = columnsOf("measure");
|
|
4563
|
+
const timed = columnsOf("dimension").flatMap((column) => {
|
|
4564
|
+
const kind = timeKind(column);
|
|
4565
|
+
return kind ? [[column, kind]] : [];
|
|
4566
|
+
});
|
|
4567
|
+
const periods = facts.map((fact) => rowPeriod(fact, timed));
|
|
4568
|
+
const hasTime = timed.length > 0 && periods.every((period) => period !== void 0);
|
|
4569
|
+
const timeColumns = new Set(hasTime ? timed.map(([column]) => column) : []);
|
|
4570
|
+
const dimensions = columnsOf("dimension").filter((column) => !timeColumns.has(column));
|
|
4571
|
+
const labels = [...dimensions, ...hasTime ? [TIME_CODE$1] : []].map(() => /* @__PURE__ */ new Map());
|
|
4572
|
+
const rows = facts.map((fact, index) => {
|
|
4573
|
+
const cells = dimensions.map((column) => {
|
|
4574
|
+
const cell = fact[column];
|
|
4575
|
+
return typeof cell === "string" ? {
|
|
4576
|
+
code: cell.trim(),
|
|
4577
|
+
label: cell.trim()
|
|
4578
|
+
} : null;
|
|
4579
|
+
});
|
|
4580
|
+
if (hasTime) cells.push(periods[index]);
|
|
4581
|
+
cells.forEach((cell, position) => {
|
|
4582
|
+
if (cell) labels[position]?.set(cell.code, cell.label);
|
|
4583
|
+
});
|
|
4584
|
+
return {
|
|
4585
|
+
codes: cells.map((cell) => cell?.code ?? TOTAL_CODE),
|
|
4586
|
+
values: measures.map((measure) => round(fact[measure]))
|
|
4587
|
+
};
|
|
4588
|
+
});
|
|
4589
|
+
const totalOf = (position) => rows.some((row) => row.codes[position] === TOTAL_CODE) ? texts.total : void 0;
|
|
4590
|
+
const variables = dimensions.map((column, position) => toVariable(column.trim(), column.trim(), labels[position] ?? /* @__PURE__ */ new Map(), totalOf(position), false));
|
|
4591
|
+
if (hasTime) {
|
|
4592
|
+
const sorted = [...labels[dimensions.length] ?? []].toSorted(([a], [b]) => a.localeCompare(b, "en", { numeric: true }));
|
|
4593
|
+
variables.push(toVariable(TIME_CODE$1, texts.period, new Map(sorted), totalOf(dimensions.length), true));
|
|
4594
|
+
}
|
|
4595
|
+
const indicator = toVariable(MEASURE_CODE, texts.measure, new Map(measures.map((measure) => [measure, measure.trim()])), void 0, false);
|
|
4596
|
+
return {
|
|
4597
|
+
metadata: {
|
|
4598
|
+
title,
|
|
4599
|
+
variables: [...variables, indicator]
|
|
4600
|
+
},
|
|
4601
|
+
variables,
|
|
4602
|
+
indicator,
|
|
4603
|
+
rows,
|
|
4604
|
+
texts
|
|
4605
|
+
};
|
|
4606
|
+
}
|
|
4607
|
+
/**
|
|
4608
|
+
* Client for be.STAT, the open data API of Statbel (Belgium).
|
|
4609
|
+
*
|
|
4610
|
+
* - Table id = be.STAT view id (a UUID). A view exists in one language only, so the
|
|
4611
|
+
* same table in another language has another id. Labels follow the view's language.
|
|
4612
|
+
* - Search: a local index over `GET /views/` (all 1,377 views in one call) joined with
|
|
4613
|
+
* `GET /datasources/` for the subject description (path) and the last data update.
|
|
4614
|
+
* Both lists are one call each and cached for an hour, so no crawled snapshot is
|
|
4615
|
+
* needed; `listFallback` can still supply one. The list is in no useful order, so
|
|
4616
|
+
* the catalogue order is the last data update, newest first: an old copy of a view
|
|
4617
|
+
* (same title, a data source that stopped) then ranks below the current one.
|
|
4618
|
+
* "Inapplicable" views answer with an empty body and are marked discontinued.
|
|
4619
|
+
* - Metadata and query read `GET /views/{id}/result/JSON`, a flat list of facts.
|
|
4620
|
+
* String columns are dimensions, number columns are indicators (one variable).
|
|
4621
|
+
* Value codes are the trimmed labels; a null cell is the total over that column
|
|
4622
|
+
* (code "_T"), so a variable with totals is optional and a left-out optional
|
|
4623
|
+
* variable keeps only its total rows when there are any. Time columns (Year, Month,
|
|
4624
|
+
* Quarter, Semester in en/nl/fr/de) merge into one "period" variable with codes
|
|
4625
|
+
* such as "2026", "2026M10", "2026Q2" and "2026S1".
|
|
4626
|
+
* - The query filters the cached facts locally and returns one row per indicator.
|
|
4627
|
+
*/
|
|
4628
|
+
function createStatbelClient(options) {
|
|
4629
|
+
const root = options.baseUrl.replace(/\/+$/, "");
|
|
4630
|
+
const maxCells = options.maxCells ?? DEFAULT_MAX_CELLS;
|
|
4631
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
4632
|
+
const request = createTextRequester(options);
|
|
4633
|
+
function get(path, map, ttlSeconds) {
|
|
4634
|
+
const url = `${root}/${path}`;
|
|
4635
|
+
return request(url, { method: "GET" }, map, ttlSeconds, url);
|
|
4636
|
+
}
|
|
4637
|
+
async function listTables(lang) {
|
|
4638
|
+
checkLanguage(lang);
|
|
4639
|
+
const [views, dataSources] = await Promise.all([get("views/", (text) => parseJson(text, z.array(viewSchema)), SEARCH_TTL_SECONDS), get("datasources/", (text) => parseJson(text, z.array(dataSourceSchema)), SEARCH_TTL_SECONDS).catch(() => [])]);
|
|
4640
|
+
const sources = new Map(dataSources.map((source) => [source.id, source]));
|
|
4641
|
+
return views.filter((view) => view.locale === lang).map((view) => {
|
|
4642
|
+
const source = sources.get(view.dataSourceId ?? "");
|
|
4643
|
+
const description = source?.descriptions?.[lang]?.trim();
|
|
4644
|
+
const updated = isoDate(source?.lastDataUpdateDate ?? view.lastPublishDate);
|
|
4645
|
+
return {
|
|
4646
|
+
id: view.id,
|
|
4647
|
+
title: view.name.trim(),
|
|
4648
|
+
...description && { path: [description] },
|
|
4649
|
+
...updated && { updated },
|
|
4650
|
+
...view.inapplicable && { discontinued: true }
|
|
4651
|
+
};
|
|
4652
|
+
}).toSorted((a, b) => (b.updated ?? "").localeCompare(a.updated ?? ""));
|
|
4653
|
+
}
|
|
4654
|
+
const tableIndex = createTableIndexLoader(listTables, {
|
|
4655
|
+
fallback: options.listFallback,
|
|
4656
|
+
ttlSeconds: SEARCH_TTL_SECONDS,
|
|
4657
|
+
currentYear: () => now().getUTCFullYear()
|
|
4658
|
+
});
|
|
4659
|
+
async function loadTable(lang, tableId) {
|
|
4660
|
+
checkLanguage(lang);
|
|
4661
|
+
if (!VIEW_ID_PATTERN.test(tableId)) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it.`, 400);
|
|
4662
|
+
const [view, result] = await Promise.all([get(`views/${tableId}`, (text) => parseJson(text, viewSchema), METADATA_TTL_SECONDS), get(`views/${tableId}/result/JSON`, (text) => text.trim() ? parseJson(text, resultSchema) : void 0, DATA_TTL_SECONDS)]).catch((err) => {
|
|
4663
|
+
if (err instanceof PxwebError && err.status === 404) throw notFound$1(tableId);
|
|
4664
|
+
if (err instanceof PxwebError && err.status >= 500) throw new PxwebError(`Statbel could not answer for table "${tableId}" (HTTP ${err.status}). Try again later or use another table.`, 502);
|
|
4665
|
+
throw err;
|
|
4666
|
+
});
|
|
4667
|
+
if (!result || result.facts.length === 0) throw new PxwebError(`Table "${tableId}" has no data now. Use search_tables to find a current table.`, 404);
|
|
4668
|
+
const texts = TEXTS[view.locale] ?? EN_TEXTS;
|
|
4669
|
+
const updated = view.dataSourceId ? await get(`datasources/${view.dataSourceId}`, (text) => isoDate(parseJson(text, dataSourceSchema).lastDataUpdateDate), DATA_TTL_SECONDS).catch(() => void 0) : void 0;
|
|
4670
|
+
const name = view.name.trim();
|
|
4671
|
+
const title = updated ? `${name} (${texts.updated}: ${updated})` : name;
|
|
4672
|
+
return toTable(result.facts, title, texts);
|
|
4673
|
+
}
|
|
4674
|
+
const tables = /* @__PURE__ */ new Map();
|
|
4675
|
+
async function cachedTable(lang, tableId) {
|
|
4676
|
+
const key = `${lang}:${tableId}`;
|
|
4677
|
+
const cached = tables.get(key);
|
|
4678
|
+
if (cached && cached.expires > Date.now()) return cached.table;
|
|
4679
|
+
const table = await loadTable(lang, tableId);
|
|
4680
|
+
tables.delete(key);
|
|
4681
|
+
tables.set(key, {
|
|
4682
|
+
expires: Date.now() + DATA_TTL_SECONDS * 1e3,
|
|
4683
|
+
table
|
|
4684
|
+
});
|
|
4685
|
+
const oldest = tables.keys().next().value;
|
|
4686
|
+
if (tables.size > MAX_CACHED_TABLES && oldest !== void 0) tables.delete(oldest);
|
|
4687
|
+
return table;
|
|
4688
|
+
}
|
|
4689
|
+
return {
|
|
4690
|
+
listTables,
|
|
4691
|
+
async search(lang, query, searchOptions) {
|
|
4692
|
+
checkLanguage(lang);
|
|
4693
|
+
return (await tableIndex(lang)).search(query, searchOptions);
|
|
4694
|
+
},
|
|
4695
|
+
async getMetadata(lang, tableId) {
|
|
4696
|
+
return (await cachedTable(lang, tableId)).metadata;
|
|
4697
|
+
},
|
|
4698
|
+
async query(lang, tableId, selections) {
|
|
4699
|
+
const table = await cachedTable(lang, tableId);
|
|
4700
|
+
const byCode = new Map(selections.map((selection) => [selection.code, selection]));
|
|
4701
|
+
let rows = table.rows;
|
|
4702
|
+
table.variables.forEach((variable, position) => {
|
|
4703
|
+
const codes = chosenCodes(variable, byCode.get(variable.code));
|
|
4704
|
+
if (!codes) return;
|
|
4705
|
+
const wanted = new Set(codes);
|
|
4706
|
+
rows = rows.filter((row) => wanted.has(row.codes[position] ?? ""));
|
|
4707
|
+
});
|
|
4708
|
+
table.variables.forEach((variable, position) => {
|
|
4709
|
+
if (!variable.eliminable || byCode.has(variable.code)) return;
|
|
4710
|
+
const totals = rows.filter((row) => row.codes[position] === TOTAL_CODE);
|
|
4711
|
+
if (totals.length > 0) rows = totals;
|
|
4712
|
+
});
|
|
4713
|
+
const indicators = (chosenCodes(table.indicator, byCode.get(MEASURE_CODE)) ?? table.indicator.values).map((code) => table.indicator.values.indexOf(code));
|
|
4714
|
+
const cells = rows.length * indicators.length;
|
|
4715
|
+
if (cells > maxCells) throw new PxwebError(`The query returns ${cells} cells, above the limit of ${maxCells}. Select fewer values.`, 400);
|
|
4716
|
+
const positions = table.variables.map((variable) => new Map(variable.values.map((value, index) => [value, index])));
|
|
4717
|
+
const sorted = rows.map((row) => ({
|
|
4718
|
+
row,
|
|
4719
|
+
key: row.codes.map((code, position) => positions[position]?.get(code) ?? 0)
|
|
4720
|
+
})).toSorted((a, b) => compareKeys(a.key, b.key));
|
|
4721
|
+
return {
|
|
4722
|
+
label: table.metadata.title,
|
|
4723
|
+
columns: [
|
|
4724
|
+
...table.variables.map((variable) => variable.label),
|
|
4725
|
+
table.indicator.label,
|
|
4726
|
+
table.texts.value
|
|
4727
|
+
],
|
|
4728
|
+
rows: sorted.flatMap(({ row, key }) => indicators.map((index) => [
|
|
4729
|
+
...row.codes.map((code, position) => table.variables[position]?.valueLabels[key[position] ?? -1] ?? code),
|
|
4730
|
+
table.indicator.valueLabels[index] ?? "",
|
|
4731
|
+
row.values[index] ?? null
|
|
4732
|
+
]))
|
|
4733
|
+
};
|
|
2402
4734
|
}
|
|
2403
4735
|
};
|
|
2404
4736
|
}
|
|
@@ -2586,13 +4918,15 @@ function createStatcanClient(options) {
|
|
|
2586
4918
|
isTime: false
|
|
2587
4919
|
}));
|
|
2588
4920
|
const periods = periodsOf(listed.cubeStartDate ?? void 0, listed.cubeEndDate ?? void 0, frequency);
|
|
4921
|
+
const incomplete = !REGULAR_FREQUENCIES[frequency ?? ""] || !listed.cubeStartDate;
|
|
2589
4922
|
variables.push({
|
|
2590
4923
|
code: TIME_CODE,
|
|
2591
4924
|
label: french ? "Période de référence" : "Reference period",
|
|
2592
4925
|
values: periods,
|
|
2593
4926
|
valueLabels: periods,
|
|
2594
4927
|
eliminable: false,
|
|
2595
|
-
isTime: true
|
|
4928
|
+
isTime: true,
|
|
4929
|
+
...incomplete && { periodsIncomplete: true }
|
|
2596
4930
|
});
|
|
2597
4931
|
return {
|
|
2598
4932
|
metadata: {
|
|
@@ -2687,31 +5021,19 @@ function createStatcanClient(options) {
|
|
|
2687
5021
|
}
|
|
2688
5022
|
};
|
|
2689
5023
|
}
|
|
2690
|
-
// src/tools/tool-input.ts
|
|
2691
|
-
/** Tool input without the `$schema` URI: clients send it to the model on every turn, and it carries no meaning there. */
|
|
2692
|
-
function toolInput(shape) {
|
|
2693
|
-
const schema = z.object(shape);
|
|
2694
|
-
const standard = schema["~standard"];
|
|
2695
|
-
const { jsonSchema } = standard;
|
|
2696
|
-
schema["~standard"] = {
|
|
2697
|
-
...standard,
|
|
2698
|
-
jsonSchema: {
|
|
2699
|
-
input: (options) => {
|
|
2700
|
-
const { $schema: _uri, ...rest } = jsonSchema.input(options);
|
|
2701
|
-
return rest;
|
|
2702
|
-
},
|
|
2703
|
-
output: (options) => {
|
|
2704
|
-
const { $schema: _uri, ...rest } = jsonSchema.output(options);
|
|
2705
|
-
return rest;
|
|
2706
|
-
}
|
|
2707
|
-
}
|
|
2708
|
-
};
|
|
2709
|
-
return schema;
|
|
2710
|
-
}
|
|
2711
5024
|
// src/query-plan.ts
|
|
2712
5025
|
const DEFAULT_MAX_RESULT_CHARS = 3e4;
|
|
2713
5026
|
const VALUE_CHARS = 10;
|
|
2714
5027
|
const CHARS_PER_TOKEN = 3.5;
|
|
5028
|
+
const CYRILLIC_PERIOD_LETTERS = {
|
|
5029
|
+
М: "M",
|
|
5030
|
+
К: "K"
|
|
5031
|
+
};
|
|
5032
|
+
const periodSortKey = (code) => code.replace(/[МК]/g, (letter) => CYRILLIC_PERIOD_LETTERS[letter] ?? letter);
|
|
5033
|
+
/** The `count` newest period codes, newest last, whatever the API's order. */
|
|
5034
|
+
function newestCodes(values, count) {
|
|
5035
|
+
return values.toSorted((a, b) => periodSortKey(a).localeCompare(periodSortKey(b), "en", { numeric: true })).slice(-count);
|
|
5036
|
+
}
|
|
2715
5037
|
function averageLabelLength(variable, values) {
|
|
2716
5038
|
if (values.length === 0) return 0;
|
|
2717
5039
|
const labels = new Map(variable.values.map((value, index) => [value, variable.valueLabels[index]]));
|
|
@@ -2749,8 +5071,24 @@ function planQuery(metadata, inputs, maxCells, maxResultChars = DEFAULT_MAX_RESU
|
|
|
2749
5071
|
const sizes = [];
|
|
2750
5072
|
for (const variable of metadata.variables) {
|
|
2751
5073
|
const input = inputByCode.get(variable.code);
|
|
5074
|
+
if (input?.latest !== void 0 && variable.latestByCode) {
|
|
5075
|
+
const newest = newestCodes(variable.values, input.latest);
|
|
5076
|
+
selections.push({
|
|
5077
|
+
code: variable.code,
|
|
5078
|
+
selection: {
|
|
5079
|
+
filter: "item",
|
|
5080
|
+
values: newest
|
|
5081
|
+
}
|
|
5082
|
+
});
|
|
5083
|
+
sizes.push({
|
|
5084
|
+
label: variable.label,
|
|
5085
|
+
count: newest.length,
|
|
5086
|
+
labelChars: averageLabelLength(variable, newest)
|
|
5087
|
+
});
|
|
5088
|
+
continue;
|
|
5089
|
+
}
|
|
2752
5090
|
if (input?.latest !== void 0) {
|
|
2753
|
-
const count = Math.min(input.latest, variable.values.length);
|
|
5091
|
+
const count = variable.periodsIncomplete ? input.latest : Math.min(input.latest, variable.values.length);
|
|
2754
5092
|
selections.push({
|
|
2755
5093
|
code: variable.code,
|
|
2756
5094
|
selection: {
|
|
@@ -2809,6 +5147,50 @@ function planQuery(metadata, inputs, maxCells, maxResultChars = DEFAULT_MAX_RESU
|
|
|
2809
5147
|
estimatedChars
|
|
2810
5148
|
};
|
|
2811
5149
|
}
|
|
5150
|
+
const MAX_VALUES_PER_SELECTION = 5e3;
|
|
5151
|
+
function checkLength(name, value, max, hint) {
|
|
5152
|
+
if (value.length > max) throw new QueryPlanError(`${name} is too long (over ${max} characters). ${hint}`);
|
|
5153
|
+
}
|
|
5154
|
+
function checkTableId(tableId) {
|
|
5155
|
+
checkLength("tableId", tableId, 200, "Use the id exactly as search_tables returns it.");
|
|
5156
|
+
}
|
|
5157
|
+
function checkSearchInput(query) {
|
|
5158
|
+
checkLength("query", query, 200, "Use a few short keywords.");
|
|
5159
|
+
}
|
|
5160
|
+
function checkMetadataInput(tableId, valueFilter) {
|
|
5161
|
+
checkTableId(tableId);
|
|
5162
|
+
if (valueFilter !== void 0) checkLength("valueFilter", valueFilter, 100, "Use a short piece of a label.");
|
|
5163
|
+
}
|
|
5164
|
+
function checkQueryInput(tableId, selections) {
|
|
5165
|
+
checkTableId(tableId);
|
|
5166
|
+
if (selections.length > 30) throw new QueryPlanError(`Too many selections (over 30). Leave out variables you do not need.`);
|
|
5167
|
+
for (const selection of selections) {
|
|
5168
|
+
const values = selection.values ?? [];
|
|
5169
|
+
if (values.length > 5e3) throw new QueryPlanError(`Too many values for "${selection.code}" (over ${MAX_VALUES_PER_SELECTION}). Select fewer values or use latest.`);
|
|
5170
|
+
for (const value of values) checkLength("A value code", value, 200, "Use value codes exactly as get_table_metadata returns them.");
|
|
5171
|
+
}
|
|
5172
|
+
}
|
|
5173
|
+
// src/tools/tool-input.ts
|
|
5174
|
+
/** Tool input without the `$schema` URI: clients send it to the model on every turn, and it carries no meaning there. */
|
|
5175
|
+
function toolInput(shape) {
|
|
5176
|
+
const schema = z.object(shape);
|
|
5177
|
+
const standard = schema["~standard"];
|
|
5178
|
+
const { jsonSchema } = standard;
|
|
5179
|
+
schema["~standard"] = {
|
|
5180
|
+
...standard,
|
|
5181
|
+
jsonSchema: {
|
|
5182
|
+
input: (options) => {
|
|
5183
|
+
const { $schema: _uri, ...rest } = jsonSchema.input(options);
|
|
5184
|
+
return rest;
|
|
5185
|
+
},
|
|
5186
|
+
output: (options) => {
|
|
5187
|
+
const { $schema: _uri, ...rest } = jsonSchema.output(options);
|
|
5188
|
+
return rest;
|
|
5189
|
+
}
|
|
5190
|
+
}
|
|
5191
|
+
};
|
|
5192
|
+
return schema;
|
|
5193
|
+
}
|
|
2812
5194
|
// src/tools/tool-result.ts
|
|
2813
5195
|
function textResult(text) {
|
|
2814
5196
|
return { content: [{
|
|
@@ -2844,7 +5226,7 @@ async function runTool(handler) {
|
|
|
2844
5226
|
return toolError(err.message);
|
|
2845
5227
|
}
|
|
2846
5228
|
console.error("Unexpected tool error", err);
|
|
2847
|
-
return toolError(
|
|
5229
|
+
return toolError(`Unexpected error while reading statistics data${err instanceof Error ? ` (${err.name})` : ""}.`);
|
|
2848
5230
|
}
|
|
2849
5231
|
}
|
|
2850
5232
|
// src/tools/search-tools.ts
|
|
@@ -2868,6 +5250,7 @@ const includeArchivedSchema = z.boolean().optional().describe("Also list discont
|
|
|
2868
5250
|
function searchTables(client, preset, args) {
|
|
2869
5251
|
const { query, lang, limit, includeArchived } = args;
|
|
2870
5252
|
return runTool(async () => {
|
|
5253
|
+
checkSearchInput(query);
|
|
2871
5254
|
const hits = await searchWithAliases(client, preset, lang, query, includeArchived);
|
|
2872
5255
|
if (!hits.length) {
|
|
2873
5256
|
const archived = includeArchived ? [] : await searchWithAliases(client, preset, lang, query, true);
|
|
@@ -2953,16 +5336,22 @@ function sourceLine(preset, language, id) {
|
|
|
2953
5336
|
}
|
|
2954
5337
|
function getTableMetadata(client, preset, args) {
|
|
2955
5338
|
return runTool(async () => {
|
|
5339
|
+
checkMetadataInput(args.tableId, args.valueFilter);
|
|
2956
5340
|
const metadata = await client.getMetadata(args.lang, args.tableId);
|
|
2957
5341
|
return textResult(`${formatMetadata(args.tableId, metadata, args.valueFilter)}\n\nOptional variables can be left out; the result then shows their total. Required variables left out return all their values.\n\n${sourceLine(preset, args.lang, args.tableId)}`);
|
|
2958
5342
|
});
|
|
2959
5343
|
}
|
|
2960
5344
|
function queryTable(client, preset, args) {
|
|
2961
5345
|
return runTool(async () => {
|
|
5346
|
+
checkQueryInput(args.tableId, args.selections);
|
|
2962
5347
|
const metadata = await client.getMetadata(args.lang, args.tableId);
|
|
2963
5348
|
const plan = planQuery(metadata, args.selections, preset.maxCells, preset.maxResultChars);
|
|
2964
5349
|
const table = await client.query(args.lang, args.tableId, plan.selections);
|
|
2965
|
-
|
|
5350
|
+
const csv = toCsv(table);
|
|
5351
|
+
const maxChars = preset.maxResultChars ?? 3e4;
|
|
5352
|
+
if (table.rows.length > preset.maxCells) throw new QueryPlanError(`The result has ${table.rows.length} rows, above the limit of ${preset.maxCells}. Select fewer values or use a smaller latest.`);
|
|
5353
|
+
if (csv.length > maxChars) throw new QueryPlanError(`The result has ${csv.length} characters, above the limit of ${maxChars}. Select fewer values or use a smaller latest.`);
|
|
5354
|
+
return textResult(`${`${table.label ?? metadata.title}. ${table.rows.length} rows.`}\n\n${csv}\n\n${sourceLine(preset, args.lang, args.tableId)}`);
|
|
2966
5355
|
});
|
|
2967
5356
|
}
|
|
2968
5357
|
function registerTableTools(server, client, preset) {
|
|
@@ -3012,7 +5401,7 @@ function createPxwebServer(preset, client) {
|
|
|
3012
5401
|
registerTableTools(server, client, preset);
|
|
3013
5402
|
return server;
|
|
3014
5403
|
}
|
|
3015
|
-
/** PxWeb v1 and
|
|
5404
|
+
/** PxWeb v1, PxStat, INE Spain and Portugal, and INSEE have no small list endpoint, so index search reads the crawled snapshot. */
|
|
3016
5405
|
function snapshotTableList(preset, tableSnapshots) {
|
|
3017
5406
|
return async (lang) => {
|
|
3018
5407
|
const snapshot = await tableSnapshots?.(preset.name, lang);
|
|
@@ -3027,6 +5416,7 @@ function createPresetClient(preset, options) {
|
|
|
3027
5416
|
...http,
|
|
3028
5417
|
baseUrl: preset.apiBaseUrl,
|
|
3029
5418
|
database: preset.database,
|
|
5419
|
+
timeVariables: preset.timeVariables,
|
|
3030
5420
|
tableIdFromHit: preset.tableIdFromHit,
|
|
3031
5421
|
isArchived: preset.isArchived,
|
|
3032
5422
|
...preset.search === "index" ? { tableList: snapshotTableList(preset, tableSnapshots) } : {}
|
|
@@ -3037,6 +5427,28 @@ function createPresetClient(preset, options) {
|
|
|
3037
5427
|
baseUrl: preset.apiBaseUrl,
|
|
3038
5428
|
tableList: snapshotTableList(preset, tableSnapshots)
|
|
3039
5429
|
});
|
|
5430
|
+
if (api === "ine-es") return createIneEsClient({
|
|
5431
|
+
...http,
|
|
5432
|
+
baseUrl: preset.apiBaseUrl,
|
|
5433
|
+
tableList: snapshotTableList(preset, tableSnapshots)
|
|
5434
|
+
});
|
|
5435
|
+
if (api === "ine-pt") return createInePtClient({
|
|
5436
|
+
...http,
|
|
5437
|
+
baseUrl: preset.apiBaseUrl,
|
|
5438
|
+
maxCells: preset.maxCells,
|
|
5439
|
+
tableList: snapshotTableList(preset, tableSnapshots)
|
|
5440
|
+
});
|
|
5441
|
+
if (api === "insee") return createInseeClient({
|
|
5442
|
+
...http,
|
|
5443
|
+
baseUrl: preset.apiBaseUrl,
|
|
5444
|
+
maxCells: preset.maxCells,
|
|
5445
|
+
tableList: snapshotTableList(preset, tableSnapshots)
|
|
5446
|
+
});
|
|
5447
|
+
if (api === "ons") return createOnsClient({
|
|
5448
|
+
...http,
|
|
5449
|
+
baseUrl: preset.apiBaseUrl,
|
|
5450
|
+
maxCells: preset.maxCells
|
|
5451
|
+
});
|
|
3040
5452
|
if (api === "singstat") return createSingstatClient({
|
|
3041
5453
|
...http,
|
|
3042
5454
|
baseUrl: preset.apiBaseUrl
|
|
@@ -3050,9 +5462,28 @@ function createPresetClient(preset, options) {
|
|
|
3050
5462
|
if (!preset.sdmxAgency) throw new Error("An sdmx preset needs sdmxAgency.");
|
|
3051
5463
|
return createSdmxClient({
|
|
3052
5464
|
...indexed,
|
|
3053
|
-
agency: preset.sdmxAgency
|
|
5465
|
+
agency: preset.sdmxAgency,
|
|
5466
|
+
languages: preset.languages
|
|
3054
5467
|
});
|
|
3055
5468
|
}
|
|
5469
|
+
if (api === "statbel") return createStatbelClient({
|
|
5470
|
+
...indexed,
|
|
5471
|
+
maxCells: preset.maxCells
|
|
5472
|
+
});
|
|
5473
|
+
if (api === "czso") return createCzsoClient({
|
|
5474
|
+
...indexed,
|
|
5475
|
+
maxCells: preset.maxCells
|
|
5476
|
+
});
|
|
5477
|
+
if (api === "ibge") return createIbgeClient({
|
|
5478
|
+
...indexed,
|
|
5479
|
+
maxCells: preset.maxCells,
|
|
5480
|
+
...tableSnapshots && { crawledList: async (lang) => (await tableSnapshots(preset.name, lang))?.docs }
|
|
5481
|
+
});
|
|
5482
|
+
if (api === "osp") return createOspClient({
|
|
5483
|
+
...indexed,
|
|
5484
|
+
maxCells: preset.maxCells,
|
|
5485
|
+
...tableSnapshots && { crawledList: async (lang) => (await tableSnapshots(preset.name, lang))?.docs }
|
|
5486
|
+
});
|
|
3056
5487
|
if (api === "statcan-wds") return createStatcanClient(indexed);
|
|
3057
5488
|
if (api === "eurostat") return createEurostatClient(indexed);
|
|
3058
5489
|
if (api === "cbs-odata") return createCbsODataClient(indexed);
|
|
@@ -3189,4 +5620,4 @@ function createMultiServer(entries, options) {
|
|
|
3189
5620
|
});
|
|
3190
5621
|
return server;
|
|
3191
5622
|
}
|
|
3192
|
-
export { DEFAULT_MAX_RESULT_CHARS, PxwebError, QueryPlanError, SNAPSHOT_VERSION, bucketSnapshotReader, createCbsODataClient, createEurostatClient, createMemoryCache, createMultiServer, createPresetClient, createPresetServer, createPxstatClient, createPxwebClient, createPxwebServer, createPxwebV2Client, createSdmxClient, createSingstatClient, createStatbankDkClient, createStatcanClient, createTableIndex, createTableIndexLoader, firstSnapshot, flattenJsonStat, planQuery, readSnapshot, searchTitles, snapshotKey, tableDocSchema, toCsv, urlSnapshotReader, writeSnapshot };
|
|
5623
|
+
export { DEFAULT_MAX_RESULT_CHARS, PxwebError, QueryPlanError, SEARCH_INDEX_VERSION, SNAPSHOT_VERSION, asPrebuiltIndex, bucketSnapshotReader, buildSearchIndex, createCbsODataClient, createCzsoClient, createEurostatClient, createIbgeClient, createIneEsClient, createInePtClient, createInseeClient, createMemoryCache, createMultiServer, createOnsClient, createOspClient, createPresetClient, createPresetServer, createPxstatClient, createPxwebClient, createPxwebServer, createPxwebV2Client, createSdmxClient, createSingstatClient, createStatbankDkClient, createStatbelClient, createStatcanClient, createTableIndex, createTableIndexLoader, firstSnapshot, flattenJsonStat, onsTableUrl, planQuery, readSnapshot, searchTitles, snapshotKey, tableDocSchema, toCsv, urlSnapshotReader, writeSnapshot };
|