@statsmcp/core 0.4.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +264 -6
- package/dist/index.js +3300 -511
- 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-CMstGbu-.js +635 -0
- package/package.json +3 -3
- 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-CMstGbu-.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,406 @@ function createTextRequester(options) {
|
|
|
214
213
|
return result;
|
|
215
214
|
};
|
|
216
215
|
}
|
|
217
|
-
// src/
|
|
218
|
-
const
|
|
219
|
-
const
|
|
220
|
-
const
|
|
221
|
-
|
|
222
|
-
const
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
216
|
+
// src/bdl-client.ts
|
|
217
|
+
const TABLE_ID_PATTERN$10 = /^P\d{1,6}$/;
|
|
218
|
+
const DEFAULT_MAX_CELLS$6 = 5e3;
|
|
219
|
+
const MAX_CACHED_TABLES$5 = 8;
|
|
220
|
+
/** The API refuses a larger page size. */
|
|
221
|
+
const PAGE_SIZE = 100;
|
|
222
|
+
/** Parallel page requests; the anonymous limit is 5 requests per second. */
|
|
223
|
+
const PAGE_BATCH = 4;
|
|
224
|
+
const MAX_VARIABLE_PAGES = 20;
|
|
225
|
+
const VAR_IDS_PER_CALL = PAGE_SIZE;
|
|
226
|
+
/** Keeps one query well inside the anonymous limit of 100 requests per 15 minutes. */
|
|
227
|
+
const MAX_DATA_CALLS = 20;
|
|
228
|
+
const DIMENSION_FIELDS = [
|
|
229
|
+
"n1",
|
|
230
|
+
"n2",
|
|
231
|
+
"n3",
|
|
232
|
+
"n4",
|
|
233
|
+
"n5"
|
|
234
|
+
];
|
|
235
|
+
const UNIT_CODE = "unit";
|
|
236
|
+
const YEAR_CODE = "year";
|
|
237
|
+
const POLAND = "000000000000";
|
|
238
|
+
const COUNTRY_LEVEL$1 = 0;
|
|
239
|
+
const VOIVODESHIP_LEVEL = 2;
|
|
240
|
+
const VOIVODESHIPS = [
|
|
241
|
+
["030200000000", "Dolnośląskie"],
|
|
242
|
+
["040400000000", "Kujawsko-pomorskie"],
|
|
243
|
+
["060600000000", "Lubelskie"],
|
|
244
|
+
["020800000000", "Lubuskie"],
|
|
245
|
+
["051000000000", "Łódzkie"],
|
|
246
|
+
["011200000000", "Małopolskie"],
|
|
247
|
+
["071400000000", "Mazowieckie"],
|
|
248
|
+
["031600000000", "Opolskie"],
|
|
249
|
+
["061800000000", "Podkarpackie"],
|
|
250
|
+
["062000000000", "Podlaskie"],
|
|
251
|
+
["042200000000", "Pomorskie"],
|
|
252
|
+
["012400000000", "Śląskie"],
|
|
253
|
+
["052600000000", "Świętokrzyskie"],
|
|
254
|
+
["042800000000", "Warmińsko-mazurskie"],
|
|
255
|
+
["023000000000", "Wielkopolskie"],
|
|
256
|
+
["023200000000", "Zachodniopomorskie"]
|
|
257
|
+
];
|
|
258
|
+
/** Attributes "x", "X", "-" and "n": the value field holds 0, but there is no value. */
|
|
259
|
+
const MISSING_ATTRIBUTES = /* @__PURE__ */ new Set([
|
|
260
|
+
4,
|
|
261
|
+
14,
|
|
262
|
+
15,
|
|
263
|
+
50,
|
|
264
|
+
91
|
|
265
|
+
]);
|
|
266
|
+
const ARCHIVE_GROUP = /archival|archiwaln/i;
|
|
267
|
+
const LABELS = {
|
|
268
|
+
pl: {
|
|
269
|
+
unit: "Jednostka terytorialna",
|
|
270
|
+
year: "Rok",
|
|
271
|
+
measure: "Jednostka miary",
|
|
272
|
+
value: "Wartość",
|
|
273
|
+
poland: "Polska",
|
|
274
|
+
dimension: "Wymiar"
|
|
275
|
+
},
|
|
276
|
+
en: {
|
|
277
|
+
unit: "Territorial unit",
|
|
278
|
+
year: "Year",
|
|
279
|
+
measure: "Measure unit",
|
|
280
|
+
value: "Value",
|
|
281
|
+
poland: "Poland",
|
|
282
|
+
dimension: "Dimension"
|
|
283
|
+
}
|
|
259
284
|
};
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
285
|
+
const subjectListSchema = z.object({
|
|
286
|
+
totalRecords: z.number(),
|
|
287
|
+
results: z.array(z.object({
|
|
288
|
+
id: z.string(),
|
|
289
|
+
parentId: z.string().nullish(),
|
|
290
|
+
name: z.string(),
|
|
291
|
+
hasVariables: z.boolean()
|
|
292
|
+
}))
|
|
293
|
+
});
|
|
294
|
+
const subjectSchema = z.object({
|
|
295
|
+
name: z.string(),
|
|
296
|
+
years: z.array(z.number()).default([]),
|
|
297
|
+
dimensions: z.array(z.string()).default([])
|
|
298
|
+
});
|
|
299
|
+
const variablesSchema = z.object({
|
|
300
|
+
totalRecords: z.number(),
|
|
301
|
+
results: z.array(z.object({
|
|
302
|
+
id: z.number(),
|
|
303
|
+
n1: z.string().nullish(),
|
|
304
|
+
n2: z.string().nullish(),
|
|
305
|
+
n3: z.string().nullish(),
|
|
306
|
+
n4: z.string().nullish(),
|
|
307
|
+
n5: z.string().nullish(),
|
|
308
|
+
level: z.number(),
|
|
309
|
+
measureUnitName: z.string().nullish()
|
|
310
|
+
}))
|
|
311
|
+
});
|
|
312
|
+
const yearValuesSchema = z.array(z.object({
|
|
313
|
+
year: z.string(),
|
|
314
|
+
val: z.number().nullable(),
|
|
315
|
+
attrId: z.number()
|
|
316
|
+
}));
|
|
317
|
+
const dataByUnitSchema = z.object({ results: z.array(z.object({
|
|
318
|
+
id: z.number(),
|
|
319
|
+
values: yearValuesSchema
|
|
320
|
+
})) });
|
|
321
|
+
const dataByVariableSchema = z.object({ results: z.array(z.object({
|
|
322
|
+
id: z.string(),
|
|
323
|
+
values: yearValuesSchema
|
|
324
|
+
})) });
|
|
325
|
+
function labelsFor(lang) {
|
|
326
|
+
const labels = LABELS[lang];
|
|
327
|
+
if (!labels) throw new PxwebError(`Language "${lang}" is not supported.`, 400);
|
|
328
|
+
return labels;
|
|
263
329
|
}
|
|
264
|
-
|
|
265
|
-
|
|
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;
|
|
330
|
+
function notFound$14(tableId) {
|
|
331
|
+
return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
272
332
|
}
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
return [...new Set(normalize(query, lang).split(/[^\p{L}\p{N}]+/u).filter((term) => term.length >= MIN_TERM_LENGTH$1))];
|
|
333
|
+
/** The API's own error reason, from a body such as `{"errors":[{"errorReason":"…"}]}`. */
|
|
334
|
+
function upstreamReason(message) {
|
|
335
|
+
return /"errorReason"\s*:\s*"([^"]+)"/.exec(message)?.[1] ?? message.replace(/^.*?HTTP \d+:\s*/, "");
|
|
277
336
|
}
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
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);
|
|
337
|
+
function upstreamError$3(err) {
|
|
338
|
+
if (!(err instanceof PxwebError)) return err;
|
|
339
|
+
if (err.status === 429) return new PxwebError("Statistics Poland (BDL) refused the request because its request limit for this server is reached. Try again in 15 minutes or later.", 503);
|
|
340
|
+
if (err.status === 401 || err.status === 403) return new PxwebError(`Statistics Poland (BDL) refused the API key of this server (HTTP ${err.status}). Check BDL_CLIENT_ID.`, 502);
|
|
341
|
+
if (err.status >= 500) return new PxwebError(`Statistics Poland (BDL) could not answer (HTTP ${err.status}). Try again later.`, 502);
|
|
342
|
+
return err;
|
|
297
343
|
}
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
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
|
-
};
|
|
344
|
+
async function inBatches(items, run) {
|
|
345
|
+
const results = [];
|
|
346
|
+
for (let start = 0; start < items.length; start += PAGE_BATCH) results.push(...await Promise.all(items.slice(start, start + PAGE_BATCH).map(run)));
|
|
347
|
+
return results;
|
|
475
348
|
}
|
|
476
|
-
|
|
477
|
-
|
|
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);
|
|
349
|
+
function range(count) {
|
|
350
|
+
return Array.from({ length: count }, (_, index) => index);
|
|
486
351
|
}
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
const year = Number(/(\d{4})/.exec(lastPeriod ?? "")?.[1]);
|
|
490
|
-
return Number.isFinite(year) && year >= currentYear - 1;
|
|
352
|
+
function chunks(items, size) {
|
|
353
|
+
return range(Math.ceil(items.length / size)).map((index) => items.slice(index * size, (index + 1) * size));
|
|
491
354
|
}
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
const
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
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
|
-
};
|
|
355
|
+
function chosenCodes$6(variable, selection) {
|
|
356
|
+
if (!selection) return variable.code === UNIT_CODE ? [POLAND] : variable.values;
|
|
357
|
+
const { filter, values } = selection.selection;
|
|
358
|
+
if (filter === "all") return variable.values;
|
|
359
|
+
if (filter === "top") return variable.values.slice(-Math.max(1, Number(values[0]) || 1));
|
|
360
|
+
const unknown = values.filter((code) => !variable.values.includes(code));
|
|
361
|
+
if (unknown.length > 0) throw new PxwebError(`Unknown value "${unknown[0]}" for ${variable.code}. Check the value codes with get_table_metadata.`, 400);
|
|
362
|
+
return [...new Set(values)];
|
|
363
|
+
}
|
|
364
|
+
function valueLabel(variable, code) {
|
|
365
|
+
return variable.valueLabels[variable.values.indexOf(code)] ?? code;
|
|
366
|
+
}
|
|
367
|
+
function toValue(entry) {
|
|
368
|
+
return MISSING_ATTRIBUTES.has(entry.attrId) ? null : entry.val;
|
|
369
|
+
}
|
|
370
|
+
async function allPages(load, maxPages) {
|
|
371
|
+
const first = await load(0);
|
|
372
|
+
const pages = Math.ceil(first.totalRecords / PAGE_SIZE);
|
|
373
|
+
if (pages > maxPages) throw new PxwebError(`Statistics Poland (BDL) lists ${first.totalRecords} entries here, more than this server reads.`, 400);
|
|
374
|
+
return [first, ...await inBatches(range(pages).slice(1), load)];
|
|
556
375
|
}
|
|
557
|
-
const DEFAULT_RETRY_SECONDS = 300;
|
|
558
376
|
/**
|
|
559
|
-
*
|
|
560
|
-
*
|
|
377
|
+
* Client for Statistics Poland (GUS), Local Data Bank (BDL) API, in Polish and English.
|
|
378
|
+
*
|
|
379
|
+
* - Table id: a BDL subgroup, the subject level that holds variables (for example "P2567").
|
|
380
|
+
* - Search: a local index over every subject. `subjects/search?name=%` matches all
|
|
381
|
+
* 2,700 subjects (28 pages of 100, the largest page size), which is far fewer calls
|
|
382
|
+
* than the K → G → P tree walk (about 300). Path is the subject's ancestors (domain,
|
|
383
|
+
* group); subjects under an "archival data" group are marked discontinued. The list
|
|
384
|
+
* has no years, so the docs have no `lastPeriod`.
|
|
385
|
+
* - Metadata: `subjects/{id}` (years, dimension names) and `variables?subject-id=…`
|
|
386
|
+
* (one call per 100 variables). A BDL variable is one series: its labels n1…n5 are
|
|
387
|
+
* the dimensions, named by the subject's `dimensions`. Each dimension becomes a
|
|
388
|
+
* variable `n1`…`n5` with ordinal value codes in API order (the same in both
|
|
389
|
+
* languages). `unit` offers Poland (eliminable, the default) and, when the series
|
|
390
|
+
* go down to level 2 or deeper, the 16 voivodeships. `year` is the subject's years.
|
|
391
|
+
* - Query: the selection picks the series whose labels match and the cell limit is
|
|
392
|
+
* checked on series × units × years. Data comes from `data/by-unit` (100 series per
|
|
393
|
+
* call for one unit) or `data/by-variable` (one series for Poland or all
|
|
394
|
+
* voivodeships per call), whichever needs fewer calls.
|
|
395
|
+
* - Limits: anonymous clients get 100 requests per 15 minutes; `clientId` raises it.
|
|
396
|
+
* HTTP 429 becomes a 503 error that says to try again later.
|
|
397
|
+
* - Caching: list pages, subjects and variables in the shared cache for a day, data
|
|
398
|
+
* for an hour; the parsed table in memory for an hour.
|
|
561
399
|
*/
|
|
562
|
-
function
|
|
563
|
-
const
|
|
564
|
-
const
|
|
565
|
-
const
|
|
566
|
-
const
|
|
567
|
-
const
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
400
|
+
function createBdlClient(options) {
|
|
401
|
+
const root = options.baseUrl.replace(/\/+$/, "");
|
|
402
|
+
const maxCells = options.maxCells ?? DEFAULT_MAX_CELLS$6;
|
|
403
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
404
|
+
const request = createRequester(options);
|
|
405
|
+
const init = options.clientId ? {
|
|
406
|
+
method: "GET",
|
|
407
|
+
headers: { "X-ClientId": options.clientId }
|
|
408
|
+
} : { method: "GET" };
|
|
409
|
+
function get(path, params, lang, schema, ttlSeconds) {
|
|
410
|
+
const query = new URLSearchParams([
|
|
411
|
+
...params,
|
|
412
|
+
["lang", lang],
|
|
413
|
+
["format", "json"]
|
|
414
|
+
]);
|
|
415
|
+
const url = `${root}/${path}?${query}`;
|
|
416
|
+
return request(url, init, schema, (data) => data, ttlSeconds, url);
|
|
417
|
+
}
|
|
418
|
+
async function listTables(lang) {
|
|
419
|
+
labelsFor(lang);
|
|
420
|
+
const subjects = (await allPages((page) => get("subjects/search", [
|
|
421
|
+
["name", "%"],
|
|
422
|
+
["sort", "Id"],
|
|
423
|
+
["page-size", String(PAGE_SIZE)],
|
|
424
|
+
["page", String(page)]
|
|
425
|
+
], lang, subjectListSchema, METADATA_TTL_SECONDS), Number.POSITIVE_INFINITY).catch((err) => {
|
|
426
|
+
throw upstreamError$3(err);
|
|
427
|
+
})).flatMap((page) => page.results);
|
|
428
|
+
const byId = new Map(subjects.map((subject) => [subject.id, subject]));
|
|
429
|
+
function ancestors(parentId) {
|
|
430
|
+
const names = [];
|
|
431
|
+
const seen = /* @__PURE__ */ new Set();
|
|
432
|
+
for (let parent = parentId ? byId.get(parentId) : void 0; parent && !seen.has(parent.id); parent = parent.parentId ? byId.get(parent.parentId) : void 0) {
|
|
433
|
+
seen.add(parent.id);
|
|
434
|
+
names.unshift(parent.name.trim());
|
|
435
|
+
}
|
|
436
|
+
return names;
|
|
574
437
|
}
|
|
438
|
+
return subjects.filter((subject) => subject.hasVariables).map((subject) => {
|
|
439
|
+
const path = ancestors(subject.parentId);
|
|
440
|
+
return {
|
|
441
|
+
id: subject.id,
|
|
442
|
+
title: subject.name.trim(),
|
|
443
|
+
path,
|
|
444
|
+
...path.some((name) => ARCHIVE_GROUP.test(name)) && { discontinued: true }
|
|
445
|
+
};
|
|
446
|
+
});
|
|
575
447
|
}
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
}).catch(
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
448
|
+
const tableIndex = createTableIndexLoader(preferCrawled(listTables, options.crawledList), {
|
|
449
|
+
fallback: options.listFallback,
|
|
450
|
+
ttlSeconds: SEARCH_TTL_SECONDS,
|
|
451
|
+
currentYear: () => now().getUTCFullYear()
|
|
452
|
+
});
|
|
453
|
+
async function loadTable(lang, tableId) {
|
|
454
|
+
const labels = labelsFor(lang);
|
|
455
|
+
const variablePage = (page) => get("variables", [
|
|
456
|
+
["subject-id", tableId],
|
|
457
|
+
["page-size", String(PAGE_SIZE)],
|
|
458
|
+
["page", String(page)]
|
|
459
|
+
], lang, variablesSchema, METADATA_TTL_SECONDS);
|
|
460
|
+
const [subject, pages] = await Promise.all([get(`subjects/${tableId}`, [], lang, subjectSchema, METADATA_TTL_SECONDS), allPages(variablePage, MAX_VARIABLE_PAGES)]).catch((err) => {
|
|
461
|
+
if (err instanceof PxwebError && err.status === 404) throw notFound$14(tableId);
|
|
462
|
+
throw upstreamError$3(err);
|
|
463
|
+
});
|
|
464
|
+
const variables = pages.flatMap((page) => page.results);
|
|
465
|
+
if (variables.length === 0) throw notFound$14(tableId);
|
|
466
|
+
const dimensionCount = Math.max(...variables.map((variable) => DIMENSION_FIELDS.findLastIndex((field) => variable[field]) + 1));
|
|
467
|
+
const dimensions = DIMENSION_FIELDS.slice(0, dimensionCount).map((field, index) => {
|
|
468
|
+
const labelsInOrder = [...new Set(variables.map((variable) => variable[field]?.trim() ?? ""))];
|
|
469
|
+
return {
|
|
470
|
+
field,
|
|
471
|
+
codes: new Map(labelsInOrder.map((label, position) => [label, String(position + 1)])),
|
|
472
|
+
variable: {
|
|
473
|
+
code: field,
|
|
474
|
+
label: subject.dimensions[index]?.trim() || `${labels.dimension} ${index + 1}`,
|
|
475
|
+
values: labelsInOrder.map((_, position) => String(position + 1)),
|
|
476
|
+
valueLabels: labelsInOrder,
|
|
477
|
+
eliminable: false,
|
|
478
|
+
isTime: false
|
|
479
|
+
}
|
|
480
|
+
};
|
|
481
|
+
});
|
|
482
|
+
const deepest = Math.max(...variables.map((variable) => variable.level));
|
|
483
|
+
const units = [[POLAND, labels.poland], ...deepest >= VOIVODESHIP_LEVEL ? VOIVODESHIPS : []];
|
|
484
|
+
const years = subject.years.toSorted((a, b) => a - b).map(String);
|
|
485
|
+
const dimensionVariables = dimensions.map((dimension) => dimension.variable);
|
|
486
|
+
const unitVariable = {
|
|
487
|
+
code: UNIT_CODE,
|
|
488
|
+
label: labels.unit,
|
|
489
|
+
values: units.map(([id]) => id),
|
|
490
|
+
valueLabels: units.map(([, name]) => name),
|
|
491
|
+
eliminable: true,
|
|
492
|
+
isTime: false
|
|
493
|
+
};
|
|
494
|
+
const yearVariable = {
|
|
495
|
+
code: YEAR_CODE,
|
|
496
|
+
label: labels.year,
|
|
497
|
+
values: years,
|
|
498
|
+
valueLabels: years,
|
|
499
|
+
eliminable: false,
|
|
500
|
+
isTime: true
|
|
501
|
+
};
|
|
502
|
+
return {
|
|
503
|
+
metadata: {
|
|
504
|
+
title: subject.name.trim(),
|
|
505
|
+
variables: [
|
|
506
|
+
...dimensionVariables,
|
|
507
|
+
unitVariable,
|
|
508
|
+
yearVariable
|
|
509
|
+
]
|
|
510
|
+
},
|
|
511
|
+
dimensions: dimensionVariables,
|
|
512
|
+
units: unitVariable,
|
|
513
|
+
years: yearVariable,
|
|
514
|
+
series: variables.map((variable) => ({
|
|
515
|
+
id: variable.id,
|
|
516
|
+
codes: dimensions.map((dimension) => dimension.codes.get(variable[dimension.field]?.trim() ?? "") ?? ""),
|
|
517
|
+
measure: variable.measureUnitName?.trim() || null
|
|
518
|
+
}))
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
const tables = /* @__PURE__ */ new Map();
|
|
522
|
+
async function cachedTable(lang, tableId) {
|
|
523
|
+
labelsFor(lang);
|
|
524
|
+
if (!TABLE_ID_PATTERN$10.test(tableId)) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it, for example "P2567".`, 400);
|
|
525
|
+
const key = `${lang}:${tableId}`;
|
|
526
|
+
const cached = tables.get(key);
|
|
527
|
+
if (cached && cached.expires > Date.now()) return cached.table;
|
|
528
|
+
const table = await loadTable(lang, tableId);
|
|
529
|
+
tables.delete(key);
|
|
530
|
+
tables.set(key, {
|
|
531
|
+
expires: Date.now() + DATA_TTL_SECONDS * 1e3,
|
|
532
|
+
table
|
|
533
|
+
});
|
|
534
|
+
const oldest = tables.keys().next().value;
|
|
535
|
+
if (tables.size > MAX_CACHED_TABLES$5 && oldest !== void 0) tables.delete(oldest);
|
|
536
|
+
return table;
|
|
537
|
+
}
|
|
538
|
+
async function fetchCells(lang, series, units, yearParams) {
|
|
539
|
+
const levels = [...units.includes(POLAND) ? [COUNTRY_LEVEL$1] : [], ...units.some((unit) => unit !== POLAND) ? [VOIVODESHIP_LEVEL] : []];
|
|
540
|
+
const byUnitCalls = units.length * Math.ceil(series.length / VAR_IDS_PER_CALL);
|
|
541
|
+
const byVariableCalls = series.length * levels.length;
|
|
542
|
+
if (Math.min(byUnitCalls, byVariableCalls) > MAX_DATA_CALLS) throw new PxwebError(`This selection needs more than ${MAX_DATA_CALLS} requests to Statistics Poland. Select fewer units or values.`, 400);
|
|
543
|
+
if (byUnitCalls <= byVariableCalls) return (await inBatches(units.flatMap((unit) => chunks(series, VAR_IDS_PER_CALL).map((chunk) => ({
|
|
544
|
+
unit,
|
|
545
|
+
chunk
|
|
546
|
+
}))), ({ unit, chunk }) => get(`data/by-unit/${unit}`, [
|
|
547
|
+
...chunk.map((entry) => ["var-id", String(entry.id)]),
|
|
548
|
+
...yearParams,
|
|
549
|
+
["page-size", String(PAGE_SIZE)]
|
|
550
|
+
], lang, dataByUnitSchema, DATA_TTL_SECONDS).then((data) => data.results.map((result) => ({
|
|
551
|
+
unit,
|
|
552
|
+
series: result.id,
|
|
553
|
+
values: result.values
|
|
554
|
+
}))))).flat();
|
|
555
|
+
return (await inBatches(series.flatMap((entry) => levels.map((level) => ({
|
|
556
|
+
entry,
|
|
557
|
+
level
|
|
558
|
+
}))), ({ entry, level }) => get(`data/by-variable/${entry.id}`, [
|
|
559
|
+
["unit-level", String(level)],
|
|
560
|
+
...yearParams,
|
|
561
|
+
["page-size", String(PAGE_SIZE)]
|
|
562
|
+
], lang, dataByVariableSchema, DATA_TTL_SECONDS).then((data) => data.results.map((result) => ({
|
|
563
|
+
unit: result.id,
|
|
564
|
+
series: entry.id,
|
|
565
|
+
values: result.values
|
|
566
|
+
}))))).flat();
|
|
567
|
+
}
|
|
568
|
+
return {
|
|
569
|
+
listTables,
|
|
570
|
+
async search(lang, query, searchOptions) {
|
|
571
|
+
labelsFor(lang);
|
|
572
|
+
return (await tableIndex(lang)).search(query, searchOptions);
|
|
573
|
+
},
|
|
574
|
+
async getMetadata(lang, tableId) {
|
|
575
|
+
return (await cachedTable(lang, tableId)).metadata;
|
|
576
|
+
},
|
|
577
|
+
async query(lang, tableId, selections) {
|
|
578
|
+
const labels = labelsFor(lang);
|
|
579
|
+
const table = await cachedTable(lang, tableId);
|
|
580
|
+
const byCode = new Map(selections.map((selection) => [selection.code, selection]));
|
|
581
|
+
const pick = (variable) => chosenCodes$6(variable, byCode.get(variable.code));
|
|
582
|
+
const chosen = table.dimensions.map(pick);
|
|
583
|
+
const units = pick(table.units);
|
|
584
|
+
const years = pick(table.years);
|
|
585
|
+
const series = table.series.filter((entry) => entry.codes.every((code, index) => chosen[index]?.includes(code)));
|
|
586
|
+
if (series.length === 0) throw new PxwebError("No series of this table has that combination of values. Choose other values with get_table_metadata.", 400);
|
|
587
|
+
const cells = series.length * units.length * years.length;
|
|
588
|
+
if (cells > maxCells) throw new PxwebError(`The query could return ${cells} cells, above the limit of ${maxCells}. Select fewer values.`, 400);
|
|
589
|
+
const yearParams = years.map((year) => ["year", year]);
|
|
590
|
+
const cellsByKey = new Map((await fetchCells(lang, series, units, years.length === table.years.values.length ? [] : yearParams).catch((err) => {
|
|
591
|
+
if (err instanceof PxwebError && (err.status === 400 || err.status === 412)) throw new PxwebError(`Statistics Poland (BDL) refused this selection: ${upstreamReason(err.message)}. Check the value codes with get_table_metadata.`, 400);
|
|
592
|
+
throw upstreamError$3(err);
|
|
593
|
+
})).map((cell) => [`${cell.unit}|${cell.series}`, cell.values]));
|
|
594
|
+
return {
|
|
595
|
+
label: table.metadata.title,
|
|
596
|
+
columns: [
|
|
597
|
+
labels.unit,
|
|
598
|
+
...table.dimensions.map((dimension) => dimension.label),
|
|
599
|
+
labels.year,
|
|
600
|
+
labels.measure,
|
|
601
|
+
labels.value
|
|
602
|
+
],
|
|
603
|
+
rows: units.flatMap((unit) => series.flatMap((entry) => (cellsByKey.get(`${unit}|${entry.id}`) ?? []).map((value) => [
|
|
604
|
+
valueLabel(table.units, unit),
|
|
605
|
+
...table.dimensions.map((dimension, index) => valueLabel(dimension, entry.codes[index] ?? "")),
|
|
606
|
+
value.year,
|
|
607
|
+
entry.measure,
|
|
608
|
+
toValue(value)
|
|
609
|
+
])))
|
|
610
|
+
};
|
|
611
|
+
}
|
|
599
612
|
};
|
|
600
613
|
}
|
|
601
614
|
// src/cbs-odata-client.ts
|
|
602
|
-
const TABLE_ID_PATTERN$
|
|
615
|
+
const TABLE_ID_PATTERN$9 = /^[A-Za-z0-9]+$/;
|
|
603
616
|
const NOT_FOUND_STATUSES$4 = /* @__PURE__ */ new Set([400, 404]);
|
|
604
617
|
const DISCONTINUED = /* @__PURE__ */ new Set(["Gediscontinueerd", "Discontinued"]);
|
|
605
618
|
const DIMENSION_TYPES = /* @__PURE__ */ new Set([
|
|
@@ -609,7 +622,7 @@ const DIMENSION_TYPES = /* @__PURE__ */ new Set([
|
|
|
609
622
|
]);
|
|
610
623
|
/** Code of the synthetic variable that holds the measures (OData columns). */
|
|
611
624
|
const TOPICS_CODE = "Topics";
|
|
612
|
-
const catalogueSchema = z.object({ value: z.array(z.object({
|
|
625
|
+
const catalogueSchema$2 = z.object({ value: z.array(z.object({
|
|
613
626
|
Identifier: z.string(),
|
|
614
627
|
Title: z.string(),
|
|
615
628
|
Language: z.string(),
|
|
@@ -679,7 +692,7 @@ function sameOriginLink(next, current) {
|
|
|
679
692
|
return;
|
|
680
693
|
}
|
|
681
694
|
}
|
|
682
|
-
function notFound$
|
|
695
|
+
function notFound$13(tableId) {
|
|
683
696
|
return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
684
697
|
}
|
|
685
698
|
function tooLarge() {
|
|
@@ -694,8 +707,8 @@ function odataUrl(base, params) {
|
|
|
694
707
|
...params
|
|
695
708
|
}).map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join("&")}`;
|
|
696
709
|
}
|
|
697
|
-
function checkTableId$
|
|
698
|
-
if (!TABLE_ID_PATTERN$
|
|
710
|
+
function checkTableId$5(tableId) {
|
|
711
|
+
if (!TABLE_ID_PATTERN$9.test(tableId)) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it.`, 400);
|
|
699
712
|
}
|
|
700
713
|
function selectedCodes$2(variable, selection) {
|
|
701
714
|
if (!selection || selection.selection.filter === "all") return variable.values;
|
|
@@ -744,7 +757,7 @@ function createCbsODataClient(options) {
|
|
|
744
757
|
});
|
|
745
758
|
/** One download serves both languages and parallel searches. */
|
|
746
759
|
function catalogue() {
|
|
747
|
-
loadingCatalogue ??= request(odataUrl(`${baseUrl}/ODataCatalog/Tables`, { $select: "Identifier,Title,Language,Modified,OutputStatus,Period" }), get, catalogueSchema, (data) => data.value, SEARCH_TTL_SECONDS, `catalogue:${baseUrl}`).finally(() => {
|
|
760
|
+
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(() => {
|
|
748
761
|
loadingCatalogue = void 0;
|
|
749
762
|
});
|
|
750
763
|
return loadingCatalogue;
|
|
@@ -811,7 +824,7 @@ function createCbsODataClient(options) {
|
|
|
811
824
|
* Dutch twin, with Dutch labels.
|
|
812
825
|
*/
|
|
813
826
|
async function loadV4Table(tableId) {
|
|
814
|
-
const datasetId = tableId.replace(/
|
|
827
|
+
const datasetId = tableId.replace(/eng$/i, (suffix) => suffix === "eng" ? "ned" : "NED");
|
|
815
828
|
const tableBase = `${datasetsUrl}/${datasetId}`;
|
|
816
829
|
const [title, dimensions, measures] = await Promise.all([
|
|
817
830
|
request(`${tableBase}/Properties`, get, v4PropertiesSchema, (data) => data.Title, METADATA_TTL_SECONDS, `meta:${tableBase}/Properties`),
|
|
@@ -850,15 +863,15 @@ function createCbsODataClient(options) {
|
|
|
850
863
|
};
|
|
851
864
|
}
|
|
852
865
|
async function table(tableId) {
|
|
853
|
-
checkTableId$
|
|
866
|
+
checkTableId$5(tableId);
|
|
854
867
|
try {
|
|
855
868
|
return await loadTable(tableId);
|
|
856
869
|
} catch (err) {
|
|
857
|
-
if (isNotFound(err)) throw notFound$
|
|
870
|
+
if (isNotFound(err)) throw notFound$13(tableId);
|
|
858
871
|
try {
|
|
859
872
|
return await loadV4Table(tableId);
|
|
860
873
|
} catch (v4Err) {
|
|
861
|
-
if (isNotFound(v4Err)) throw isTransient(err) ? err : notFound$
|
|
874
|
+
if (isNotFound(v4Err)) throw isTransient(err) ? err : notFound$13(tableId);
|
|
862
875
|
throw v4Err;
|
|
863
876
|
}
|
|
864
877
|
}
|
|
@@ -945,10 +958,294 @@ function createCbsODataClient(options) {
|
|
|
945
958
|
}
|
|
946
959
|
};
|
|
947
960
|
}
|
|
961
|
+
// src/czso-client.ts
|
|
962
|
+
const TABLE_ID_PATTERN$8 = /^[A-Za-z0-9_]{1,40}$/;
|
|
963
|
+
const LANGUAGES$4 = /* @__PURE__ */ new Set(["cs", "en"]);
|
|
964
|
+
const INDICATOR_CODE = "IndicatorType";
|
|
965
|
+
const INDICATOR_LABELS = {
|
|
966
|
+
cs: "Ukazatel",
|
|
967
|
+
en: "Indicator"
|
|
968
|
+
};
|
|
969
|
+
const TIME_TYPE = "REF_CAS";
|
|
970
|
+
const DEFAULT_LEVEL = "#DEFAULT";
|
|
971
|
+
const DEFAULT_MAX_CELLS$5 = 5e3;
|
|
972
|
+
const MAX_CACHED_TABLES$4 = 8;
|
|
973
|
+
const catalogueSchema$1 = z.array(z.object({
|
|
974
|
+
kod: z.string(),
|
|
975
|
+
verze: z.string(),
|
|
976
|
+
nazev: z.string(),
|
|
977
|
+
casZmenyDefinice: z.string().nullish()
|
|
978
|
+
}));
|
|
979
|
+
const contentListSchema = z.array(z.object({
|
|
980
|
+
sadaKod: z.string(),
|
|
981
|
+
verzeKod: z.string(),
|
|
982
|
+
metadata: z.object({
|
|
983
|
+
casZmeny: z.string().nullish(),
|
|
984
|
+
casovaDimenzeDo: z.string().nullish()
|
|
985
|
+
}).nullish()
|
|
986
|
+
}));
|
|
987
|
+
const variantSchema = z.object({
|
|
988
|
+
kod: z.string(),
|
|
989
|
+
verze: z.string(),
|
|
990
|
+
typDimenzeKod: z.string(),
|
|
991
|
+
nazev: z.string(),
|
|
992
|
+
vychoziVariantaDimenze: z.boolean().nullish(),
|
|
993
|
+
urovneDimenze: z.array(z.object({ pocetPolozek: z.number().nullish() })).default([])
|
|
994
|
+
});
|
|
995
|
+
const datasetSchema = z.object({
|
|
996
|
+
verze: z.string(),
|
|
997
|
+
nazev: z.string(),
|
|
998
|
+
ukazatele: z.array(z.object({
|
|
999
|
+
kod: z.string(),
|
|
1000
|
+
nazev: z.string(),
|
|
1001
|
+
mericiJednotka: z.object({ nazev: z.string() }).nullish()
|
|
1002
|
+
})).default([]),
|
|
1003
|
+
variantyDimenze: z.array(variantSchema).default([])
|
|
1004
|
+
});
|
|
1005
|
+
const itemsSchema = z.array(z.object({
|
|
1006
|
+
kod: z.string(),
|
|
1007
|
+
nazev: z.string(),
|
|
1008
|
+
kodUrovne: z.string().nullish(),
|
|
1009
|
+
poradi: z.number(),
|
|
1010
|
+
agregacniPolozka: z.boolean().nullish()
|
|
1011
|
+
}));
|
|
1012
|
+
const contentSchema = z.object({ dimenze: z.array(z.object({
|
|
1013
|
+
kod: z.string(),
|
|
1014
|
+
rozsahHodnot: z.array(z.object({
|
|
1015
|
+
kodUrovne: z.string(),
|
|
1016
|
+
poradiPolozkyOd: z.number().nullish(),
|
|
1017
|
+
poradiPolozkyDo: z.number().nullish()
|
|
1018
|
+
})).default([])
|
|
1019
|
+
})).nullish() });
|
|
1020
|
+
function notFound$12(tableId) {
|
|
1021
|
+
return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
1022
|
+
}
|
|
1023
|
+
function checkLanguage$5(lang) {
|
|
1024
|
+
if (!LANGUAGES$4.has(lang)) throw new PxwebError(`Language "${lang}" is not supported.`, 400);
|
|
1025
|
+
}
|
|
1026
|
+
function upstreamError$2(err) {
|
|
1027
|
+
if (err instanceof PxwebError && err.status >= 500) return new PxwebError(`DataStat could not answer (HTTP ${err.status}). Try again later.`, 502);
|
|
1028
|
+
return err;
|
|
1029
|
+
}
|
|
1030
|
+
function variantRank(variant) {
|
|
1031
|
+
return [
|
|
1032
|
+
variant.vychoziVariantaDimenze ? 1 : 0,
|
|
1033
|
+
variant.urovneDimenze.length,
|
|
1034
|
+
variant.urovneDimenze.reduce((sum, level) => sum + (level.pocetPolozek ?? 0), 0)
|
|
1035
|
+
];
|
|
1036
|
+
}
|
|
1037
|
+
function outranks(a, b) {
|
|
1038
|
+
const rankB = variantRank(b);
|
|
1039
|
+
for (const [index, value] of variantRank(a).entries()) {
|
|
1040
|
+
const difference = value - (rankB[index] ?? 0);
|
|
1041
|
+
if (difference !== 0) return difference > 0;
|
|
1042
|
+
}
|
|
1043
|
+
return false;
|
|
1044
|
+
}
|
|
1045
|
+
/** A dataset offers alternative variants of one dimension type; one query can use only one. */
|
|
1046
|
+
function oneVariantPerType(variants) {
|
|
1047
|
+
const byType = /* @__PURE__ */ new Map();
|
|
1048
|
+
for (const variant of variants) {
|
|
1049
|
+
const current = byType.get(variant.typDimenzeKod);
|
|
1050
|
+
if (!current || outranks(variant, current)) byType.set(variant.typDimenzeKod, variant);
|
|
1051
|
+
}
|
|
1052
|
+
return [...byType.values()];
|
|
1053
|
+
}
|
|
1054
|
+
/** Time dimensions list every period of the code list; keep those inside the data range. */
|
|
1055
|
+
function periodsWithData(variant, items, content) {
|
|
1056
|
+
const ranges = content?.dimenze?.find((dimension) => dimension.kod === variant.kod)?.rozsahHodnot;
|
|
1057
|
+
if (!ranges) return items;
|
|
1058
|
+
return items.filter((item) => {
|
|
1059
|
+
const range = ranges.find((entry) => entry.kodUrovne === (item.kodUrovne ?? DEFAULT_LEVEL));
|
|
1060
|
+
return range?.poradiPolozkyOd != null && range.poradiPolozkyDo != null && item.poradi >= range.poradiPolozkyOd && item.poradi <= range.poradiPolozkyDo;
|
|
1061
|
+
});
|
|
1062
|
+
}
|
|
1063
|
+
function toVariable$1(variant, items, isTime) {
|
|
1064
|
+
const unique = [...new Map(items.toSorted((a, b) => a.poradi - b.poradi).map((item) => [item.kod, item])).values()];
|
|
1065
|
+
return {
|
|
1066
|
+
code: variant.kod,
|
|
1067
|
+
label: variant.nazev.trim(),
|
|
1068
|
+
values: unique.map((item) => item.kod),
|
|
1069
|
+
valueLabels: unique.map((item) => item.nazev.trim()),
|
|
1070
|
+
eliminable: !isTime && unique.some((item) => item.agregacniPolozka),
|
|
1071
|
+
isTime
|
|
1072
|
+
};
|
|
1073
|
+
}
|
|
1074
|
+
function indicatorLabel(name, unit) {
|
|
1075
|
+
const label = name.trim();
|
|
1076
|
+
return unit && !label.endsWith(")") ? `${label} (${unit})` : label;
|
|
1077
|
+
}
|
|
1078
|
+
/** `latest` picks the newest periods of each level, so a years-and-quarters dimension gives both. */
|
|
1079
|
+
function newestPerLevel(codes, levels, count) {
|
|
1080
|
+
const byLevel = /* @__PURE__ */ new Map();
|
|
1081
|
+
for (const code of codes) {
|
|
1082
|
+
const level = levels.get(code) ?? DEFAULT_LEVEL;
|
|
1083
|
+
byLevel.set(level, [...byLevel.get(level) ?? [], code]);
|
|
1084
|
+
}
|
|
1085
|
+
const newest = new Set([...byLevel.values()].flatMap((list) => list.slice(-count)));
|
|
1086
|
+
return codes.filter((code) => newest.has(code));
|
|
1087
|
+
}
|
|
1088
|
+
function chosenCodes$5(variable, selection, timeLevels) {
|
|
1089
|
+
if (!selection || selection.selection.filter === "all") return [];
|
|
1090
|
+
const { filter, values } = selection.selection;
|
|
1091
|
+
if (filter === "item") return values;
|
|
1092
|
+
const count = Math.max(1, Number(values[0]) || 1);
|
|
1093
|
+
if (variable.isTime) return newestPerLevel(variable.values, timeLevels, count);
|
|
1094
|
+
return variable.values.slice(-count);
|
|
1095
|
+
}
|
|
1096
|
+
/**
|
|
1097
|
+
* Client for DataStat, the CZSO (Czech Statistical Office) API, in Czech and English.
|
|
1098
|
+
*
|
|
1099
|
+
* - Table id: the dataset code (`kod`, for example "CEN0101H").
|
|
1100
|
+
* - Search: a local index over the live catalogue (`katalog/v1/sady`, per language) and
|
|
1101
|
+
* the content list (`dotaz/v1/metadata/sady/seznam`, for the data update date and
|
|
1102
|
+
* last period), both cached for an hour. No crawled snapshot is needed; `listFallback`
|
|
1103
|
+
* is used when the live catalogue fails.
|
|
1104
|
+
* - Metadata: the dataset detail gives the indicators and the dimension variants. A
|
|
1105
|
+
* dataset can have several variants of one dimension type (years, quarters, or years
|
|
1106
|
+
* and quarters; regions or districts), and a query can use only one, so each type
|
|
1107
|
+
* exposes its default variant, else the one with the most levels, then the most items.
|
|
1108
|
+
* Items come from the variant's code list; time items are cut to the data range of the
|
|
1109
|
+
* dataset content metadata and ordered by the code list order. A dimension with a
|
|
1110
|
+
* total item is eliminable: DataStat returns the total when it is left out.
|
|
1111
|
+
* - Query: one GET custom selection (`data/sady/{kod}/vlastni`, JSON-stat 2.0) with one
|
|
1112
|
+
* parameter per selected dimension. `latest` gives the newest periods of each time level.
|
|
1113
|
+
* The cell limit is checked before the request. Predefined selections (`data/vybery`)
|
|
1114
|
+
* are not used: they cover one variant each and cost the same single request.
|
|
1115
|
+
* - Caching: catalogue and code lists in the shared cache; the parsed table in memory for
|
|
1116
|
+
* an hour, so new periods appear soon after a release.
|
|
1117
|
+
*/
|
|
1118
|
+
function createCzsoClient(options) {
|
|
1119
|
+
const root = options.baseUrl.replace(/\/+$/, "");
|
|
1120
|
+
const maxCells = options.maxCells ?? DEFAULT_MAX_CELLS$5;
|
|
1121
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
1122
|
+
const request = createRequester(options);
|
|
1123
|
+
function get(lang, path, schema, ttlSeconds) {
|
|
1124
|
+
const url = `${root}/${path}`;
|
|
1125
|
+
return request(url, {
|
|
1126
|
+
method: "GET",
|
|
1127
|
+
...lang && { headers: { "accept-language": lang } }
|
|
1128
|
+
}, schema, (data) => data, ttlSeconds, `${lang ?? "*"}:${url}`);
|
|
1129
|
+
}
|
|
1130
|
+
async function listTables(lang) {
|
|
1131
|
+
checkLanguage$5(lang);
|
|
1132
|
+
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(() => [])]);
|
|
1133
|
+
const contentOf = new Map(contents.map((entry) => [`${entry.sadaKod}:${entry.verzeKod}`, entry.metadata]));
|
|
1134
|
+
return datasets.map((dataset) => {
|
|
1135
|
+
const content = contentOf.get(`${dataset.kod}:${dataset.verze}`);
|
|
1136
|
+
const updated = (content?.casZmeny ?? dataset.casZmenyDefinice)?.slice(0, 10);
|
|
1137
|
+
const lastPeriod = content?.casovaDimenzeDo?.slice(0, 4);
|
|
1138
|
+
return {
|
|
1139
|
+
id: dataset.kod,
|
|
1140
|
+
title: dataset.nazev.trim(),
|
|
1141
|
+
...updated && { updated },
|
|
1142
|
+
...lastPeriod && { lastPeriod }
|
|
1143
|
+
};
|
|
1144
|
+
});
|
|
1145
|
+
}
|
|
1146
|
+
const tableIndex = createTableIndexLoader(listTables, {
|
|
1147
|
+
fallback: options.listFallback,
|
|
1148
|
+
ttlSeconds: SEARCH_TTL_SECONDS,
|
|
1149
|
+
currentYear: () => now().getUTCFullYear()
|
|
1150
|
+
});
|
|
1151
|
+
async function loadTable(lang, tableId) {
|
|
1152
|
+
checkLanguage$5(lang);
|
|
1153
|
+
if (!TABLE_ID_PATTERN$8.test(tableId)) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it.`, 400);
|
|
1154
|
+
const dataset = await get(lang, `katalog/v1/sady/${tableId}`, datasetSchema, METADATA_TTL_SECONDS).catch((err) => {
|
|
1155
|
+
if (err instanceof PxwebError && err.status === 404) throw notFound$12(tableId);
|
|
1156
|
+
throw upstreamError$2(err);
|
|
1157
|
+
});
|
|
1158
|
+
const variants = oneVariantPerType(dataset.variantyDimenze);
|
|
1159
|
+
const hasTime = variants.some((variant) => variant.typDimenzeKod === TIME_TYPE);
|
|
1160
|
+
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) => {
|
|
1161
|
+
throw upstreamError$2(err);
|
|
1162
|
+
});
|
|
1163
|
+
const timeLevels = /* @__PURE__ */ new Map();
|
|
1164
|
+
const dimensions = variants.map((variant, index) => {
|
|
1165
|
+
const isTime = variant.typDimenzeKod === TIME_TYPE;
|
|
1166
|
+
const items = itemLists[index] ?? [];
|
|
1167
|
+
if (!isTime) return toVariable$1(variant, items, false);
|
|
1168
|
+
const periods = periodsWithData(variant, items, content);
|
|
1169
|
+
for (const item of periods) timeLevels.set(item.kod, item.kodUrovne ?? DEFAULT_LEVEL);
|
|
1170
|
+
return toVariable$1(variant, periods, true);
|
|
1171
|
+
});
|
|
1172
|
+
const indicator = {
|
|
1173
|
+
code: INDICATOR_CODE,
|
|
1174
|
+
label: INDICATOR_LABELS[lang] ?? INDICATOR_CODE,
|
|
1175
|
+
values: dataset.ukazatele.map((item) => item.kod),
|
|
1176
|
+
valueLabels: dataset.ukazatele.map((item) => indicatorLabel(item.nazev, item.mericiJednotka?.nazev)),
|
|
1177
|
+
eliminable: false,
|
|
1178
|
+
isTime: false
|
|
1179
|
+
};
|
|
1180
|
+
return {
|
|
1181
|
+
metadata: {
|
|
1182
|
+
title: dataset.nazev.trim(),
|
|
1183
|
+
variables: [
|
|
1184
|
+
indicator,
|
|
1185
|
+
...dimensions.filter((variable) => !variable.isTime),
|
|
1186
|
+
...dimensions.filter((variable) => variable.isTime)
|
|
1187
|
+
]
|
|
1188
|
+
},
|
|
1189
|
+
timeLevels
|
|
1190
|
+
};
|
|
1191
|
+
}
|
|
1192
|
+
const tables = /* @__PURE__ */ new Map();
|
|
1193
|
+
async function cachedTable(lang, tableId) {
|
|
1194
|
+
const key = `${lang}:${tableId}`;
|
|
1195
|
+
const cached = tables.get(key);
|
|
1196
|
+
if (cached && cached.expires > Date.now()) return cached.table;
|
|
1197
|
+
const table = await loadTable(lang, tableId);
|
|
1198
|
+
tables.delete(key);
|
|
1199
|
+
tables.set(key, {
|
|
1200
|
+
expires: Date.now() + DATA_TTL_SECONDS * 1e3,
|
|
1201
|
+
table
|
|
1202
|
+
});
|
|
1203
|
+
const oldest = tables.keys().next().value;
|
|
1204
|
+
if (tables.size > MAX_CACHED_TABLES$4 && oldest !== void 0) tables.delete(oldest);
|
|
1205
|
+
return table;
|
|
1206
|
+
}
|
|
1207
|
+
return {
|
|
1208
|
+
listTables,
|
|
1209
|
+
async search(lang, query, searchOptions) {
|
|
1210
|
+
checkLanguage$5(lang);
|
|
1211
|
+
return (await tableIndex(lang)).search(query, searchOptions);
|
|
1212
|
+
},
|
|
1213
|
+
async getMetadata(lang, tableId) {
|
|
1214
|
+
return (await cachedTable(lang, tableId)).metadata;
|
|
1215
|
+
},
|
|
1216
|
+
async query(lang, tableId, selections) {
|
|
1217
|
+
const table = await cachedTable(lang, tableId);
|
|
1218
|
+
const byCode = new Map(selections.map((selection) => [selection.code, selection]));
|
|
1219
|
+
const params = ["format=JSON_STAT"];
|
|
1220
|
+
let cells = 1;
|
|
1221
|
+
for (const variable of table.metadata.variables) {
|
|
1222
|
+
const selection = byCode.get(variable.code);
|
|
1223
|
+
if (!selection && variable.eliminable) continue;
|
|
1224
|
+
const codes = chosenCodes$5(variable, selection, table.timeLevels);
|
|
1225
|
+
cells *= codes.length || variable.values.length;
|
|
1226
|
+
const value = codes.length > 0 ? codes.map(encodeURIComponent).join(",") : "*";
|
|
1227
|
+
params.push(`${encodeURIComponent(variable.code)}=${value}`);
|
|
1228
|
+
}
|
|
1229
|
+
if (cells > maxCells) throw new PxwebError(`The query could return ${cells} cells, above the limit of ${maxCells}. Select fewer values.`, 400);
|
|
1230
|
+
return get(lang, `dotaz/v1/data/sady/${tableId}/vlastni?${params.join("&")}`, jsonStatDatasetSchema, DATA_TTL_SECONDS).then((dataset) => {
|
|
1231
|
+
const flat = toFlatTable$2(dataset);
|
|
1232
|
+
return {
|
|
1233
|
+
label: table.metadata.title,
|
|
1234
|
+
columns: flat.columns.map((column) => column.trim()),
|
|
1235
|
+
rows: flat.rows.map((row) => row.map((cell) => typeof cell === "string" ? cell.trim() : cell))
|
|
1236
|
+
};
|
|
1237
|
+
}).catch((err) => {
|
|
1238
|
+
if (err instanceof PxwebError && err.status === 404) throw notFound$12(tableId);
|
|
1239
|
+
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);
|
|
1240
|
+
throw upstreamError$2(err);
|
|
1241
|
+
});
|
|
1242
|
+
}
|
|
1243
|
+
};
|
|
1244
|
+
}
|
|
948
1245
|
// src/eurostat-client.ts
|
|
949
1246
|
const CODE_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9_$.-]+$/;
|
|
950
|
-
const CLOSED_TITLE = /\(\d{4}\s*-\s*\d{4}\)\s*$/;
|
|
951
|
-
const TIME_CODE$
|
|
1247
|
+
const CLOSED_TITLE$1 = /\(\d{4}\s*-\s*\d{4}\)\s*$/;
|
|
1248
|
+
const TIME_CODE$6 = "time";
|
|
952
1249
|
const NOT_FOUND_STATUSES$3 = /* @__PURE__ */ new Set([400, 404]);
|
|
953
1250
|
const TEXT = {
|
|
954
1251
|
method: "GET",
|
|
@@ -965,42 +1262,42 @@ const XML_ENTITIES = {
|
|
|
965
1262
|
quot: "\"",
|
|
966
1263
|
apos: "'"
|
|
967
1264
|
};
|
|
968
|
-
const MAX_CODE_POINT = 1114111;
|
|
969
|
-
function decodeXml(text) {
|
|
1265
|
+
const MAX_CODE_POINT$1 = 1114111;
|
|
1266
|
+
function decodeXml$1(text) {
|
|
970
1267
|
return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (entity, name) => {
|
|
971
1268
|
if (!name.startsWith("#")) return Object.hasOwn(XML_ENTITIES, name) ? XML_ENTITIES[name] ?? entity : entity;
|
|
972
1269
|
const point = name[1]?.toLowerCase() === "x" ? Number.parseInt(name.slice(2), 16) : Number(name.slice(1));
|
|
973
|
-
return point <= MAX_CODE_POINT ? String.fromCodePoint(point) : entity;
|
|
1270
|
+
return point <= MAX_CODE_POINT$1 ? String.fromCodePoint(point) : entity;
|
|
974
1271
|
});
|
|
975
1272
|
}
|
|
976
1273
|
/** Turns `<s:Code id="X"/>` into `<s:Code id="X"></s:Code>`, so one pattern reads both forms. */
|
|
977
1274
|
function expandSelfClosing(xml) {
|
|
978
1275
|
return xml.replace(/<(s:(?:Concept|Codelist|Code|Dimension))\b([^>]*?)\/>/g, "<$1$2></$1>");
|
|
979
1276
|
}
|
|
980
|
-
function attribute(tag, name) {
|
|
1277
|
+
function attribute$1(tag, name) {
|
|
981
1278
|
return new RegExp(`\\b${name}="([^"]*)"`).exec(tag)?.[1];
|
|
982
1279
|
}
|
|
983
1280
|
/** Name in the asked language, else English, else the code. */
|
|
984
1281
|
function nameIn(block, lang) {
|
|
985
1282
|
const names = [...block.matchAll(/<c:Name xml:lang="([a-z]+)">([^<]*)<\/c:Name>/g)];
|
|
986
1283
|
const match = names.find((name) => name[1] === lang) ?? names.find((name) => name[1] === "en");
|
|
987
|
-
return match?.[2] === void 0 ? void 0 : decodeXml(match[2]);
|
|
1284
|
+
return match?.[2] === void 0 ? void 0 : decodeXml$1(match[2]);
|
|
988
1285
|
}
|
|
989
1286
|
/** Dimension order and codes from an SDMX-ML 2.1 structure message. */
|
|
990
|
-
function parseStructure(xml, lang) {
|
|
1287
|
+
function parseStructure$1(xml, lang) {
|
|
991
1288
|
xml = expandSelfClosing(xml);
|
|
992
1289
|
const concepts = /* @__PURE__ */ new Map();
|
|
993
1290
|
for (const concept of xml.matchAll(/<s:Concept\b([^>]*)>([\s\S]*?)<\/s:Concept>/g)) {
|
|
994
|
-
const id = attribute(concept[1] ?? "", "id");
|
|
1291
|
+
const id = attribute$1(concept[1] ?? "", "id");
|
|
995
1292
|
const name = nameIn(concept[2] ?? "", lang);
|
|
996
1293
|
if (id && name) concepts.set(id, name);
|
|
997
1294
|
}
|
|
998
1295
|
const codelists = /* @__PURE__ */ new Map();
|
|
999
1296
|
for (const list of xml.matchAll(/<s:Codelist\b([^>]*)>([\s\S]*?)<\/s:Codelist>/g)) {
|
|
1000
|
-
const id = attribute(list[1] ?? "", "id");
|
|
1297
|
+
const id = attribute$1(list[1] ?? "", "id");
|
|
1001
1298
|
if (!id) continue;
|
|
1002
1299
|
const codes = [...(list[2] ?? "").matchAll(/<s:Code\b([^>]*)>([\s\S]*?)<\/s:Code>/g)].map((code) => {
|
|
1003
|
-
const codeId = decodeXml(attribute(code[1] ?? "", "id") ?? "");
|
|
1300
|
+
const codeId = decodeXml$1(attribute$1(code[1] ?? "", "id") ?? "");
|
|
1004
1301
|
return {
|
|
1005
1302
|
id: codeId,
|
|
1006
1303
|
label: nameIn(code[2] ?? "", lang) ?? codeId
|
|
@@ -1011,9 +1308,9 @@ function parseStructure(xml, lang) {
|
|
|
1011
1308
|
return { dimensions: [...xml.matchAll(/<s:Dimension\b([^>]*)>([\s\S]*?)<\/s:Dimension>/g)].map((dimension) => {
|
|
1012
1309
|
const reference = /<Ref\b[^>]*\bclass="Codelist"[^>]*>/.exec(dimension[2] ?? "")?.[0] ?? "";
|
|
1013
1310
|
return {
|
|
1014
|
-
id: attribute(dimension[1] ?? "", "id") ?? "",
|
|
1015
|
-
position: Number(attribute(dimension[1] ?? "", "position") ?? 0),
|
|
1016
|
-
codes: codelists.get(attribute(reference, "id") ?? "") ?? []
|
|
1311
|
+
id: attribute$1(dimension[1] ?? "", "id") ?? "",
|
|
1312
|
+
position: Number(attribute$1(dimension[1] ?? "", "position") ?? 0),
|
|
1313
|
+
codes: codelists.get(attribute$1(reference, "id") ?? "") ?? []
|
|
1017
1314
|
};
|
|
1018
1315
|
}).filter((dimension) => dimension.id).toSorted((a, b) => a.position - b.position).map(({ id, codes }) => ({
|
|
1019
1316
|
id,
|
|
@@ -1095,7 +1392,7 @@ function uniqueByCode(entries) {
|
|
|
1095
1392
|
return true;
|
|
1096
1393
|
});
|
|
1097
1394
|
}
|
|
1098
|
-
function notFound$
|
|
1395
|
+
function notFound$11(code) {
|
|
1099
1396
|
return new PxwebError(`Table "${code}" was not found. Use search_tables to find a table id.`, 404);
|
|
1100
1397
|
}
|
|
1101
1398
|
function checkCode(code) {
|
|
@@ -1133,88 +1430,2065 @@ function createEurostatClient(options) {
|
|
|
1133
1430
|
loading.set(lang, promise);
|
|
1134
1431
|
return promise;
|
|
1135
1432
|
}
|
|
1136
|
-
const listTables = async (lang) => (await toc(lang)).map((entry) => ({
|
|
1137
|
-
id: entry.code,
|
|
1138
|
-
title: entry.title,
|
|
1139
|
-
path: entry.path,
|
|
1140
|
-
...entry.updated ? { updated: entry.updated } : {},
|
|
1141
|
-
...entry.end ? { lastPeriod: entry.end } : {},
|
|
1142
|
-
...CLOSED_TITLE.test(entry.title) ? { discontinued: true } : {}
|
|
1143
|
-
}));
|
|
1144
|
-
const tableIndex = createTableIndexLoader(listTables, {
|
|
1433
|
+
const listTables = async (lang) => (await toc(lang)).map((entry) => ({
|
|
1434
|
+
id: entry.code,
|
|
1435
|
+
title: entry.title,
|
|
1436
|
+
path: entry.path,
|
|
1437
|
+
...entry.updated ? { updated: entry.updated } : {},
|
|
1438
|
+
...entry.end ? { lastPeriod: entry.end } : {},
|
|
1439
|
+
...CLOSED_TITLE$1.test(entry.title) ? { discontinued: true } : {}
|
|
1440
|
+
}));
|
|
1441
|
+
const tableIndex = createTableIndexLoader(listTables, {
|
|
1442
|
+
fallback: options.listFallback,
|
|
1443
|
+
ttlSeconds: SEARCH_TTL_SECONDS,
|
|
1444
|
+
currentYear: () => now().getUTCFullYear()
|
|
1445
|
+
});
|
|
1446
|
+
async function metadata(lang, code) {
|
|
1447
|
+
const entry = (await toc(lang)).find((item) => item.code === code);
|
|
1448
|
+
if (!entry) throw notFound$11(code);
|
|
1449
|
+
const url = `${baseUrl}/sdmx/2.1/dataflow/ESTAT/${encodeURIComponent(code)}/latest?references=descendants&detail=referencepartial`;
|
|
1450
|
+
const variables = (await requestText(url, TEXT, (xml) => {
|
|
1451
|
+
const result = parseStructure$1(xml, lang);
|
|
1452
|
+
if (result.dimensions.length === 0) throw new PxwebError("Eurostat returned a structure without dimensions.", 502);
|
|
1453
|
+
return result;
|
|
1454
|
+
}, METADATA_TTL_SECONDS, `meta:${url}:${lang}`).catch((err) => {
|
|
1455
|
+
if (err instanceof PxwebError && NOT_FOUND_STATUSES$3.has(err.status)) throw notFound$11(code);
|
|
1456
|
+
throw err;
|
|
1457
|
+
})).dimensions.map((dimension) => ({
|
|
1458
|
+
code: dimension.id,
|
|
1459
|
+
label: dimension.label,
|
|
1460
|
+
values: dimension.codes.map((item) => item.id),
|
|
1461
|
+
valueLabels: dimension.codes.map((item) => item.label),
|
|
1462
|
+
eliminable: false,
|
|
1463
|
+
isTime: false
|
|
1464
|
+
}));
|
|
1465
|
+
const periods = periodsBetween(entry.start, entry.end);
|
|
1466
|
+
const incomplete = stepOf(entry.end) === void 0 || !periodParts(entry.start) || !periodParts(entry.end);
|
|
1467
|
+
variables.push({
|
|
1468
|
+
code: TIME_CODE$6,
|
|
1469
|
+
label: TIME_CODE$6,
|
|
1470
|
+
values: periods,
|
|
1471
|
+
valueLabels: periods,
|
|
1472
|
+
eliminable: false,
|
|
1473
|
+
isTime: true,
|
|
1474
|
+
...incomplete && { periodsIncomplete: true }
|
|
1475
|
+
});
|
|
1476
|
+
return {
|
|
1477
|
+
title: entry.title,
|
|
1478
|
+
variables
|
|
1479
|
+
};
|
|
1480
|
+
}
|
|
1481
|
+
return {
|
|
1482
|
+
listTables,
|
|
1483
|
+
async search(lang, query, searchOptions) {
|
|
1484
|
+
return (await tableIndex(lang)).search(query, searchOptions);
|
|
1485
|
+
},
|
|
1486
|
+
async getMetadata(lang, code) {
|
|
1487
|
+
checkCode(code);
|
|
1488
|
+
return metadata(lang, code);
|
|
1489
|
+
},
|
|
1490
|
+
async query(lang, code, selections) {
|
|
1491
|
+
checkCode(code);
|
|
1492
|
+
const params = new URLSearchParams({ lang });
|
|
1493
|
+
const known = selections.some((selection) => selection.selection.filter === "top" && selection.code !== TIME_CODE$6) ? await metadata(lang, code) : void 0;
|
|
1494
|
+
for (const selection of selections) {
|
|
1495
|
+
const { filter, values } = selection.selection;
|
|
1496
|
+
if (filter === "all") continue;
|
|
1497
|
+
const count = Math.max(1, Number(values[0]) || 1);
|
|
1498
|
+
if (filter === "top" && selection.code === TIME_CODE$6) {
|
|
1499
|
+
params.append("lastTimePeriod", String(count));
|
|
1500
|
+
continue;
|
|
1501
|
+
}
|
|
1502
|
+
let codes = values;
|
|
1503
|
+
if (filter === "top") {
|
|
1504
|
+
const variable = known?.variables.find((item) => item.code === selection.code);
|
|
1505
|
+
if (!variable) throw new PxwebError(`Table "${code}" has no variable "${selection.code}". Call get_table_metadata to see its variables.`, 400);
|
|
1506
|
+
codes = variable.values.slice(-count);
|
|
1507
|
+
}
|
|
1508
|
+
for (const value of codes) params.append(selection.code, value);
|
|
1509
|
+
}
|
|
1510
|
+
const url = `${baseUrl}/statistics/1.0/data/${encodeURIComponent(code)}?${params.toString()}`;
|
|
1511
|
+
return request(url, { method: "GET" }, jsonStatDatasetSchema, toFlatTable$2, DATA_TTL_SECONDS, `data:${url}`).catch((err) => {
|
|
1512
|
+
if (err instanceof PxwebError && err.status === 404) throw notFound$11(code);
|
|
1513
|
+
throw err;
|
|
1514
|
+
});
|
|
1515
|
+
}
|
|
1516
|
+
};
|
|
1517
|
+
}
|
|
1518
|
+
// src/ibge-client.ts
|
|
1519
|
+
const TABLE_ID_PATTERN$7 = /^\d{1,7}$/;
|
|
1520
|
+
const LANGUAGE = "pt";
|
|
1521
|
+
const DEFAULT_SIDRA_URL = "https://apisidra.ibge.gov.br/values";
|
|
1522
|
+
const DEFAULT_MAX_CELLS$4 = 5e3;
|
|
1523
|
+
const MAX_CACHED_TABLES$3 = 8;
|
|
1524
|
+
const VARIABLE_CODE = "variavel";
|
|
1525
|
+
const LOCALITY_CODE = "localidade";
|
|
1526
|
+
const PERIOD_CODE = "periodo";
|
|
1527
|
+
const COUNTRY_LEVEL = "N1";
|
|
1528
|
+
/**
|
|
1529
|
+
* Brazil, major regions, states and municipalities. The localities endpoint answers
|
|
1530
|
+
* an empty list for metropolitan regions (N7) and some other levels, and one empty
|
|
1531
|
+
* level empties the whole answer, so only these are asked for.
|
|
1532
|
+
*/
|
|
1533
|
+
const LOCALITY_LEVELS = [
|
|
1534
|
+
"N1",
|
|
1535
|
+
"N2",
|
|
1536
|
+
"N3",
|
|
1537
|
+
"N6"
|
|
1538
|
+
];
|
|
1539
|
+
const LOCALITY_PATTERN = /^N(\d+):(\d+)$/;
|
|
1540
|
+
/** "(série encerrada em 2021)", or a closed range such as "(de janeiro/2012 até dezembro/2019)". */
|
|
1541
|
+
const CLOSED_TITLE = /s[ée]rie (encerrada|descontinuada|suspensa)|até (\p{L}+\/)?\d{4}\)\s*$/iu;
|
|
1542
|
+
/**
|
|
1543
|
+
* Survey groups whose aggregates all ended long ago (checked on 2026-11-27):
|
|
1544
|
+
* PME (ended 2016-02), PNAD (2015), PIMES (2015-12), PIM Dados Gerais (2001),
|
|
1545
|
+
* the old PIA (1995), IPC-r (1995), IRSM and INPC-E (1994).
|
|
1546
|
+
*/
|
|
1547
|
+
const DISCONTINUED_GROUPS = /* @__PURE__ */ new Set([
|
|
1548
|
+
"PE",
|
|
1549
|
+
"PD",
|
|
1550
|
+
"XY",
|
|
1551
|
+
"DG",
|
|
1552
|
+
"PI",
|
|
1553
|
+
"IL",
|
|
1554
|
+
"IJ",
|
|
1555
|
+
"PG"
|
|
1556
|
+
]);
|
|
1557
|
+
const catalogueSchema = z.array(z.object({
|
|
1558
|
+
id: z.string(),
|
|
1559
|
+
nome: z.string(),
|
|
1560
|
+
agregados: z.array(z.object({
|
|
1561
|
+
id: z.string(),
|
|
1562
|
+
nome: z.string()
|
|
1563
|
+
}))
|
|
1564
|
+
}));
|
|
1565
|
+
const metadataSchema$5 = z.object({
|
|
1566
|
+
nome: z.string(),
|
|
1567
|
+
nivelTerritorial: z.record(z.string(), z.array(z.string())),
|
|
1568
|
+
variaveis: z.array(z.object({
|
|
1569
|
+
id: z.number(),
|
|
1570
|
+
nome: z.string(),
|
|
1571
|
+
unidade: z.string().nullish()
|
|
1572
|
+
})),
|
|
1573
|
+
classificacoes: z.array(z.object({
|
|
1574
|
+
id: z.number(),
|
|
1575
|
+
nome: z.string(),
|
|
1576
|
+
sumarizacao: z.object({ status: z.boolean() }),
|
|
1577
|
+
categorias: z.array(z.object({
|
|
1578
|
+
id: z.number(),
|
|
1579
|
+
nome: z.string()
|
|
1580
|
+
}))
|
|
1581
|
+
})).default([])
|
|
1582
|
+
});
|
|
1583
|
+
const periodsSchema = z.array(z.object({
|
|
1584
|
+
id: z.string(),
|
|
1585
|
+
literals: z.array(z.string())
|
|
1586
|
+
}));
|
|
1587
|
+
const localitiesSchema = z.array(z.object({
|
|
1588
|
+
id: z.string(),
|
|
1589
|
+
nome: z.string(),
|
|
1590
|
+
nivel: z.object({ id: z.string() })
|
|
1591
|
+
}));
|
|
1592
|
+
/** The first row holds the column titles; the rest are cells. */
|
|
1593
|
+
const valuesSchema$1 = z.array(z.record(z.string(), z.string()));
|
|
1594
|
+
function notFound$10(tableId) {
|
|
1595
|
+
return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
1596
|
+
}
|
|
1597
|
+
function checkLanguage$4(lang) {
|
|
1598
|
+
if (lang !== LANGUAGE) throw new PxwebError(`Language "${lang}" is not supported.`, 400);
|
|
1599
|
+
}
|
|
1600
|
+
function upstreamError$1(err) {
|
|
1601
|
+
if (err instanceof PxwebError && err.status >= 500) return new PxwebError(`IBGE could not answer (HTTP ${err.status}). Try again later.`, 502);
|
|
1602
|
+
return err;
|
|
1603
|
+
}
|
|
1604
|
+
function withUnit(name, unit) {
|
|
1605
|
+
const label = name.trim();
|
|
1606
|
+
if (!unit || unit === "Nenhuma" || label.endsWith(")")) return label;
|
|
1607
|
+
return `${label} (${unit})`;
|
|
1608
|
+
}
|
|
1609
|
+
/** IBGE writes "-" for a true zero and "..", "..." or "X" for missing or withheld data. */
|
|
1610
|
+
function toNumber$1(value) {
|
|
1611
|
+
if (value === "-") return 0;
|
|
1612
|
+
const number = Number(value);
|
|
1613
|
+
return value && Number.isFinite(number) ? number : null;
|
|
1614
|
+
}
|
|
1615
|
+
function chosenCodes$4(variable, selection) {
|
|
1616
|
+
if (!selection || selection.selection.filter === "all") return void 0;
|
|
1617
|
+
const { filter, values } = selection.selection;
|
|
1618
|
+
if (filter === "item") return values;
|
|
1619
|
+
return variable.values.slice(-Math.max(1, Number(values[0]) || 1));
|
|
1620
|
+
}
|
|
1621
|
+
function localitySegments(codes) {
|
|
1622
|
+
const byLevel = /* @__PURE__ */ new Map();
|
|
1623
|
+
for (const code of codes) {
|
|
1624
|
+
const match = LOCALITY_PATTERN.exec(code);
|
|
1625
|
+
if (!match) throw new PxwebError(`Unknown locality "${code}". Use the codes from get_table_metadata.`, 400);
|
|
1626
|
+
const level = `n${match[1]}`;
|
|
1627
|
+
byLevel.set(level, [...byLevel.get(level) ?? [], match[2] ?? ""]);
|
|
1628
|
+
}
|
|
1629
|
+
return [...byLevel].map(([level, ids]) => `${level}/${ids.join(",")}`).join("/");
|
|
1630
|
+
}
|
|
1631
|
+
function allLevels(variable) {
|
|
1632
|
+
return [...new Set(variable.values.map((code) => code.split(":")[0]?.toLowerCase()))].map((level) => `${level}/all`).join("/");
|
|
1633
|
+
}
|
|
1634
|
+
/**
|
|
1635
|
+
* Client for IBGE (Instituto Brasileiro de Geografia e Estatística), in Portuguese.
|
|
1636
|
+
*
|
|
1637
|
+
* - Table id: the aggregate id, which is also the SIDRA table number (for example "1737").
|
|
1638
|
+
* - Search: a local index over the aggregates catalogue (`/agregados`, one 2 MB call
|
|
1639
|
+
* cached for an hour); the survey group is the path. The catalogue has no dates, so
|
|
1640
|
+
* there is no recency ranking. Aggregates are marked discontinued when the title
|
|
1641
|
+
* says "série encerrada" (or "descontinuada", "suspensa"), ends with a closed range
|
|
1642
|
+
* ("… até dezembro/2019)") or the survey ended long ago (`DISCONTINUED_GROUPS`).
|
|
1643
|
+
* - Metadata: `/agregados/{id}/metadados`, `/periodos` and `/localidades/{levels}`.
|
|
1644
|
+
* Variables: `variavel` (the IBGE variables, with the unit in the label), one `c{id}`
|
|
1645
|
+
* per classification (eliminable when IBGE sums it, which gives the total category
|
|
1646
|
+
* when it is left out), `localidade` (codes "N1:1", "N3:35", "N6:3550308"; levels
|
|
1647
|
+
* Brazil, regions, states and municipalities; eliminable when Brazil is offered) and
|
|
1648
|
+
* `periodo` (ordered oldest first).
|
|
1649
|
+
* - Query: one SIDRA values request (`/t/{id}/n…/v/…/p/…/c…`), because SIDRA answers a
|
|
1650
|
+
* refused selection with HTTP 400 and a message, where the aggregates API answers 500.
|
|
1651
|
+
* The cell limit is checked first. SIDRA orders the columns as the request does
|
|
1652
|
+
* (locality, variable, period, then classifications) and adds the left-out
|
|
1653
|
+
* classifications after them, so only the requested ones become columns.
|
|
1654
|
+
* - Not found: the aggregates API answers HTTP 500 for an unknown id, so a failed
|
|
1655
|
+
* metadata call is checked against the catalogue.
|
|
1656
|
+
* - Caching: catalogue, metadata and localities in the shared cache; the parsed table in
|
|
1657
|
+
* memory for an hour.
|
|
1658
|
+
*/
|
|
1659
|
+
function createIbgeClient(options) {
|
|
1660
|
+
const root = options.baseUrl.replace(/\/+$/, "");
|
|
1661
|
+
const sidraRoot = (options.sidraUrl ?? DEFAULT_SIDRA_URL).replace(/\/+$/, "");
|
|
1662
|
+
const maxCells = options.maxCells ?? DEFAULT_MAX_CELLS$4;
|
|
1663
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
1664
|
+
const request = createRequester(options);
|
|
1665
|
+
function get(url, schema, ttlSeconds) {
|
|
1666
|
+
return request(url, { method: "GET" }, schema, (data) => data, ttlSeconds, url);
|
|
1667
|
+
}
|
|
1668
|
+
async function listTables(lang) {
|
|
1669
|
+
checkLanguage$4(lang);
|
|
1670
|
+
const groups = await get(root, catalogueSchema, SEARCH_TTL_SECONDS);
|
|
1671
|
+
const docs = /* @__PURE__ */ new Map();
|
|
1672
|
+
for (const group of groups) for (const aggregate of group.agregados) {
|
|
1673
|
+
if (docs.has(aggregate.id)) continue;
|
|
1674
|
+
docs.set(aggregate.id, {
|
|
1675
|
+
id: aggregate.id,
|
|
1676
|
+
title: aggregate.nome.trim(),
|
|
1677
|
+
path: [group.nome.trim()],
|
|
1678
|
+
...(DISCONTINUED_GROUPS.has(group.id) || CLOSED_TITLE.test(aggregate.nome)) && { discontinued: true }
|
|
1679
|
+
});
|
|
1680
|
+
}
|
|
1681
|
+
return [...docs.values()];
|
|
1682
|
+
}
|
|
1683
|
+
const tableIndex = createTableIndexLoader(preferCrawled(listTables, options.crawledList), {
|
|
1684
|
+
fallback: options.listFallback,
|
|
1685
|
+
ttlSeconds: SEARCH_TTL_SECONDS,
|
|
1686
|
+
currentYear: () => now().getUTCFullYear()
|
|
1687
|
+
});
|
|
1688
|
+
async function missingOrUpstream(tableId, err) {
|
|
1689
|
+
if (!(err instanceof PxwebError)) return err;
|
|
1690
|
+
const tables = await listTables(LANGUAGE).catch(() => void 0);
|
|
1691
|
+
if (tables && !tables.some((table) => table.id === tableId)) return notFound$10(tableId);
|
|
1692
|
+
return upstreamError$1(err);
|
|
1693
|
+
}
|
|
1694
|
+
async function loadTable(tableId) {
|
|
1695
|
+
const base = `${root}/${tableId}`;
|
|
1696
|
+
const metadata = await get(`${base}/metadados`, metadataSchema$5, METADATA_TTL_SECONDS).catch(async (err) => {
|
|
1697
|
+
throw await missingOrUpstream(tableId, err);
|
|
1698
|
+
});
|
|
1699
|
+
const offered = Object.values(metadata.nivelTerritorial).flat();
|
|
1700
|
+
const preferred = LOCALITY_LEVELS.filter((level) => offered.includes(level));
|
|
1701
|
+
const levels = preferred.length > 0 ? preferred : offered;
|
|
1702
|
+
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) => {
|
|
1703
|
+
throw upstreamError$1(err);
|
|
1704
|
+
});
|
|
1705
|
+
const orderedPeriods = periods.toSorted((a, b) => a.id.localeCompare(b.id, "en", { numeric: true }));
|
|
1706
|
+
const orderedLocalities = levels.flatMap((level) => localities.filter((locality) => locality.nivel.id === level));
|
|
1707
|
+
return {
|
|
1708
|
+
title: metadata.nome.trim(),
|
|
1709
|
+
variables: [
|
|
1710
|
+
{
|
|
1711
|
+
code: VARIABLE_CODE,
|
|
1712
|
+
label: "Variável",
|
|
1713
|
+
values: metadata.variaveis.map((variable) => String(variable.id)),
|
|
1714
|
+
valueLabels: metadata.variaveis.map((variable) => withUnit(variable.nome, variable.unidade)),
|
|
1715
|
+
eliminable: false,
|
|
1716
|
+
isTime: false
|
|
1717
|
+
},
|
|
1718
|
+
...metadata.classificacoes.map((classification) => ({
|
|
1719
|
+
code: `c${classification.id}`,
|
|
1720
|
+
label: classification.nome.trim(),
|
|
1721
|
+
values: classification.categorias.map((category) => String(category.id)),
|
|
1722
|
+
valueLabels: classification.categorias.map((category) => category.nome.trim()),
|
|
1723
|
+
eliminable: classification.sumarizacao.status,
|
|
1724
|
+
isTime: false
|
|
1725
|
+
})),
|
|
1726
|
+
{
|
|
1727
|
+
code: LOCALITY_CODE,
|
|
1728
|
+
label: "Localidade",
|
|
1729
|
+
values: orderedLocalities.map((locality) => `${locality.nivel.id}:${locality.id}`),
|
|
1730
|
+
valueLabels: orderedLocalities.map((locality) => locality.nome.trim()),
|
|
1731
|
+
eliminable: levels.includes(COUNTRY_LEVEL),
|
|
1732
|
+
isTime: false
|
|
1733
|
+
},
|
|
1734
|
+
{
|
|
1735
|
+
code: PERIOD_CODE,
|
|
1736
|
+
label: "Período",
|
|
1737
|
+
values: orderedPeriods.map((period) => period.id),
|
|
1738
|
+
valueLabels: orderedPeriods.map((period) => period.literals[0] ?? period.id),
|
|
1739
|
+
eliminable: false,
|
|
1740
|
+
isTime: true
|
|
1741
|
+
}
|
|
1742
|
+
]
|
|
1743
|
+
};
|
|
1744
|
+
}
|
|
1745
|
+
const tables = /* @__PURE__ */ new Map();
|
|
1746
|
+
async function cachedTable(lang, tableId) {
|
|
1747
|
+
checkLanguage$4(lang);
|
|
1748
|
+
if (!TABLE_ID_PATTERN$7.test(tableId)) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it.`, 400);
|
|
1749
|
+
const cached = tables.get(tableId);
|
|
1750
|
+
if (cached && cached.expires > Date.now()) return cached.table;
|
|
1751
|
+
const table = await loadTable(tableId);
|
|
1752
|
+
tables.delete(tableId);
|
|
1753
|
+
tables.set(tableId, {
|
|
1754
|
+
expires: Date.now() + DATA_TTL_SECONDS * 1e3,
|
|
1755
|
+
table
|
|
1756
|
+
});
|
|
1757
|
+
const oldest = tables.keys().next().value;
|
|
1758
|
+
if (tables.size > MAX_CACHED_TABLES$3 && oldest !== void 0) tables.delete(oldest);
|
|
1759
|
+
return table;
|
|
1760
|
+
}
|
|
1761
|
+
return {
|
|
1762
|
+
listTables,
|
|
1763
|
+
async search(lang, query, searchOptions) {
|
|
1764
|
+
checkLanguage$4(lang);
|
|
1765
|
+
return (await tableIndex(lang)).search(query, searchOptions);
|
|
1766
|
+
},
|
|
1767
|
+
async getMetadata(lang, tableId) {
|
|
1768
|
+
return cachedTable(lang, tableId);
|
|
1769
|
+
},
|
|
1770
|
+
async query(lang, tableId, selections) {
|
|
1771
|
+
const table = await cachedTable(lang, tableId);
|
|
1772
|
+
const byCode = new Map(selections.map((selection) => [selection.code, selection]));
|
|
1773
|
+
let locality = `${COUNTRY_LEVEL.toLowerCase()}/all`;
|
|
1774
|
+
let variables = "v/all";
|
|
1775
|
+
let periods = "p/all";
|
|
1776
|
+
const classificationPaths = [];
|
|
1777
|
+
const classifications = [];
|
|
1778
|
+
let cells = 1;
|
|
1779
|
+
for (const variable of table.variables) {
|
|
1780
|
+
const selection = byCode.get(variable.code);
|
|
1781
|
+
if (!selection && variable.eliminable) continue;
|
|
1782
|
+
const codes = chosenCodes$4(variable, selection);
|
|
1783
|
+
cells *= codes?.length ?? variable.values.length;
|
|
1784
|
+
const list = codes?.map(encodeURIComponent).join(",") ?? "all";
|
|
1785
|
+
if (variable.code === LOCALITY_CODE) locality = codes ? localitySegments(codes) : allLevels(variable);
|
|
1786
|
+
else if (variable.code === VARIABLE_CODE) variables = `v/${list}`;
|
|
1787
|
+
else if (variable.code === PERIOD_CODE) periods = `p/${list}`;
|
|
1788
|
+
else {
|
|
1789
|
+
classifications.push(variable);
|
|
1790
|
+
classificationPaths.push(`${variable.code}/${list}`);
|
|
1791
|
+
}
|
|
1792
|
+
}
|
|
1793
|
+
if (cells > maxCells) throw new PxwebError(`The query could return ${cells} cells, above the limit of ${maxCells}. Select fewer values.`, 400);
|
|
1794
|
+
const path = [
|
|
1795
|
+
`t/${tableId}`,
|
|
1796
|
+
locality,
|
|
1797
|
+
variables,
|
|
1798
|
+
periods,
|
|
1799
|
+
...classificationPaths
|
|
1800
|
+
].join("/");
|
|
1801
|
+
const rows = await get(`${sidraRoot}/${path}`, valuesSchema$1, DATA_TTL_SECONDS).catch((err) => {
|
|
1802
|
+
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);
|
|
1803
|
+
throw upstreamError$1(err);
|
|
1804
|
+
});
|
|
1805
|
+
const variable = table.variables.find((entry) => entry.code === VARIABLE_CODE);
|
|
1806
|
+
const variableLabels = new Map(variable?.values.map((code, index) => [code, variable.valueLabels[index] ?? code]));
|
|
1807
|
+
return {
|
|
1808
|
+
label: table.title,
|
|
1809
|
+
columns: [
|
|
1810
|
+
"Localidade",
|
|
1811
|
+
"Variável",
|
|
1812
|
+
...classifications.map((entry) => entry.label),
|
|
1813
|
+
"Período",
|
|
1814
|
+
"Valor"
|
|
1815
|
+
],
|
|
1816
|
+
rows: rows.slice(1).map((row) => [
|
|
1817
|
+
row.D1N ?? null,
|
|
1818
|
+
variableLabels.get(row.D2C ?? "") ?? row.D2N ?? null,
|
|
1819
|
+
...classifications.map((_, index) => row[`D${index + 4}N`] ?? null),
|
|
1820
|
+
row.D3N ?? null,
|
|
1821
|
+
toNumber$1(row.V)
|
|
1822
|
+
])
|
|
1823
|
+
};
|
|
1824
|
+
}
|
|
1825
|
+
};
|
|
1826
|
+
}
|
|
1827
|
+
// src/ine-es-client.ts
|
|
1828
|
+
const TABLE_ID_PATTERN$6 = /^\d+$/;
|
|
1829
|
+
const LANGUAGES$3 = {
|
|
1830
|
+
es: "ES",
|
|
1831
|
+
en: "EN"
|
|
1832
|
+
};
|
|
1833
|
+
const TIME_CODE$5 = "period";
|
|
1834
|
+
const TIME_LABELS = {
|
|
1835
|
+
es: "Periodo",
|
|
1836
|
+
en: "Period"
|
|
1837
|
+
};
|
|
1838
|
+
const VALUE_LABELS$1 = {
|
|
1839
|
+
es: "Valor",
|
|
1840
|
+
en: "Value"
|
|
1841
|
+
};
|
|
1842
|
+
/** The INE licence asks reusers to give the date of the last update. */
|
|
1843
|
+
const UPDATED_LABELS$1 = {
|
|
1844
|
+
es: "última actualización",
|
|
1845
|
+
en: "last update"
|
|
1846
|
+
};
|
|
1847
|
+
/** DATOS_TABLA without nult or date sends the full history of every series. */
|
|
1848
|
+
const PROBE_PERIODS = 1e4;
|
|
1849
|
+
const MONTHS$2 = [
|
|
1850
|
+
"Jan",
|
|
1851
|
+
"Feb",
|
|
1852
|
+
"Mar",
|
|
1853
|
+
"Apr",
|
|
1854
|
+
"May",
|
|
1855
|
+
"Jun",
|
|
1856
|
+
"Jul",
|
|
1857
|
+
"Aug",
|
|
1858
|
+
"Sep",
|
|
1859
|
+
"Oct",
|
|
1860
|
+
"Nov",
|
|
1861
|
+
"Dec"
|
|
1862
|
+
];
|
|
1863
|
+
const operationsSchema = z.array(z.object({
|
|
1864
|
+
Id: z.number(),
|
|
1865
|
+
Nombre: z.string()
|
|
1866
|
+
}));
|
|
1867
|
+
const tablesSchema = z.array(z.object({
|
|
1868
|
+
Id: z.number(),
|
|
1869
|
+
Nombre: z.string(),
|
|
1870
|
+
Ultima_Modificacion: z.string().optional(),
|
|
1871
|
+
FK_Periodo_fin: z.number().optional(),
|
|
1872
|
+
Anyo_Periodo_fin: z.string().optional()
|
|
1873
|
+
}));
|
|
1874
|
+
const groupsSchema = z.array(z.object({
|
|
1875
|
+
Id: z.number(),
|
|
1876
|
+
Nombre: z.string()
|
|
1877
|
+
}));
|
|
1878
|
+
const valuesSchema = z.array(z.object({
|
|
1879
|
+
Id: z.number(),
|
|
1880
|
+
FK_Variable: z.number(),
|
|
1881
|
+
Nombre: z.string()
|
|
1882
|
+
}));
|
|
1883
|
+
const seriesSchema$1 = z.array(z.object({
|
|
1884
|
+
MetaData: z.array(z.object({ Id: z.number() })).default([]),
|
|
1885
|
+
Data: z.array(z.object({
|
|
1886
|
+
Fecha: z.number(),
|
|
1887
|
+
FK_Periodo: z.number(),
|
|
1888
|
+
Anyo: z.number(),
|
|
1889
|
+
Valor: z.number().nullish(),
|
|
1890
|
+
Secreto: z.boolean().optional()
|
|
1891
|
+
}))
|
|
1892
|
+
}));
|
|
1893
|
+
function periodCode$2(year, period) {
|
|
1894
|
+
if (period >= 1 && period <= 12) return `${year}M${String(period).padStart(2, "0")}`;
|
|
1895
|
+
if (period >= 19 && period <= 22) return `${year}Q${period - 18}`;
|
|
1896
|
+
if (period === 28) return String(year);
|
|
1897
|
+
}
|
|
1898
|
+
/** Fecha is midnight in Madrid; noon UTC of the same instant keeps its calendar day. */
|
|
1899
|
+
function madridDate(fecha) {
|
|
1900
|
+
return new Date(fecha + 432e5).toISOString().slice(0, 10);
|
|
1901
|
+
}
|
|
1902
|
+
function pointCode(point) {
|
|
1903
|
+
return periodCode$2(point.Anyo, point.FK_Periodo) ?? madridDate(point.Fecha);
|
|
1904
|
+
}
|
|
1905
|
+
/** "Fri Nov 13 09:00:00 CET 2026" → "2026-11-13". */
|
|
1906
|
+
function isoDate$2(text) {
|
|
1907
|
+
const match = /^\w{3} (\w{3}) (\d{2}) \S+ \S+ (\d{4})$/.exec(text ?? "");
|
|
1908
|
+
const month = MONTHS$2.indexOf(match?.[1] ?? "");
|
|
1909
|
+
if (!match || month < 0) return void 0;
|
|
1910
|
+
return `${match[3]}-${String(month + 1).padStart(2, "0")}-${match[2]}`;
|
|
1911
|
+
}
|
|
1912
|
+
function notFound$9(tableId) {
|
|
1913
|
+
return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
1914
|
+
}
|
|
1915
|
+
function pathLanguage(lang) {
|
|
1916
|
+
const code = LANGUAGES$3[lang];
|
|
1917
|
+
if (!code) throw new PxwebError(`Language "${lang}" is not supported.`, 400);
|
|
1918
|
+
return code;
|
|
1919
|
+
}
|
|
1920
|
+
function chosenCodes$3(variable, selection) {
|
|
1921
|
+
if (!selection || selection.selection.filter === "all") return [];
|
|
1922
|
+
const { filter, values } = selection.selection;
|
|
1923
|
+
if (filter === "top") return variable.values.slice(-Math.max(1, Number(values[0]) || 1));
|
|
1924
|
+
return values;
|
|
1925
|
+
}
|
|
1926
|
+
function timeParams(table, selection) {
|
|
1927
|
+
const periods = table.periodDates.size;
|
|
1928
|
+
if (!selection || selection.selection.filter === "all") {
|
|
1929
|
+
if (periods === 0) throw new PxwebError(`The periods of this table are not known. Use latest on "${TIME_CODE$5}".`, 400);
|
|
1930
|
+
return { params: [`nult=${periods}`] };
|
|
1931
|
+
}
|
|
1932
|
+
const { filter, values } = selection.selection;
|
|
1933
|
+
if (filter === "top") return { params: [`nult=${Math.max(1, Number(values[0]) || 1)}`] };
|
|
1934
|
+
const dates = values.map((code) => table.periodDates.get(code)).filter((date) => date !== void 0).toSorted();
|
|
1935
|
+
const [first] = dates;
|
|
1936
|
+
const last = dates.at(-1);
|
|
1937
|
+
if (!first || !last) throw new PxwebError(`Unknown periods ${values.join(", ")}. Call get_table_metadata to see valid periods.`, 400);
|
|
1938
|
+
return {
|
|
1939
|
+
params: [`date=${first}:${last}`],
|
|
1940
|
+
keep: new Set(values)
|
|
1941
|
+
};
|
|
1942
|
+
}
|
|
1943
|
+
function createIneEsClient(options) {
|
|
1944
|
+
const root = options.baseUrl.replace(/\/+$/, "");
|
|
1945
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
1946
|
+
const request = createRequester(options);
|
|
1947
|
+
const tableIndex = createTableIndexLoader(async (lang) => {
|
|
1948
|
+
if (!options.tableList) throw new PxwebError("The table list is not available now.", 503);
|
|
1949
|
+
return options.tableList(lang);
|
|
1950
|
+
}, {
|
|
1951
|
+
ttlSeconds: SEARCH_TTL_SECONDS,
|
|
1952
|
+
currentYear: () => now().getUTCFullYear()
|
|
1953
|
+
});
|
|
1954
|
+
function get(url, schema, map, ttlSeconds) {
|
|
1955
|
+
return request(url, { method: "GET" }, schema, map, ttlSeconds, url);
|
|
1956
|
+
}
|
|
1957
|
+
async function titleOf(lang, tableId) {
|
|
1958
|
+
const hit = await tableIndex(lang).then((index) => index.search(tableId)[0]).catch(() => void 0);
|
|
1959
|
+
if (hit?.tableId !== tableId) return `INE ${tableId}`;
|
|
1960
|
+
if (!hit.published) return hit.title;
|
|
1961
|
+
return `${hit.title} (${UPDATED_LABELS$1[lang] ?? UPDATED_LABELS$1.en}: ${hit.published})`;
|
|
1962
|
+
}
|
|
1963
|
+
async function loadTable(lang, tableId) {
|
|
1964
|
+
if (!TABLE_ID_PATTERN$6.test(tableId)) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it.`, 400);
|
|
1965
|
+
const base = `${root}/${pathLanguage(lang)}`;
|
|
1966
|
+
const groups = await get(`${base}/GRUPOS_TABLA/${tableId}`, groupsSchema, (data) => data, METADATA_TTL_SECONDS).catch((err) => {
|
|
1967
|
+
if (err instanceof PxwebError && err.status === 404) throw notFound$9(tableId);
|
|
1968
|
+
throw err;
|
|
1969
|
+
});
|
|
1970
|
+
if (groups.length === 0) throw notFound$9(tableId);
|
|
1971
|
+
const groupValues = await Promise.all(groups.map((group) => get(`${base}/VALORES_GRUPOSTABLA/${tableId}/${group.Id}`, valuesSchema, (data) => data, METADATA_TTL_SECONDS)));
|
|
1972
|
+
const variableOf = /* @__PURE__ */ new Map();
|
|
1973
|
+
const variables = groups.map((group, index) => {
|
|
1974
|
+
const values = groupValues[index] ?? [];
|
|
1975
|
+
for (const value of values) if (!variableOf.has(String(value.Id))) variableOf.set(String(value.Id), value.FK_Variable);
|
|
1976
|
+
return {
|
|
1977
|
+
code: String(group.Id),
|
|
1978
|
+
label: group.Nombre.trim(),
|
|
1979
|
+
values: values.map((value) => String(value.Id)),
|
|
1980
|
+
valueLabels: values.map((value) => value.Nombre.trim()),
|
|
1981
|
+
eliminable: false,
|
|
1982
|
+
isTime: false
|
|
1983
|
+
};
|
|
1984
|
+
});
|
|
1985
|
+
const [series] = await get(`${base}/DATOS_TABLA/${tableId}?${[
|
|
1986
|
+
...groupValues.map((values) => values[0]).filter((value) => value !== void 0).map((value) => `tv=${value.FK_Variable}:${value.Id}`),
|
|
1987
|
+
`nult=${PROBE_PERIODS}`,
|
|
1988
|
+
"tip=M"
|
|
1989
|
+
].join("&")}`, seriesSchema$1, (data) => data, DATA_TTL_SECONDS).catch(() => []);
|
|
1990
|
+
const periodDates = new Map((series?.Data ?? []).toSorted((a, b) => a.Fecha - b.Fecha).map((point) => [pointCode(point), madridDate(point.Fecha).replaceAll("-", "")]));
|
|
1991
|
+
const periods = [...periodDates.keys()];
|
|
1992
|
+
variables.push({
|
|
1993
|
+
code: TIME_CODE$5,
|
|
1994
|
+
label: TIME_LABELS[lang] ?? TIME_CODE$5,
|
|
1995
|
+
values: periods,
|
|
1996
|
+
valueLabels: periods,
|
|
1997
|
+
eliminable: false,
|
|
1998
|
+
isTime: true,
|
|
1999
|
+
...periods.length === 0 && { periodsIncomplete: true }
|
|
2000
|
+
});
|
|
2001
|
+
return {
|
|
2002
|
+
metadata: {
|
|
2003
|
+
title: await titleOf(lang, tableId),
|
|
2004
|
+
variables
|
|
2005
|
+
},
|
|
2006
|
+
variableOf,
|
|
2007
|
+
periodDates
|
|
2008
|
+
};
|
|
2009
|
+
}
|
|
2010
|
+
async function listTables(lang) {
|
|
2011
|
+
const base = `${root}/${pathLanguage(lang)}`;
|
|
2012
|
+
const operations = await get(`${base}/OPERACIONES_DISPONIBLES`, operationsSchema, (data) => data, SEARCH_TTL_SECONDS);
|
|
2013
|
+
const docs = /* @__PURE__ */ new Map();
|
|
2014
|
+
for (const operation of operations) {
|
|
2015
|
+
const tables = await get(`${base}/TABLAS_OPERACION/${operation.Id}`, tablesSchema, (data) => data, SEARCH_TTL_SECONDS);
|
|
2016
|
+
for (const table of tables) {
|
|
2017
|
+
const id = String(table.Id);
|
|
2018
|
+
if (docs.has(id)) continue;
|
|
2019
|
+
const updated = isoDate$2(table.Ultima_Modificacion);
|
|
2020
|
+
const endYear = table.Anyo_Periodo_fin;
|
|
2021
|
+
const lastPeriod = endYear && (periodCode$2(Number(endYear), table.FK_Periodo_fin ?? 0) ?? endYear);
|
|
2022
|
+
docs.set(id, {
|
|
2023
|
+
id,
|
|
2024
|
+
title: table.Nombre.trim(),
|
|
2025
|
+
path: [operation.Nombre.trim()],
|
|
2026
|
+
...updated && { updated },
|
|
2027
|
+
...lastPeriod && { lastPeriod }
|
|
2028
|
+
});
|
|
2029
|
+
}
|
|
2030
|
+
}
|
|
2031
|
+
return [...docs.values()];
|
|
2032
|
+
}
|
|
2033
|
+
return {
|
|
2034
|
+
listTables,
|
|
2035
|
+
async search(lang, query, searchOptions) {
|
|
2036
|
+
pathLanguage(lang);
|
|
2037
|
+
return (await tableIndex(lang)).search(query, searchOptions);
|
|
2038
|
+
},
|
|
2039
|
+
async getMetadata(lang, tableId) {
|
|
2040
|
+
return (await loadTable(lang, tableId)).metadata;
|
|
2041
|
+
},
|
|
2042
|
+
async query(lang, tableId, selections) {
|
|
2043
|
+
const table = await loadTable(lang, tableId);
|
|
2044
|
+
const byCode = new Map(selections.map((selection) => [selection.code, selection]));
|
|
2045
|
+
const groups = table.metadata.variables.filter((variable) => !variable.isTime);
|
|
2046
|
+
const filters = groups.flatMap((variable) => chosenCodes$3(variable, byCode.get(variable.code)).map((code) => {
|
|
2047
|
+
const variableId = table.variableOf.get(code);
|
|
2048
|
+
if (variableId === void 0) throw new PxwebError(`Variable "${variable.code}" has no value ${code}. Call get_table_metadata to see valid value codes.`, 400);
|
|
2049
|
+
return `tv=${variableId}:${code}`;
|
|
2050
|
+
}));
|
|
2051
|
+
const time = timeParams(table, byCode.get(TIME_CODE$5));
|
|
2052
|
+
const url = `${root}/${pathLanguage(lang)}/DATOS_TABLA/${tableId}?${[
|
|
2053
|
+
...filters,
|
|
2054
|
+
...time.params,
|
|
2055
|
+
"tip=M"
|
|
2056
|
+
].join("&")}`;
|
|
2057
|
+
const labels = groups.map((variable) => new Map(variable.values.map((value, index) => [Number(value), variable.valueLabels[index] ?? value])));
|
|
2058
|
+
return get(url, seriesSchema$1, (series) => ({
|
|
2059
|
+
label: table.metadata.title,
|
|
2060
|
+
columns: [
|
|
2061
|
+
...groups.map((variable) => variable.label),
|
|
2062
|
+
TIME_LABELS[lang] ?? TIME_CODE$5,
|
|
2063
|
+
VALUE_LABELS$1[lang] ?? "Value"
|
|
2064
|
+
],
|
|
2065
|
+
rows: series.flatMap((item) => {
|
|
2066
|
+
const cells = labels.map((byId) => item.MetaData.map((meta) => byId.get(meta.Id)).find((label) => label !== void 0) ?? null);
|
|
2067
|
+
return item.Data.toSorted((a, b) => a.Fecha - b.Fecha).map((point) => ({
|
|
2068
|
+
point,
|
|
2069
|
+
code: pointCode(point)
|
|
2070
|
+
})).filter(({ code }) => !time.keep || time.keep.has(code)).map(({ point, code }) => [
|
|
2071
|
+
...cells,
|
|
2072
|
+
code,
|
|
2073
|
+
point.Secreto ? null : point.Valor ?? null
|
|
2074
|
+
]);
|
|
2075
|
+
})
|
|
2076
|
+
}), DATA_TTL_SECONDS).catch((err) => {
|
|
2077
|
+
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);
|
|
2078
|
+
throw err;
|
|
2079
|
+
});
|
|
2080
|
+
}
|
|
2081
|
+
};
|
|
2082
|
+
}
|
|
2083
|
+
// src/ine-pt-client.ts
|
|
2084
|
+
const INDICATOR_PATTERN = /^\d{7}$/;
|
|
2085
|
+
const TIME_DIMENSION = "1";
|
|
2086
|
+
const GEOGRAPHY_DIMENSION = "2";
|
|
2087
|
+
const NOT_FOUND_CODE = "1";
|
|
2088
|
+
/** INE refuses requests above 1,000,000 rows. */
|
|
2089
|
+
const API_MAX_CELLS = 1e6;
|
|
2090
|
+
/** The full catalogue is about 21 MB of XML; downloads have taken from 30 s to more than 120 s. */
|
|
2091
|
+
const CATALOGUE_MAX_BYTES = 67108864;
|
|
2092
|
+
const CATALOGUE_TIMEOUT_MS = 3e5;
|
|
2093
|
+
const failureSchema = z.object({ Sucesso: z.object({ Falso: z.array(z.object({
|
|
2094
|
+
Msg: z.string().optional(),
|
|
2095
|
+
Cod: z.string().optional()
|
|
2096
|
+
})) }) });
|
|
2097
|
+
const categorySchema$1 = z.object({
|
|
2098
|
+
dim_num: z.string(),
|
|
2099
|
+
cat_id: z.string(),
|
|
2100
|
+
categ_dsg: z.string(),
|
|
2101
|
+
categ_ord: z.string().optional()
|
|
2102
|
+
});
|
|
2103
|
+
const indicatorSchema = z.object({
|
|
2104
|
+
IndicadorNome: z.string(),
|
|
2105
|
+
Dimensoes: z.object({
|
|
2106
|
+
Descricao_Dim: z.array(z.object({
|
|
2107
|
+
dim_num: z.string(),
|
|
2108
|
+
abrv: z.string()
|
|
2109
|
+
})),
|
|
2110
|
+
Categoria_Dim: z.array(z.record(z.string(), z.array(categorySchema$1)))
|
|
2111
|
+
})
|
|
2112
|
+
});
|
|
2113
|
+
const dataSetSchema = z.object({ Dados: z.record(z.string(), z.array(z.record(z.string(), z.unknown()))) });
|
|
2114
|
+
const metadataSchema$4 = z.tuple([z.union([indicatorSchema, failureSchema])], z.unknown());
|
|
2115
|
+
const dataSchema$3 = z.tuple([z.union([dataSetSchema, failureSchema])], z.unknown());
|
|
2116
|
+
function notFound$8(tableId) {
|
|
2117
|
+
return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
2118
|
+
}
|
|
2119
|
+
function checkTableId$4(tableId) {
|
|
2120
|
+
if (!INDICATOR_PATTERN.test(tableId)) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it.`, 400);
|
|
2121
|
+
}
|
|
2122
|
+
/** INE answers errors with HTTP 200 and a bilingual message: "(PT) … / (EN) …". */
|
|
2123
|
+
function failure(tableId, data) {
|
|
2124
|
+
const first = data.Sucesso.Falso[0];
|
|
2125
|
+
if (first?.Cod === NOT_FOUND_CODE) return notFound$8(tableId);
|
|
2126
|
+
return new PxwebError(`INE refused the request: ${first?.Msg?.split("(EN)").at(-1)?.trim() || "unknown error"}`, 400);
|
|
2127
|
+
}
|
|
2128
|
+
function toMetadata(tableId, [indicator]) {
|
|
2129
|
+
if (!("IndicadorNome" in indicator)) throw failure(tableId, indicator);
|
|
2130
|
+
const categories = Object.values(indicator.Dimensoes.Categoria_Dim[0] ?? {}).flatMap((entries) => entries.slice(0, 1));
|
|
2131
|
+
return {
|
|
2132
|
+
title: indicator.IndicadorNome,
|
|
2133
|
+
variables: indicator.Dimensoes.Descricao_Dim.map((dimension) => {
|
|
2134
|
+
const own = categories.filter((category) => category.dim_num === dimension.dim_num).toSorted((a, b) => Number(a.categ_ord ?? 0) - Number(b.categ_ord ?? 0));
|
|
2135
|
+
return {
|
|
2136
|
+
code: `Dim${dimension.dim_num}`,
|
|
2137
|
+
label: dimension.abrv,
|
|
2138
|
+
values: own.map((category) => category.cat_id),
|
|
2139
|
+
valueLabels: own.map((category) => category.categ_dsg),
|
|
2140
|
+
eliminable: false,
|
|
2141
|
+
isTime: dimension.dim_num === TIME_DIMENSION
|
|
2142
|
+
};
|
|
2143
|
+
})
|
|
2144
|
+
};
|
|
2145
|
+
}
|
|
2146
|
+
/** Codes to request, or undefined to leave the dimension out (INE then returns all of it). */
|
|
2147
|
+
function requestedCodes$1(variable, selection) {
|
|
2148
|
+
const filter = selection?.selection.filter ?? "all";
|
|
2149
|
+
if (filter === "top") {
|
|
2150
|
+
const count = Math.max(1, Number(selection?.selection.values[0]) || 1);
|
|
2151
|
+
return variable.values.slice(-count);
|
|
2152
|
+
}
|
|
2153
|
+
if (filter === "item") return selection?.selection.values ?? [];
|
|
2154
|
+
return variable.isTime ? variable.values : void 0;
|
|
2155
|
+
}
|
|
2156
|
+
function rowCode(row, variable) {
|
|
2157
|
+
const number = variable.slice(3);
|
|
2158
|
+
return String(number === GEOGRAPHY_DIMENSION ? row.geocod : row[`dim_${number}`]);
|
|
2159
|
+
}
|
|
2160
|
+
function numberOrNull$1(value) {
|
|
2161
|
+
if (typeof value !== "string" || value.trim() === "") return null;
|
|
2162
|
+
const parsed = Number(value);
|
|
2163
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
2164
|
+
}
|
|
2165
|
+
const compareOrder = (a, b) => a.reduce((result, value, i) => result || value - (b[i] ?? 0), 0);
|
|
2166
|
+
const apiLang = (lang) => encodeURIComponent(lang.toUpperCase());
|
|
2167
|
+
const positions = (keys) => new Map(keys.map((key, index) => [key, index]));
|
|
2168
|
+
/** Data comes grouped by period label in no useful order, so rows are sorted like the metadata. */
|
|
2169
|
+
function toFlatTable$1(metadata, dados) {
|
|
2170
|
+
const time = metadata.variables.find((variable) => variable.isTime);
|
|
2171
|
+
const others = metadata.variables.filter((variable) => !variable.isTime);
|
|
2172
|
+
const periodIndex = positions(time?.valueLabels ?? []);
|
|
2173
|
+
const indexes = others.map((variable) => positions(variable.values));
|
|
2174
|
+
const rows = Object.entries(dados).flatMap(([period, entries]) => entries.map((entry) => {
|
|
2175
|
+
const codes = others.map((variable) => rowCode(entry, variable.code));
|
|
2176
|
+
const order = codes.map((code, d) => indexes[d]?.get(code) ?? -1);
|
|
2177
|
+
const labels = codes.map((code, d) => others[d]?.valueLabels[order[d] ?? -1] ?? code);
|
|
2178
|
+
return {
|
|
2179
|
+
order: [periodIndex.get(period) ?? -1, ...order],
|
|
2180
|
+
cells: [
|
|
2181
|
+
period,
|
|
2182
|
+
...labels,
|
|
2183
|
+
numberOrNull$1(entry.valor)
|
|
2184
|
+
]
|
|
2185
|
+
};
|
|
2186
|
+
}));
|
|
2187
|
+
return {
|
|
2188
|
+
label: metadata.title,
|
|
2189
|
+
columns: [
|
|
2190
|
+
...time ? [time.label] : [],
|
|
2191
|
+
...others.map((variable) => variable.label),
|
|
2192
|
+
"Value"
|
|
2193
|
+
],
|
|
2194
|
+
rows: rows.toSorted((a, b) => compareOrder(a.order, b.order)).map((row) => row.cells)
|
|
2195
|
+
};
|
|
2196
|
+
}
|
|
2197
|
+
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;
|
|
2198
|
+
function isoDate$1(day) {
|
|
2199
|
+
const match = /^(\d{2})-(\d{2})-(\d{4})$/.exec(day ?? "");
|
|
2200
|
+
return match ? `${match[3]}-${match[2]}-${match[1]}` : void 0;
|
|
2201
|
+
}
|
|
2202
|
+
/**
|
|
2203
|
+
* Many indicators share a short title ("Resident population (No.)"), so the
|
|
2204
|
+
* title is the description, which adds the dimensions and the source. The
|
|
2205
|
+
* catalogue has no meaningful order, so the most recently updated go first
|
|
2206
|
+
* (sorting by last period would put projections to 2100 first).
|
|
2207
|
+
*/
|
|
2208
|
+
function parseCatalogue(xml) {
|
|
2209
|
+
return [...xml.matchAll(/<indicator id="(\d{7})">([\s\S]*?)<\/indicator>/g)].flatMap(([, id = "", block = ""]) => {
|
|
2210
|
+
const title = field(block, "description") ?? field(block, "title");
|
|
2211
|
+
if (!title) return [];
|
|
2212
|
+
const path = [field(block, "theme"), field(block, "subtheme")].filter((part) => part !== void 0);
|
|
2213
|
+
const updated = isoDate$1(field(block, "last_update"));
|
|
2214
|
+
const lastPeriod = field(block, "last_period_available")?.replace(/^S?\d+A/, "");
|
|
2215
|
+
return [{
|
|
2216
|
+
id,
|
|
2217
|
+
title,
|
|
2218
|
+
...path.length ? { path } : {},
|
|
2219
|
+
...updated ? { updated } : {},
|
|
2220
|
+
...lastPeriod ? { lastPeriod } : {}
|
|
2221
|
+
}];
|
|
2222
|
+
}).toSorted((a, b) => (b.updated ?? "").localeCompare(a.updated ?? "") || a.id.localeCompare(b.id));
|
|
2223
|
+
}
|
|
2224
|
+
function createInePtClient(options) {
|
|
2225
|
+
const root = options.baseUrl.replace(/\/+$/, "");
|
|
2226
|
+
const maxCells = options.maxCells ?? API_MAX_CELLS;
|
|
2227
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
2228
|
+
const request = createRequester(options);
|
|
2229
|
+
const doFetch = options.fetch ?? fetch;
|
|
2230
|
+
const tableIndex = createTableIndexLoader(async (lang) => {
|
|
2231
|
+
if (!options.tableList) throw new PxwebError("The table list is not available now.", 503);
|
|
2232
|
+
return options.tableList(lang);
|
|
2233
|
+
}, {
|
|
2234
|
+
ttlSeconds: SEARCH_TTL_SECONDS,
|
|
2235
|
+
currentYear: () => now().getUTCFullYear()
|
|
2236
|
+
});
|
|
2237
|
+
async function getMetadata(lang, tableId) {
|
|
2238
|
+
checkTableId$4(tableId);
|
|
2239
|
+
const url = `${root}/json_indicador/pindicaMeta.jsp?varcd=${tableId}&lang=${apiLang(lang)}`;
|
|
2240
|
+
return request(url, { method: "GET" }, metadataSchema$4, (data) => toMetadata(tableId, data), METADATA_TTL_SECONDS, `meta:${url}`);
|
|
2241
|
+
}
|
|
2242
|
+
return {
|
|
2243
|
+
async search(lang, query, searchOptions) {
|
|
2244
|
+
return (await tableIndex(lang)).search(query, searchOptions);
|
|
2245
|
+
},
|
|
2246
|
+
getMetadata,
|
|
2247
|
+
async listTables(lang) {
|
|
2248
|
+
const url = `${root}/xml_indic.jsp?opc=2&lang=${apiLang(lang)}`;
|
|
2249
|
+
const response = await doFetch(url, {
|
|
2250
|
+
headers: options.userAgent ? { "user-agent": options.userAgent } : {},
|
|
2251
|
+
signal: AbortSignal.timeout(CATALOGUE_TIMEOUT_MS)
|
|
2252
|
+
}).catch((err) => {
|
|
2253
|
+
throw new PxwebError(`INE catalogue request failed: ${err instanceof Error ? err.message : String(err)}`, 502);
|
|
2254
|
+
});
|
|
2255
|
+
const xml = await readCappedText(response, CATALOGUE_MAX_BYTES);
|
|
2256
|
+
if (!response.ok) throw new PxwebError(`INE catalogue returned HTTP ${response.status}.`, response.status);
|
|
2257
|
+
if (!/<\/catalog>\s*$/.test(xml)) throw new PxwebError("INE returned an incomplete catalogue.", 502);
|
|
2258
|
+
const docs = parseCatalogue(xml);
|
|
2259
|
+
if (docs.length === 0) throw new PxwebError("INE returned an empty catalogue.", 502);
|
|
2260
|
+
return docs;
|
|
2261
|
+
},
|
|
2262
|
+
async query(lang, tableId, selections) {
|
|
2263
|
+
const metadata = await getMetadata(lang, tableId);
|
|
2264
|
+
const byCode = new Map(selections.map((selection) => [selection.code, selection]));
|
|
2265
|
+
let cells = 1;
|
|
2266
|
+
const params = [`op=2`, `varcd=${tableId}`];
|
|
2267
|
+
for (const variable of metadata.variables) {
|
|
2268
|
+
const codes = requestedCodes$1(variable, byCode.get(variable.code));
|
|
2269
|
+
cells *= codes?.length ?? variable.values.length;
|
|
2270
|
+
if (codes) params.push(`${variable.code}=${codes.map(encodeURIComponent).join(",")}`);
|
|
2271
|
+
}
|
|
2272
|
+
if (cells > maxCells) throw new PxwebError(`The query would return ${cells} cells, above the limit of ${maxCells}. Select fewer values.`, 400);
|
|
2273
|
+
params.push(`lang=${apiLang(lang)}`);
|
|
2274
|
+
const url = `${root}/json_indicador/pindica.jsp?${params.join("&")}`;
|
|
2275
|
+
return request(url, { method: "GET" }, dataSchema$3, ([data]) => {
|
|
2276
|
+
if (!("Dados" in data)) throw failure(tableId, data);
|
|
2277
|
+
return toFlatTable$1(metadata, data.Dados);
|
|
2278
|
+
}, DATA_TTL_SECONDS, `data:${url}`);
|
|
2279
|
+
}
|
|
2280
|
+
};
|
|
2281
|
+
}
|
|
2282
|
+
// src/insee-client.ts
|
|
2283
|
+
const TABLE_ID_PATTERN$5 = /^[A-Z][A-Z0-9_]{0,99}$/;
|
|
2284
|
+
const LANGUAGES$2 = /* @__PURE__ */ new Set(["fr", "en"]);
|
|
2285
|
+
const TIME_CODE$4 = "TIME_PERIOD";
|
|
2286
|
+
/** Data answers name a territory with its vintage ("2025-DEP-976"); filters take "DEP-976". */
|
|
2287
|
+
const GEO_VINTAGE = /^\d{4}-/;
|
|
2288
|
+
const DEFAULT_MAX_CELLS$3 = 1e5;
|
|
2289
|
+
const MAX_CACHED_TABLES$2 = 20;
|
|
2290
|
+
const VALUE_LABELS = {
|
|
2291
|
+
fr: "Valeur",
|
|
2292
|
+
en: "Value"
|
|
2293
|
+
};
|
|
2294
|
+
/** Licence Ouverte asks reusers to give the date of the last update. */
|
|
2295
|
+
const UPDATED_LABELS = {
|
|
2296
|
+
fr: "dernière mise à jour",
|
|
2297
|
+
en: "last update"
|
|
2298
|
+
};
|
|
2299
|
+
const labelsSchema = z.record(z.string(), z.string()).optional();
|
|
2300
|
+
const textsSchema = z.array(z.object({
|
|
2301
|
+
content: z.string().optional(),
|
|
2302
|
+
lang: z.string()
|
|
2303
|
+
})).nullish();
|
|
2304
|
+
const rangeSchema = z.object({
|
|
2305
|
+
label: labelsSchema,
|
|
2306
|
+
range: z.array(z.object({
|
|
2307
|
+
concept: z.object({
|
|
2308
|
+
code: z.string(),
|
|
2309
|
+
label: labelsSchema
|
|
2310
|
+
}),
|
|
2311
|
+
type: z.string(),
|
|
2312
|
+
values: z.array(z.object({
|
|
2313
|
+
code: z.string(),
|
|
2314
|
+
id: z.string().optional(),
|
|
2315
|
+
label: labelsSchema
|
|
2316
|
+
})).nullish()
|
|
2317
|
+
}))
|
|
2318
|
+
});
|
|
2319
|
+
const dataSchema$2 = z.object({ observations: z.array(z.object({
|
|
2320
|
+
dimensions: z.record(z.string(), z.string().nullable()),
|
|
2321
|
+
measures: z.record(z.string(), z.object({ value: z.unknown().optional() }).nullable()).optional()
|
|
2322
|
+
})) });
|
|
2323
|
+
const catalogSchema = z.array(z.object({
|
|
2324
|
+
identifier: z.string(),
|
|
2325
|
+
title: textsSchema,
|
|
2326
|
+
modified: z.string().nullish(),
|
|
2327
|
+
numObservations: z.number().nullish(),
|
|
2328
|
+
temporal: z.object({ endPeriod: z.string().optional() }).nullish(),
|
|
2329
|
+
theme: z.array(z.object({
|
|
2330
|
+
label: textsSchema,
|
|
2331
|
+
themeTaxonomy: z.string()
|
|
2332
|
+
})).nullish()
|
|
2333
|
+
}));
|
|
2334
|
+
function text(texts, lang) {
|
|
2335
|
+
const pick = (wanted) => texts?.find((item) => item.lang === wanted)?.content?.trim();
|
|
2336
|
+
return pick(lang) || pick("fr");
|
|
2337
|
+
}
|
|
2338
|
+
function label$1(labels, lang, fallback) {
|
|
2339
|
+
return (labels?.[lang] ?? labels?.fr ?? fallback).trim();
|
|
2340
|
+
}
|
|
2341
|
+
function byPeriod(a, b) {
|
|
2342
|
+
return a.localeCompare(b, "en", { numeric: true });
|
|
2343
|
+
}
|
|
2344
|
+
/** "2026", "2026-09" and "2026-Q3" have different shapes: one per frequency. */
|
|
2345
|
+
function periodShape(code) {
|
|
2346
|
+
return code.replace(/\d/g, "9");
|
|
2347
|
+
}
|
|
2348
|
+
/** `latest` picks the newest periods of each frequency, so annual and monthly series both get data. */
|
|
2349
|
+
function newestPerFrequency$1(codes, count) {
|
|
2350
|
+
const byShape = /* @__PURE__ */ new Map();
|
|
2351
|
+
for (const code of codes) {
|
|
2352
|
+
const shape = periodShape(code);
|
|
2353
|
+
byShape.set(shape, [...byShape.get(shape) ?? [], code]);
|
|
2354
|
+
}
|
|
2355
|
+
return [...byShape.values()].flatMap((list) => list.slice(-count));
|
|
2356
|
+
}
|
|
2357
|
+
function chosenCodes$2(variable, selection) {
|
|
2358
|
+
if (!selection || selection.selection.filter === "all") return [];
|
|
2359
|
+
const { filter, values } = selection.selection;
|
|
2360
|
+
if (filter === "item") return values;
|
|
2361
|
+
const count = Math.max(1, Number(values[0]) || 1);
|
|
2362
|
+
if (variable.isTime) return newestPerFrequency$1(variable.values, count);
|
|
2363
|
+
return variable.values.slice(-count);
|
|
2364
|
+
}
|
|
2365
|
+
function compareKeys$1(a, b) {
|
|
2366
|
+
for (const [index, value] of a.entries()) {
|
|
2367
|
+
const difference = value - (b[index] ?? 0);
|
|
2368
|
+
if (difference !== 0) return difference;
|
|
2369
|
+
}
|
|
2370
|
+
return 0;
|
|
2371
|
+
}
|
|
2372
|
+
function notFound$7(tableId) {
|
|
2373
|
+
return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
2374
|
+
}
|
|
2375
|
+
function checkLanguage$3(lang) {
|
|
2376
|
+
if (!LANGUAGES$2.has(lang)) throw new PxwebError(`Language "${lang}" is not supported.`, 400);
|
|
2377
|
+
}
|
|
2378
|
+
function toVariables(range, dimensions, lang) {
|
|
2379
|
+
const variables = range.range.filter((entry) => dimensions.has(entry.concept.code)).map((entry) => {
|
|
2380
|
+
const values = (entry.values ?? []).map((value) => ({
|
|
2381
|
+
code: entry.type === "geo" && value.id ? value.id.replace(GEO_VINTAGE, "") : value.code,
|
|
2382
|
+
label: label$1(value.label, lang, value.code)
|
|
2383
|
+
}));
|
|
2384
|
+
const isTime = entry.concept.code === TIME_CODE$4;
|
|
2385
|
+
if (isTime) values.sort((a, b) => byPeriod(a.code, b.code));
|
|
2386
|
+
return {
|
|
2387
|
+
code: entry.concept.code,
|
|
2388
|
+
label: label$1(entry.concept.label, lang, entry.concept.code),
|
|
2389
|
+
values: values.map((value) => value.code),
|
|
2390
|
+
valueLabels: values.map((value) => value.label),
|
|
2391
|
+
eliminable: false,
|
|
2392
|
+
isTime
|
|
2393
|
+
};
|
|
2394
|
+
});
|
|
2395
|
+
return [...variables.filter((variable) => !variable.isTime), ...variables.filter((variable) => variable.isTime)];
|
|
2396
|
+
}
|
|
2397
|
+
function measureValue(observation) {
|
|
2398
|
+
const value = Object.values(observation.measures ?? {})[0]?.value;
|
|
2399
|
+
return typeof value === "number" ? value : null;
|
|
2400
|
+
}
|
|
2401
|
+
function createInseeClient(options) {
|
|
2402
|
+
const root = options.baseUrl.replace(/\/+$/, "");
|
|
2403
|
+
const maxCells = options.maxCells ?? DEFAULT_MAX_CELLS$3;
|
|
2404
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
2405
|
+
const request = createRequester(options);
|
|
2406
|
+
const tableIndex = createTableIndexLoader(async (lang) => {
|
|
2407
|
+
if (!options.tableList) throw new PxwebError("The table list is not available now.", 503);
|
|
2408
|
+
return options.tableList(lang);
|
|
2409
|
+
}, {
|
|
2410
|
+
ttlSeconds: SEARCH_TTL_SECONDS,
|
|
2411
|
+
currentYear: () => now().getUTCFullYear()
|
|
2412
|
+
});
|
|
2413
|
+
function get(url, schema, map, ttlSeconds) {
|
|
2414
|
+
return request(url, {
|
|
2415
|
+
method: "GET",
|
|
2416
|
+
headers: { "accept-encoding": "gzip" }
|
|
2417
|
+
}, schema, map, ttlSeconds, url);
|
|
2418
|
+
}
|
|
2419
|
+
async function titleOf(lang, tableId, title) {
|
|
2420
|
+
const hit = await tableIndex(lang).then((index) => index.search(tableId)[0]).catch(() => void 0);
|
|
2421
|
+
if (hit?.tableId !== tableId || !hit.published) return title;
|
|
2422
|
+
return `${title} (${UPDATED_LABELS[lang] ?? UPDATED_LABELS.en}: ${hit.published})`;
|
|
2423
|
+
}
|
|
2424
|
+
const tables = /* @__PURE__ */ new Map();
|
|
2425
|
+
async function cachedTable(lang, tableId) {
|
|
2426
|
+
const key = `${lang}:${tableId}`;
|
|
2427
|
+
const cached = tables.get(key);
|
|
2428
|
+
if (cached && cached.expires > Date.now()) return cached.table;
|
|
2429
|
+
const table = await loadTable(lang, tableId);
|
|
2430
|
+
tables.delete(key);
|
|
2431
|
+
tables.set(key, {
|
|
2432
|
+
expires: Date.now() + METADATA_TTL_SECONDS * 1e3,
|
|
2433
|
+
table
|
|
2434
|
+
});
|
|
2435
|
+
const oldest = tables.keys().next().value;
|
|
2436
|
+
if (tables.size > MAX_CACHED_TABLES$2 && oldest !== void 0) tables.delete(oldest);
|
|
2437
|
+
return table;
|
|
2438
|
+
}
|
|
2439
|
+
async function loadTable(lang, tableId) {
|
|
2440
|
+
checkLanguage$3(lang);
|
|
2441
|
+
if (!TABLE_ID_PATTERN$5.test(tableId)) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it.`, 400);
|
|
2442
|
+
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) => {
|
|
2443
|
+
if (err instanceof PxwebError && (err.status === 400 || err.status === 404)) throw notFound$7(tableId);
|
|
2444
|
+
throw err;
|
|
2445
|
+
});
|
|
2446
|
+
if (!probe) throw new PxwebError(`Dataset "${tableId}" has no data. Use search_tables to find a current dataset.`, 404);
|
|
2447
|
+
const variables = toVariables(range, new Set(Object.keys(probe.dimensions)), lang);
|
|
2448
|
+
const geoCodes = new Set(range.range.filter((entry) => entry.type === "geo").map((entry) => entry.concept.code));
|
|
2449
|
+
return {
|
|
2450
|
+
metadata: {
|
|
2451
|
+
title: await titleOf(lang, tableId, label$1(range.label, lang, tableId)),
|
|
2452
|
+
variables
|
|
2453
|
+
},
|
|
2454
|
+
geoCodes
|
|
2455
|
+
};
|
|
2456
|
+
}
|
|
2457
|
+
async function listTables(lang) {
|
|
2458
|
+
checkLanguage$3(lang);
|
|
2459
|
+
return get(`${root}/catalog/all`, catalogSchema, (datasets) => datasets.map((dataset) => {
|
|
2460
|
+
const theme = dataset.theme?.find((item) => item.themeTaxonomy === "inseeTheme");
|
|
2461
|
+
const folder = theme && text(theme.label, lang);
|
|
2462
|
+
const updated = dataset.modified?.slice(0, 10);
|
|
2463
|
+
const lastPeriod = dataset.temporal?.endPeriod?.slice(0, 4);
|
|
2464
|
+
return {
|
|
2465
|
+
id: dataset.identifier,
|
|
2466
|
+
title: text(dataset.title, lang) ?? dataset.identifier,
|
|
2467
|
+
...folder && { path: [folder] },
|
|
2468
|
+
...updated && { updated },
|
|
2469
|
+
...lastPeriod && { lastPeriod },
|
|
2470
|
+
...!dataset.numObservations && { discontinued: true }
|
|
2471
|
+
};
|
|
2472
|
+
}), SEARCH_TTL_SECONDS);
|
|
2473
|
+
}
|
|
2474
|
+
return {
|
|
2475
|
+
listTables,
|
|
2476
|
+
async search(lang, query, searchOptions) {
|
|
2477
|
+
checkLanguage$3(lang);
|
|
2478
|
+
return (await tableIndex(lang)).search(query, searchOptions);
|
|
2479
|
+
},
|
|
2480
|
+
async getMetadata(lang, tableId) {
|
|
2481
|
+
return (await cachedTable(lang, tableId)).metadata;
|
|
2482
|
+
},
|
|
2483
|
+
async query(lang, tableId, selections) {
|
|
2484
|
+
const table = await cachedTable(lang, tableId);
|
|
2485
|
+
const { variables } = table.metadata;
|
|
2486
|
+
const byCode = new Map(selections.map((selection) => [selection.code, selection]));
|
|
2487
|
+
const params = [];
|
|
2488
|
+
let cells = 1;
|
|
2489
|
+
let periods;
|
|
2490
|
+
for (const variable of variables) {
|
|
2491
|
+
const codes = chosenCodes$2(variable, byCode.get(variable.code));
|
|
2492
|
+
cells *= codes.length || variable.values.length;
|
|
2493
|
+
if (variable.isTime && codes.length > 0) periods = new Set(codes);
|
|
2494
|
+
for (const code of codes) params.push(`${encodeURIComponent(variable.code)}=${encodeURIComponent(code)}`);
|
|
2495
|
+
}
|
|
2496
|
+
if (cells > maxCells) throw new PxwebError(`The query could return ${cells} cells, above the limit of ${maxCells}. Select fewer values.`, 400);
|
|
2497
|
+
const timeIndex = variables.findIndex((variable) => variable.isTime);
|
|
2498
|
+
const frequencies = new Set(variables[timeIndex]?.values.map(periodShape)).size || 1;
|
|
2499
|
+
const url = `${root}/data/${tableId}?${[...params, `maxResult=${Math.max(1, cells * frequencies)}`].join("&")}`;
|
|
2500
|
+
const positions = variables.map((variable) => new Map(variable.values.map((value, index) => [value, index])));
|
|
2501
|
+
const toRow = (observation) => {
|
|
2502
|
+
const codes = variables.map((variable) => {
|
|
2503
|
+
const raw = observation.dimensions[variable.code] ?? "";
|
|
2504
|
+
return table.geoCodes.has(variable.code) ? raw.replace(GEO_VINTAGE, "") : raw;
|
|
2505
|
+
});
|
|
2506
|
+
return {
|
|
2507
|
+
codes,
|
|
2508
|
+
key: codes.map((code, index) => positions[index]?.get(code) ?? Number.MAX_SAFE_INTEGER),
|
|
2509
|
+
value: measureValue(observation)
|
|
2510
|
+
};
|
|
2511
|
+
};
|
|
2512
|
+
return get(url, dataSchema$2, (data) => ({
|
|
2513
|
+
label: table.metadata.title,
|
|
2514
|
+
columns: [...variables.map((variable) => variable.label), VALUE_LABELS[lang] ?? "Value"],
|
|
2515
|
+
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])
|
|
2516
|
+
}), DATA_TTL_SECONDS).catch((err) => {
|
|
2517
|
+
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);
|
|
2518
|
+
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);
|
|
2519
|
+
throw err;
|
|
2520
|
+
});
|
|
2521
|
+
}
|
|
2522
|
+
};
|
|
2523
|
+
}
|
|
2524
|
+
// src/ons-client.ts
|
|
2525
|
+
const ONS_SITE = "https://www.ons.gov.uk";
|
|
2526
|
+
const TABLE_ID_PATTERN$4 = /^([A-Z0-9]{1,20})\/([A-Z0-9]{1,20})$/i;
|
|
2527
|
+
const FREQUENCY_CODE = "frequency";
|
|
2528
|
+
const FREQUENCY_LABEL = "Frequency";
|
|
2529
|
+
const TIME_CODE$3 = "period";
|
|
2530
|
+
const TIME_LABEL$1 = "Period";
|
|
2531
|
+
const SEARCH_LIMIT = 50;
|
|
2532
|
+
const DEFAULT_MAX_CELLS$2 = 5e3;
|
|
2533
|
+
const MAX_KNOWN_URIS = 1e3;
|
|
2534
|
+
const FREQUENCIES = [
|
|
2535
|
+
{
|
|
2536
|
+
key: "years",
|
|
2537
|
+
code: "A",
|
|
2538
|
+
label: "Annual"
|
|
2539
|
+
},
|
|
2540
|
+
{
|
|
2541
|
+
key: "quarters",
|
|
2542
|
+
code: "Q",
|
|
2543
|
+
label: "Quarterly"
|
|
2544
|
+
},
|
|
2545
|
+
{
|
|
2546
|
+
key: "months",
|
|
2547
|
+
code: "M",
|
|
2548
|
+
label: "Monthly"
|
|
2549
|
+
}
|
|
2550
|
+
];
|
|
2551
|
+
const MONTHS$1 = [
|
|
2552
|
+
"JAN",
|
|
2553
|
+
"FEB",
|
|
2554
|
+
"MAR",
|
|
2555
|
+
"APR",
|
|
2556
|
+
"MAY",
|
|
2557
|
+
"JUN",
|
|
2558
|
+
"JUL",
|
|
2559
|
+
"AUG",
|
|
2560
|
+
"SEP",
|
|
2561
|
+
"OCT",
|
|
2562
|
+
"NOV",
|
|
2563
|
+
"DEC"
|
|
2564
|
+
];
|
|
2565
|
+
const searchSchema$1 = z.object({ items: z.array(z.object({
|
|
2566
|
+
cdid: z.string().nullish(),
|
|
2567
|
+
dataset_id: z.string().nullish(),
|
|
2568
|
+
release_date: z.string().nullish(),
|
|
2569
|
+
title: z.string(),
|
|
2570
|
+
uri: z.string()
|
|
2571
|
+
})) });
|
|
2572
|
+
const pointsSchema = z.array(z.object({
|
|
2573
|
+
date: z.string(),
|
|
2574
|
+
value: z.string(),
|
|
2575
|
+
label: z.string().nullish()
|
|
2576
|
+
})).nullish();
|
|
2577
|
+
const seriesSchema = z.object({
|
|
2578
|
+
description: z.object({
|
|
2579
|
+
title: z.string(),
|
|
2580
|
+
unit: z.string().nullish(),
|
|
2581
|
+
preUnit: z.string().nullish(),
|
|
2582
|
+
datasetId: z.string(),
|
|
2583
|
+
releaseDate: z.string().nullish(),
|
|
2584
|
+
nextRelease: z.string().nullish()
|
|
2585
|
+
}),
|
|
2586
|
+
years: pointsSchema,
|
|
2587
|
+
quarters: pointsSchema,
|
|
2588
|
+
months: pointsSchema
|
|
2589
|
+
});
|
|
2590
|
+
const knownUris = /* @__PURE__ */ new Map();
|
|
2591
|
+
function rememberUri(tableId, uri) {
|
|
2592
|
+
knownUris.delete(tableId);
|
|
2593
|
+
knownUris.set(tableId, uri);
|
|
2594
|
+
const oldest = knownUris.keys().next().value;
|
|
2595
|
+
if (knownUris.size > MAX_KNOWN_URIS && oldest !== void 0) knownUris.delete(oldest);
|
|
2596
|
+
}
|
|
2597
|
+
/** The series page after this process resolved the id, otherwise an ONS search for its CDID. */
|
|
2598
|
+
function onsTableUrl(tableId) {
|
|
2599
|
+
const id = tableId.trim().toUpperCase();
|
|
2600
|
+
const uri = knownUris.get(id);
|
|
2601
|
+
if (uri) return `${ONS_SITE}${uri}`;
|
|
2602
|
+
const cdid = id.split("/").at(-1) ?? id;
|
|
2603
|
+
return `${ONS_SITE}/search?q=${encodeURIComponent(cdid)}&filter=time_series`;
|
|
2604
|
+
}
|
|
2605
|
+
function hitId(item) {
|
|
2606
|
+
if (!item.cdid || !item.dataset_id || !item.uri.startsWith("/")) return;
|
|
2607
|
+
const id = `${item.dataset_id}/${item.cdid}`.toUpperCase();
|
|
2608
|
+
return TABLE_ID_PATTERN$4.test(id) ? id : void 0;
|
|
2609
|
+
}
|
|
2610
|
+
/** ONS writes UK midnight as UTC ("2026-09-29T23:00Z" is 30 September); noon keeps the UK day. */
|
|
2611
|
+
function ukDate(timestamp) {
|
|
2612
|
+
const time = Date.parse(timestamp ?? "");
|
|
2613
|
+
if (Number.isNaN(time)) return void 0;
|
|
2614
|
+
return new Date(time + 432e5).toISOString().slice(0, 10);
|
|
2615
|
+
}
|
|
2616
|
+
/** "2025" → "2025", "2026 Q3" → "2026-Q3", "2026 OCT" → "2026-10". */
|
|
2617
|
+
function periodCode$1(date) {
|
|
2618
|
+
const [year, part] = date.trim().split(/\s+/);
|
|
2619
|
+
if (!part) return date.trim();
|
|
2620
|
+
const month = MONTHS$1.indexOf(part.toUpperCase());
|
|
2621
|
+
if (month >= 0) return `${year}-${String(month + 1).padStart(2, "0")}`;
|
|
2622
|
+
return `${year}-${part}`;
|
|
2623
|
+
}
|
|
2624
|
+
function numeric(value) {
|
|
2625
|
+
const number = Number(value);
|
|
2626
|
+
return value.trim() === "" || !Number.isFinite(number) ? null : number;
|
|
2627
|
+
}
|
|
2628
|
+
function seriesTitle(tableId, series) {
|
|
2629
|
+
const { description } = series;
|
|
2630
|
+
const unit = `${description.preUnit ?? ""}${description.unit ?? ""}`.trim();
|
|
2631
|
+
const released = ukDate(description.releaseDate);
|
|
2632
|
+
const notes = [
|
|
2633
|
+
`dataset ${description.datasetId.toUpperCase()}`,
|
|
2634
|
+
unit && `unit: ${unit}`,
|
|
2635
|
+
released && `last update: ${released}`,
|
|
2636
|
+
description.nextRelease && `next release: ${description.nextRelease}`
|
|
2637
|
+
].filter(Boolean);
|
|
2638
|
+
return `${description.title.trim() || tableId} (${notes.join("; ")})`;
|
|
2639
|
+
}
|
|
2640
|
+
function toTable$2(tableId, series) {
|
|
2641
|
+
const points = /* @__PURE__ */ new Map();
|
|
2642
|
+
for (const frequency of FREQUENCIES) {
|
|
2643
|
+
const list = (series[frequency.key] ?? []).map((point) => ({
|
|
2644
|
+
code: periodCode$1(point.date),
|
|
2645
|
+
label: point.label?.trim() || point.date.trim(),
|
|
2646
|
+
value: numeric(point.value)
|
|
2647
|
+
}));
|
|
2648
|
+
if (list.length > 0) points.set(frequency.code, list);
|
|
2649
|
+
}
|
|
2650
|
+
const present = FREQUENCIES.filter((frequency) => points.has(frequency.code));
|
|
2651
|
+
const periods = [...points.values()].flat();
|
|
2652
|
+
return {
|
|
2653
|
+
metadata: {
|
|
2654
|
+
title: seriesTitle(tableId, series),
|
|
2655
|
+
variables: [{
|
|
2656
|
+
code: FREQUENCY_CODE,
|
|
2657
|
+
label: FREQUENCY_LABEL,
|
|
2658
|
+
values: present.map((frequency) => frequency.code),
|
|
2659
|
+
valueLabels: present.map((frequency) => frequency.label),
|
|
2660
|
+
eliminable: false,
|
|
2661
|
+
isTime: false
|
|
2662
|
+
}, {
|
|
2663
|
+
code: TIME_CODE$3,
|
|
2664
|
+
label: TIME_LABEL$1,
|
|
2665
|
+
values: periods.map((point) => point.code),
|
|
2666
|
+
valueLabels: periods.map((point) => point.label),
|
|
2667
|
+
eliminable: false,
|
|
2668
|
+
isTime: true
|
|
2669
|
+
}]
|
|
2670
|
+
},
|
|
2671
|
+
points
|
|
2672
|
+
};
|
|
2673
|
+
}
|
|
2674
|
+
function chosenFrequencies(variable, selection) {
|
|
2675
|
+
const codes = variable?.values ?? [];
|
|
2676
|
+
if (!selection || selection.selection.filter === "all") return codes;
|
|
2677
|
+
const { filter, values } = selection.selection;
|
|
2678
|
+
if (filter === "item") return values;
|
|
2679
|
+
return codes.slice(-Math.max(1, Number(values[0]) || 1));
|
|
2680
|
+
}
|
|
2681
|
+
function chosenPoints(points, selection) {
|
|
2682
|
+
if (!selection || selection.selection.filter === "all") return points;
|
|
2683
|
+
const { filter, values } = selection.selection;
|
|
2684
|
+
if (filter === "top") return points.slice(-Math.max(1, Number(values[0]) || 1));
|
|
2685
|
+
const wanted = new Set(values);
|
|
2686
|
+
return points.filter((point) => wanted.has(point.code));
|
|
2687
|
+
}
|
|
2688
|
+
function notFound$6(tableId) {
|
|
2689
|
+
return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
2690
|
+
}
|
|
2691
|
+
function checkLanguage$2(lang) {
|
|
2692
|
+
if (lang !== "en") throw new PxwebError(`Language "${lang}" is not supported.`, 400);
|
|
2693
|
+
}
|
|
2694
|
+
/**
|
|
2695
|
+
* ONS time series client. One table is one time series, with the id
|
|
2696
|
+
* `<DATASET>/<CDID>` in upper case, for example "MM23/D7G7" (CPI annual rate).
|
|
2697
|
+
* Lower case input is accepted.
|
|
2698
|
+
*
|
|
2699
|
+
* - Search uses the live search API (`/search?content_type=timeseries`); there is
|
|
2700
|
+
* no crawled index. Hits keep the API order, adjusted for release recency.
|
|
2701
|
+
* - An id resolves to its page uri through a search for the CDID; the hit must
|
|
2702
|
+
* match both the CDID and the dataset. The requester cache keeps the answer.
|
|
2703
|
+
* - Metadata and data come from one request, `https://www.ons.gov.uk/<uri>/data`.
|
|
2704
|
+
* The variables are "frequency" (A, Q, M; only those that the series has) and
|
|
2705
|
+
* "period" (codes "2025", "2026-Q3", "2026-10"; labels as ONS gives them, for
|
|
2706
|
+
* example "2026 JUL-SEP" for a rolling quarter). The title gives the dataset,
|
|
2707
|
+
* the unit, the release date and the next release.
|
|
2708
|
+
* - `latest` on "period" gives the newest N periods of each selected frequency.
|
|
2709
|
+
* - The beta dataset API (`/v1/datasets`) is not used: it is out of date.
|
|
2710
|
+
*/
|
|
2711
|
+
function createOnsClient(options) {
|
|
2712
|
+
const root = options.baseUrl.replace(/\/+$/, "");
|
|
2713
|
+
const maxCells = options.maxCells ?? DEFAULT_MAX_CELLS$2;
|
|
2714
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
2715
|
+
const request = createRequester(options);
|
|
2716
|
+
async function get(url, schema, ttlSeconds, tableId) {
|
|
2717
|
+
try {
|
|
2718
|
+
return await request(url, { method: "GET" }, schema, (data) => data, ttlSeconds, url);
|
|
2719
|
+
} catch (err) {
|
|
2720
|
+
if (!(err instanceof PxwebError)) throw err;
|
|
2721
|
+
if (tableId && err.status === 404) throw notFound$6(tableId);
|
|
2722
|
+
if (err.status >= 400 && err.status < 500) throw new PxwebError(`ONS refused the request (HTTP ${err.status}). Change the query and try again.`, 400);
|
|
2723
|
+
throw new PxwebError(`ONS could not answer (HTTP ${err.status}). Try again later.`, 502);
|
|
2724
|
+
}
|
|
2725
|
+
}
|
|
2726
|
+
function searchUrl(query) {
|
|
2727
|
+
return `${root}/search?q=${encodeURIComponent(query)}&content_type=timeseries&limit=${SEARCH_LIMIT}`;
|
|
2728
|
+
}
|
|
2729
|
+
async function loadTable(lang, tableId) {
|
|
2730
|
+
checkLanguage$2(lang);
|
|
2731
|
+
const id = tableId.trim().toUpperCase();
|
|
2732
|
+
const match = TABLE_ID_PATTERN$4.exec(id);
|
|
2733
|
+
if (!match?.[2]) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it, for example "MM23/D7G7".`, 400);
|
|
2734
|
+
const { items } = await get(searchUrl(match[2]), searchSchema$1, METADATA_TTL_SECONDS);
|
|
2735
|
+
const uri = items.find((item) => hitId(item) === id)?.uri;
|
|
2736
|
+
if (!uri) throw notFound$6(tableId);
|
|
2737
|
+
rememberUri(id, uri);
|
|
2738
|
+
return toTable$2(id, await get(`${ONS_SITE}${uri}/data`, seriesSchema, DATA_TTL_SECONDS, tableId));
|
|
2739
|
+
}
|
|
2740
|
+
return {
|
|
2741
|
+
async search(lang, query) {
|
|
2742
|
+
checkLanguage$2(lang);
|
|
2743
|
+
const { items } = await get(searchUrl(query), searchSchema$1, SEARCH_TTL_SECONDS);
|
|
2744
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2745
|
+
const hits = items.flatMap((item) => {
|
|
2746
|
+
const tableId = hitId(item);
|
|
2747
|
+
if (!tableId || seen.has(tableId)) return [];
|
|
2748
|
+
seen.add(tableId);
|
|
2749
|
+
const dataset = tableId.split("/")[0];
|
|
2750
|
+
return [{
|
|
2751
|
+
tableId,
|
|
2752
|
+
title: `${item.title.trim()} (dataset ${dataset})`,
|
|
2753
|
+
published: ukDate(item.release_date)
|
|
2754
|
+
}];
|
|
2755
|
+
});
|
|
2756
|
+
return rankSearchHits(hits, now().getUTCFullYear());
|
|
2757
|
+
},
|
|
2758
|
+
async getMetadata(lang, tableId) {
|
|
2759
|
+
return (await loadTable(lang, tableId)).metadata;
|
|
2760
|
+
},
|
|
2761
|
+
async query(lang, tableId, selections) {
|
|
2762
|
+
const table = await loadTable(lang, tableId);
|
|
2763
|
+
const [frequency] = table.metadata.variables;
|
|
2764
|
+
const byCode = new Map(selections.map((selection) => [selection.code, selection]));
|
|
2765
|
+
const wanted = new Set(chosenFrequencies(frequency, byCode.get(FREQUENCY_CODE)));
|
|
2766
|
+
const rows = FREQUENCIES.filter((item) => wanted.has(item.code)).flatMap((item) => chosenPoints(table.points.get(item.code) ?? [], byCode.get(TIME_CODE$3)).map((point) => [
|
|
2767
|
+
item.label,
|
|
2768
|
+
point.label,
|
|
2769
|
+
point.value
|
|
2770
|
+
]));
|
|
2771
|
+
if (rows.length > maxCells) throw new PxwebError(`The query would return ${rows.length} cells, above the limit of ${maxCells}. Select fewer values.`, 400);
|
|
2772
|
+
return {
|
|
2773
|
+
label: table.metadata.title,
|
|
2774
|
+
columns: [
|
|
2775
|
+
FREQUENCY_LABEL,
|
|
2776
|
+
TIME_LABEL$1,
|
|
2777
|
+
"Value"
|
|
2778
|
+
],
|
|
2779
|
+
rows
|
|
2780
|
+
};
|
|
2781
|
+
}
|
|
2782
|
+
};
|
|
2783
|
+
}
|
|
2784
|
+
// src/sdmx-ml.ts
|
|
2785
|
+
const ENTITIES = {
|
|
2786
|
+
amp: "&",
|
|
2787
|
+
lt: "<",
|
|
2788
|
+
gt: ">",
|
|
2789
|
+
quot: "\"",
|
|
2790
|
+
apos: "'"
|
|
2791
|
+
};
|
|
2792
|
+
const MAX_CODE_POINT = 1114111;
|
|
2793
|
+
function decodeOnce(text) {
|
|
2794
|
+
return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (entity, name) => {
|
|
2795
|
+
if (!name.startsWith("#")) return Object.hasOwn(ENTITIES, name) ? ENTITIES[name] ?? entity : entity;
|
|
2796
|
+
const point = name[1]?.toLowerCase() === "x" ? Number.parseInt(name.slice(2), 16) : Number(name.slice(1));
|
|
2797
|
+
return point <= MAX_CODE_POINT ? String.fromCodePoint(point) : entity;
|
|
2798
|
+
});
|
|
2799
|
+
}
|
|
2800
|
+
/** Some OSP labels are escaped twice ("&apos;"), so a second pass is needed. */
|
|
2801
|
+
function decodeXml(text) {
|
|
2802
|
+
return decodeOnce(decodeOnce(text)).replace(/\s+/g, " ").trim();
|
|
2803
|
+
}
|
|
2804
|
+
function attribute(tag, name) {
|
|
2805
|
+
const value = new RegExp(`\\b${name}="([^"]*)"`).exec(tag)?.[1];
|
|
2806
|
+
return value === void 0 ? void 0 : decodeOnce(value);
|
|
2807
|
+
}
|
|
2808
|
+
const localizedPatterns = /* @__PURE__ */ new Map();
|
|
2809
|
+
function localizedPattern(element) {
|
|
2810
|
+
let pattern = localizedPatterns.get(element);
|
|
2811
|
+
if (!pattern) {
|
|
2812
|
+
pattern = new RegExp(`<${element} xml:lang="([a-z-]+)">([^<]*)</${element}>`, "g");
|
|
2813
|
+
localizedPatterns.set(element, pattern);
|
|
2814
|
+
}
|
|
2815
|
+
return pattern;
|
|
2816
|
+
}
|
|
2817
|
+
function localized(block, element) {
|
|
2818
|
+
const texts = /* @__PURE__ */ new Map();
|
|
2819
|
+
const pattern = localizedPattern(element);
|
|
2820
|
+
for (const [, lang, text] of block.matchAll(pattern)) if (lang && text !== void 0) texts.set(lang, decodeXml(text));
|
|
2821
|
+
return texts;
|
|
2822
|
+
}
|
|
2823
|
+
/** The text in `lang`, else in English, else in any language that has one. */
|
|
2824
|
+
function textIn(texts, lang) {
|
|
2825
|
+
if (!texts) return void 0;
|
|
2826
|
+
return [
|
|
2827
|
+
texts.get(lang),
|
|
2828
|
+
texts.get("en"),
|
|
2829
|
+
...texts.values()
|
|
2830
|
+
].find((text) => text !== void 0 && text !== "");
|
|
2831
|
+
}
|
|
2832
|
+
function expectRoot(xml, root) {
|
|
2833
|
+
if (!xml.includes(`<${root}`) || !xml.trimEnd().endsWith(`</${root}>`)) throw new PxwebError("Statistics Lithuania returned an incomplete or unexpected response.", 502);
|
|
2834
|
+
}
|
|
2835
|
+
/** The error that OSP puts in the footer of an HTTP 200 answer, if any. */
|
|
2836
|
+
function footerMessage(xml) {
|
|
2837
|
+
const match = /<footer:Message\b([^>]*)>([\s\S]*?)<\/footer:Message>/.exec(xml);
|
|
2838
|
+
if (!match) return void 0;
|
|
2839
|
+
return {
|
|
2840
|
+
code: attribute(match[1] ?? "", "code") ?? "",
|
|
2841
|
+
texts: localized(match[2] ?? "", "com:Text")
|
|
2842
|
+
};
|
|
2843
|
+
}
|
|
2844
|
+
function parseDataflows(xml) {
|
|
2845
|
+
expectRoot(xml, "mes:Structure");
|
|
2846
|
+
return [...xml.matchAll(/<str:Dataflow\b([^>]*)>([\s\S]*?)<\/str:Dataflow>/g)].flatMap(([, tag = "", body = ""]) => {
|
|
2847
|
+
const id = attribute(tag, "id");
|
|
2848
|
+
if (!id) return [];
|
|
2849
|
+
const reference = /<str:Structure>\s*<Ref\b([^>]*)>/.exec(body)?.[1];
|
|
2850
|
+
return [{
|
|
2851
|
+
id,
|
|
2852
|
+
names: localized(body, "com:Name"),
|
|
2853
|
+
descriptions: localized(body, "com:Description"),
|
|
2854
|
+
structureId: reference ? attribute(reference, "id") : void 0
|
|
2855
|
+
}];
|
|
2856
|
+
});
|
|
2857
|
+
}
|
|
2858
|
+
function parseCodes(body) {
|
|
2859
|
+
return [...body.matchAll(/<str:Code\b([^>]*?)(?:\/>|>([\s\S]*?)<\/str:Code>)/g)].flatMap(([, tag = "", content = ""]) => {
|
|
2860
|
+
const id = attribute(tag, "id");
|
|
2861
|
+
return id ? [{
|
|
2862
|
+
id,
|
|
2863
|
+
names: localized(content, "com:Name")
|
|
2864
|
+
}] : [];
|
|
2865
|
+
});
|
|
2866
|
+
}
|
|
2867
|
+
function parseStructure(xml) {
|
|
2868
|
+
expectRoot(xml, "mes:Structure");
|
|
2869
|
+
const codelists = /* @__PURE__ */ new Map();
|
|
2870
|
+
for (const [, tag = "", body = ""] of xml.matchAll(/<str:Codelist\b([^>]*)>([\s\S]*?)<\/str:Codelist>/g)) {
|
|
2871
|
+
const id = attribute(tag, "id");
|
|
2872
|
+
if (id) codelists.set(id, parseCodes(body));
|
|
2873
|
+
}
|
|
2874
|
+
const concepts = /* @__PURE__ */ new Map();
|
|
2875
|
+
for (const [, tag = "", body = ""] of xml.matchAll(/<str:Concept\b([^>]*)>([\s\S]*?)<\/str:Concept>/g)) {
|
|
2876
|
+
const id = attribute(tag, "id");
|
|
2877
|
+
if (id) concepts.set(id, localized(body, "com:Name"));
|
|
2878
|
+
}
|
|
2879
|
+
const dimensions = [...xml.matchAll(/<str:(Dimension|MeasureDimension|TimeDimension)\b([^>]*)>([\s\S]*?)<\/str:\1>/g)].flatMap(([, kind, tag = "", body = ""]) => {
|
|
2880
|
+
const id = attribute(tag, "id");
|
|
2881
|
+
if (!id) return [];
|
|
2882
|
+
const reference = /<str:Enumeration>\s*<Ref\b([^>]*)>/.exec(body)?.[1];
|
|
2883
|
+
return [{
|
|
2884
|
+
id,
|
|
2885
|
+
position: Number(attribute(tag, "position") ?? 0),
|
|
2886
|
+
isTime: kind === "TimeDimension",
|
|
2887
|
+
codelistId: reference ? attribute(reference, "id") : void 0
|
|
2888
|
+
}];
|
|
2889
|
+
}).toSorted((a, b) => a.position - b.position);
|
|
2890
|
+
if (dimensions.length === 0) throw new PxwebError("Statistics Lithuania returned a data structure without dimensions.", 502);
|
|
2891
|
+
return {
|
|
2892
|
+
dimensions,
|
|
2893
|
+
concepts,
|
|
2894
|
+
codelists
|
|
2895
|
+
};
|
|
2896
|
+
}
|
|
2897
|
+
function values(block) {
|
|
2898
|
+
const found = /* @__PURE__ */ new Map();
|
|
2899
|
+
for (const [, tag = ""] of block.matchAll(/<g:Value\b([^>]*?)\/?>/g)) {
|
|
2900
|
+
const id = attribute(tag, "id");
|
|
2901
|
+
const value = attribute(tag, "value");
|
|
2902
|
+
if (id && value !== void 0) found.set(id, value);
|
|
2903
|
+
}
|
|
2904
|
+
return found;
|
|
2905
|
+
}
|
|
2906
|
+
const OBS_OPEN = "<g:Obs>";
|
|
2907
|
+
const OBS_CLOSE = "</g:Obs>";
|
|
2908
|
+
function parseObservation(body) {
|
|
2909
|
+
const key = /<g:ObsKey>([\s\S]*?)<\/g:ObsKey>/.exec(body)?.[1] ?? "";
|
|
2910
|
+
const valueTag = /<g:ObsValue\b([^>]*)>/.exec(body)?.[1];
|
|
2911
|
+
const attributes = /<g:Attributes>([\s\S]*?)<\/g:Attributes>/.exec(body)?.[1] ?? "";
|
|
2912
|
+
return {
|
|
2913
|
+
key: values(key),
|
|
2914
|
+
value: valueTag ? attribute(valueTag, "value") : void 0,
|
|
2915
|
+
attributes: values(attributes)
|
|
2916
|
+
};
|
|
2917
|
+
}
|
|
2918
|
+
/**
|
|
2919
|
+
* Reads SDMX-ML 2.1 generic data (all dimensions at the observation level) in
|
|
2920
|
+
* chunks, so a large message is never held in memory as a whole.
|
|
2921
|
+
*/
|
|
2922
|
+
function createGenericDataReader(onObservation) {
|
|
2923
|
+
let head;
|
|
2924
|
+
let buffer = "";
|
|
2925
|
+
return {
|
|
2926
|
+
push(text) {
|
|
2927
|
+
buffer += text;
|
|
2928
|
+
let offset = 0;
|
|
2929
|
+
for (;;) {
|
|
2930
|
+
const start = buffer.indexOf(OBS_OPEN, offset);
|
|
2931
|
+
const end = start < 0 ? -1 : buffer.indexOf(OBS_CLOSE, start);
|
|
2932
|
+
if (end < 0) break;
|
|
2933
|
+
head ??= buffer.slice(0, start);
|
|
2934
|
+
onObservation(parseObservation(buffer.slice(start + 7, end)));
|
|
2935
|
+
offset = end + 8;
|
|
2936
|
+
}
|
|
2937
|
+
buffer = buffer.slice(offset);
|
|
2938
|
+
},
|
|
2939
|
+
finish() {
|
|
2940
|
+
const header = head ?? buffer;
|
|
2941
|
+
expectRoot((head ?? "") + buffer, "mes:GenericData");
|
|
2942
|
+
const dataSet = header.slice(Math.max(0, header.indexOf("<mes:DataSet")));
|
|
2943
|
+
return {
|
|
2944
|
+
prepared: /<mes:Prepared>([^<]*)<\/mes:Prepared>/.exec(header)?.[1],
|
|
2945
|
+
attributes: values(/<g:Attributes>([\s\S]*?)<\/g:Attributes>/.exec(dataSet)?.[1] ?? ""),
|
|
2946
|
+
footer: footerMessage(buffer)
|
|
2947
|
+
};
|
|
2948
|
+
}
|
|
2949
|
+
};
|
|
2950
|
+
}
|
|
2951
|
+
// src/osp-client.ts
|
|
2952
|
+
const AGENCY = "LSD";
|
|
2953
|
+
const LANGUAGES$1 = ["lt", "en"];
|
|
2954
|
+
const TABLE_ID_PATTERN$3 = /^(?!\.{1,2}$)[\w.-](?:[\w. -]{0,62}[\w.-])?$/;
|
|
2955
|
+
const DEFAULT_MAX_CELLS$1 = 5e3;
|
|
2956
|
+
/**
|
|
2957
|
+
* OSP cannot filter by dimension, so every code of every dimension is downloaded:
|
|
2958
|
+
* about 400 bytes and 0.3 ms per observation, streamed and filtered here.
|
|
2959
|
+
*/
|
|
2960
|
+
const DEFAULT_MAX_DOWNLOAD_OBSERVATIONS = 6e4;
|
|
2961
|
+
const MAX_DATA_BYTES = 67108864;
|
|
2962
|
+
const MAX_CACHED_TABLES$1 = 8;
|
|
2963
|
+
/** Separate period runs are fetched one request each, up to this many. */
|
|
2964
|
+
const MAX_PERIOD_RANGES = 4;
|
|
2965
|
+
const NO_DATA_MESSAGE = /did not return the data/i;
|
|
2966
|
+
const MAX_LISTED_PERIODS = 5e3;
|
|
2967
|
+
const DEFAULT_TIMEOUT_MS = 3e4;
|
|
2968
|
+
const XML_ACCEPT = "application/xml";
|
|
2969
|
+
const STATUS_CONCEPT = "OBS_STATUS";
|
|
2970
|
+
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;
|
|
2971
|
+
const TEXTS$1 = {
|
|
2972
|
+
lt: {
|
|
2973
|
+
value: "Reikšmė",
|
|
2974
|
+
status: "Sutartinis simbolis",
|
|
2975
|
+
updated: "atnaujinta",
|
|
2976
|
+
retrieved: "gauta",
|
|
2977
|
+
noData: "Pasirinktais laikotarpiais duomenų nėra."
|
|
2978
|
+
},
|
|
2979
|
+
en: {
|
|
2980
|
+
value: "Value",
|
|
2981
|
+
status: "Status",
|
|
2982
|
+
updated: "last update",
|
|
2983
|
+
retrieved: "retrieved",
|
|
2984
|
+
noData: "No data for the selected periods."
|
|
2985
|
+
}
|
|
2986
|
+
};
|
|
2987
|
+
const flatTableSchema = z.object({
|
|
2988
|
+
label: z.string(),
|
|
2989
|
+
columns: z.array(z.string()),
|
|
2990
|
+
rows: z.array(z.array(z.union([
|
|
2991
|
+
z.string(),
|
|
2992
|
+
z.number(),
|
|
2993
|
+
z.null()
|
|
2994
|
+
])))
|
|
2995
|
+
});
|
|
2996
|
+
function isLanguage(lang) {
|
|
2997
|
+
return LANGUAGES$1.some((language) => language === lang);
|
|
2998
|
+
}
|
|
2999
|
+
function checkLanguage$1(lang) {
|
|
3000
|
+
if (!isLanguage(lang)) throw new PxwebError(`Language "${lang}" is not supported.`, 400);
|
|
3001
|
+
return lang;
|
|
3002
|
+
}
|
|
3003
|
+
function notFound$5(tableId) {
|
|
3004
|
+
return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
3005
|
+
}
|
|
3006
|
+
function upstreamError(err) {
|
|
3007
|
+
if (err instanceof PxwebError && ![
|
|
3008
|
+
400,
|
|
3009
|
+
404,
|
|
3010
|
+
502
|
|
3011
|
+
].includes(err.status)) return new PxwebError(`Statistics Lithuania could not answer (HTTP ${err.status}). Try again later.`, 502);
|
|
3012
|
+
return err;
|
|
3013
|
+
}
|
|
3014
|
+
function parseCached(text) {
|
|
3015
|
+
if (text === void 0) return void 0;
|
|
3016
|
+
try {
|
|
3017
|
+
return JSON.parse(text);
|
|
3018
|
+
} catch {
|
|
3019
|
+
return;
|
|
3020
|
+
}
|
|
3021
|
+
}
|
|
3022
|
+
/** "Sex | Age (1996 - 2026) (Was renewed: 2026-05-07)" or "… (Not be renewed)". */
|
|
3023
|
+
function parseDescription(text) {
|
|
3024
|
+
let rest = text;
|
|
3025
|
+
let updated;
|
|
3026
|
+
let discontinued = false;
|
|
3027
|
+
const status = /\(([^()]*)\)$/.exec(rest);
|
|
3028
|
+
if (status && !/^\S+ - \S+$/.test(status[1] ?? "")) {
|
|
3029
|
+
updated = /\d{4}-\d{2}-\d{2}/.exec(status[1] ?? "")?.[0];
|
|
3030
|
+
discontinued = updated === void 0;
|
|
3031
|
+
rest = rest.slice(0, status.index).trim();
|
|
3032
|
+
}
|
|
3033
|
+
const range = /\((\S+) - (\S+)\)$/.exec(rest);
|
|
3034
|
+
if (range) rest = rest.slice(0, range.index).trim();
|
|
3035
|
+
return {
|
|
3036
|
+
dimensions: rest,
|
|
3037
|
+
first: range?.[1],
|
|
3038
|
+
last: range?.[2],
|
|
3039
|
+
updated,
|
|
3040
|
+
discontinued
|
|
3041
|
+
};
|
|
3042
|
+
}
|
|
3043
|
+
function flowTitle(name, description) {
|
|
3044
|
+
const title = description.dimensions ? `${name}: ${description.dimensions}` : name;
|
|
3045
|
+
return description.first && description.last ? `${title} (${description.first} - ${description.last})` : title;
|
|
3046
|
+
}
|
|
3047
|
+
function toTableDoc(flow, lang) {
|
|
3048
|
+
const description = parseDescription(textIn(flow.descriptions, lang) ?? "");
|
|
3049
|
+
return {
|
|
3050
|
+
id: flow.id,
|
|
3051
|
+
title: flowTitle(textIn(flow.names, lang) ?? flow.id, description),
|
|
3052
|
+
...description.updated && { updated: description.updated },
|
|
3053
|
+
...description.last && { lastPeriod: description.last },
|
|
3054
|
+
...description.discontinued && { discontinued: true }
|
|
3055
|
+
};
|
|
3056
|
+
}
|
|
3057
|
+
const PERIOD_FORMATS = [
|
|
3058
|
+
{
|
|
3059
|
+
pattern: /^(\d{4})$/,
|
|
3060
|
+
perYear: 1,
|
|
3061
|
+
code: (year) => String(year),
|
|
3062
|
+
api: (match) => match[1] ?? ""
|
|
3063
|
+
},
|
|
3064
|
+
{
|
|
3065
|
+
pattern: /^(\d{4})P([12])$/,
|
|
3066
|
+
perYear: 2,
|
|
3067
|
+
code: (year, index) => `${year}P${index + 1}`,
|
|
3068
|
+
api: (match) => `${match[1]}-S${match[2]}`
|
|
3069
|
+
},
|
|
3070
|
+
{
|
|
3071
|
+
pattern: /^(\d{4})K([1-4])$/,
|
|
3072
|
+
perYear: 4,
|
|
3073
|
+
code: (year, index) => `${year}K${index + 1}`,
|
|
3074
|
+
api: (match) => `${match[1]}-Q${match[2]}`
|
|
3075
|
+
},
|
|
3076
|
+
{
|
|
3077
|
+
pattern: /^(\d{4})M(0[1-9]|1[0-2])$/,
|
|
3078
|
+
perYear: 12,
|
|
3079
|
+
code: (year, index) => `${year}M${String(index + 1).padStart(2, "0")}`,
|
|
3080
|
+
api: (match) => `${match[1]}-${match[2]}`
|
|
3081
|
+
},
|
|
3082
|
+
{
|
|
3083
|
+
pattern: /^(\d{4})-(\d{4})$/,
|
|
3084
|
+
perYear: 1,
|
|
3085
|
+
code: (year) => `${year}-${year + 1}`,
|
|
3086
|
+
api: (match, edge) => (edge === "start" ? match[1] : match[2]) ?? ""
|
|
3087
|
+
}
|
|
3088
|
+
];
|
|
3089
|
+
function matchPeriod(code) {
|
|
3090
|
+
for (const format of PERIOD_FORMATS) {
|
|
3091
|
+
const match = format.pattern.exec(code);
|
|
3092
|
+
if (match) return {
|
|
3093
|
+
format,
|
|
3094
|
+
match
|
|
3095
|
+
};
|
|
3096
|
+
}
|
|
3097
|
+
}
|
|
3098
|
+
/** Position of a period on its format's scale; undefined for multi-year spans. */
|
|
3099
|
+
function periodStep(format, match) {
|
|
3100
|
+
const year = Number(match[1]);
|
|
3101
|
+
if (format.perYear === 1) return match[2] === void 0 || Number(match[2]) === year + 1 ? year : void 0;
|
|
3102
|
+
return year * format.perYear + Number(match[2]) - 1;
|
|
3103
|
+
}
|
|
3104
|
+
/**
|
|
3105
|
+
* The API lists no periods, so they come from the range in the dataflow description.
|
|
3106
|
+
* Multi-year spans ("2008-2010 - 2022-2024") and mixed ranges have gaps that cannot
|
|
3107
|
+
* be known, so only their first and last periods are listed.
|
|
3108
|
+
*/
|
|
3109
|
+
function periodList(first, last) {
|
|
3110
|
+
const start = matchPeriod(first);
|
|
3111
|
+
const end = matchPeriod(last);
|
|
3112
|
+
const from = start && periodStep(start.format, start.match);
|
|
3113
|
+
const to = end && periodStep(end.format, end.match);
|
|
3114
|
+
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])];
|
|
3115
|
+
const { format } = start;
|
|
3116
|
+
const codes = [];
|
|
3117
|
+
for (let step = from; step <= to; step++) codes.push(format.code(Math.floor(step / format.perYear), step % format.perYear));
|
|
3118
|
+
return codes;
|
|
3119
|
+
}
|
|
3120
|
+
function apiPeriod(code, edge) {
|
|
3121
|
+
const found = matchPeriod(code);
|
|
3122
|
+
if (found) return found.format.api(found.match, edge);
|
|
3123
|
+
const years = code.match(/\d{4}/g) ?? [];
|
|
3124
|
+
return (edge === "start" ? years[0] : years.at(-1)) ?? code;
|
|
3125
|
+
}
|
|
3126
|
+
function compareCodes(a, b) {
|
|
3127
|
+
const numericA = /^\d+$/.test(a);
|
|
3128
|
+
const numericB = /^\d+$/.test(b);
|
|
3129
|
+
if (numericA && numericB) return Number(a) - Number(b) || a.length - b.length;
|
|
3130
|
+
if (numericA !== numericB) return numericA ? -1 : 1;
|
|
3131
|
+
if (a === b) return 0;
|
|
3132
|
+
return a < b ? -1 : 1;
|
|
3133
|
+
}
|
|
3134
|
+
function totalCode(codes) {
|
|
3135
|
+
const totals = codes.filter((code) => [...code.names.values()].some((name) => TOTAL_LABEL.test(name)));
|
|
3136
|
+
return totals.length === 1 ? totals[0]?.id : void 0;
|
|
3137
|
+
}
|
|
3138
|
+
function buildTable(flow, structure, lang) {
|
|
3139
|
+
const description = parseDescription(textIn(flow.descriptions, lang) ?? "");
|
|
3140
|
+
const totals = /* @__PURE__ */ new Map();
|
|
3141
|
+
const dimensions = [];
|
|
3142
|
+
let time;
|
|
3143
|
+
for (const dimension of structure.dimensions) {
|
|
3144
|
+
const label = textIn(structure.concepts.get(dimension.id), lang) ?? dimension.id;
|
|
3145
|
+
if (dimension.isTime) {
|
|
3146
|
+
const periods = description.first && description.last ? periodList(description.first, description.last) : [];
|
|
3147
|
+
time = {
|
|
3148
|
+
code: dimension.id,
|
|
3149
|
+
label,
|
|
3150
|
+
values: periods,
|
|
3151
|
+
valueLabels: periods,
|
|
3152
|
+
eliminable: false,
|
|
3153
|
+
isTime: true
|
|
3154
|
+
};
|
|
3155
|
+
continue;
|
|
3156
|
+
}
|
|
3157
|
+
const codes = structure.codelists.get(dimension.codelistId ?? "") ?? [];
|
|
3158
|
+
const total = codes.length > 1 ? totalCode(codes) : void 0;
|
|
3159
|
+
if (total !== void 0) totals.set(dimension.id, total);
|
|
3160
|
+
const ordered = codes.toSorted((a, b) => {
|
|
3161
|
+
if (a.id === total) return -1;
|
|
3162
|
+
if (b.id === total) return 1;
|
|
3163
|
+
return compareCodes(a.id, b.id);
|
|
3164
|
+
});
|
|
3165
|
+
dimensions.push({
|
|
3166
|
+
code: dimension.id,
|
|
3167
|
+
label,
|
|
3168
|
+
values: ordered.map((code) => code.id),
|
|
3169
|
+
valueLabels: ordered.map((code) => textIn(code.names, lang) ?? code.id),
|
|
3170
|
+
eliminable: total !== void 0,
|
|
3171
|
+
isTime: false
|
|
3172
|
+
});
|
|
3173
|
+
}
|
|
3174
|
+
if (!time) throw new PxwebError(`Table "${flow.id}" has no time dimension in its data structure.`, 502);
|
|
3175
|
+
const statuses = structure.codelists.get(STATUS_CONCEPT) ?? [];
|
|
3176
|
+
return {
|
|
3177
|
+
flowId: flow.id,
|
|
3178
|
+
metadata: {
|
|
3179
|
+
title: flowTitle(textIn(flow.names, lang) ?? flow.id, description),
|
|
3180
|
+
variables: [...dimensions, time]
|
|
3181
|
+
},
|
|
3182
|
+
totals,
|
|
3183
|
+
statusTexts: new Map(statuses.map((code) => [code.id, textIn(code.names, lang) ?? code.id]))
|
|
3184
|
+
};
|
|
3185
|
+
}
|
|
3186
|
+
/**
|
|
3187
|
+
* Index ranges of the chosen periods: one per adjacent run, or one span over all
|
|
3188
|
+
* of them when there are many runs.
|
|
3189
|
+
*/
|
|
3190
|
+
function periodRanges(periods, chosen) {
|
|
3191
|
+
const runs = [];
|
|
3192
|
+
periods.forEach((period, index) => {
|
|
3193
|
+
if (!chosen.has(period)) return;
|
|
3194
|
+
const last = runs.at(-1);
|
|
3195
|
+
if (last && last[1] === index - 1) last[1] = index;
|
|
3196
|
+
else runs.push([index, index]);
|
|
3197
|
+
});
|
|
3198
|
+
const first = runs[0];
|
|
3199
|
+
const end = runs.at(-1);
|
|
3200
|
+
if (runs.length <= MAX_PERIOD_RANGES || !first || !end) return runs;
|
|
3201
|
+
return [[first[0], end[1]]];
|
|
3202
|
+
}
|
|
3203
|
+
function chosenCodes$1(variable, selection) {
|
|
3204
|
+
if (!selection || selection.selection.filter === "all") return variable.values;
|
|
3205
|
+
const { filter, values } = selection.selection;
|
|
3206
|
+
if (filter === "top") {
|
|
3207
|
+
const count = Math.max(1, Number(values[0]) || 1);
|
|
3208
|
+
return variable.values.slice(-count);
|
|
3209
|
+
}
|
|
3210
|
+
const known = new Set(variable.values);
|
|
3211
|
+
const unknown = values.filter((value) => !known.has(value));
|
|
3212
|
+
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);
|
|
3213
|
+
return values;
|
|
3214
|
+
}
|
|
3215
|
+
function toNumber(value) {
|
|
3216
|
+
if (value === void 0 || value.trim() === "") return null;
|
|
3217
|
+
const number = Number(value);
|
|
3218
|
+
return Number.isFinite(number) ? number : null;
|
|
3219
|
+
}
|
|
3220
|
+
function selectCodes(table, selections, maxCells) {
|
|
3221
|
+
const byCode = new Map(selections.map((selection) => [selection.code, selection]));
|
|
3222
|
+
const chosen = /* @__PURE__ */ new Map();
|
|
3223
|
+
const hidden = /* @__PURE__ */ new Set();
|
|
3224
|
+
let cells = 1;
|
|
3225
|
+
let perPeriod = 1;
|
|
3226
|
+
for (const variable of table.metadata.variables) {
|
|
3227
|
+
const selection = byCode.get(variable.code);
|
|
3228
|
+
const total = table.totals.get(variable.code);
|
|
3229
|
+
if (!variable.isTime) perPeriod *= Math.max(1, variable.values.length);
|
|
3230
|
+
if (!selection && total !== void 0) {
|
|
3231
|
+
chosen.set(variable.code, /* @__PURE__ */ new Set([total]));
|
|
3232
|
+
hidden.add(variable.code);
|
|
3233
|
+
continue;
|
|
3234
|
+
}
|
|
3235
|
+
const codes = chosenCodes$1(variable, selection);
|
|
3236
|
+
chosen.set(variable.code, new Set(codes));
|
|
3237
|
+
cells *= codes.length;
|
|
3238
|
+
}
|
|
3239
|
+
if (cells > maxCells) throw new PxwebError(`The query could return ${cells} cells, above the limit of ${maxCells}. Select fewer values.`, 400);
|
|
3240
|
+
return {
|
|
3241
|
+
chosen,
|
|
3242
|
+
hidden,
|
|
3243
|
+
perPeriod
|
|
3244
|
+
};
|
|
3245
|
+
}
|
|
3246
|
+
function collectRows(table, filter, lang) {
|
|
3247
|
+
const variables = table.metadata.variables;
|
|
3248
|
+
const shown = variables.filter((variable) => !filter.hidden.has(variable.code));
|
|
3249
|
+
const timeCode = variables.at(-1)?.code ?? "";
|
|
3250
|
+
const dimensionCodes = new Set(variables.filter((variable) => !variable.isTime).map((v) => v.code));
|
|
3251
|
+
const positions = new Map(variables.map((variable) => [variable.code, new Map(variable.values.map((value, index) => [value, index]))]));
|
|
3252
|
+
const found = [];
|
|
3253
|
+
let hasStatus = false;
|
|
3254
|
+
return {
|
|
3255
|
+
add(observation) {
|
|
3256
|
+
const codes = /* @__PURE__ */ new Map();
|
|
3257
|
+
for (const [id, code] of observation.key) codes.set(dimensionCodes.has(id) ? id : timeCode, code);
|
|
3258
|
+
if (!variables.every((variable) => {
|
|
3259
|
+
const code = codes.get(variable.code);
|
|
3260
|
+
return code !== void 0 && filter.chosen.get(variable.code)?.has(code);
|
|
3261
|
+
})) return;
|
|
3262
|
+
const status = observation.attributes.get(STATUS_CONCEPT);
|
|
3263
|
+
if (status) hasStatus = true;
|
|
3264
|
+
const order = shown.map((variable) => positions.get(variable.code)?.get(codes.get(variable.code) ?? "") ?? 0);
|
|
3265
|
+
found.push({
|
|
3266
|
+
order,
|
|
3267
|
+
cells: [
|
|
3268
|
+
...shown.map((variable, index) => variable.valueLabels[order[index] ?? -1] ?? codes.get(variable.code) ?? ""),
|
|
3269
|
+
toNumber(observation.value),
|
|
3270
|
+
status ? table.statusTexts.get(status) ?? status : null
|
|
3271
|
+
]
|
|
3272
|
+
});
|
|
3273
|
+
},
|
|
3274
|
+
build(headers) {
|
|
3275
|
+
const header = headers.find((entry) => entry.attributes.size > 0) ?? headers[0];
|
|
3276
|
+
found.sort((a, b) => {
|
|
3277
|
+
for (const [index, value] of a.order.entries()) {
|
|
3278
|
+
const difference = value - (b.order[index] ?? 0);
|
|
3279
|
+
if (difference !== 0) return difference;
|
|
3280
|
+
}
|
|
3281
|
+
return 0;
|
|
3282
|
+
});
|
|
3283
|
+
const texts = TEXTS$1[lang];
|
|
3284
|
+
const updated = header?.attributes.get("DS_LAST_UPDATE");
|
|
3285
|
+
const retrieved = header?.prepared?.slice(0, 10);
|
|
3286
|
+
const dates = [updated && `${texts.updated}: ${updated}`, retrieved && `${texts.retrieved}: ${retrieved}`].filter(Boolean);
|
|
3287
|
+
const title = dates.length ? `${table.metadata.title} (${dates.join("; ")})` : table.metadata.title;
|
|
3288
|
+
return {
|
|
3289
|
+
label: found.length ? title : `${title}. ${texts.noData}`,
|
|
3290
|
+
columns: [
|
|
3291
|
+
...shown.map((variable) => variable.label),
|
|
3292
|
+
texts.value,
|
|
3293
|
+
...hasStatus ? [texts.status] : []
|
|
3294
|
+
],
|
|
3295
|
+
rows: found.map((row) => hasStatus ? row.cells : row.cells.slice(0, -1))
|
|
3296
|
+
};
|
|
3297
|
+
}
|
|
3298
|
+
};
|
|
3299
|
+
}
|
|
3300
|
+
/**
|
|
3301
|
+
* Client for the Official Statistics Portal (OSP) of Statistics Lithuania (State
|
|
3302
|
+
* Data Agency), an SDMX 2.1 REST service that answers only SDMX-ML, in Lithuanian
|
|
3303
|
+
* and English (every message carries both).
|
|
3304
|
+
*
|
|
3305
|
+
* - Table id: the dataflow id, for example "S7R121_M2020103_1". One indicator
|
|
3306
|
+
* ("S7R121") has one dataflow per breakdown, so the title adds the dimensions
|
|
3307
|
+
* and the period range from the dataflow description.
|
|
3308
|
+
* - Search: a local index over the full dataflow list (`dataflow/`, 7 MB, one call
|
|
3309
|
+
* for both languages). The parsed list is kept in memory for an hour; it is too
|
|
3310
|
+
* large for the shared cache. The description gives the update date, the last
|
|
3311
|
+
* period and "not renewed" (discontinued) dataflows.
|
|
3312
|
+
* - Metadata: `dataflow/LSD/{id}` and `datastructure/LSD/{dsd}` (code lists and
|
|
3313
|
+
* concept names). Code lists come unordered and are sorted by code. A dimension is
|
|
3314
|
+
* eliminable only when exactly one code is labelled as a total ("Total by age",
|
|
3315
|
+
* "Republic of Lithuania", "Males and females" …); left out, it is filtered to that
|
|
3316
|
+
* code. The structure lists no periods, so they are expanded from the range in the
|
|
3317
|
+
* dataflow description.
|
|
3318
|
+
* - Query: OSP supports only `startPeriod` and `endPeriod` (no key, no
|
|
3319
|
+
* `lastNObservations`, so URLs stay far below its 1,000-character limit). Each
|
|
3320
|
+
* run of adjacent chosen periods is one request (more than four runs become one
|
|
3321
|
+
* span) with every code of every dimension; the message is streamed and filtered
|
|
3322
|
+
* here, never held whole. `latest` picks the newest listed periods. The cell
|
|
3323
|
+
* limit applies to the result, and a separate limit (60,000 observations, about
|
|
3324
|
+
* 20 s) to the download. Errors and "no data" come as HTTP 200 with a footer.
|
|
3325
|
+
* - Caching: dataflow and structure messages in the shared cache; the parsed table
|
|
3326
|
+
* in memory for an hour (finished values only); the filtered result in the shared
|
|
3327
|
+
* cache for an hour. Titles of results carry the data update and retrieval dates.
|
|
3328
|
+
*/
|
|
3329
|
+
function createOspClient(options) {
|
|
3330
|
+
const root = options.baseUrl.replace(/\/+$/, "");
|
|
3331
|
+
const maxCells = options.maxCells ?? DEFAULT_MAX_CELLS$1;
|
|
3332
|
+
const maxDownload = options.maxDownloadObservations ?? DEFAULT_MAX_DOWNLOAD_OBSERVATIONS;
|
|
3333
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
3334
|
+
const cache = options.cache ?? createMemoryCache();
|
|
3335
|
+
const doFetch = options.fetch ?? fetch;
|
|
3336
|
+
const request = createTextRequester({
|
|
3337
|
+
...options,
|
|
3338
|
+
cache
|
|
3339
|
+
});
|
|
3340
|
+
const xmlGet = {
|
|
3341
|
+
method: "GET",
|
|
3342
|
+
headers: { accept: XML_ACCEPT }
|
|
3343
|
+
};
|
|
3344
|
+
async function open(url) {
|
|
3345
|
+
const response = await doFetch(url, {
|
|
3346
|
+
headers: {
|
|
3347
|
+
accept: XML_ACCEPT,
|
|
3348
|
+
...options.userAgent && { "user-agent": options.userAgent }
|
|
3349
|
+
},
|
|
3350
|
+
signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS)
|
|
3351
|
+
}).catch((err) => {
|
|
3352
|
+
throw new PxwebError(`Statistics Lithuania request failed: ${err instanceof Error ? err.message : String(err)}`, 502);
|
|
3353
|
+
});
|
|
3354
|
+
if (!response.ok) {
|
|
3355
|
+
await response.body?.cancel().catch(() => void 0);
|
|
3356
|
+
throw upstreamError(new PxwebError(`Statistics Lithuania returned HTTP ${response.status}.`, response.status));
|
|
3357
|
+
}
|
|
3358
|
+
return response;
|
|
3359
|
+
}
|
|
3360
|
+
async function streamData(url, onObservation) {
|
|
3361
|
+
const response = await open(url);
|
|
3362
|
+
const reader = createGenericDataReader(onObservation);
|
|
3363
|
+
const decoder = new TextDecoder();
|
|
3364
|
+
const body = response.body?.getReader();
|
|
3365
|
+
let size = 0;
|
|
3366
|
+
try {
|
|
3367
|
+
for (;;) {
|
|
3368
|
+
const chunk = await body?.read();
|
|
3369
|
+
if (!chunk || chunk.done) break;
|
|
3370
|
+
size += chunk.value.byteLength;
|
|
3371
|
+
if (size > MAX_DATA_BYTES) {
|
|
3372
|
+
await body?.cancel().catch(() => void 0);
|
|
3373
|
+
throw new PxwebError("Statistics Lithuania response is too large.", 502);
|
|
3374
|
+
}
|
|
3375
|
+
reader.push(decoder.decode(chunk.value, { stream: true }));
|
|
3376
|
+
}
|
|
3377
|
+
} catch (err) {
|
|
3378
|
+
await body?.cancel().catch(() => void 0);
|
|
3379
|
+
if (err instanceof PxwebError) throw err;
|
|
3380
|
+
throw new PxwebError(`Statistics Lithuania response could not be read: ${err instanceof Error ? err.message : String(err)}`, 502);
|
|
3381
|
+
}
|
|
3382
|
+
reader.push(decoder.decode());
|
|
3383
|
+
return reader.finish();
|
|
3384
|
+
}
|
|
3385
|
+
let catalogue;
|
|
3386
|
+
async function listTables(lang) {
|
|
3387
|
+
const language = checkLanguage$1(lang);
|
|
3388
|
+
if (!catalogue || catalogue.expires <= Date.now()) {
|
|
3389
|
+
const flows = parseDataflows(await readCappedText(await open(`${root}/dataflow/`)));
|
|
3390
|
+
if (flows.length === 0) throw new PxwebError("Statistics Lithuania returned no dataflows.", 502);
|
|
3391
|
+
catalogue = {
|
|
3392
|
+
expires: Date.now() + SEARCH_TTL_SECONDS * 1e3,
|
|
3393
|
+
flows
|
|
3394
|
+
};
|
|
3395
|
+
}
|
|
3396
|
+
return catalogue.flows.map((flow) => toTableDoc(flow, language));
|
|
3397
|
+
}
|
|
3398
|
+
const tableIndex = createTableIndexLoader(preferCrawled(listTables, options.crawledList), {
|
|
1145
3399
|
fallback: options.listFallback,
|
|
1146
3400
|
ttlSeconds: SEARCH_TTL_SECONDS,
|
|
1147
3401
|
currentYear: () => now().getUTCFullYear()
|
|
1148
3402
|
});
|
|
1149
|
-
|
|
1150
|
-
const
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
const variables = (await requestText(url, TEXT, (xml) => {
|
|
1154
|
-
const result = parseStructure(xml, lang);
|
|
1155
|
-
if (result.dimensions.length === 0) throw new PxwebError("Eurostat returned a structure without dimensions.", 502);
|
|
1156
|
-
return result;
|
|
1157
|
-
}, METADATA_TTL_SECONDS, `meta:${url}:${lang}`).catch((err) => {
|
|
1158
|
-
if (err instanceof PxwebError && NOT_FOUND_STATUSES$3.has(err.status)) throw notFound$4(code);
|
|
1159
|
-
throw err;
|
|
1160
|
-
})).dimensions.map((dimension) => ({
|
|
1161
|
-
code: dimension.id,
|
|
1162
|
-
label: dimension.label,
|
|
1163
|
-
values: dimension.codes.map((item) => item.id),
|
|
1164
|
-
valueLabels: dimension.codes.map((item) => item.label),
|
|
1165
|
-
eliminable: false,
|
|
1166
|
-
isTime: false
|
|
1167
|
-
}));
|
|
1168
|
-
const periods = periodsBetween(entry.start, entry.end);
|
|
1169
|
-
const incomplete = stepOf(entry.end) === void 0 || !periodParts(entry.start) || !periodParts(entry.end);
|
|
1170
|
-
variables.push({
|
|
1171
|
-
code: TIME_CODE$2,
|
|
1172
|
-
label: TIME_CODE$2,
|
|
1173
|
-
values: periods,
|
|
1174
|
-
valueLabels: periods,
|
|
1175
|
-
eliminable: false,
|
|
1176
|
-
isTime: true,
|
|
1177
|
-
...incomplete && { periodsIncomplete: true }
|
|
3403
|
+
function getStructure(path, ttlSeconds, parse) {
|
|
3404
|
+
const url = `${root}/${path}`;
|
|
3405
|
+
return request(url, xmlGet, parse, ttlSeconds, `osp:${url}`).catch((err) => {
|
|
3406
|
+
throw upstreamError(err);
|
|
1178
3407
|
});
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
}
|
|
3408
|
+
}
|
|
3409
|
+
async function loadTable(lang, tableId) {
|
|
3410
|
+
if (!TABLE_ID_PATTERN$3.test(tableId)) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it.`, 400);
|
|
3411
|
+
const flow = await getStructure(`dataflow/${AGENCY}/${encodeURIComponent(tableId)}`, SEARCH_TTL_SECONDS, (xml) => {
|
|
3412
|
+
const [found] = parseDataflows(xml);
|
|
3413
|
+
if (found?.id !== tableId || !found.structureId) throw notFound$5(tableId);
|
|
3414
|
+
return {
|
|
3415
|
+
...found,
|
|
3416
|
+
structureId: found.structureId
|
|
3417
|
+
};
|
|
3418
|
+
});
|
|
3419
|
+
return buildTable(flow, await getStructure(`datastructure/${AGENCY}/${encodeURIComponent(flow.structureId)}`, METADATA_TTL_SECONDS, (xml) => {
|
|
3420
|
+
const footer = footerMessage(xml);
|
|
3421
|
+
if (footer) throw new PxwebError(`Statistics Lithuania has no data structure for table "${tableId}": ${textIn(footer.texts, lang) ?? footer.code}`, 502);
|
|
3422
|
+
return parseStructure(xml);
|
|
3423
|
+
}), lang);
|
|
3424
|
+
}
|
|
3425
|
+
const tables = /* @__PURE__ */ new Map();
|
|
3426
|
+
async function cachedTable(lang, tableId) {
|
|
3427
|
+
const language = checkLanguage$1(lang);
|
|
3428
|
+
const key = `${language}:${tableId}`;
|
|
3429
|
+
const cached = tables.get(key);
|
|
3430
|
+
if (cached && cached.expires > Date.now()) return cached.table;
|
|
3431
|
+
const table = await loadTable(language, tableId);
|
|
3432
|
+
tables.delete(key);
|
|
3433
|
+
tables.set(key, {
|
|
3434
|
+
expires: Date.now() + DATA_TTL_SECONDS * 1e3,
|
|
3435
|
+
table
|
|
3436
|
+
});
|
|
3437
|
+
const oldest = tables.keys().next().value;
|
|
3438
|
+
if (tables.size > MAX_CACHED_TABLES$1 && oldest !== void 0) tables.delete(oldest);
|
|
3439
|
+
return table;
|
|
1183
3440
|
}
|
|
1184
3441
|
return {
|
|
1185
3442
|
listTables,
|
|
1186
3443
|
async search(lang, query, searchOptions) {
|
|
3444
|
+
checkLanguage$1(lang);
|
|
1187
3445
|
return (await tableIndex(lang)).search(query, searchOptions);
|
|
1188
3446
|
},
|
|
1189
|
-
async getMetadata(lang,
|
|
1190
|
-
|
|
1191
|
-
return metadata(lang, code);
|
|
3447
|
+
async getMetadata(lang, tableId) {
|
|
3448
|
+
return (await cachedTable(lang, tableId)).metadata;
|
|
1192
3449
|
},
|
|
1193
|
-
async query(lang,
|
|
1194
|
-
|
|
1195
|
-
const
|
|
1196
|
-
const
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
}
|
|
1205
|
-
let codes = values;
|
|
1206
|
-
if (filter === "top") {
|
|
1207
|
-
const variable = known?.variables.find((item) => item.code === selection.code);
|
|
1208
|
-
if (!variable) throw new PxwebError(`Table "${code}" has no variable "${selection.code}". Call get_table_metadata to see its variables.`, 400);
|
|
1209
|
-
codes = variable.values.slice(-count);
|
|
1210
|
-
}
|
|
1211
|
-
for (const value of codes) params.append(selection.code, value);
|
|
3450
|
+
async query(lang, tableId, selections) {
|
|
3451
|
+
const language = checkLanguage$1(lang);
|
|
3452
|
+
const table = await cachedTable(language, tableId);
|
|
3453
|
+
const { chosen, hidden, perPeriod } = selectCodes(table, selections, maxCells);
|
|
3454
|
+
const time = table.metadata.variables.at(-1);
|
|
3455
|
+
const ranges = periodRanges(time?.values ?? [], chosen.get(time?.code ?? "") ?? /* @__PURE__ */ new Set());
|
|
3456
|
+
const periods = ranges.reduce((sum, [from, to]) => sum + to - from + 1, 0);
|
|
3457
|
+
if (periods === 0 || !time) throw new PxwebError(`Table "${tableId}" lists no periods.`, 400);
|
|
3458
|
+
const download = perPeriod * periods;
|
|
3459
|
+
if (download > maxDownload) {
|
|
3460
|
+
const fit = Math.floor(maxDownload / perPeriod);
|
|
3461
|
+
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);
|
|
1212
3462
|
}
|
|
1213
|
-
const
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
3463
|
+
const urls = ranges.map(([from, to]) => `${root}/data/${encodeURIComponent(table.flowId)}?startPeriod=${apiPeriod(time.values[from] ?? "", "start")}&endPeriod=${apiPeriod(time.values[to] ?? "", "end")}`);
|
|
3464
|
+
const signature = [...chosen].map(([code, values]) => `${code}=${[...values].join(",")}`).join("&");
|
|
3465
|
+
const cacheKey = `osp:rows:${language}:${urls.join(" ")}:${signature}`;
|
|
3466
|
+
const cached = await cache.get(cacheKey);
|
|
3467
|
+
const parsed = flatTableSchema.safeParse(parseCached(cached));
|
|
3468
|
+
if (parsed.success) return parsed.data;
|
|
3469
|
+
const rows = collectRows(table, {
|
|
3470
|
+
chosen,
|
|
3471
|
+
hidden
|
|
3472
|
+
}, language);
|
|
3473
|
+
let observations = 0;
|
|
3474
|
+
const countObservation = (observation) => {
|
|
3475
|
+
observations += 1;
|
|
3476
|
+
if (observations > maxDownload) throw new PxwebError(`Statistics Lithuania sent more than ${maxDownload} observations for these periods. Select fewer periods.`, 400);
|
|
3477
|
+
rows.add(observation);
|
|
3478
|
+
};
|
|
3479
|
+
const headers = [];
|
|
3480
|
+
for (const url of urls) {
|
|
3481
|
+
const header = await streamData(url, countObservation).catch((err) => {
|
|
3482
|
+
if (err instanceof PxwebError && err.status === 404) throw notFound$5(tableId);
|
|
3483
|
+
throw err;
|
|
3484
|
+
});
|
|
3485
|
+
const footer = header.footer;
|
|
3486
|
+
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);
|
|
3487
|
+
headers.push(header);
|
|
3488
|
+
}
|
|
3489
|
+
const result = rows.build(headers);
|
|
3490
|
+
await cache.set(cacheKey, JSON.stringify(result), DATA_TTL_SECONDS);
|
|
3491
|
+
return result;
|
|
1218
3492
|
}
|
|
1219
3493
|
};
|
|
1220
3494
|
}
|
|
@@ -1241,7 +3515,7 @@ function categoryCodes(index) {
|
|
|
1241
3515
|
if (Array.isArray(index)) return index;
|
|
1242
3516
|
return Object.entries(index).toSorted((a, b) => a[1] - b[1]).map(([code]) => code);
|
|
1243
3517
|
}
|
|
1244
|
-
function toTable(data) {
|
|
3518
|
+
function toTable$1(data) {
|
|
1245
3519
|
const elimination = Object.fromEntries(Object.entries(data.extension?.elimination ?? {}).filter((entry) => entry[1] !== null));
|
|
1246
3520
|
const timeCodes = new Set(data.role?.time ?? []);
|
|
1247
3521
|
return {
|
|
@@ -1263,7 +3537,7 @@ function toTable(data) {
|
|
|
1263
3537
|
}
|
|
1264
3538
|
};
|
|
1265
3539
|
}
|
|
1266
|
-
function notFound$
|
|
3540
|
+
function notFound$4(tableId) {
|
|
1267
3541
|
return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
1268
3542
|
}
|
|
1269
3543
|
function checkTableId$3(tableId) {
|
|
@@ -1291,9 +3565,9 @@ function createPxstatClient(options) {
|
|
|
1291
3565
|
checkTableId$3(tableId);
|
|
1292
3566
|
const url = `${root}/api.restful/PxStat.Data.Cube_API.ReadMetadata/${tableId}/JSON-stat/2.0/${encodeURIComponent(lang)}`;
|
|
1293
3567
|
try {
|
|
1294
|
-
return await request(url, { method: "GET" }, metadataSchema$3, toTable, METADATA_TTL_SECONDS, `meta:${url}`);
|
|
3568
|
+
return await request(url, { method: "GET" }, metadataSchema$3, toTable$1, METADATA_TTL_SECONDS, `meta:${url}`);
|
|
1295
3569
|
} catch (err) {
|
|
1296
|
-
if (err instanceof PxwebError && err.status === 404) throw notFound$
|
|
3570
|
+
if (err instanceof PxwebError && err.status === 404) throw notFound$4(tableId);
|
|
1297
3571
|
throw err;
|
|
1298
3572
|
}
|
|
1299
3573
|
}
|
|
@@ -1339,8 +3613,8 @@ function createPxstatClient(options) {
|
|
|
1339
3613
|
headers: { "content-type": "application/json" }
|
|
1340
3614
|
}, rpcSchema, (data) => {
|
|
1341
3615
|
if (data.error) throw new PxwebError(`PxStat refused the query: ${data.error.message ?? "unknown error"}`, 400);
|
|
1342
|
-
if (!data.result) throw notFound$
|
|
1343
|
-
return toFlatTable$
|
|
3616
|
+
if (!data.result) throw notFound$4(tableId);
|
|
3617
|
+
return toFlatTable$2(data.result);
|
|
1344
3618
|
}, DATA_TTL_SECONDS, `data:${url}:${body}`);
|
|
1345
3619
|
}
|
|
1346
3620
|
};
|
|
@@ -1441,21 +3715,26 @@ function createPxwebClient(options) {
|
|
|
1441
3715
|
const failure = results.find((result) => result.status === "rejected");
|
|
1442
3716
|
if (found.length === 0 && failure) throw failure.reason;
|
|
1443
3717
|
const merged = found.flat();
|
|
1444
|
-
|
|
3718
|
+
const hits = (multiDatabase ? merged.toSorted((a, b) => b.score - a.score) : merged).map(({ score: _score, ...hit }) => hit);
|
|
3719
|
+
return rankSearchHits(uniqueByTableId(hits), now().getUTCFullYear());
|
|
1445
3720
|
},
|
|
1446
3721
|
async getMetadata(lang, tableId) {
|
|
1447
3722
|
const url = tableUrl(lang, tableId);
|
|
1448
3723
|
try {
|
|
1449
3724
|
return await request(url, { method: "GET" }, metadataSchema$2, (parsed) => ({
|
|
1450
3725
|
title: parsed.title,
|
|
1451
|
-
variables: parsed.variables.map((variable) =>
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
3726
|
+
variables: parsed.variables.map((variable) => {
|
|
3727
|
+
const namedTime = variable.time !== true && (options.timeVariables?.includes(variable.code) ?? false);
|
|
3728
|
+
return {
|
|
3729
|
+
code: variable.code,
|
|
3730
|
+
label: variable.text,
|
|
3731
|
+
values: variable.values,
|
|
3732
|
+
valueLabels: variable.valueTexts,
|
|
3733
|
+
eliminable: variable.elimination ?? false,
|
|
3734
|
+
isTime: variable.time === true || namedTime,
|
|
3735
|
+
...namedTime && { latestByCode: true }
|
|
3736
|
+
};
|
|
3737
|
+
})
|
|
1459
3738
|
}), METADATA_TTL_SECONDS, `meta:${url}`);
|
|
1460
3739
|
} catch (err) {
|
|
1461
3740
|
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);
|
|
@@ -1472,7 +3751,7 @@ function createPxwebClient(options) {
|
|
|
1472
3751
|
method: "POST",
|
|
1473
3752
|
body,
|
|
1474
3753
|
headers: { "content-type": "application/json" }
|
|
1475
|
-
}, jsonStatDatasetSchema, toFlatTable$
|
|
3754
|
+
}, jsonStatDatasetSchema, toFlatTable$2, DATA_TTL_SECONDS, `data:${url}:${body}`);
|
|
1476
3755
|
}
|
|
1477
3756
|
};
|
|
1478
3757
|
}
|
|
@@ -1585,7 +3864,7 @@ function createPxwebV2Client(options) {
|
|
|
1585
3864
|
pageSize: String(SEARCH_PAGE_SIZE)
|
|
1586
3865
|
});
|
|
1587
3866
|
const url = `${baseUrl}/tables?${params.toString()}`;
|
|
1588
|
-
|
|
3867
|
+
const hits = await request(url, { method: "GET" }, tableListSchema$1, ({ tables }) => tables.map((table) => {
|
|
1589
3868
|
const hit = {
|
|
1590
3869
|
id: table.id,
|
|
1591
3870
|
title: table.label,
|
|
@@ -1598,7 +3877,8 @@ function createPxwebV2Client(options) {
|
|
|
1598
3877
|
published: hit.published,
|
|
1599
3878
|
...archived ? { archived: true } : {}
|
|
1600
3879
|
};
|
|
1601
|
-
}), SEARCH_TTL_SECONDS, `search:${url}`)
|
|
3880
|
+
}), SEARCH_TTL_SECONDS, `search:${url}`);
|
|
3881
|
+
return rankSearchHits(hits, now().getUTCFullYear());
|
|
1602
3882
|
},
|
|
1603
3883
|
async getMetadata(lang, tableId) {
|
|
1604
3884
|
const url = `${tablePath(tableId)}/metadata?${new URLSearchParams({ lang }).toString()}`;
|
|
@@ -1623,7 +3903,7 @@ function createPxwebV2Client(options) {
|
|
|
1623
3903
|
method: "POST",
|
|
1624
3904
|
body,
|
|
1625
3905
|
headers: { "content-type": "application/json" }
|
|
1626
|
-
}, jsonStatDatasetSchema, toFlatTable$
|
|
3906
|
+
}, jsonStatDatasetSchema, toFlatTable$2, DATA_TTL_SECONDS, `data:${url}:${body}`);
|
|
1627
3907
|
}
|
|
1628
3908
|
};
|
|
1629
3909
|
}
|
|
@@ -1687,7 +3967,7 @@ function periodCodes(freq, start, end) {
|
|
|
1687
3967
|
for (let step = first; step <= last; step++) codes.push(periodCode(freq, Math.floor(step / perYear), step % perYear));
|
|
1688
3968
|
return codes;
|
|
1689
3969
|
}
|
|
1690
|
-
function parsePeriod(code) {
|
|
3970
|
+
function parsePeriod$1(code) {
|
|
1691
3971
|
for (const { freq, pattern } of PERIOD_PATTERNS) {
|
|
1692
3972
|
const match = pattern.exec(code);
|
|
1693
3973
|
if (!match) continue;
|
|
@@ -1701,8 +3981,8 @@ function parsePeriod(code) {
|
|
|
1701
3981
|
}
|
|
1702
3982
|
/** Sorts by start date, then year before half-year, quarter and month; unknown codes last. */
|
|
1703
3983
|
function comparePeriods(a, b) {
|
|
1704
|
-
const left = parsePeriod(a);
|
|
1705
|
-
const right = parsePeriod(b);
|
|
3984
|
+
const left = parsePeriod$1(a);
|
|
3985
|
+
const right = parsePeriod$1(b);
|
|
1706
3986
|
if (!left || !right) {
|
|
1707
3987
|
if (left) return -1;
|
|
1708
3988
|
if (right) return 1;
|
|
@@ -1953,7 +4233,7 @@ const STRUCTURE_ACCEPT = "application/vnd.sdmx.structure+json;version=1.0";
|
|
|
1953
4233
|
const DATA_ACCEPT = "application/vnd.sdmx.data+json;version=1.0";
|
|
1954
4234
|
const MAX_URL_LENGTH = 4e3;
|
|
1955
4235
|
const NO_DATA_NOTE = "No data for these periods. This table may have data only for some years; use latest.";
|
|
1956
|
-
function notFound$
|
|
4236
|
+
function notFound$3(tableId) {
|
|
1957
4237
|
return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
1958
4238
|
}
|
|
1959
4239
|
function unknownValues(code, values) {
|
|
@@ -1989,13 +4269,20 @@ function createSdmxClient(options) {
|
|
|
1989
4269
|
const { agency } = options;
|
|
1990
4270
|
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
1991
4271
|
const request = createRequester(options);
|
|
4272
|
+
const language = options.languages?.length ? { "accept-language": options.languages.join(",") } : {};
|
|
1992
4273
|
const structureGet = {
|
|
1993
4274
|
method: "GET",
|
|
1994
|
-
headers: {
|
|
4275
|
+
headers: {
|
|
4276
|
+
accept: STRUCTURE_ACCEPT,
|
|
4277
|
+
...language
|
|
4278
|
+
}
|
|
1995
4279
|
};
|
|
1996
4280
|
const dataGet = {
|
|
1997
4281
|
method: "GET",
|
|
1998
|
-
headers: {
|
|
4282
|
+
headers: {
|
|
4283
|
+
accept: DATA_ACCEPT,
|
|
4284
|
+
...language
|
|
4285
|
+
}
|
|
1999
4286
|
};
|
|
2000
4287
|
let loadingCatalogue;
|
|
2001
4288
|
function busy(promise) {
|
|
@@ -2039,14 +4326,14 @@ function createSdmxClient(options) {
|
|
|
2039
4326
|
} catch (err) {
|
|
2040
4327
|
const upper = tableId.toUpperCase();
|
|
2041
4328
|
if (!(err instanceof PxwebError && err.status === 404)) throw err;
|
|
2042
|
-
if (upper === tableId) throw notFound$
|
|
4329
|
+
if (upper === tableId) throw notFound$3(tableId);
|
|
2043
4330
|
try {
|
|
2044
4331
|
return {
|
|
2045
4332
|
flowId: upper,
|
|
2046
4333
|
data: await structure(upper)
|
|
2047
4334
|
};
|
|
2048
4335
|
} catch (retryErr) {
|
|
2049
|
-
if (retryErr instanceof PxwebError && retryErr.status === 404) throw notFound$
|
|
4336
|
+
if (retryErr instanceof PxwebError && retryErr.status === 404) throw notFound$3(tableId);
|
|
2050
4337
|
throw retryErr;
|
|
2051
4338
|
}
|
|
2052
4339
|
}
|
|
@@ -2122,7 +4409,7 @@ function createSdmxClient(options) {
|
|
|
2122
4409
|
// src/singstat-client.ts
|
|
2123
4410
|
const TABLE_ID_PATTERN$1 = /^[A-Za-z0-9]+$/;
|
|
2124
4411
|
const SERIES_CODE = "series";
|
|
2125
|
-
const TIME_CODE$
|
|
4412
|
+
const TIME_CODE$2 = "time";
|
|
2126
4413
|
const TIME_SERIES = "time series";
|
|
2127
4414
|
const searchSchema = z.object({
|
|
2128
4415
|
StatusCode: z.number().nullish(),
|
|
@@ -2167,7 +4454,7 @@ function unwrap(envelope) {
|
|
|
2167
4454
|
function checkTableId$2(tableId) {
|
|
2168
4455
|
if (!TABLE_ID_PATTERN$1.test(tableId)) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it.`, 400);
|
|
2169
4456
|
}
|
|
2170
|
-
function notFound$
|
|
4457
|
+
function notFound$2(tableId) {
|
|
2171
4458
|
return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
2172
4459
|
}
|
|
2173
4460
|
function numberOrNull(value) {
|
|
@@ -2193,11 +4480,11 @@ function createSingstatClient(options) {
|
|
|
2193
4480
|
async function metadata(tableId) {
|
|
2194
4481
|
const url = `${baseUrl}/metadata/${tableId}`;
|
|
2195
4482
|
const records = await request(url, get, metadataSchema, (data) => unwrap(data).records, METADATA_TTL_SECONDS, `meta:${url}`).catch((err) => {
|
|
2196
|
-
if (err instanceof PxwebError && err.status === 404) throw notFound$
|
|
4483
|
+
if (err instanceof PxwebError && err.status === 404) throw notFound$2(tableId);
|
|
2197
4484
|
throw err;
|
|
2198
4485
|
});
|
|
2199
4486
|
const first = records.row[0];
|
|
2200
|
-
if (!first) throw notFound$
|
|
4487
|
+
if (!first) throw notFound$2(tableId);
|
|
2201
4488
|
const periodsUrl = `${baseUrl}/tabledata/${tableId}?seriesNoORrowNo=${encodeURIComponent(first.seriesNo)}`;
|
|
2202
4489
|
const periods = await request(periodsUrl, get, dataSchema$1, (data) => unwrap(data).row[0]?.columns.map((column) => column.key) ?? [], METADATA_TTL_SECONDS, `meta:${periodsUrl}`);
|
|
2203
4490
|
return {
|
|
@@ -2210,7 +4497,7 @@ function createSingstatClient(options) {
|
|
|
2210
4497
|
eliminable: false,
|
|
2211
4498
|
isTime: false
|
|
2212
4499
|
}, {
|
|
2213
|
-
code: TIME_CODE$
|
|
4500
|
+
code: TIME_CODE$2,
|
|
2214
4501
|
label: "Period",
|
|
2215
4502
|
values: periods,
|
|
2216
4503
|
valueLabels: periods,
|
|
@@ -2245,7 +4532,7 @@ function createSingstatClient(options) {
|
|
|
2245
4532
|
const byCode = new Map(selections.map((selection) => [selection.code, selection]));
|
|
2246
4533
|
const [seriesVariable, timeVariable] = table.variables;
|
|
2247
4534
|
const series = selected(seriesVariable?.values ?? [], byCode.get(SERIES_CODE));
|
|
2248
|
-
const periods = selected(timeVariable?.values ?? [], byCode.get(TIME_CODE$
|
|
4535
|
+
const periods = selected(timeVariable?.values ?? [], byCode.get(TIME_CODE$2));
|
|
2249
4536
|
if (series?.length === 0 || periods?.length === 0) throw new PxwebError("Select at least one value for every variable.", 400);
|
|
2250
4537
|
const params = [];
|
|
2251
4538
|
if (series) params.push(`seriesNoORrowNo=${encodeURIComponent(series.join(","))}`);
|
|
@@ -2413,7 +4700,435 @@ function createStatbankDkClient(options) {
|
|
|
2413
4700
|
values: valueCodes(selection)
|
|
2414
4701
|
}))
|
|
2415
4702
|
};
|
|
2416
|
-
return request(url, post$1(body), jsonStat1Schema, (raw) => toFlatTable$
|
|
4703
|
+
return request(url, post$1(body), jsonStat1Schema, (raw) => toFlatTable$2(toJsonStat2(raw)), DATA_TTL_SECONDS, `data:${url}:${JSON.stringify(body)}`);
|
|
4704
|
+
}
|
|
4705
|
+
};
|
|
4706
|
+
}
|
|
4707
|
+
// src/statbel-client.ts
|
|
4708
|
+
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;
|
|
4709
|
+
const LANGUAGES = /* @__PURE__ */ new Set([
|
|
4710
|
+
"nl",
|
|
4711
|
+
"fr",
|
|
4712
|
+
"en",
|
|
4713
|
+
"de"
|
|
4714
|
+
]);
|
|
4715
|
+
const DEFAULT_MAX_CELLS = 5e3;
|
|
4716
|
+
const MAX_CACHED_TABLES = 20;
|
|
4717
|
+
const TIME_CODE$1 = "period";
|
|
4718
|
+
const MEASURE_CODE = "indicator";
|
|
4719
|
+
/** Code of the row that a view writes with an empty (null) cell: the total over that column. */
|
|
4720
|
+
const TOTAL_CODE = "_T";
|
|
4721
|
+
/** Measures carry float noise, for example 100.75000000000036. */
|
|
4722
|
+
const SIGNIFICANT_DIGITS = 12;
|
|
4723
|
+
const EN_TEXTS = {
|
|
4724
|
+
period: "Period",
|
|
4725
|
+
measure: "Indicator",
|
|
4726
|
+
value: "Value",
|
|
4727
|
+
total: "Total",
|
|
4728
|
+
updated: "last update"
|
|
4729
|
+
};
|
|
4730
|
+
const TEXTS = {
|
|
4731
|
+
en: EN_TEXTS,
|
|
4732
|
+
nl: {
|
|
4733
|
+
period: "Periode",
|
|
4734
|
+
measure: "Indicator",
|
|
4735
|
+
value: "Waarde",
|
|
4736
|
+
total: "Totaal",
|
|
4737
|
+
updated: "laatst bijgewerkt"
|
|
4738
|
+
},
|
|
4739
|
+
fr: {
|
|
4740
|
+
period: "Période",
|
|
4741
|
+
measure: "Indicateur",
|
|
4742
|
+
value: "Valeur",
|
|
4743
|
+
total: "Total",
|
|
4744
|
+
updated: "dernière mise à jour"
|
|
4745
|
+
},
|
|
4746
|
+
de: {
|
|
4747
|
+
period: "Zeitraum",
|
|
4748
|
+
measure: "Indikator",
|
|
4749
|
+
value: "Wert",
|
|
4750
|
+
total: "Insgesamt",
|
|
4751
|
+
updated: "letzte Aktualisierung"
|
|
4752
|
+
}
|
|
4753
|
+
};
|
|
4754
|
+
const REFERENCE = "(?:reference ?|referentie|referenz)?";
|
|
4755
|
+
const TIME_COLUMNS = [
|
|
4756
|
+
["month", new RegExp(`^${REFERENCE}(?:month|maand|mois|monat)$`)],
|
|
4757
|
+
["quarter", /^(?:quarter|kwartaal|trimester|trimestre|quartal)$/],
|
|
4758
|
+
["half", /^(?:semester|semestre|halbjahr)$/],
|
|
4759
|
+
["year", new RegExp(`^${REFERENCE}(?:year|jaar|annee|jahr)$`)]
|
|
4760
|
+
];
|
|
4761
|
+
const PERIOD_LETTERS = {
|
|
4762
|
+
month: "M",
|
|
4763
|
+
quarter: "Q",
|
|
4764
|
+
half: "S",
|
|
4765
|
+
year: ""
|
|
4766
|
+
};
|
|
4767
|
+
const PERIOD_MAX = {
|
|
4768
|
+
month: 12,
|
|
4769
|
+
quarter: 4,
|
|
4770
|
+
half: 2,
|
|
4771
|
+
year: 0
|
|
4772
|
+
};
|
|
4773
|
+
const MONTHS = new Map([
|
|
4774
|
+
[
|
|
4775
|
+
"january",
|
|
4776
|
+
"januari",
|
|
4777
|
+
"janvier",
|
|
4778
|
+
"januar"
|
|
4779
|
+
],
|
|
4780
|
+
[
|
|
4781
|
+
"february",
|
|
4782
|
+
"februari",
|
|
4783
|
+
"fevrier",
|
|
4784
|
+
"februar"
|
|
4785
|
+
],
|
|
4786
|
+
[
|
|
4787
|
+
"march",
|
|
4788
|
+
"maart",
|
|
4789
|
+
"mars",
|
|
4790
|
+
"marz"
|
|
4791
|
+
],
|
|
4792
|
+
["april", "avril"],
|
|
4793
|
+
[
|
|
4794
|
+
"may",
|
|
4795
|
+
"mei",
|
|
4796
|
+
"mai"
|
|
4797
|
+
],
|
|
4798
|
+
[
|
|
4799
|
+
"june",
|
|
4800
|
+
"juni",
|
|
4801
|
+
"juin"
|
|
4802
|
+
],
|
|
4803
|
+
[
|
|
4804
|
+
"july",
|
|
4805
|
+
"juli",
|
|
4806
|
+
"juillet"
|
|
4807
|
+
],
|
|
4808
|
+
[
|
|
4809
|
+
"august",
|
|
4810
|
+
"augustus",
|
|
4811
|
+
"aout"
|
|
4812
|
+
],
|
|
4813
|
+
["september", "septembre"],
|
|
4814
|
+
[
|
|
4815
|
+
"october",
|
|
4816
|
+
"oktober",
|
|
4817
|
+
"octobre"
|
|
4818
|
+
],
|
|
4819
|
+
["november", "novembre"],
|
|
4820
|
+
[
|
|
4821
|
+
"december",
|
|
4822
|
+
"decembre",
|
|
4823
|
+
"dezember"
|
|
4824
|
+
]
|
|
4825
|
+
].flatMap((names, index) => names.map((name) => [name, index + 1])));
|
|
4826
|
+
const viewSchema = z.object({
|
|
4827
|
+
id: z.string(),
|
|
4828
|
+
name: z.string(),
|
|
4829
|
+
locale: z.string(),
|
|
4830
|
+
dataSourceId: z.string().nullish(),
|
|
4831
|
+
lastPublishDate: z.number().nullish(),
|
|
4832
|
+
inapplicable: z.boolean().nullish()
|
|
4833
|
+
});
|
|
4834
|
+
const dataSourceSchema = z.object({
|
|
4835
|
+
id: z.string(),
|
|
4836
|
+
descriptions: z.record(z.string(), z.string().nullable()).nullish(),
|
|
4837
|
+
lastDataUpdateDate: z.number().nullish()
|
|
4838
|
+
});
|
|
4839
|
+
const resultSchema = z.object({ facts: z.array(z.record(z.string(), z.union([
|
|
4840
|
+
z.string(),
|
|
4841
|
+
z.number(),
|
|
4842
|
+
z.null()
|
|
4843
|
+
]))) });
|
|
4844
|
+
function parseJson(text, schema) {
|
|
4845
|
+
let json;
|
|
4846
|
+
try {
|
|
4847
|
+
json = JSON.parse(text);
|
|
4848
|
+
} catch {
|
|
4849
|
+
throw new PxwebError("Statbel returned a response that is not JSON.", 502);
|
|
4850
|
+
}
|
|
4851
|
+
const result = schema.safeParse(json);
|
|
4852
|
+
if (!result.success) throw new PxwebError("Statbel returned an unexpected response shape.", 502);
|
|
4853
|
+
return result.data;
|
|
4854
|
+
}
|
|
4855
|
+
function isoDate(ms) {
|
|
4856
|
+
return ms ? new Date(ms).toISOString().slice(0, 10) : void 0;
|
|
4857
|
+
}
|
|
4858
|
+
function checkLanguage(lang) {
|
|
4859
|
+
if (!LANGUAGES.has(lang)) throw new PxwebError(`Language "${lang}" is not supported.`, 400);
|
|
4860
|
+
}
|
|
4861
|
+
function notFound$1(tableId) {
|
|
4862
|
+
return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
4863
|
+
}
|
|
4864
|
+
function timeKind(column) {
|
|
4865
|
+
const name = normalize(column.trim(), "en");
|
|
4866
|
+
return TIME_COLUMNS.find(([, pattern]) => pattern.test(name))?.[0];
|
|
4867
|
+
}
|
|
4868
|
+
/** "October 2025", "Octobre 2025", " 1", "3rd quarter 2025", "1ste kwartaal 2024", "2026". */
|
|
4869
|
+
function parsePeriod(kind, text) {
|
|
4870
|
+
const year = /(?<!\d)(\d{4})(?!\d)/.exec(text)?.[1];
|
|
4871
|
+
if (kind === "year") return /^\d{4}$/.test(text) ? { year: text } : void 0;
|
|
4872
|
+
const rest = normalize(text.replace(year ?? "", ""), "en").trim();
|
|
4873
|
+
const part = kind === "month" && !/^\d+$/.test(rest) ? MONTHS.get(rest) : Number(/^(\d{1,2})(?!\d)/.exec(rest)?.[1]);
|
|
4874
|
+
if (!part || part > PERIOD_MAX[kind]) return void 0;
|
|
4875
|
+
return {
|
|
4876
|
+
...year && { year },
|
|
4877
|
+
part
|
|
4878
|
+
};
|
|
4879
|
+
}
|
|
4880
|
+
/** The finest period of a row: null when every time cell is empty (a total), undefined when one does not parse. */
|
|
4881
|
+
function rowPeriod(fact, columns) {
|
|
4882
|
+
let year;
|
|
4883
|
+
let finest;
|
|
4884
|
+
for (const [column, kind] of columns) {
|
|
4885
|
+
const cell = fact[column];
|
|
4886
|
+
if (typeof cell !== "string") continue;
|
|
4887
|
+
const label = cell.trim();
|
|
4888
|
+
const parsed = parsePeriod(kind, label);
|
|
4889
|
+
if (!parsed) return void 0;
|
|
4890
|
+
year ??= parsed.year;
|
|
4891
|
+
if (parsed.part && (!finest || PERIOD_MAX[kind] > PERIOD_MAX[finest.kind])) finest = {
|
|
4892
|
+
kind,
|
|
4893
|
+
part: parsed.part,
|
|
4894
|
+
label
|
|
4895
|
+
};
|
|
4896
|
+
}
|
|
4897
|
+
if (!year && !finest) return null;
|
|
4898
|
+
if (!year) return void 0;
|
|
4899
|
+
if (!finest) return {
|
|
4900
|
+
code: year,
|
|
4901
|
+
label: year
|
|
4902
|
+
};
|
|
4903
|
+
const width = finest.kind === "month" ? 2 : 1;
|
|
4904
|
+
const code = `${year}${PERIOD_LETTERS[finest.kind]}${String(finest.part).padStart(width, "0")}`;
|
|
4905
|
+
return {
|
|
4906
|
+
code,
|
|
4907
|
+
label: finest.label.includes(year) ? finest.label : code
|
|
4908
|
+
};
|
|
4909
|
+
}
|
|
4910
|
+
/** `latest` picks the newest periods of each frequency, so annual and monthly rows both get data. */
|
|
4911
|
+
function newestPerFrequency(codes, count) {
|
|
4912
|
+
const byShape = /* @__PURE__ */ new Map();
|
|
4913
|
+
for (const code of codes) {
|
|
4914
|
+
if (code === TOTAL_CODE) continue;
|
|
4915
|
+
const shape = code.replace(/\d/g, "9");
|
|
4916
|
+
byShape.set(shape, [...byShape.get(shape) ?? [], code]);
|
|
4917
|
+
}
|
|
4918
|
+
return [...byShape.values()].flatMap((list) => list.slice(-count));
|
|
4919
|
+
}
|
|
4920
|
+
function chosenCodes(variable, selection) {
|
|
4921
|
+
if (!selection || selection.selection.filter === "all") return void 0;
|
|
4922
|
+
const { filter, values } = selection.selection;
|
|
4923
|
+
if (filter === "top") {
|
|
4924
|
+
const count = Math.max(1, Number(values[0]) || 1);
|
|
4925
|
+
if (variable.isTime) return newestPerFrequency(variable.values, count);
|
|
4926
|
+
return variable.values.slice(-count);
|
|
4927
|
+
}
|
|
4928
|
+
const known = new Set(variable.values);
|
|
4929
|
+
const unknown = values.filter((value) => !known.has(value));
|
|
4930
|
+
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);
|
|
4931
|
+
return values;
|
|
4932
|
+
}
|
|
4933
|
+
/** The total, when the column has one, comes first. */
|
|
4934
|
+
function toVariable(code, label, labels, total, isTime) {
|
|
4935
|
+
const entries = [...total === void 0 ? [] : [[TOTAL_CODE, total]], ...labels];
|
|
4936
|
+
return {
|
|
4937
|
+
code,
|
|
4938
|
+
label,
|
|
4939
|
+
values: entries.map(([value]) => value),
|
|
4940
|
+
valueLabels: entries.map(([, text]) => text),
|
|
4941
|
+
eliminable: total !== void 0,
|
|
4942
|
+
isTime
|
|
4943
|
+
};
|
|
4944
|
+
}
|
|
4945
|
+
function round(value) {
|
|
4946
|
+
return typeof value === "number" ? Number(value.toPrecision(SIGNIFICANT_DIGITS)) : null;
|
|
4947
|
+
}
|
|
4948
|
+
function compareKeys(a, b) {
|
|
4949
|
+
for (const [index, value] of a.entries()) {
|
|
4950
|
+
const difference = value - (b[index] ?? 0);
|
|
4951
|
+
if (difference !== 0) return difference;
|
|
4952
|
+
}
|
|
4953
|
+
return 0;
|
|
4954
|
+
}
|
|
4955
|
+
function toTable(facts, title, texts) {
|
|
4956
|
+
const kinds = /* @__PURE__ */ new Map();
|
|
4957
|
+
for (const fact of facts) for (const [column, cell] of Object.entries(fact)) if (typeof cell === "string") kinds.set(column, "dimension");
|
|
4958
|
+
else if (typeof cell === "number" && !kinds.has(column)) kinds.set(column, "measure");
|
|
4959
|
+
const columnsOf = (kind) => [...kinds].filter(([, value]) => value === kind).map(([column]) => column);
|
|
4960
|
+
const measures = columnsOf("measure");
|
|
4961
|
+
const timed = columnsOf("dimension").flatMap((column) => {
|
|
4962
|
+
const kind = timeKind(column);
|
|
4963
|
+
return kind ? [[column, kind]] : [];
|
|
4964
|
+
});
|
|
4965
|
+
const periods = facts.map((fact) => rowPeriod(fact, timed));
|
|
4966
|
+
const hasTime = timed.length > 0 && periods.every((period) => period !== void 0);
|
|
4967
|
+
const timeColumns = new Set(hasTime ? timed.map(([column]) => column) : []);
|
|
4968
|
+
const dimensions = columnsOf("dimension").filter((column) => !timeColumns.has(column));
|
|
4969
|
+
const labels = [...dimensions, ...hasTime ? [TIME_CODE$1] : []].map(() => /* @__PURE__ */ new Map());
|
|
4970
|
+
const rows = facts.map((fact, index) => {
|
|
4971
|
+
const cells = dimensions.map((column) => {
|
|
4972
|
+
const cell = fact[column];
|
|
4973
|
+
return typeof cell === "string" ? {
|
|
4974
|
+
code: cell.trim(),
|
|
4975
|
+
label: cell.trim()
|
|
4976
|
+
} : null;
|
|
4977
|
+
});
|
|
4978
|
+
if (hasTime) cells.push(periods[index]);
|
|
4979
|
+
cells.forEach((cell, position) => {
|
|
4980
|
+
if (cell) labels[position]?.set(cell.code, cell.label);
|
|
4981
|
+
});
|
|
4982
|
+
return {
|
|
4983
|
+
codes: cells.map((cell) => cell?.code ?? TOTAL_CODE),
|
|
4984
|
+
values: measures.map((measure) => round(fact[measure]))
|
|
4985
|
+
};
|
|
4986
|
+
});
|
|
4987
|
+
const totalOf = (position) => rows.some((row) => row.codes[position] === TOTAL_CODE) ? texts.total : void 0;
|
|
4988
|
+
const variables = dimensions.map((column, position) => toVariable(column.trim(), column.trim(), labels[position] ?? /* @__PURE__ */ new Map(), totalOf(position), false));
|
|
4989
|
+
if (hasTime) {
|
|
4990
|
+
const sorted = [...labels[dimensions.length] ?? []].toSorted(([a], [b]) => a.localeCompare(b, "en", { numeric: true }));
|
|
4991
|
+
variables.push(toVariable(TIME_CODE$1, texts.period, new Map(sorted), totalOf(dimensions.length), true));
|
|
4992
|
+
}
|
|
4993
|
+
const indicator = toVariable(MEASURE_CODE, texts.measure, new Map(measures.map((measure) => [measure, measure.trim()])), void 0, false);
|
|
4994
|
+
return {
|
|
4995
|
+
metadata: {
|
|
4996
|
+
title,
|
|
4997
|
+
variables: [...variables, indicator]
|
|
4998
|
+
},
|
|
4999
|
+
variables,
|
|
5000
|
+
indicator,
|
|
5001
|
+
rows,
|
|
5002
|
+
texts
|
|
5003
|
+
};
|
|
5004
|
+
}
|
|
5005
|
+
/**
|
|
5006
|
+
* Client for be.STAT, the open data API of Statbel (Belgium).
|
|
5007
|
+
*
|
|
5008
|
+
* - Table id = be.STAT view id (a UUID). A view exists in one language only, so the
|
|
5009
|
+
* same table in another language has another id. Labels follow the view's language.
|
|
5010
|
+
* - Search: a local index over `GET /views/` (all 1,377 views in one call) joined with
|
|
5011
|
+
* `GET /datasources/` for the subject description (path) and the last data update.
|
|
5012
|
+
* Both lists are one call each and cached for an hour, so no crawled snapshot is
|
|
5013
|
+
* needed; `listFallback` can still supply one. The list is in no useful order, so
|
|
5014
|
+
* the catalogue order is the last data update, newest first: an old copy of a view
|
|
5015
|
+
* (same title, a data source that stopped) then ranks below the current one.
|
|
5016
|
+
* "Inapplicable" views answer with an empty body and are marked discontinued.
|
|
5017
|
+
* - Metadata and query read `GET /views/{id}/result/JSON`, a flat list of facts.
|
|
5018
|
+
* String columns are dimensions, number columns are indicators (one variable).
|
|
5019
|
+
* Value codes are the trimmed labels; a null cell is the total over that column
|
|
5020
|
+
* (code "_T"), so a variable with totals is optional and a left-out optional
|
|
5021
|
+
* variable keeps only its total rows when there are any. Time columns (Year, Month,
|
|
5022
|
+
* Quarter, Semester in en/nl/fr/de) merge into one "period" variable with codes
|
|
5023
|
+
* such as "2026", "2026M10", "2026Q2" and "2026S1".
|
|
5024
|
+
* - The query filters the cached facts locally and returns one row per indicator.
|
|
5025
|
+
*/
|
|
5026
|
+
function createStatbelClient(options) {
|
|
5027
|
+
const root = options.baseUrl.replace(/\/+$/, "");
|
|
5028
|
+
const maxCells = options.maxCells ?? DEFAULT_MAX_CELLS;
|
|
5029
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
5030
|
+
const request = createTextRequester(options);
|
|
5031
|
+
function get(path, map, ttlSeconds) {
|
|
5032
|
+
const url = `${root}/${path}`;
|
|
5033
|
+
return request(url, { method: "GET" }, map, ttlSeconds, url);
|
|
5034
|
+
}
|
|
5035
|
+
async function listTables(lang) {
|
|
5036
|
+
checkLanguage(lang);
|
|
5037
|
+
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(() => [])]);
|
|
5038
|
+
const sources = new Map(dataSources.map((source) => [source.id, source]));
|
|
5039
|
+
return views.filter((view) => view.locale === lang).map((view) => {
|
|
5040
|
+
const source = sources.get(view.dataSourceId ?? "");
|
|
5041
|
+
const description = source?.descriptions?.[lang]?.trim();
|
|
5042
|
+
const updated = isoDate(source?.lastDataUpdateDate ?? view.lastPublishDate);
|
|
5043
|
+
return {
|
|
5044
|
+
id: view.id,
|
|
5045
|
+
title: view.name.trim(),
|
|
5046
|
+
...description && { path: [description] },
|
|
5047
|
+
...updated && { updated },
|
|
5048
|
+
...view.inapplicable && { discontinued: true }
|
|
5049
|
+
};
|
|
5050
|
+
}).toSorted((a, b) => (b.updated ?? "").localeCompare(a.updated ?? ""));
|
|
5051
|
+
}
|
|
5052
|
+
const tableIndex = createTableIndexLoader(listTables, {
|
|
5053
|
+
fallback: options.listFallback,
|
|
5054
|
+
ttlSeconds: SEARCH_TTL_SECONDS,
|
|
5055
|
+
currentYear: () => now().getUTCFullYear()
|
|
5056
|
+
});
|
|
5057
|
+
async function loadTable(lang, tableId) {
|
|
5058
|
+
checkLanguage(lang);
|
|
5059
|
+
if (!VIEW_ID_PATTERN.test(tableId)) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it.`, 400);
|
|
5060
|
+
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) => {
|
|
5061
|
+
if (err instanceof PxwebError && err.status === 404) throw notFound$1(tableId);
|
|
5062
|
+
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);
|
|
5063
|
+
throw err;
|
|
5064
|
+
});
|
|
5065
|
+
if (!result || result.facts.length === 0) throw new PxwebError(`Table "${tableId}" has no data now. Use search_tables to find a current table.`, 404);
|
|
5066
|
+
const texts = TEXTS[view.locale] ?? EN_TEXTS;
|
|
5067
|
+
const updated = view.dataSourceId ? await get(`datasources/${view.dataSourceId}`, (text) => isoDate(parseJson(text, dataSourceSchema).lastDataUpdateDate), DATA_TTL_SECONDS).catch(() => void 0) : void 0;
|
|
5068
|
+
const name = view.name.trim();
|
|
5069
|
+
const title = updated ? `${name} (${texts.updated}: ${updated})` : name;
|
|
5070
|
+
return toTable(result.facts, title, texts);
|
|
5071
|
+
}
|
|
5072
|
+
const tables = /* @__PURE__ */ new Map();
|
|
5073
|
+
async function cachedTable(lang, tableId) {
|
|
5074
|
+
const key = `${lang}:${tableId}`;
|
|
5075
|
+
const cached = tables.get(key);
|
|
5076
|
+
if (cached && cached.expires > Date.now()) return cached.table;
|
|
5077
|
+
const table = await loadTable(lang, tableId);
|
|
5078
|
+
tables.delete(key);
|
|
5079
|
+
tables.set(key, {
|
|
5080
|
+
expires: Date.now() + DATA_TTL_SECONDS * 1e3,
|
|
5081
|
+
table
|
|
5082
|
+
});
|
|
5083
|
+
const oldest = tables.keys().next().value;
|
|
5084
|
+
if (tables.size > MAX_CACHED_TABLES && oldest !== void 0) tables.delete(oldest);
|
|
5085
|
+
return table;
|
|
5086
|
+
}
|
|
5087
|
+
return {
|
|
5088
|
+
listTables,
|
|
5089
|
+
async search(lang, query, searchOptions) {
|
|
5090
|
+
checkLanguage(lang);
|
|
5091
|
+
return (await tableIndex(lang)).search(query, searchOptions);
|
|
5092
|
+
},
|
|
5093
|
+
async getMetadata(lang, tableId) {
|
|
5094
|
+
return (await cachedTable(lang, tableId)).metadata;
|
|
5095
|
+
},
|
|
5096
|
+
async query(lang, tableId, selections) {
|
|
5097
|
+
const table = await cachedTable(lang, tableId);
|
|
5098
|
+
const byCode = new Map(selections.map((selection) => [selection.code, selection]));
|
|
5099
|
+
let rows = table.rows;
|
|
5100
|
+
table.variables.forEach((variable, position) => {
|
|
5101
|
+
const codes = chosenCodes(variable, byCode.get(variable.code));
|
|
5102
|
+
if (!codes) return;
|
|
5103
|
+
const wanted = new Set(codes);
|
|
5104
|
+
rows = rows.filter((row) => wanted.has(row.codes[position] ?? ""));
|
|
5105
|
+
});
|
|
5106
|
+
table.variables.forEach((variable, position) => {
|
|
5107
|
+
if (!variable.eliminable || byCode.has(variable.code)) return;
|
|
5108
|
+
const totals = rows.filter((row) => row.codes[position] === TOTAL_CODE);
|
|
5109
|
+
if (totals.length > 0) rows = totals;
|
|
5110
|
+
});
|
|
5111
|
+
const indicators = (chosenCodes(table.indicator, byCode.get(MEASURE_CODE)) ?? table.indicator.values).map((code) => table.indicator.values.indexOf(code));
|
|
5112
|
+
const cells = rows.length * indicators.length;
|
|
5113
|
+
if (cells > maxCells) throw new PxwebError(`The query returns ${cells} cells, above the limit of ${maxCells}. Select fewer values.`, 400);
|
|
5114
|
+
const positions = table.variables.map((variable) => new Map(variable.values.map((value, index) => [value, index])));
|
|
5115
|
+
const sorted = rows.map((row) => ({
|
|
5116
|
+
row,
|
|
5117
|
+
key: row.codes.map((code, position) => positions[position]?.get(code) ?? 0)
|
|
5118
|
+
})).toSorted((a, b) => compareKeys(a.key, b.key));
|
|
5119
|
+
return {
|
|
5120
|
+
label: table.metadata.title,
|
|
5121
|
+
columns: [
|
|
5122
|
+
...table.variables.map((variable) => variable.label),
|
|
5123
|
+
table.indicator.label,
|
|
5124
|
+
table.texts.value
|
|
5125
|
+
],
|
|
5126
|
+
rows: sorted.flatMap(({ row, key }) => indicators.map((index) => [
|
|
5127
|
+
...row.codes.map((code, position) => table.variables[position]?.valueLabels[key[position] ?? -1] ?? code),
|
|
5128
|
+
table.indicator.valueLabels[index] ?? "",
|
|
5129
|
+
row.values[index] ?? null
|
|
5130
|
+
]))
|
|
5131
|
+
};
|
|
2417
5132
|
}
|
|
2418
5133
|
};
|
|
2419
5134
|
}
|
|
@@ -2708,6 +5423,15 @@ function createStatcanClient(options) {
|
|
|
2708
5423
|
const DEFAULT_MAX_RESULT_CHARS = 3e4;
|
|
2709
5424
|
const VALUE_CHARS = 10;
|
|
2710
5425
|
const CHARS_PER_TOKEN = 3.5;
|
|
5426
|
+
const CYRILLIC_PERIOD_LETTERS = {
|
|
5427
|
+
М: "M",
|
|
5428
|
+
К: "K"
|
|
5429
|
+
};
|
|
5430
|
+
const periodSortKey = (code) => code.replace(/[МК]/g, (letter) => CYRILLIC_PERIOD_LETTERS[letter] ?? letter);
|
|
5431
|
+
/** The `count` newest period codes, newest last, whatever the API's order. */
|
|
5432
|
+
function newestCodes(values, count) {
|
|
5433
|
+
return values.toSorted((a, b) => periodSortKey(a).localeCompare(periodSortKey(b), "en", { numeric: true })).slice(-count);
|
|
5434
|
+
}
|
|
2711
5435
|
function averageLabelLength(variable, values) {
|
|
2712
5436
|
if (values.length === 0) return 0;
|
|
2713
5437
|
const labels = new Map(variable.values.map((value, index) => [value, variable.valueLabels[index]]));
|
|
@@ -2745,6 +5469,22 @@ function planQuery(metadata, inputs, maxCells, maxResultChars = DEFAULT_MAX_RESU
|
|
|
2745
5469
|
const sizes = [];
|
|
2746
5470
|
for (const variable of metadata.variables) {
|
|
2747
5471
|
const input = inputByCode.get(variable.code);
|
|
5472
|
+
if (input?.latest !== void 0 && variable.latestByCode) {
|
|
5473
|
+
const newest = newestCodes(variable.values, input.latest);
|
|
5474
|
+
selections.push({
|
|
5475
|
+
code: variable.code,
|
|
5476
|
+
selection: {
|
|
5477
|
+
filter: "item",
|
|
5478
|
+
values: newest
|
|
5479
|
+
}
|
|
5480
|
+
});
|
|
5481
|
+
sizes.push({
|
|
5482
|
+
label: variable.label,
|
|
5483
|
+
count: newest.length,
|
|
5484
|
+
labelChars: averageLabelLength(variable, newest)
|
|
5485
|
+
});
|
|
5486
|
+
continue;
|
|
5487
|
+
}
|
|
2748
5488
|
if (input?.latest !== void 0) {
|
|
2749
5489
|
const count = variable.periodsIncomplete ? input.latest : Math.min(input.latest, variable.values.length);
|
|
2750
5490
|
selections.push({
|
|
@@ -2884,7 +5624,7 @@ async function runTool(handler) {
|
|
|
2884
5624
|
return toolError(err.message);
|
|
2885
5625
|
}
|
|
2886
5626
|
console.error("Unexpected tool error", err);
|
|
2887
|
-
return toolError(
|
|
5627
|
+
return toolError(`Unexpected error while reading statistics data${err instanceof Error ? ` (${err.name})` : ""}.`);
|
|
2888
5628
|
}
|
|
2889
5629
|
}
|
|
2890
5630
|
// src/tools/search-tools.ts
|
|
@@ -3059,7 +5799,7 @@ function createPxwebServer(preset, client) {
|
|
|
3059
5799
|
registerTableTools(server, client, preset);
|
|
3060
5800
|
return server;
|
|
3061
5801
|
}
|
|
3062
|
-
/** PxWeb v1 and
|
|
5802
|
+
/** PxWeb v1, PxStat, INE Spain and Portugal, and INSEE have no small list endpoint, so index search reads the crawled snapshot. */
|
|
3063
5803
|
function snapshotTableList(preset, tableSnapshots) {
|
|
3064
5804
|
return async (lang) => {
|
|
3065
5805
|
const snapshot = await tableSnapshots?.(preset.name, lang);
|
|
@@ -3068,12 +5808,13 @@ function snapshotTableList(preset, tableSnapshots) {
|
|
|
3068
5808
|
};
|
|
3069
5809
|
}
|
|
3070
5810
|
function createPresetClient(preset, options) {
|
|
3071
|
-
const { tableSnapshots, ...http } = options;
|
|
5811
|
+
const { tableSnapshots, clientId, ...http } = options;
|
|
3072
5812
|
const api = preset.api ?? "pxweb-v1";
|
|
3073
5813
|
if (api === "pxweb-v1") return createPxwebClient({
|
|
3074
5814
|
...http,
|
|
3075
5815
|
baseUrl: preset.apiBaseUrl,
|
|
3076
5816
|
database: preset.database,
|
|
5817
|
+
timeVariables: preset.timeVariables,
|
|
3077
5818
|
tableIdFromHit: preset.tableIdFromHit,
|
|
3078
5819
|
isArchived: preset.isArchived,
|
|
3079
5820
|
...preset.search === "index" ? { tableList: snapshotTableList(preset, tableSnapshots) } : {}
|
|
@@ -3084,6 +5825,28 @@ function createPresetClient(preset, options) {
|
|
|
3084
5825
|
baseUrl: preset.apiBaseUrl,
|
|
3085
5826
|
tableList: snapshotTableList(preset, tableSnapshots)
|
|
3086
5827
|
});
|
|
5828
|
+
if (api === "ine-es") return createIneEsClient({
|
|
5829
|
+
...http,
|
|
5830
|
+
baseUrl: preset.apiBaseUrl,
|
|
5831
|
+
tableList: snapshotTableList(preset, tableSnapshots)
|
|
5832
|
+
});
|
|
5833
|
+
if (api === "ine-pt") return createInePtClient({
|
|
5834
|
+
...http,
|
|
5835
|
+
baseUrl: preset.apiBaseUrl,
|
|
5836
|
+
maxCells: preset.maxCells,
|
|
5837
|
+
tableList: snapshotTableList(preset, tableSnapshots)
|
|
5838
|
+
});
|
|
5839
|
+
if (api === "insee") return createInseeClient({
|
|
5840
|
+
...http,
|
|
5841
|
+
baseUrl: preset.apiBaseUrl,
|
|
5842
|
+
maxCells: preset.maxCells,
|
|
5843
|
+
tableList: snapshotTableList(preset, tableSnapshots)
|
|
5844
|
+
});
|
|
5845
|
+
if (api === "ons") return createOnsClient({
|
|
5846
|
+
...http,
|
|
5847
|
+
baseUrl: preset.apiBaseUrl,
|
|
5848
|
+
maxCells: preset.maxCells
|
|
5849
|
+
});
|
|
3087
5850
|
if (api === "singstat") return createSingstatClient({
|
|
3088
5851
|
...http,
|
|
3089
5852
|
baseUrl: preset.apiBaseUrl
|
|
@@ -3097,9 +5860,34 @@ function createPresetClient(preset, options) {
|
|
|
3097
5860
|
if (!preset.sdmxAgency) throw new Error("An sdmx preset needs sdmxAgency.");
|
|
3098
5861
|
return createSdmxClient({
|
|
3099
5862
|
...indexed,
|
|
3100
|
-
agency: preset.sdmxAgency
|
|
5863
|
+
agency: preset.sdmxAgency,
|
|
5864
|
+
languages: preset.languages
|
|
3101
5865
|
});
|
|
3102
5866
|
}
|
|
5867
|
+
if (api === "statbel") return createStatbelClient({
|
|
5868
|
+
...indexed,
|
|
5869
|
+
maxCells: preset.maxCells
|
|
5870
|
+
});
|
|
5871
|
+
if (api === "czso") return createCzsoClient({
|
|
5872
|
+
...indexed,
|
|
5873
|
+
maxCells: preset.maxCells
|
|
5874
|
+
});
|
|
5875
|
+
if (api === "ibge") return createIbgeClient({
|
|
5876
|
+
...indexed,
|
|
5877
|
+
maxCells: preset.maxCells,
|
|
5878
|
+
...tableSnapshots && { crawledList: async (lang) => (await tableSnapshots(preset.name, lang))?.docs }
|
|
5879
|
+
});
|
|
5880
|
+
if (api === "bdl") return createBdlClient({
|
|
5881
|
+
...indexed,
|
|
5882
|
+
maxCells: preset.maxCells,
|
|
5883
|
+
...clientId && { clientId },
|
|
5884
|
+
...tableSnapshots && { crawledList: async (lang) => (await tableSnapshots(preset.name, lang))?.docs }
|
|
5885
|
+
});
|
|
5886
|
+
if (api === "osp") return createOspClient({
|
|
5887
|
+
...indexed,
|
|
5888
|
+
maxCells: preset.maxCells,
|
|
5889
|
+
...tableSnapshots && { crawledList: async (lang) => (await tableSnapshots(preset.name, lang))?.docs }
|
|
5890
|
+
});
|
|
3103
5891
|
if (api === "statcan-wds") return createStatcanClient(indexed);
|
|
3104
5892
|
if (api === "eurostat") return createEurostatClient(indexed);
|
|
3105
5893
|
if (api === "cbs-odata") return createCbsODataClient(indexed);
|
|
@@ -3115,6 +5903,7 @@ function createPresetServer(preset, options = {}) {
|
|
|
3115
5903
|
cache: options.cache,
|
|
3116
5904
|
fetch: options.fetch,
|
|
3117
5905
|
tableSnapshots: options.tableSnapshots,
|
|
5906
|
+
...options.clientId && { clientId: options.clientId },
|
|
3118
5907
|
userAgent: options.userAgent ?? `${preset.name}-mcp/${preset.version}`
|
|
3119
5908
|
}));
|
|
3120
5909
|
}
|
|
@@ -3236,4 +6025,4 @@ function createMultiServer(entries, options) {
|
|
|
3236
6025
|
});
|
|
3237
6026
|
return server;
|
|
3238
6027
|
}
|
|
3239
|
-
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 };
|
|
6028
|
+
export { DEFAULT_MAX_RESULT_CHARS, PxwebError, QueryPlanError, SEARCH_INDEX_VERSION, SNAPSHOT_VERSION, asPrebuiltIndex, bucketSnapshotReader, buildSearchIndex, createBdlClient, 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 };
|