Files
CatoandClaude Opus 5.5 266a4d5b68 perf: the World Bank fetched from a runner; statistics in one query; imports and deploys skip what did not change (#576)
* perf(places): place pages kept for an hour; the run log indexed and bounded; a place's country by its ISO code

- A place's country (its profile, budget, photograph and share card) is its
  own ISO 3166-1 code, else its pack's root, else a world nation's slug, never
  the last slug segment: the Djibouti Region (world/djibouti/djibouti), the
  City of San Marino and the US state of Georgia showed a country's page.
- /places/[...slug] is ISR for an hour with nothing built ahead, instead of
  force-dynamic: its queries run about once an hour per place and language.
- place_import_runs gets indexes on (source_key, started_at) and (status,
  finished_at); sourceRuns is one DISTINCT ON query, read once per call and
  passed to the worker.
- Runs a stopped process left `running` are closed as failed after two worker
  budgets, so they are reported once and backed off.
- The worker starts on a day with nothing due as well, for the daily rebuild
  of the ancestors view.
- verify runs places:world-countries --check, now comparing the countries the
  file holds rather than CLDR's names; geography:world writes its registry as
  Prettier formats it. The engineering audit's claim that both were checked is
  corrected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k

* feat(places): a source a publisher refuses to the box is fetched daily from a runner

The World Bank's API answers the box HTTP 403 (2026-11-10), and its source is
the only one for eight statistics in about 210 countries: none had ever loaded
in production, and the box's queue failed it and alerted every cycle.

- A source may say `fetchFrom: "runner"`. The box's worker leaves it out of
  its queue; `pnpm run places:queue --from runner` drains it, with the same
  cadence, retries and run log.
- places-load-cloud.yml runs that daily (and on dispatch with kind=queue),
  through its SSH tunnel to the production database, copying the snapshots
  back to the box as it already did for hand-dispatched loads.
- The World Bank's source is the one runner source; a test fails if another
  side gets it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k

* refactor(statistics): a governance indicator is five lines; shared scopes and sentence()

- statistic-templates.ts holds sentence() (moved from the budgets' metrics),
  the scope of general government at every level and the scope of a
  perception score, and wgiMetric({ key, code, name }).
- The six Worldwide Governance Indicators are written with wgiMetric: 204
  lines become 66, and the generated metrics were checked identical to the
  hand-written ones, word for word in every language.
- Government consumption and tax revenue share one scope sentence instead of
  two copies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k

* perf(statistics): every statistic in one query; a new statistic adds no queries

- loadSeriesFor(db, config, keys, locale, { latestOnly }) reads any number of
  metrics in one facts query and names their places once. latestOnly keeps
  each place's latest value within the metric's plausible band, as a chart's
  screening leaves it.
- /statistics: 4 queries instead of 136 (34 statistics x loadSeries +
  placeLabels); 104-131 ms instead of 325-548 ms on a database holding the
  live OECD, Eurostat and World Bank figures. Checked identical to the old
  per-metric query for all 34 statistics (2,403 series), and latest-only
  identical to the screened full series.
- The dimension, event, compare and saved-view pages load their metrics in
  one call each.
- placeLabels groups names and codes once instead of filtering every row per
  place, and builds one Intl.DisplayNames for the list.
- facts gets a partial index on (metric_key, jurisdiction_id, valid_from DESC)
  for current, unvaried figures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k

* perf(ci): a deploy that touched no Places data clones, installs and reads nothing

places-data.yml ran after every deploy: a full clone and pnpm install on the
memory-tight box, a runner install, and 798 image requests through the live
site, though most deploys change no Places data and no photograph.

- A first job diffs the deployed commit against the one this workflow last
  loaded successfully (a failed load is retried by the next deploy; a
  dispatch, perhaps a dry run, does not count). The import runs when Places
  data, its config, adapters or importer changed; the photo warm-up when
  photos.json or the photo code changed. A dispatch runs both.
- The box fetches the deployed commit at depth 1 instead of cloning the
  repository's history.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k

* perf(places): an old /places/<slug> link is redirected after a two-query lookup

It ran the full place-page load (about 17 queries) only to learn whether the
world pack holds the place. Links no longer point there (#572); the redirect
stays for old ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k

* perf(law): a register import reads only its own register, and stops when nothing changed

About 34 register imports run every week. Each made one query per law
authority (311, one after another) and read every current act, title, number
and page in the law database, however small its register; and
missingFromSource counted every act sharing the identity scheme, so it was
wrong for every publisher_ref register.

- A retrieval whose acts, as read, are those the register last applied is
  recorded as applied and `unchanged` and goes no further. The recorded
  importer version carries a hash of the rows read, so the same bytes read by
  a changed reader are applied again.
- The authorities the retrieval names are resolved to places in one query.
- Known acts are read for the identities the retrieval lists, a thousand at
  a time, with their titles, numbers and pages for those acts only.
- missingFromSource counts only the identities this register itself stated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k

* fix(law): the weekly sync waits for a heavy load; verify reads a sample, a second apart

- law-sync.yml took /tmp/solon-law-load.lock while a heavy load dispatched by
  hand (law-text.yml) takes /tmp/solon-law-load-heavy.lock, so the two never
  excluded each other, the pairing that ran the box out of memory on
  2026-11-08. The sync now takes the heavy lock, and after two hours' wait
  leaves that week's sync be, saying so.
- `law:text verify` read its sample size from --limit, which the workflow
  passes every source (1,500 by default): a dispatch read 1,500 publisher
  pages back to back. It reads --sample (30 by default) and pauses a second
  between reads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k

* fix(law): an act held in two languages is listed once, titled in the reader's language

recentChanges joined every current title to every current version, so an act
held in German and French appeared up to four times in a place's recent
changes (with repeated React keys), and a constitution's title on the
profile card came out in whichever language the database returned first.

- actTitleSql (src/lib/law/act-title.ts): an act's current title in the
  reader's language, else its first other language, as one value.
- recentChanges takes the reader's language and keeps one row an act, its
  latest current version; the profile's constitution lookup uses the same
  title rule.
- An integration test holds one act in two languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k

* refactor(generators): one polite Wikidata client; scratch scripts removed

world-profiles, places-photos and law-plan each carried their own SPARQL
helper: world-profiles retried any error four times (a 400 included), law-plan
did not retry at all, and each sent its own user agent. They use the shared
client (src/lib/wikidata/query.ts), which waits as long as the server asks on
a 429 or 503 and fails at once on anything else. law-plan now checks that
Constitute's index answered before reading it. scripts/_ws.ts and _ws2.ts,
committed scratch files, are deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k

* refactor(statistics): one rule a unit, so a statistic in a new unit is a line in units.ts

What a unit means was decided in six places: the chart scale (present.ts),
the label (shared.ts), the brief's value text and points (brief.ts), the
profile figure's format (place-figures.tsx), the axis panel's percent sign
and the divisor a published percentage is stored with (sources.ts). A
statistic in a count or a currency would have been shown with no unit, or
scaled wrong, in some of them.

src/lib/config/places/units.ts holds, per unit, its scale and decimals,
whether publishers print it in per cent, whether it is a percentage, and the
key of its words under Statistics.units; every site reads it. A test fails
when a unit's words are missing in a language. Nothing shown changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k

* perf(law): a place's page counts its own authorities' acts, not the whole register's

loadPlaceLaw ran loadLawCoverage, three aggregates over every act and version
in the law database, to show the counts of a handful of authorities: the
place's chain and the parts of its nearest. loadLawCoverage takes an optional
list of authorities and counts only theirs; a place's page passes the ones it
shows. Checked against a database of 9,119 acts in 14 authorities: the counts
of all 132 shown authorities are the same as before. The pages that show the
whole register still count it all.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k

* fix: findings of an adversarial review of this stack

- Place pages are rendered on every visit again: ISR made Next keep every
  rendered URL on the server's disk (a few thousand places in five languages,
  and any made-up path besides, with no bound), and kept a not-found path as
  not found for an hour. A view's cost is cut where it is spent instead.
- A failed source retried by a once-a-day queue (the runner's) waited a full
  24 hours from the failed run's start, so the next day's run, starting a few
  minutes earlier, missed it: retries allow two hours' slack.
- Abandoned runs are closed after eight hours, longer than any import runs
  from the box or a runner (a workflow job stops at six), instead of after
  two worker budgets.
- One concurrency group for every cloud load, so the daily queue and a fetch
  dispatched by hand never write the same source at once.
- The saved-axis page scores, as the index does, on each place's latest
  plausible value; loadSeriesFor dedupes its keys.
- places-data runs the import weekly whatever changed, for a file applied
  while some of its places were not held (`+partial`) or one whose import
  failed.
- An unchanged register import still reports what the register no longer
  lists.
- The shared Wikidata client retries 500, 502 and 504 too, as world-profiles
  did; a bad query still fails at once.
- The weekly law sync waits 45 minutes for the heavy lock, not two hours.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-12 09:11:31 +01:00

539 lines
23 KiB
TypeScript

/**
* Load the text of the law from its publisher (design: docs/design/2026-10-law-as-data.md, L1).
*
* pnpm run law:text fedlex [--lang de] [--limit 200] [--day YYYY-MM-DD] [--dry-run]
* pnpm run law:text lilex [--limit 200] [--lr 210.0] [--dry-run]
* pnpm run law:text cantons [--authority zh] [--limit 200] [--dry-run]
* pnpm run law:text legilux [--limit 200] [--dry-run] (Luxembourg: the register and each act's applicable text)
* pnpm run law:text riigiteataja [--limit 500] [--dry-run] (Estonia: the national acts in force, and each one's text)
* pnpm run law:text parliamentrso [--limit 60] [--term 2] [--dry-run] (South Ossetia: the Parliament's register of acts, at the site's 90-second crawl-delay; --limit is listing pages, 10 acts each)
* pnpm run law:text presidentruo [--limit 30] [--dry-run] (South Ossetia: the President's register of decrees, treaties and documents from the site's API, 100 a page)
* pnpm run law:text parliamentrso-text|presidentruo-text [--limit 50] [--act 89961,89934] [--stubs] [--dry-run] (South Ossetia: the text of the acts the register holds, cut into articles; the Parliament's at its 90-second crawl-delay, the President's a second apart; a page that only links the act's Word file is read from the file, and --stubs reads again the acts held only as such a page)
* pnpm run law:text plan-constitutions [--country RU,UA] [--again] [--dry-run] (every country's constitution from the source data/law/plan.json chose, stored as a copy with who keeps it and the day read; docs/design/2026-11-law-of-every-country.md)
* pnpm run law:text pravo-gov-ru [--authority ru,ru-se] [--limit 5] [--dry-run] (Russia: the federal laws and a subject's laws listed by the official publication portal, 200 a page, two seconds apart; the register only, since the portal's robots.txt disallows the files that hold the texts)
* pnpm run law:text eurlex [--limit 1000] [--year 2016,2024] [--dry-run] (European Union: regulations and directives in force, in English; a dry run reads and cuts `limit` texts and stores nothing)
* pnpm run law:text ukleg [--limit 1000] [--type ukpga,uksi] [--year 2018,2024] [--dry-run] (United Kingdom: Public General Acts and Statutory Instruments from legislation.gov.uk, a year at a time, newest first; paced by the site's robots.txt crawl-delay, 5 seconds when checked)
* pnpm run law:text ris [--limit 500] [--act 10001622,10000138] [--dry-run] (Austria: the consolidated federal acts in force from the RIS, in German; a dry run reads and cuts `limit` texts and stores nothing)
* pnpm run law:text gii [--limit 1500] [--again] [--act bgb,gg] [--dry-run] (Germany: the federal acts in force, each act's XML cut into paragraphs, articles and annexes; about a request a second; an act read this week is skipped unless --again, and a new version is stored only when the text changed)
* pnpm run law:text wyoleg [--limit 50] [--again] [--title 15] [--dry-run] (Wyoming: each title of the statutes and the Constitution)
* pnpm run law:text gcnh [--limit 1000] [--again] [--title III] [--chapter 39] [--dry-run] (New Hampshire: each chapter of the RSA, about 11 seconds apart)
* pnpm run law:text lexwork [--host zug.tlex.ch] [--limit 500] [--dry-run] (communes' LexWork collections: acts and their dated versions)
* pnpm run law:text refresh [--limit 500] [--dry-run] (read held cantonal and Lilex documents again, oldest first; a changed one becomes a new version)
* pnpm run law:text recut [--authority lu] [--limit 2000] [--dry-run] (cut the held cantonal acts again, from their snapshots)
* pnpm run law:text recut-eurlex [--limit 5000] [--dry-run] (the same for the EU acts held)
* pnpm run law:text recut-municipal [--authority ch-ne-neuchatel] [--limit 5000] [--dry-run] (the same for the communes' PDFs held)
* pnpm run law:text recut-lilex [--limit 5000] [--dry-run] (the same for Liechtenstein's acts held: the text outside the articles)
* pnpm run law:text recut-gii [--limit 5000] [--dry-run] (the same for the German federal acts held)
* pnpm run law:text recut-ukleg [--limit 5000] [--dry-run] (the same for the UK acts held)
* pnpm run law:text verify --authority li [--sample 30] (read a random sample of held HTML acts again, a second apart, and report how much of each page's words the stored text holds; --limit, a batch size for the loaders, is not read here)
* pnpm run law:text zhlex [--limit 200] [--dry-run]
* pnpm run law:text municipal --publisher zurich-city|all [--history] [--limit 200] [--dry-run]
*
* Resumable: acts whose version is already held are skipped, so a run limited to
* N continues where the last stopped. Exit 1 when an act failed, so a runner alerts.
*/
import {
recutCantonalText,
recutEurLexText,
recutGiiText,
recutLilexText,
recutPublisherText,
recutUkLegText,
} from "@/lib/law/text/recut";
import { importLegilux } from "@/lib/law/text/import-legilux";
import { importWyoleg } from "@/lib/law/text/import-wyoleg";
import { importGcnh } from "@/lib/law/text/import-gcnh";
import { registerParliament, registerPresident } from "@/lib/law/text/import-so-registers";
import { registerPravoGovRu } from "@/lib/law/text/import-pravo-gov-ru";
import { importPlanCopies } from "@/lib/law/text/import-plan-copies";
import { readPlan } from "@/lib/law/plan/load";
import { importSoText } from "@/lib/law/text/import-so-text";
import { importRiigiTeataja } from "@/lib/law/text/import-riigiteataja";
import { importEurLex } from "@/lib/law/text/import-eurlex";
import { importUkLeg } from "@/lib/law/text/import-ukleg";
import { importRis } from "@/lib/law/text/import-ris";
import { importGii } from "@/lib/law/text/import-gii";
import { importLexwork } from "@/lib/law/text/import-lexwork";
import { refreshText } from "@/lib/law/text/refresh";
import { verifyAuthority } from "@/lib/law/text/verify";
import { FEDLEX, LILEX } from "@/lib/config/law";
import { db } from "@/lib/db/client";
import { defaultSnapshotStore } from "@/lib/places/importer/snapshots";
import { importFedlexText } from "@/lib/law/text/import";
import { importCantonalText } from "@/lib/law/text/import-cantonal";
import { importLilexText } from "@/lib/law/text/import-lilex";
import { PUBLISHERS } from "@/lib/law/publishers";
import { loadPublisher } from "@/lib/law/publishers/load";
import { importZhlexText } from "@/lib/law/text/import-zhlex";
const args = process.argv.slice(2);
const flag = (name: string): string | undefined => {
const at = args.indexOf(`--${name}`);
return at >= 0 ? args[at + 1] : undefined;
};
const [sourceKey] = args.filter((a, i) => !a.startsWith("--") && !args[i - 1]?.startsWith("--"));
async function main(): Promise<number> {
if (sourceKey === "municipal") {
// `--publisher all` reads every commune in config, one after another; one that fails does not stop the rest.
const which = flag("publisher") ?? "";
const adapters =
which === "all" ? Object.values(PUBLISHERS) : [PUBLISHERS[which]].filter(Boolean);
if (adapters.length === 0) {
console.error(`--publisher is all, or one of: ${Object.keys(PUBLISHERS).join(", ")}`);
return 2;
}
let failures = 0;
for (const adapter of adapters) {
try {
const report = await loadPublisher(db, adapter!, {
today: new Date().toISOString().slice(0, 10),
history: args.includes("--history"),
limit: flag("limit") ? Number(flag("limit")) : undefined,
snapshots: defaultSnapshotStore(),
dryRun: args.includes("--dry-run"),
onProgress: (message) => console.error(message),
});
failures += report.failures.length;
console.log(
JSON.stringify(
{
publisher: adapter!.key,
...report,
failures: report.failures.slice(0, 30),
failureCount: report.failures.length,
},
null,
2,
),
);
} catch (error) {
failures++;
console.log(JSON.stringify({ publisher: adapter!.key, error: String(error) }));
}
}
return failures > 0 ? 1 : 0;
}
if (sourceKey === "verify") {
const authority = flag("authority");
if (!authority) throw new Error("verify needs --authority, e.g. li");
const report = await verifyAuthority(db, {
authority,
// Its own flag: the workflow passes every source a batch --limit (1,500 by default), and
// reading that many publisher pages back to back is not a sample.
sample: flag("sample") ? Number(flag("sample")) : 30,
onProgress: (message) => console.error(message),
});
// One line an act, the lowest first, then the totals: the workflow shows only the end of the output.
const lines = [...report.acts]
.sort((x, y) => (x.coverage?.ratio ?? -1) - (y.coverage?.ratio ?? -1))
.map((a) =>
a.coverage
? `${(a.coverage.ratio * 100).toFixed(1)}% bag ` +
`${a.sequence ? `${(a.sequence.ratio * 100).toFixed(1)}% in order, longest missing run ${a.sequence.longestMissing.words}` : "order not compared"}` +
`${a.wordForWord ? " WORD-FOR-WORD" : a.sequence?.afterTitleBlock ? ` WORD-FOR-WORD-AFTER-${a.sequence.leading}-WORD-TITLE-BLOCK` : ""} page ${a.coverage.pageWords} held ${a.coverage.storedWords} ` +
`${a.title.slice(0, 40)} | missing: ${a.coverage.missing
.slice(0, 8)
.map((m) => `${m.word}x${m.count}`)
.join(" ")}`
: a.scanned
? `SCANNED (not compared) ${a.title.slice(0, 40)}`
: `ERROR ${a.title.slice(0, 40)} | ${a.error}`,
);
console.log(lines.join("\n"));
// What the three lowest pages hold that the provisions do not, and how those pages are built.
for (const a of [...report.acts]
.filter((x) => x.coverage)
.sort((x, y) => x.coverage!.ratio - y.coverage!.ratio)
.slice(0, 3)) {
console.log(`LOW ${a.title.slice(0, 30)} ${a.url} | classes: ${a.classes}`);
for (const run of a.runs ?? []) console.log(` RUN ${run.slice(0, 260)}`);
if (a.around) console.log(` HTML ${a.around.slice(0, 480)}`);
}
console.log(
JSON.stringify({
authority: report.authority,
inForceHtmlVersions: report.inForceHtmlVersions,
sampled: report.sampled,
meanRatio: Number(report.meanRatio.toFixed(4)),
short: report.short,
wordForWord: report.wordForWord,
scanned: report.scanned,
afterTitleBlock: report.afterTitleBlock,
failed: report.failed,
}),
);
return report.short > 0 || report.failed > 0 ? 1 : 0;
}
if (sourceKey === "refresh") {
const report = await refreshText(db, {
today: new Date().toISOString().slice(0, 10),
limit: flag("limit") ? Number(flag("limit")) : undefined,
snapshots: defaultSnapshotStore(),
dryRun: args.includes("--dry-run"),
onProgress: (message) => console.error(message),
});
console.log(
JSON.stringify(
{ ...report, failures: report.failures.slice(0, 30), failureCount: report.failures.length },
null,
2,
),
);
return report.failures.length > report.checked / 2 ? 1 : 0;
}
if (sourceKey === "lexwork") {
const report = await importLexwork(db, {
today: new Date().toISOString().slice(0, 10),
host: flag("host"),
limit: flag("limit") ? Number(flag("limit")) : undefined,
snapshots: defaultSnapshotStore(),
dryRun: args.includes("--dry-run"),
onProgress: (message) => console.error(message),
});
console.log(
JSON.stringify(
{ ...report, failures: report.failures.slice(0, 30), failureCount: report.failures.length },
null,
2,
),
);
return report.failures.length > 0 ? 1 : 0;
}
if (sourceKey === "legilux") {
const report = await importLegilux(db, {
limit: flag("limit") ? Number(flag("limit")) : undefined,
snapshots: defaultSnapshotStore(),
dryRun: args.includes("--dry-run"),
onProgress: (message) => console.error(message),
});
console.log(
JSON.stringify(
{ ...report, failures: report.failures.slice(0, 30), failureCount: report.failures.length },
null,
2,
),
);
return report.failures.length > 0 ? 1 : 0;
}
if (sourceKey === "plan-constitutions") {
const report = await importPlanCopies(db, readPlan(), {
countries: flag("country")?.split(","),
again: args.includes("--again"),
snapshots: defaultSnapshotStore(),
dryRun: args.includes("--dry-run"),
onProgress: (message: string) => console.error(message),
});
console.log(JSON.stringify(report, null, 2));
return report.failures.length > 0 ? 1 : 0;
}
if (sourceKey === "pravo-gov-ru") {
const reports = await registerPravoGovRu(db, {
authorities: flag("authority")?.split(","),
limit: flag("limit") ? Number(flag("limit")) : undefined,
snapshots: defaultSnapshotStore(),
dryRun: args.includes("--dry-run"),
onProgress: (message: string) => console.error(message),
});
console.log(JSON.stringify(reports, null, 2));
return reports.some((r) => r.register.status === "failed") ? 1 : 0;
}
if (sourceKey === "parliamentrso" || sourceKey === "presidentruo") {
const options = {
limit: flag("limit") ? Number(flag("limit")) : undefined,
term: flag("term"),
snapshots: defaultSnapshotStore(),
dryRun: args.includes("--dry-run"),
onProgress: (message: string) => console.error(message),
};
const report =
sourceKey === "parliamentrso"
? await registerParliament(db, options)
: await registerPresident(db, options);
console.log(JSON.stringify(report, null, 2));
return report.register.status === "failed" ? 1 : 0;
}
if (sourceKey === "parliamentrso-text" || sourceKey === "presidentruo-text") {
const report = await importSoText(
db,
sourceKey === "parliamentrso-text" ? "parliamentrso" : "presidentruo",
{
limit: flag("limit") ? Number(flag("limit")) : undefined,
ids: flag("act")?.split(","),
stubs: args.includes("--stubs"),
snapshots: defaultSnapshotStore(),
dryRun: args.includes("--dry-run"),
onProgress: (message) => console.error(message),
},
);
console.log(
JSON.stringify(
{ ...report, failures: report.failures.slice(0, 5), failureCount: report.failures.length },
null,
2,
),
);
return report.failures.length > 0 ? 1 : 0;
}
if (sourceKey === "riigiteataja") {
const report = await importRiigiTeataja(db, {
limit: flag("limit") ? Number(flag("limit")) : undefined,
snapshots: defaultSnapshotStore(),
dryRun: args.includes("--dry-run"),
onProgress: (message) => console.error(message),
});
console.log(
JSON.stringify(
{ ...report, failures: report.failures.slice(0, 5), failureCount: report.failures.length },
null,
2,
),
);
return report.failures.length > 0 ? 1 : 0;
}
if (sourceKey === "eurlex") {
const years = flag("year")
?.split(",")
.map(Number)
.filter((y) => Number.isInteger(y) && y > 1900);
const report = await importEurLex(db, {
limit: flag("limit") ? Number(flag("limit")) : undefined,
years: years?.length ? years : undefined,
snapshots: defaultSnapshotStore(),
dryRun: args.includes("--dry-run"),
onProgress: (message) => console.error(message),
});
console.log(
JSON.stringify(
{ ...report, failures: report.failures.slice(0, 10), failureCount: report.failures.length },
null,
2,
),
);
return report.failures.length > 0 ? 1 : 0;
}
if (sourceKey === "ukleg") {
const numbers = (value: string | undefined) =>
value
?.split(",")
.map(Number)
.filter((y) => Number.isInteger(y) && y > 1200);
const report = await importUkLeg(db, {
limit: flag("limit") ? Number(flag("limit")) : undefined,
types: flag("type")?.split(",").filter(Boolean),
years: numbers(flag("year"))?.length ? numbers(flag("year")) : undefined,
snapshots: defaultSnapshotStore(),
dryRun: args.includes("--dry-run"),
onProgress: (message) => console.error(message),
});
console.log(
JSON.stringify(
{ ...report, failures: report.failures.slice(0, 10), failureCount: report.failures.length },
null,
2,
),
);
return report.failures.length > 0 ? 1 : 0;
}
if (sourceKey === "ris") {
const report = await importRis(db, {
limit: flag("limit") ? Number(flag("limit")) : undefined,
only: flag("act")
?.split(",")
.filter((n) => /^\d+$/.test(n)),
snapshots: defaultSnapshotStore(),
dryRun: args.includes("--dry-run"),
onProgress: (message) => console.error(message),
});
console.log(
JSON.stringify(
{ ...report, failures: report.failures.slice(0, 10), failureCount: report.failures.length },
null,
2,
),
);
return report.failures.length > 0 ? 1 : 0;
}
if (sourceKey === "gii") {
const only = flag("act")
?.split(",")
.map((a) => a.trim())
.filter(Boolean);
const report = await importGii(db, {
limit: flag("limit") ? Number(flag("limit")) : undefined,
only: only?.length ? only : undefined,
again: args.includes("--again"),
snapshots: defaultSnapshotStore(),
dryRun: args.includes("--dry-run"),
onProgress: (message) => console.error(message),
});
console.log(
JSON.stringify(
{ ...report, failures: report.failures.slice(0, 10), failureCount: report.failures.length },
null,
2,
),
);
return report.failures.length > 0 ? 1 : 0;
}
if (sourceKey === "wyoleg") {
const report = await importWyoleg(db, {
limit: flag("limit") ? Number(flag("limit")) : undefined,
again: args.includes("--again"),
only: flag("title") ? [flag("title")!] : undefined,
snapshots: defaultSnapshotStore(),
dryRun: args.includes("--dry-run"),
onProgress: (message) => console.error(message),
});
console.log(JSON.stringify({ ...report, failureCount: report.failures.length }, null, 2));
return report.failures.length > 0 ? 1 : 0;
}
if (sourceKey === "gcnh") {
const report = await importGcnh(db, {
limit: flag("limit") ? Number(flag("limit")) : undefined,
again: args.includes("--again"),
titles: flag("title") ? [flag("title")!] : undefined,
chapters: flag("chapter") ? [flag("chapter")!] : undefined,
snapshots: defaultSnapshotStore(),
dryRun: args.includes("--dry-run"),
onProgress: (message) => console.error(message),
});
console.log(
JSON.stringify(
{ ...report, failures: report.failures.slice(0, 30), failureCount: report.failures.length },
null,
2,
),
);
return report.failures.length > 0 ? 1 : 0;
}
if (
sourceKey === "recut" ||
sourceKey === "recut-eurlex" ||
sourceKey === "recut-gii" ||
sourceKey === "recut-lilex" ||
sourceKey === "recut-ukleg" ||
sourceKey === "recut-municipal"
) {
const recut =
sourceKey === "recut"
? recutCantonalText
: sourceKey === "recut-ukleg"
? recutUkLegText
: sourceKey === "recut-gii"
? recutGiiText
: sourceKey === "recut-lilex"
? recutLilexText
: sourceKey === "recut-municipal"
? recutPublisherText
: recutEurLexText;
const report = await recut(db, {
authority: flag("authority"),
limit: flag("limit") ? Number(flag("limit")) : undefined,
snapshots: defaultSnapshotStore(),
dryRun: args.includes("--dry-run"),
onProgress: (message) => console.error(message),
});
console.log(
JSON.stringify(
{ ...report, failures: report.failures.slice(0, 30), failureCount: report.failures.length },
null,
2,
),
);
return report.failures.length > 0 ? 1 : 0;
}
if (sourceKey === "zhlex") {
const report = await importZhlexText(db, {
limit: flag("limit") ? Number(flag("limit")) : undefined,
snapshots: defaultSnapshotStore(),
dryRun: args.includes("--dry-run"),
onProgress: (message) => console.error(message),
});
console.log(
JSON.stringify(
{ ...report, failures: report.failures.slice(0, 30), failureCount: report.failures.length },
null,
2,
),
);
return report.failures.length > 0 ? 1 : 0;
}
if (sourceKey === "cantons") {
const report = await importCantonalText(db, {
today: new Date().toISOString().slice(0, 10),
limit: flag("limit") ? Number(flag("limit")) : undefined,
authority: flag("authority"),
snapshots: defaultSnapshotStore(),
dryRun: args.includes("--dry-run"),
onProgress: (message) => console.error(message),
});
console.log(
JSON.stringify(
{ ...report, failures: report.failures.slice(0, 30), failureCount: report.failures.length },
null,
2,
),
);
return report.refusedForSpace || report.failures.length > 0 ? 1 : 0;
}
if (sourceKey === LILEX.key) {
const report = await importLilexText(db, {
today: new Date().toISOString().slice(0, 10),
limit: flag("limit") ? Number(flag("limit")) : undefined,
lr: flag("lr"),
snapshots: defaultSnapshotStore(),
dryRun: args.includes("--dry-run"),
onProgress: (message) => console.error(message),
});
console.log(
JSON.stringify(
{
...report,
noPageId: report.noPageId.slice(0, 20),
noPageIdCount: report.noPageId.length,
failures: report.failures.slice(0, 30),
failureCount: report.failures.length,
},
null,
2,
),
);
return report.stoppedByChallenge || report.failures.length > 0 ? 1 : 0;
}
if (sourceKey !== FEDLEX.key) {
console.error(
`usage: pnpm run law:text ${FEDLEX.key}|${LILEX.key}|cantons|zhlex|municipal [--lang de] [--limit N] [--day YYYY-MM-DD] [--dry-run]`,
);
return 2;
}
const report = await importFedlexText(db, {
lang: flag("lang") ?? "de",
day: flag("day") ?? new Date().toISOString().slice(0, 10),
limit: flag("limit") ? Number(flag("limit")) : undefined,
snapshots: defaultSnapshotStore(),
dryRun: args.includes("--dry-run"),
onProgress: (message) => console.error(message),
});
console.log(
JSON.stringify(
{
...report,
notInRegister: report.notInRegister.slice(0, 20),
notInRegisterCount: report.notInRegister.length,
},
null,
2,
),
);
return report.failures.length > 0 ? 1 : 0;
}
main().then(
(code) => process.exit(code),
(error: unknown) => {
console.error(error);
process.exit(2);
},
);