@nulib/authoritex-js
v0.2.0
Published
TypeScript client for searching and fetching controlled vocabulary authority terms.
Downloads
200
Keywords
Readme
@nulib/authoritex-js
TypeScript client for searching and fetching normalized authority records across FAST, Library of Congress, GeoNames, Homosaurus, and related sources.
- npm:
@nulib/authoritex-js - repo: https://github.com/nulib-labs/authoritex-js
- companion MCP server:
@nulib/authoritex-mcp
Install
npm install @nulib/authoritex-js@nulib/authoritex-js is an ESM package and uses the runtime fetch implementation. It works in Node.js 18+ and browser environments, subject to the CORS behavior of each authority service.
Quick Start
import { search, fetch } from "@nulib/authoritex-js";
const results = await search("fast", "Northwestern University", 5);
console.log(results);
const record = await fetch("http://id.loc.gov/authorities/names/n79091588");
console.log(record.label);search() and fetch() make live network requests. GeoNames lookups require a GEONAMES_USERNAME environment variable unless you pass credentials through AuthoritexClient.
GEONAMES_USERNAME=your_username node app.jsAuthoritexClient
Use AuthoritexClient when you want explicit control over options such as GeoNames credentials or redirect handling.
import { AuthoritexClient } from "@nulib/authoritex-js";
const client = new AuthoritexClient({
geonamesUsername: process.env.GEONAMES_USERNAME
});
const geoResults = await client.search("geonames", "Chicago", 3);
console.log(geoResults);
const record = await client.fetch(
"http://id.loc.gov/authorities/subjects/sh87003768",
{ redirect: true }
);
console.log(record);Caching
By default, AuthoritexClient uses the included in-memory cache so successful fetch() and search() results are reused across calls. The built-in reference cache is bounded and TTL-aware: fetch() results default to a 24-hour TTL and search() results default to a 5-minute TTL.
To disable caching, pass cache: false:
import { AuthoritexClient } from "@nulib/authoritex-js";
const client = new AuthoritexClient({
cache: false
});To customize TTLs or the underlying store:
import { AuthoritexClient, MemoryAuthoritexCache } from "@nulib/authoritex-js";
const client = new AuthoritexClient({
cache: {
store: new MemoryAuthoritexCache({ maxEntries: 5000 }),
fetchTtlMs: 7 * 24 * 60 * 60 * 1000,
searchTtlMs: 10 * 60 * 1000
}
});Production applications can provide their own cache store, such as Redis, a database-backed cache, or an application cache. Stores implement get() and set():
const client = new AuthoritexClient({
cache: {
store: {
get: async (key) =>
redis.get(key).then((value) => (value === null ? undefined : JSON.parse(value))),
set: async (key, value, options) => {
await redis.set(key, JSON.stringify(value), { PX: options?.ttlMs });
}
}
}
});Caches may also implement delete() and clear() so applications can invalidate entries semantically through the client:
if (client.cacheDeletionSupported()) {
await client.deleteCachedFetch("http://id.loc.gov/authorities/names/n79091588");
await client.deleteCachedSearch("fast", "baseball cards", 5);
}
if (client.cacheClearSupported()) {
await client.clearCache();
}deleteCachedFetch(id) clears both redirected and non-redirected cached fetches for the id unless you pass { redirect: true } or { redirect: false }. deleteCachedSearch() clears the exact authority, query, and max-results combination.
authorities() and authorityFor() return named metadata objects:
const info = client.authorityFor("http://id.loc.gov/authorities/names/n79091588");
if (info) {
console.log(info.code);
console.log(info.description);
}API Shapes
Search results use a compact shape:
interface SearchResult {
id: string;
label: string;
hint: string | null;
}Fetched records use a normalized authority-record shape:
interface AuthorityRecord {
id: string;
label: string;
qualified_label: string;
hint: string | null;
variants: string[];
related: {
replaced_by?: string;
replaces?: string;
[relation: string]: string | undefined;
};
}Error Handling
Operations return values directly and throw typed errors for control flow.
Useful exported error classes include:
UnknownAuthorityErrorNotFoundErrorHttpStatusErrorBadResponseErrorAuthorityServiceErrorNetworkError
Custom Clients
Pass your own authority implementations to AuthoritexClient when you want to control the available authorities. MockAuthority is exported for tests, demos, placeholders, and other local workflows that need the same Authority interface without live network calls.
import { AuthoritexClient, MockAuthority } from "@nulib/authoritex-js";
const mock = new MockAuthority(
[
{
id: "placeholder:1",
label: "Placeholder term",
hint: "Example collection",
variants: ["Placeholder alternate label"],
related: {
replaced_by: "placeholder:2"
}
}
],
{
code: "placeholder",
description: "Placeholder authority",
canResolve: (id) => id.startsWith("placeholder:")
}
);
const client = new AuthoritexClient({ authorities: [mock] });
await client.fetch("placeholder:1");Mock records require id and label. They may also include qualified_label, hint, variants, and related; missing fields are normalized to the same shape as live authority records.
To implement a custom live authority, provide an object that satisfies the exported Authority interface:
import type { Authority } from "@nulib/authoritex-js";
const authority: Authority = {
canResolve: (id) => id.startsWith("local:"),
code: () => "local",
description: () => "Local authority",
fetch: async (id) => ({
id,
label: "Local term",
qualified_label: "Local term",
hint: null,
variants: [],
related: {}
}),
search: async () => []
};Supported Authority Codes
fastfast-corporate-namefast-event-namefast-formfast-geographicfast-personalfast-topicalfast-uniform-titlegeonameshomosauruslclanglcnaflcshlcgftloc
MCP Server
The MCP server is published separately as @nulib/authoritex-mcp.
- npm:
@nulib/authoritex-mcp - repo: https://github.com/nulib-labs/authoritex-mcp
Related Projects
@nulib/authoritex-js is a TypeScript port of Northwestern University Libraries' long-maintained Elixir library, nulib/authoritex.
Development
Clone the library repo and use the standard local workflow:
git clone https://github.com/nulib-labs/authoritex-js.git
cd authoritex-js
npm installRecommended commands:
npm run typechecknpm run testnpm run test:coveragenpm run test:watchnpm run buildnpm run devnpm run dev:buildnpm run dev:preview
npm run dev launches the Vite integration workbench on http://localhost:3003 by default. If that port is unavailable, Vite will use the next open port, or you can choose one explicitly with npm run dev -- --port 4173.
Node REPL
To test the built package directly from a clone:
npm install
npm run build
nodeThen in the REPL:
const authoritex = await import("./dist/index.js")
const { authorities, search, fetch, AuthoritexClient } = authoritex
authorities()
await search("fast", "baseball cards", 5)
await fetch("http://id.loc.gov/authorities/names/n79091588")To test GeoNames in the REPL:
GEONAMES_USERNAME=your_username nodeThen:
const { AuthoritexClient } = await import("./dist/index.js")
const client = new AuthoritexClient({ geonamesUsername: process.env.GEONAMES_USERNAME })
await client.search("geonames", "Chicago", 3)Authority development workbench
dev/ contains a Vite + React integration harness with:
- real authority calls through the dev proxy
- side-by-side search and fetch panels with URI handoff
- authority resolution and normalized record inspection

The Vite app (npm run dev or npm run dev:preview) uses a local /__authoritex_proxy route to avoid browser CORS restrictions against authority services. That proxy is only part of the local development workbench.
