@jdcpuwiz/zoo-kit 1.0.1 → 1.2.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/health.js CHANGED
@@ -7,6 +7,12 @@
7
7
  * a check that throws, returns false or outlives its timeout marks itself and
8
8
  * `ok` false; it never makes the route throw or hang.
9
9
  *
10
+ * ERROR TEXT IS GENERIC, ALWAYS. This route is open on the LAN and a raw error
11
+ * (a Prisma one names the database host and port) must not be readable there.
12
+ * A thrown check reports "check failed" and its real message goes to the app's
13
+ * log, one console.warn per failure. A timeout keeps "timed out after N ms",
14
+ * which the kit wrote itself. `detail` is the app's own text and stays as is.
15
+ *
10
16
  * version: opts.version, else APP_VERSION, else the `version` in the package.json
11
17
  * in the working directory, else null.
12
18
  * sha: opts.sha, else GIT_SHA, else null. "unknown" counts as unknown.
@@ -33,14 +39,18 @@ function packageVersion() {
33
39
  }
34
40
  return cwdVersion;
35
41
  }
36
- async function runCheck(fn, timeoutMs) {
42
+ const messageOf = (err) => (err instanceof Error ? err.message : String(err));
43
+ async function runCheck(name, fn, timeoutMs) {
37
44
  const started = Date.now();
38
45
  let timer;
46
+ // Compared by identity: a check that throws its own "timed out…" text is
47
+ // still app text and may name a host.
48
+ const timedOut = new Error(`timed out after ${timeoutMs} ms`);
39
49
  try {
40
50
  const value = await Promise.race([
41
51
  Promise.resolve().then(fn),
42
52
  new Promise((_, reject) => {
43
- timer = setTimeout(() => reject(new Error(`timed out after ${timeoutMs} ms`)), timeoutMs);
53
+ timer = setTimeout(() => reject(timedOut), timeoutMs);
44
54
  }),
45
55
  ]);
46
56
  const ms = Date.now() - started;
@@ -53,7 +63,11 @@ async function runCheck(fn, timeoutMs) {
53
63
  return { ok: true, ms };
54
64
  }
55
65
  catch (err) {
56
- return { ok: false, ms: Date.now() - started, error: (err instanceof Error ? err.message : String(err)).slice(0, 300) };
66
+ const ms = Date.now() - started;
67
+ if (err === timedOut)
68
+ return { ok: false, ms, error: timedOut.message };
69
+ console.warn(`[zoo-kit] health check "${name}" failed: ${messageOf(err)}`);
70
+ return { ok: false, ms, error: "check failed" };
57
71
  }
58
72
  finally {
59
73
  clearTimeout(timer);
@@ -63,7 +77,7 @@ async function runCheck(fn, timeoutMs) {
63
77
  export async function healthBody(opts) {
64
78
  const timeout = opts.checkTimeoutMs ?? 3_000;
65
79
  const names = Object.keys(opts.checks ?? {});
66
- const results = await Promise.all(names.map((n) => runCheck(opts.checks[n], timeout)));
80
+ const results = await Promise.all(names.map((n) => runCheck(n, opts.checks[n], timeout)));
67
81
  const checks = Object.fromEntries(names.map((n, i) => [n, results[i]]));
68
82
  if (opts.requiredEnv?.length)
69
83
  checks.config = checkConfig(opts.requiredEnv);
@@ -90,6 +104,7 @@ export function healthHandler(opts) {
90
104
  body = await healthBody(opts);
91
105
  }
92
106
  catch (err) {
107
+ console.warn(`[zoo-kit] health failed: ${messageOf(err)}`);
93
108
  body = {
94
109
  ok: false,
95
110
  app: opts.app,
@@ -97,7 +112,7 @@ export function healthHandler(opts) {
97
112
  sha: null,
98
113
  kit: KIT_VERSION,
99
114
  uptimeS: Math.floor(process.uptime()),
100
- checks: { kit: { ok: false, ms: 0, error: err instanceof Error ? err.message : String(err) } },
115
+ checks: { kit: { ok: false, ms: 0, error: "health failed" } },
101
116
  };
102
117
  }
103
118
  return new Response(JSON.stringify(body), {
package/dist/index.d.ts CHANGED
@@ -12,7 +12,7 @@
12
12
  export { ENV, appKeyEnv, appKeyForEnv, appUrlsEnv, checkConfig, envSuffix, type ConfigReport } from "./env.js";
13
13
  export { CATEGORIES, CATEGORY_ALIASES, CATEGORY_SLUGS, canonicalCategory, customCategory, isCanonicalCategory, isCategoryAlias, toCategory, type CategoryAlias, type CategoryInput, type CustomCategory, type NotifyCategory, } from "./categories.js";
14
14
  export { NOTIFY_DEFAULTS, NOTIFY_PATH, dedupeKey, notify, notifyConfigured, type NotifyAction, type NotifyDryRun, type NotifyFailed, type NotifyInput, type NotifyOptions, type NotifyPriority, type NotifyResult, type NotifySent, } from "./notify.js";
15
- export { PEOPLE_DEFAULTS, PEOPLE_PATHS, createPeople, people, toPerson, type People, type PeopleList, type PeopleOptions, type PeopleStatus, type Person, type ResolveStatus, type ResolvedUsername, } from "./people.js";
15
+ export { PEOPLE_DEFAULTS, PEOPLE_PATHS, createPeople, people, toPerson, type Contact, type Contacts, type ContactsResult, type ContactsStatus, type People, type PeopleClient, type PeopleList, type PeopleOptions, type PeopleStatus, type Person, type ResolveStatus, type ResolvedUsername, } from "./people.js";
16
16
  export { ZooKitAuthError, cameThroughGate, gateSecretOk, readAuthentikUsername, requireApp, requirePerson, whoami, type Anonymous, type AuthentikOptions, type DeviceAnswer, type Identity, type PersonIdentity, type SessionAnswer, type WhoamiOptions, } from "./whoami.js";
17
17
  export { ZooKitConfigError, bearerOf, callApp, checkApp, safeEqual, type AppIdentity, type AppVerdict, type CallAppOptions, type HeaderBag, type RequestLike, } from "./keys.js";
18
18
  export { healthBody, healthHandler, type CheckFn, type CheckResult, type HealthBody, type HealthOptions } from "./health.js";
package/dist/notify.d.ts CHANGED
@@ -11,6 +11,10 @@ export type NotifyInput = Omit<Schemas["NotifyInput"], "category"> & {
11
11
  export interface NotifyOptions extends FailoverOptions {
12
12
  /** Build and return the request, send nothing. Still requires the config. */
13
13
  dryRun?: boolean;
14
+ /** Hub base URLs for this call, instead of ZOO_NOTIFIER_URLS. Empty = use the env. */
15
+ urls?: string[];
16
+ /** This app's hub key for this call, instead of ZOO_NOTIFIER_KEY. Empty = use the env. */
17
+ key?: string;
14
18
  }
15
19
  export interface NotifySent {
16
20
  ok: true;
@@ -59,7 +63,7 @@ export declare const NOTIFY_DEFAULTS: Required<FailoverOptions>;
59
63
  * Throws TypeError on an unusable `kind` — that is a bug at the call site.
60
64
  */
61
65
  export declare function dedupeKey(kind: string, ...parts: Array<string | number | bigint | boolean | null | undefined>): string;
62
- /** Is notify configured? Names only. */
66
+ /** Is notify configured through the env? Names only; per-call overrides are not counted. */
63
67
  export declare function notifyConfigured(): {
64
68
  ok: boolean;
65
69
  missing: string[];
package/dist/notify.js CHANGED
@@ -9,6 +9,10 @@
9
9
  * list, logs one line and resolves `{ ok: false, error }`.
10
10
  *
11
11
  * Missing config is one logged warning and a no-op — never a guessed host.
12
+ *
13
+ * An app that keeps its hub settings somewhere other than env (an encrypted
14
+ * settings table) passes `{ urls, key }` per call; the key is sent as the Bearer
15
+ * header and nowhere else, so it never reaches a result or a log line.
12
16
  */
13
17
  import { createHash, randomUUID } from "node:crypto";
14
18
  import { ENV, firstList, str, warnOnce } from "./env.js";
@@ -43,9 +47,10 @@ export function dedupeKey(kind, ...parts) {
43
47
  return key;
44
48
  return `${kind.toLowerCase()}:sha256-${createHash("sha256").update(key).digest("hex").slice(0, 48)}`;
45
49
  }
46
- function config() {
47
- const urls = firstList(ENV.NOTIFIER_URLS, ENV.NOTIFIER_URL);
48
- const key = str(ENV.NOTIFIER_KEY);
50
+ function config(override = {}) {
51
+ const urlsOverride = (override.urls ?? []).map((u) => u.trim().replace(/\/+$/, "")).filter(Boolean);
52
+ const urls = urlsOverride.length ? urlsOverride : firstList(ENV.NOTIFIER_URLS, ENV.NOTIFIER_URL);
53
+ const key = override.key?.trim() || str(ENV.NOTIFIER_KEY);
49
54
  const missing = [];
50
55
  if (!urls.length)
51
56
  missing.push(ENV.NOTIFIER_URLS);
@@ -53,7 +58,7 @@ function config() {
53
58
  missing.push(ENV.NOTIFIER_KEY);
54
59
  return { urls, key, missing };
55
60
  }
56
- /** Is notify configured? Names only. */
61
+ /** Is notify configured through the env? Names only; per-call overrides are not counted. */
57
62
  export function notifyConfigured() {
58
63
  const { missing } = config();
59
64
  return { ok: missing.length === 0, missing };
@@ -70,7 +75,8 @@ function failed(error, extra = {}) {
70
75
  */
71
76
  export async function notify(input, opts = {}) {
72
77
  try {
73
- const { urls, key, missing } = config();
78
+ const { urls: urlsOverride, key: keyOverride, dryRun, ...failover } = opts;
79
+ const { urls, key, missing } = config({ urls: urlsOverride, key: keyOverride });
74
80
  if (missing.length) {
75
81
  warnOnce("notify-unconfigured", `notify is a no-op: ${missing.join(", ")} not set`);
76
82
  return failed(`not configured: ${missing.join(", ")} not set`, { skipped: "unconfigured" });
@@ -84,14 +90,14 @@ export async function notify(input, opts = {}) {
84
90
  const body = stripUndefined({ ...input });
85
91
  if (!body.dedupeKey)
86
92
  body.dedupeKey = dedupeKey("kit-once", randomUUID());
87
- if (opts.dryRun) {
93
+ if (dryRun) {
88
94
  return { ok: true, dryRun: true, queued: false, deduped: false, urls, path: NOTIFY_PATH, body };
89
95
  }
90
96
  const outcome = await failoverFetch(urls, NOTIFY_PATH, {
91
97
  method: "POST",
92
98
  headers: { "Content-Type": "application/json", Authorization: `Bearer ${key}` },
93
99
  body: JSON.stringify(body),
94
- }, { ...NOTIFY_DEFAULTS, ...stripUndefined(opts) });
100
+ }, { ...NOTIFY_DEFAULTS, ...stripUndefined(failover) });
95
101
  if (outcome.kind === "failed") {
96
102
  console.warn(`[zoo-kit] notify failed after ${outcome.attempts.length} attempt(s): ${outcome.error}`);
97
103
  return failed(outcome.error, { status: outcome.status, attempts: outcome.attempts });
package/dist/people.d.ts CHANGED
@@ -38,7 +38,35 @@ export declare const PEOPLE_DEFAULTS: {
38
38
  export declare const PEOPLE_PATHS: {
39
39
  readonly list: "/api/v1/people";
40
40
  readonly whoamiResolve: "/api/v1/whoami-resolve";
41
+ readonly contactsSearch: "/api/v1/contacts/search";
41
42
  };
43
+ /**
44
+ * A card from the directory's Contacts book (v1.2, additive — BP#127 P9c).
45
+ * Not a Person: the Contacts book is anyone Wiz keeps, not the family roster.
46
+ */
47
+ export interface Contact {
48
+ uid: string | null;
49
+ name: string;
50
+ /** Lower-cased. */
51
+ emails: string[];
52
+ phones: string[];
53
+ org: string | null;
54
+ hasPhoto: boolean;
55
+ }
56
+ export type ContactsStatus = "fresh" | "stale" | "unavailable" | "unconfigured";
57
+ export interface ContactsResult {
58
+ contacts: Contact[];
59
+ status: ContactsStatus;
60
+ error?: string;
61
+ }
62
+ export interface Contacts {
63
+ /** Ranked search (exact email first, then name prefix …). Never throws; an outage is status "unavailable". */
64
+ search(q: string, opts?: {
65
+ limit?: number;
66
+ }): Promise<ContactsResult>;
67
+ /** The contact holding exactly this email, or null. Cached like search. */
68
+ byEmail(email: string): Promise<Contact | null>;
69
+ }
42
70
  /** Keep only the contract's Person keys; null for anything that is not a usable person. */
43
71
  export declare function toPerson(raw: unknown): Person | null;
44
72
  export interface People {
@@ -55,7 +83,16 @@ export interface People {
55
83
  /** Drop every cached answer. */
56
84
  clear(): void;
57
85
  }
86
+ /**
87
+ * The client {@link createPeople} returns: People plus the Contacts book
88
+ * (v1.2, additive). Kept OUT of the People interface so an app's hand-rolled
89
+ * People stub (whoami tests) still type-checks after the bump.
90
+ */
91
+ export type PeopleClient = People & {
92
+ /** Search Wiz's own Contacts book through the directory. */
93
+ contacts: Contacts;
94
+ };
58
95
  /** A people client with its own cache. Most apps use the shared {@link people}. */
59
- export declare function createPeople(options?: PeopleOptions): People;
96
+ export declare function createPeople(options?: PeopleOptions): PeopleClient;
60
97
  /** The process-wide people client. */
61
- export declare const people: People;
98
+ export declare const people: PeopleClient;
package/dist/people.js CHANGED
@@ -32,7 +32,24 @@ export const PEOPLE_DEFAULTS = {
32
32
  export const PEOPLE_PATHS = {
33
33
  list: "/api/v1/people",
34
34
  whoamiResolve: "/api/v1/whoami-resolve",
35
+ contactsSearch: "/api/v1/contacts/search",
35
36
  };
37
+ function toContact(raw) {
38
+ if (!raw || typeof raw !== "object")
39
+ return null;
40
+ const r = raw;
41
+ if (typeof r.name !== "string" || !r.name)
42
+ return null;
43
+ const strs = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string") : []);
44
+ return {
45
+ uid: typeof r.uid === "string" ? r.uid : null,
46
+ name: r.name,
47
+ emails: strs(r.emails).map((e) => e.toLowerCase()),
48
+ phones: strs(r.phones),
49
+ org: typeof r.org === "string" ? r.org : null,
50
+ hasPhoto: r.hasPhoto === true,
51
+ };
52
+ }
36
53
  const KEYS = new Set(PERSON_KEYS);
37
54
  /** Keep only the contract's Person keys; null for anything that is not a usable person. */
38
55
  export function toPerson(raw) {
@@ -67,6 +84,7 @@ export function createPeople(options = {}) {
67
84
  let listCache = null;
68
85
  let listInflight = null;
69
86
  const users = new Map();
87
+ const searches = new Map();
70
88
  async function get(path) {
71
89
  const c = config();
72
90
  if (c.missing.length) {
@@ -154,9 +172,46 @@ export function createPeople(options = {}) {
154
172
  return { ok: true, detail: `stale since ${l.loadedAt?.toISOString()}: ${l.error ?? ""}`.trim() };
155
173
  throw new Error(`roster ${l.status}${l.error ? `: ${l.error}` : ""}`);
156
174
  },
175
+ contacts: {
176
+ async search(q, opts = {}) {
177
+ const needle = (q ?? "").trim().toLowerCase();
178
+ if (!needle)
179
+ return { contacts: [], status: "fresh" };
180
+ const limit = Math.max(1, Math.min(50, Math.floor(opts.limit ?? 20)));
181
+ const key = `${limit}|${needle}`;
182
+ const hit = searches.get(key);
183
+ const age = hit ? now() - hit.at : Infinity;
184
+ if (hit && age < o.ttlMs)
185
+ return hit.result;
186
+ const got = await get(`${PEOPLE_PATHS.contactsSearch}?q=${encodeURIComponent(needle)}&limit=${limit}`);
187
+ if (got.kind === "ok") {
188
+ const j = got.json;
189
+ if (Array.isArray(j?.contacts)) {
190
+ const contacts = j.contacts.map(toContact).filter((c) => c !== null);
191
+ const result = { contacts, status: j?.status === "stale" ? "stale" : "fresh" };
192
+ if (searches.size > 500)
193
+ searches.clear();
194
+ searches.set(key, { result, at: now() });
195
+ return result;
196
+ }
197
+ }
198
+ const error = got.kind === "ok" ? "malformed contacts answer" : got.kind === "not-found" ? "HTTP 404" : got.error;
199
+ if (hit && age <= o.staleUsernameMs)
200
+ return { ...hit.result, status: "stale", error };
201
+ return { contacts: [], status: got.kind === "unconfigured" ? "unconfigured" : "unavailable", error };
202
+ },
203
+ async byEmail(email) {
204
+ const e = (email ?? "").trim().toLowerCase();
205
+ if (!e)
206
+ return null;
207
+ const r = await api.contacts.search(e, { limit: 5 });
208
+ return r.contacts.find((c) => c.emails.includes(e)) ?? null;
209
+ },
210
+ },
157
211
  clear() {
158
212
  listCache = null;
159
213
  users.clear();
214
+ searches.clear();
160
215
  },
161
216
  };
162
217
  return api;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jdcpuwiz/zoo-kit",
3
- "version": "1.0.1",
3
+ "version": "1.2.0",
4
4
  "description": "Thin, pinned server-side client for the homelab's shared services: notify, whoami, people, health, app keys.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -12,14 +12,21 @@
12
12
  "types": "./dist/index.d.ts",
13
13
  "exports": {
14
14
  ".": {
15
- "types": "./dist/index.d.ts",
16
- "import": "./dist/index.js"
15
+ "import": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ },
19
+ "require": {
20
+ "types": "./dist/cjs/index.d.ts",
21
+ "default": "./dist/cjs/index.js"
22
+ }
17
23
  },
18
24
  "./package.json": "./package.json"
19
25
  },
20
26
  "files": [
21
27
  "dist/**/*.js",
22
28
  "dist/**/*.d.ts",
29
+ "dist/cjs/package.json",
23
30
  "README.md",
24
31
  "LICENSE"
25
32
  ],
@@ -36,8 +43,9 @@
36
43
  "gen:check": "node scripts/generate.mjs --check",
37
44
  "typecheck": "tsc --noEmit -p tsconfig.json && tsc --noEmit -p tsconfig.test.json",
38
45
  "test": "npm run gen:check && vitest run",
39
- "build": "npm run gen:check && rm -rf dist && tsc -p tsconfig.build.json",
46
+ "build": "npm run gen:check && rm -rf dist && tsc -p tsconfig.build.json && tsc -p tsconfig.cjs.json && node scripts/write-cjs-package.mjs",
40
47
  "prepack": "npm run build",
48
+ "test:tarball": "node scripts/tarball-test.mjs",
41
49
  "smoke:live": "npm run build && node scripts/live-smoke.mjs"
42
50
  },
43
51
  "devDependencies": {