@htilabs/platform-common-models 0.86.0 → 0.87.1

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.
Files changed (40) hide show
  1. package/README.md +20 -0
  2. package/dist/{index-XWSYon40.d.cts → index-Bj-s0nZy.d.cts} +1 -1
  3. package/dist/{index-Bh1zO_Vu.d.ts → index-DvAypMJV.d.ts} +1 -1
  4. package/dist/index.d.cts +2 -2
  5. package/dist/index.d.ts +2 -2
  6. package/dist/models/index.d.cts +2 -2
  7. package/dist/models/index.d.ts +2 -2
  8. package/dist/org-merge/index.cjs.map +1 -1
  9. package/dist/org-merge/index.js.map +1 -1
  10. package/dist/points-of-contact/index.cjs +222 -23
  11. package/dist/points-of-contact/index.cjs.map +1 -1
  12. package/dist/points-of-contact/index.d.cts +50 -5
  13. package/dist/points-of-contact/index.d.ts +50 -5
  14. package/dist/points-of-contact/index.js +219 -22
  15. package/dist/points-of-contact/index.js.map +1 -1
  16. package/dist/reader-BmhzOis-.d.ts +273 -0
  17. package/dist/reader-DfQtdw6n.d.cts +273 -0
  18. package/dist/schemas/index.d.cts +25 -25
  19. package/dist/schemas/index.d.ts +25 -25
  20. package/dist/seat-logs/index.cjs +815 -0
  21. package/dist/seat-logs/index.cjs.map +1 -0
  22. package/dist/seat-logs/index.d.cts +274 -0
  23. package/dist/seat-logs/index.d.ts +274 -0
  24. package/dist/seat-logs/index.js +742 -0
  25. package/dist/seat-logs/index.js.map +1 -0
  26. package/package.json +6 -1
  27. package/src/pointsOfContact/__tests__/seatContactLog.test.ts +170 -0
  28. package/src/pointsOfContact/readRules.ts +22 -4
  29. package/src/pointsOfContact/reader.ts +95 -1
  30. package/src/pointsOfContact/schemas.ts +4 -3
  31. package/src/seatLogs/__tests__/seatLogs.review.test.ts +222 -0
  32. package/src/seatLogs/__tests__/seatLogs.test.ts +335 -0
  33. package/src/seatLogs/index.ts +15 -0
  34. package/src/seatLogs/log.ts +700 -0
  35. package/src/seatLogs/personId.ts +100 -0
  36. package/src/seatLogs/personSlugWordlists.ts +40 -0
  37. package/src/seatLogs/reader.ts +143 -0
  38. package/src/seatLogs/schemas.ts +118 -0
  39. package/dist/{cvcEntry-D787utvP.d.cts → cvcEntry-BLeRivoF.d.cts} +8 -8
  40. package/dist/{cvcEntry-D787utvP.d.ts → cvcEntry-BLeRivoF.d.ts} +8 -8
@@ -0,0 +1,742 @@
1
+ // src/seatLogs/schemas.ts
2
+ import { z } from "zod";
3
+
4
+ // src/generated/cvc-enums.ts
5
+ var NameTypeKeys = {
6
+ missingness_root: "001-000-000-000-000-000-000",
7
+ unknown: "001-000-000-000-000-000-001",
8
+ anonymous: "001-000-000-000-000-000-002",
9
+ data_not_collected: "001-000-000-000-000-000-003",
10
+ alias: "001-001-000-000-000-000-000",
11
+ code_name: "001-002-000-000-000-000-000",
12
+ handle_screenname: "001-003-000-000-000-000-000",
13
+ legal: "001-004-000-000-000-000-000",
14
+ maiden_former: "001-005-000-000-000-000-000",
15
+ nickname: "001-006-000-000-000-000-000",
16
+ street_name: "001-007-000-000-000-000-000",
17
+ trade_name_stage_name: "001-008-000-000-000-000-000"
18
+ };
19
+
20
+ // src/seatLogs/schemas.ts
21
+ var SEAT_NAMES_COLLECTION = "seat_names";
22
+ var SEAT_CONTACTS_COLLECTION = "seat_contacts";
23
+ var SEAT_LOG_SUBJECT_TYPES = ["user", "person"];
24
+ var SEAT_CONTACT_TYPES = ["email", "phone"];
25
+ var SEAT_NAME_TYPES = Object.keys(NameTypeKeys);
26
+ var SEAT_NAME_ADD_TYPES = [
27
+ { name_type: "alias", label: "Also known as" },
28
+ { name_type: "legal", label: "Legal name" }
29
+ ];
30
+ var SeatLogEventSchema = z.object({
31
+ /** `add`, `set_display`, `set_preferred`, `archive`, or `cascade` (a sibling's flag moved). */
32
+ act: z.string().min(1),
33
+ /** ISO instant. */
34
+ at: z.string().min(1),
35
+ /** The acting seat's id. */
36
+ actor: z.string()
37
+ });
38
+ var DayOrEmpty = z.union([z.literal(""), z.string().regex(/^\d{4}-\d{2}-\d{2}$/)]);
39
+ var subjectShape = {
40
+ entry_id: z.string().min(1),
41
+ subject_id: z.string().min(1),
42
+ subject_type: z.enum(SEAT_LOG_SUBJECT_TYPES),
43
+ period_start: DayOrEmpty,
44
+ period_end: DayOrEmpty,
45
+ /** Where the entry came from (`admin_hub` on the profile). */
46
+ source: z.string(),
47
+ /** How it was captured (`direct_entry` on the profile). */
48
+ method: z.string(),
49
+ notes: z.string(),
50
+ events: z.array(SeatLogEventSchema).optional()
51
+ };
52
+ var SeatNameEntrySchema = z.object({
53
+ ...subjectShape,
54
+ name_type: z.enum(SEAT_NAME_TYPES),
55
+ /** The name as written. */
56
+ raw: z.string().min(1),
57
+ /** The display name: one live entry per subject carries it. */
58
+ is_display: z.boolean(),
59
+ /** Set with the display mark on the profile (prototype acts both together). */
60
+ is_preferred: z.boolean()
61
+ });
62
+ var SeatContactEntrySchema = z.object({
63
+ ...subjectShape,
64
+ contact_type: z.enum(SEAT_CONTACT_TYPES),
65
+ /** Email trimmed; phone in the store's canonical display form ({@link canonSeatContactValue}). */
66
+ value: z.string().min(1),
67
+ use: z.string(),
68
+ /** The preferred entry of its type: one live entry per subject and type carries it. */
69
+ is_preferred: z.boolean(),
70
+ safety_status: z.string(),
71
+ /** Phone only: the identity key ({@link seatContactKey}), stamped by the store. */
72
+ digits: z.string().optional()
73
+ });
74
+
75
+ // src/seatLogs/log.ts
76
+ var FLAT_NAME_ENTRY_ID = "__flat__";
77
+ var SeatLogRefusal = class extends Error {
78
+ constructor(code, message) {
79
+ super(message);
80
+ this.code = code;
81
+ this.name = "SeatLogRefusal";
82
+ }
83
+ };
84
+ var B36 = "0123456789abcdefghijklmnopqrstuvwxyz";
85
+ function randomB36(n) {
86
+ const c = globalThis.crypto;
87
+ const bytes = new Uint8Array(n);
88
+ if (c?.getRandomValues) c.getRandomValues(bytes);
89
+ else for (let i = 0; i < n; i++) bytes[i] = Math.floor(Math.random() * 256);
90
+ let out = "";
91
+ for (let i = 0; i < n; i++) out += B36[bytes[i] % 36];
92
+ return out;
93
+ }
94
+ function mintSeatLogEntryId(kind, subject) {
95
+ return (kind === "name" ? "nm-" : "ci-") + subject.subject_id + "-rt" + Date.now().toString(36).slice(-5) + randomB36(8);
96
+ }
97
+ var isLive = (e) => !e.period_end;
98
+ var sigOf = (e) => ["is_display" in e ? !!e.is_display : false, !!e.is_preferred, false, e.period_end || ""].join("|");
99
+ var flagOf = (r, flag) => !!r[flag];
100
+ var setFlagValue = (r, flag, v) => {
101
+ r[flag] = v;
102
+ };
103
+ var Draft = class {
104
+ constructor(entries, subject, ctx) {
105
+ this.subject = subject;
106
+ this.ctx = ctx;
107
+ this.rows = entries.filter((e) => e.subject_id === subject.subject_id && e.subject_type === subject.subject_type).map((e) => JSON.parse(JSON.stringify(e)));
108
+ this.at = ctx.at ?? (/* @__PURE__ */ new Date()).toISOString();
109
+ this.day = this.at.slice(0, 10);
110
+ }
111
+ rows;
112
+ added = /* @__PURE__ */ new Set();
113
+ touched = /* @__PURE__ */ new Set();
114
+ at;
115
+ day;
116
+ live() {
117
+ return this.rows.filter(isLive);
118
+ }
119
+ /** The LIVE entry an act targets. A retired entry is refused, never acted on. */
120
+ findLive(id) {
121
+ const r = this.rows.find((x) => x.entry_id === id);
122
+ if (!r) throw new SeatLogRefusal("entry_not_found", `No entry ${id} in this log.`);
123
+ if (!isLive(r)) throw new SeatLogRefusal("entry_not_live", `Entry ${id} is retired.`);
124
+ return r;
125
+ }
126
+ stamp(r, act) {
127
+ r.events = [...r.events ?? [], { act, at: this.at, actor: this.ctx.actor }];
128
+ this.touched.add(r.entry_id);
129
+ }
130
+ unit(mutate, target, act, skip) {
131
+ const before = new Map(this.rows.map((r) => [r, sigOf(r)]));
132
+ mutate();
133
+ for (const r of this.rows) {
134
+ const was = before.get(r);
135
+ if (r !== skip && was !== void 0 && was !== sigOf(r)) this.stamp(r, "cascade");
136
+ }
137
+ this.stamp(target, act);
138
+ }
139
+ /**
140
+ * Insert a new row (canon `addEntry`): a flag it carries clears that flag
141
+ * on the subject's other live rows (contacts: same type only).
142
+ */
143
+ insert(r) {
144
+ if (this.rows.some((x) => x.entry_id === r.entry_id)) {
145
+ throw new Error(`seat-logs: entry_id_exists: ${r.entry_id}`);
146
+ }
147
+ this.unit(() => {
148
+ this.rows.push(r);
149
+ const scope = (x) => !("contact_type" in r) || x.contact_type === r.contact_type;
150
+ for (const flag of ["is_display", "is_preferred"]) {
151
+ if (flagOf(r, flag)) this.clearOthers(r, flag, scope);
152
+ }
153
+ }, r, "add", r);
154
+ this.added.add(r.entry_id);
155
+ }
156
+ clearOthers(target, flag, scope) {
157
+ for (const x of this.rows) {
158
+ if (x !== target && isLive(x) && scope(x) && flagOf(x, flag)) setFlagValue(x, flag, false);
159
+ }
160
+ }
161
+ /** Act `set_display` / `set_preferred`: the mark moves to `target` within `scope`. */
162
+ mark(target, flag, scope) {
163
+ this.unit(() => {
164
+ this.clearOthers(target, flag, scope);
165
+ setFlagValue(target, flag, true);
166
+ }, target, flag === "is_display" ? "set_display" : "set_preferred");
167
+ }
168
+ /** Act `archive`: stamp `period_end`, clear both marks (spine `archiveEntry`). */
169
+ archive(r) {
170
+ this.unit(() => {
171
+ r.period_end = this.day;
172
+ if ("is_display" in r) setFlagValue(r, "is_display", false);
173
+ r.is_preferred = false;
174
+ }, r, "archive");
175
+ }
176
+ /** A fresh id, re-minted on a clash with any row in this log. */
177
+ newId(kind) {
178
+ const mint = this.ctx.mintId ?? mintSeatLogEntryId;
179
+ for (let i = 0; i < 20; i++) {
180
+ const id = mint(kind, this.subject);
181
+ if (!this.rows.some((x) => x.entry_id === id)) return id;
182
+ }
183
+ throw new Error("seat-logs: entry_id_exists: could not mint an unused entry id in 20 tries");
184
+ }
185
+ done() {
186
+ return {
187
+ entries: this.rows,
188
+ inserted: this.rows.filter((r) => this.added.has(r.entry_id)),
189
+ updated: this.rows.filter((r) => this.touched.has(r.entry_id) && !this.added.has(r.entry_id))
190
+ };
191
+ }
192
+ };
193
+ var base = (subject) => ({
194
+ subject_id: subject.subject_id,
195
+ subject_type: subject.subject_type,
196
+ source: "admin_hub",
197
+ method: "direct_entry"
198
+ });
199
+ var correctsNote = (prior, old) => [prior, "Corrects \u201C" + old + "\u201D"].filter(Boolean).join(" \xB7 ");
200
+ var SEAT_NAME_BLANK_REFUSAL = "A member keeps a name \u2014 the directory row can't go blank.";
201
+ function liveSeatNames(entries) {
202
+ return entries.filter(isLive);
203
+ }
204
+ function pastSeatNames(entries) {
205
+ return entries.filter((e) => !isLive(e));
206
+ }
207
+ function seatDisplayNameEntry(entries) {
208
+ const live = liveSeatNames(entries);
209
+ return live.find((e) => e.is_display) ?? live[0] ?? null;
210
+ }
211
+ function seatNameProjection(entries) {
212
+ return seatDisplayNameEntry(entries)?.raw || null;
213
+ }
214
+ function seatNameRows(entries, flatName) {
215
+ const live = liveSeatNames(entries);
216
+ if (live.length) return live;
217
+ const flat = (flatName ?? "").trim();
218
+ return flat ? [{ entry_id: FLAT_NAME_ENTRY_ID, raw: flat, name_type: "legal", is_display: true }] : [];
219
+ }
220
+ function seedFromFlat(d, flatName) {
221
+ const flat = (flatName ?? "").trim();
222
+ if (d.live().length || !flat) return;
223
+ d.insert(SeatNameEntrySchema.parse({
224
+ entry_id: d.newId("name"),
225
+ ...base(d.subject),
226
+ name_type: "legal",
227
+ raw: flat,
228
+ is_display: true,
229
+ is_preferred: true,
230
+ period_start: "",
231
+ period_end: "",
232
+ notes: ""
233
+ }));
234
+ }
235
+ function seedSeatNameLog(entries, subject, flatName, ctx) {
236
+ const d = new Draft(entries, subject, ctx);
237
+ seedFromFlat(d, flatName);
238
+ return d.done();
239
+ }
240
+ function addSeatName(entries, subject, input, ctx) {
241
+ const v = input.raw.trim();
242
+ if (!v) throw new SeatLogRefusal("name_blank", SEAT_NAME_BLANK_REFUSAL);
243
+ const d = new Draft(entries, subject, ctx);
244
+ seedFromFlat(d, ctx.flatName);
245
+ if (d.live().some((r) => r.raw === v)) return d.done();
246
+ const first = d.live().length === 0;
247
+ d.insert(SeatNameEntrySchema.parse({
248
+ entry_id: d.newId("name"),
249
+ ...base(subject),
250
+ name_type: input.name_type,
251
+ raw: v,
252
+ is_display: first,
253
+ is_preferred: first,
254
+ period_start: "",
255
+ period_end: "",
256
+ notes: ""
257
+ }));
258
+ return d.done();
259
+ }
260
+ function markDisplay(d, target) {
261
+ d.mark(target, "is_display", () => true);
262
+ d.mark(target, "is_preferred", () => true);
263
+ }
264
+ function setSeatDisplayName(entries, subject, entryId, ctx) {
265
+ const d = new Draft(entries, subject, ctx);
266
+ seedFromFlat(d, ctx.flatName);
267
+ markDisplay(d, d.findLive(entryId));
268
+ return d.done();
269
+ }
270
+ function correctSeatName(entries, subject, entryId, next, ctx) {
271
+ const v = next.trim();
272
+ if (!v) throw new SeatLogRefusal("name_blank", SEAT_NAME_BLANK_REFUSAL);
273
+ const d = new Draft(entries, subject, ctx);
274
+ let target;
275
+ if (entryId === FLAT_NAME_ENTRY_ID) {
276
+ const flat = (ctx.flatName ?? "").trim();
277
+ if (flat && v === flat && !d.live().length) return d.done();
278
+ seedFromFlat(d, ctx.flatName);
279
+ const hit = d.live().find((x) => x.raw === flat);
280
+ if (!hit) throw new SeatLogRefusal("entry_not_found", "No flat name to correct.");
281
+ target = hit;
282
+ } else {
283
+ target = d.findLive(entryId);
284
+ }
285
+ if (v === target.raw) return d.done();
286
+ const dupe = d.live().find((x) => x.raw === v && x.entry_id !== target.entry_id);
287
+ if (dupe) {
288
+ if (target.is_display) markDisplay(d, dupe);
289
+ d.archive(target);
290
+ return d.done();
291
+ }
292
+ const added = SeatNameEntrySchema.parse({
293
+ entry_id: d.newId("name"),
294
+ ...base(subject),
295
+ name_type: target.name_type || "legal",
296
+ raw: v,
297
+ is_display: false,
298
+ is_preferred: false,
299
+ period_start: target.period_start || "",
300
+ period_end: "",
301
+ notes: correctsNote(target.notes, target.raw)
302
+ });
303
+ d.insert(added);
304
+ if (target.is_display) markDisplay(d, added);
305
+ d.archive(target);
306
+ return d.done();
307
+ }
308
+ function retireSeatName(entries, subject, entryId, ctx) {
309
+ const d = new Draft(entries, subject, ctx);
310
+ const target = d.findLive(entryId);
311
+ if (target.is_display) {
312
+ throw new SeatLogRefusal(
313
+ "display_name_not_retirable",
314
+ "The display name can't be retired \u2014 star another name first."
315
+ );
316
+ }
317
+ d.archive(target);
318
+ return d.done();
319
+ }
320
+ function formatSeatPhone(s) {
321
+ let d = String(s ?? "").replace(/\D/g, "");
322
+ if (!d) return "";
323
+ if (d.length === 11 && d.charAt(0) === "1") d = d.slice(1);
324
+ if (d.length <= 3) return `(${d}`;
325
+ if (d.length <= 6) return `(${d.slice(0, 3)}) ${d.slice(3)}`;
326
+ if (d.length <= 10) return `(${d.slice(0, 3)}) ${d.slice(3, 6)}-${d.slice(6)}`;
327
+ const cc = d.slice(0, d.length - 10);
328
+ const r = d.slice(d.length - 10);
329
+ return `+${cc} (${r.slice(0, 3)}) ${r.slice(3, 6)}-${r.slice(6)}`;
330
+ }
331
+ function canonSeatContactValue(type, value) {
332
+ const v = String(value ?? "").trim();
333
+ if (type !== "phone" || !v) return v;
334
+ return formatSeatPhone(v) || v;
335
+ }
336
+ function seatContactKey(type, value) {
337
+ const v = String(value ?? "").trim();
338
+ if (!v) return "";
339
+ if (type === "phone") {
340
+ const d = v.replace(/\D/g, "");
341
+ return d.length === 11 && d.charAt(0) === "1" ? d.slice(1) : d;
342
+ }
343
+ return v.toLowerCase();
344
+ }
345
+ function seatPhoneRefusal(value) {
346
+ const t = String(value ?? "").trim();
347
+ if (!t) return "";
348
+ const d = t.replace(/\D/g, "");
349
+ if (!d) return "That doesn't have any numbers in it \u2014 a phone entry needs digits.";
350
+ if (d.length < 7) return "That's too short for a phone number \u2014 it needs at least 7 digits.";
351
+ if (d.length > 15) return "That's too long for a phone number \u2014 15 digits is the international maximum.";
352
+ return "";
353
+ }
354
+ function seatEmailRefusal(value, otherSeatEmails = []) {
355
+ const t = String(value ?? "").trim();
356
+ if (!t) return "";
357
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)) {
358
+ return "That isn't a working address yet \u2014 it needs an @ and a domain.";
359
+ }
360
+ const key = t.toLowerCase();
361
+ for (const e of otherSeatEmails) {
362
+ if ((e ?? "").toLowerCase() === key) return "Already in the directory \u2014 two seats can't share an address.";
363
+ }
364
+ return "";
365
+ }
366
+ function guardContact(type, value, otherSeatEmails) {
367
+ if (type === "email") {
368
+ const m2 = seatEmailRefusal(value, otherSeatEmails);
369
+ if (m2) {
370
+ throw new SeatLogRefusal(m2.startsWith("Already") ? "email_taken" : "email_shape", m2);
371
+ }
372
+ return;
373
+ }
374
+ const m = seatPhoneRefusal(value);
375
+ if (!m) return;
376
+ const code = m.includes("numbers in it") ? "phone_no_digits" : m.includes("too short") ? "phone_too_short" : "phone_too_long";
377
+ throw new SeatLogRefusal(code, m);
378
+ }
379
+ function liveSeatContacts(entries) {
380
+ return entries.filter(isLive);
381
+ }
382
+ function pastSeatContacts(entries) {
383
+ return entries.filter((e) => !isLive(e));
384
+ }
385
+ function preferredSeatContact(entries, type) {
386
+ const live = liveSeatContacts(entries).filter((e) => e.contact_type === type);
387
+ return live.find((e) => e.is_preferred) ?? live[0] ?? null;
388
+ }
389
+ function seatEmailProjection(entries) {
390
+ return preferredSeatContact(entries, "email")?.value ?? "";
391
+ }
392
+ function canRetireSeatContact(entries, entry) {
393
+ if (!entry.is_preferred) return true;
394
+ return liveSeatContacts(entries).filter((x) => x.contact_type === entry.contact_type).length <= 1;
395
+ }
396
+ function contactRow(d, fields) {
397
+ const row = {
398
+ entry_id: d.newId("contact"),
399
+ ...base(d.subject),
400
+ ...fields
401
+ };
402
+ if (row.contact_type === "phone") row.digits = seatContactKey("phone", row.value);
403
+ return SeatContactEntrySchema.parse(row);
404
+ }
405
+ function addSeatContact(entries, subject, input, ctx) {
406
+ const v0 = String(input.value ?? "").trim();
407
+ const d = new Draft(entries, subject, ctx);
408
+ if (!v0) return d.done();
409
+ guardContact(input.contact_type, v0, ctx.otherSeatEmails);
410
+ const type = input.contact_type;
411
+ const v = canonSeatContactValue(type, v0);
412
+ const key = seatContactKey(type, v);
413
+ const sameType = d.live().filter((r) => r.contact_type === type);
414
+ if (sameType.some((r) => seatContactKey(type, r.value) === key)) return d.done();
415
+ d.insert(contactRow(d, {
416
+ contact_type: type,
417
+ value: v,
418
+ use: "",
419
+ is_preferred: sameType.length === 0,
420
+ safety_status: "",
421
+ period_start: "",
422
+ period_end: "",
423
+ notes: ""
424
+ }));
425
+ return d.done();
426
+ }
427
+ function markPreferred(d, target) {
428
+ d.mark(target, "is_preferred", (r) => r.contact_type === target.contact_type);
429
+ }
430
+ function setPreferredSeatContact(entries, subject, entryId, ctx) {
431
+ const d = new Draft(entries, subject, ctx);
432
+ markPreferred(d, d.findLive(entryId));
433
+ return d.done();
434
+ }
435
+ function correctSeatContact(entries, subject, entryId, next, ctx) {
436
+ const d = new Draft(entries, subject, ctx);
437
+ const target = d.findLive(entryId);
438
+ const type = target.contact_type;
439
+ guardContact(type, String(next ?? "").trim(), ctx.otherSeatEmails);
440
+ const v = canonSeatContactValue(type, next);
441
+ if (!v || v === target.value) return d.done();
442
+ const key = seatContactKey(type, v);
443
+ const dupe = d.live().find((x) => x.contact_type === type && seatContactKey(type, x.value) === key && x.entry_id !== target.entry_id);
444
+ if (dupe) {
445
+ if (target.is_preferred) markPreferred(d, dupe);
446
+ d.archive(target);
447
+ return d.done();
448
+ }
449
+ const added = contactRow(d, {
450
+ contact_type: type,
451
+ value: v,
452
+ use: target.use || "",
453
+ is_preferred: false,
454
+ safety_status: target.safety_status || "",
455
+ period_start: target.period_start || "",
456
+ period_end: "",
457
+ notes: correctsNote(target.notes, target.value)
458
+ });
459
+ d.insert(added);
460
+ if (target.is_preferred) markPreferred(d, added);
461
+ d.archive(target);
462
+ return d.done();
463
+ }
464
+ function retireSeatContact(entries, subject, entryId, ctx) {
465
+ const d = new Draft(entries, subject, ctx);
466
+ const target = d.findLive(entryId);
467
+ if (!canRetireSeatContact(d.rows, target)) {
468
+ throw new SeatLogRefusal(
469
+ "preferred_contact_not_retirable",
470
+ `Prefer another ${target.contact_type} before retiring this one.`
471
+ );
472
+ }
473
+ d.archive(target);
474
+ return d.done();
475
+ }
476
+
477
+ // src/seatLogs/personSlugWordlists.ts
478
+ var PERSON_SLUG_FIRST = Object.freeze([
479
+ "agate",
480
+ "alabaster",
481
+ "amber",
482
+ "amethyst",
483
+ "azure",
484
+ "basalt",
485
+ "beryl",
486
+ "bronze",
487
+ "carnelian",
488
+ "cedar",
489
+ "chrome",
490
+ "cinnabar",
491
+ "citrine",
492
+ "copper",
493
+ "coral",
494
+ "crystal",
495
+ "ember",
496
+ "feldspar",
497
+ "flint",
498
+ "garnet",
499
+ "granite",
500
+ "graphite",
501
+ "hematite",
502
+ "indigo",
503
+ "iron",
504
+ "ivory",
505
+ "jade",
506
+ "jasper",
507
+ "lapis",
508
+ "malachite",
509
+ "marble",
510
+ "obsidian",
511
+ "onyx",
512
+ "opal",
513
+ "pearl",
514
+ "pewter",
515
+ "pyrite",
516
+ "quartz",
517
+ "sable",
518
+ "silver",
519
+ "slate",
520
+ "sterling",
521
+ "tin",
522
+ "topaz",
523
+ "tungsten"
524
+ ]);
525
+ var PERSON_SLUG_SECOND = Object.freeze([
526
+ "augur",
527
+ "beacon",
528
+ "cairn",
529
+ "cipher",
530
+ "compass",
531
+ "crest",
532
+ "crown",
533
+ "ember",
534
+ "envoy",
535
+ "flame",
536
+ "glyph",
537
+ "harbor",
538
+ "herald",
539
+ "keep",
540
+ "ledger",
541
+ "lighthouse",
542
+ "lyre",
543
+ "mantle",
544
+ "monolith",
545
+ "oracle",
546
+ "pillar",
547
+ "plume",
548
+ "quill",
549
+ "relic",
550
+ "rune",
551
+ "scribe",
552
+ "scroll",
553
+ "seal",
554
+ "sentinel",
555
+ "sigil",
556
+ "sojourner",
557
+ "spire",
558
+ "standard",
559
+ "tablet",
560
+ "talisman",
561
+ "thread",
562
+ "torch",
563
+ "totem",
564
+ "tower",
565
+ "verse",
566
+ "vessel",
567
+ "warden",
568
+ "watch",
569
+ "witness",
570
+ "wreath"
571
+ ]);
572
+ var PERSON_SLUG_WORDLISTS = Object.freeze({
573
+ first: PERSON_SLUG_FIRST,
574
+ second: PERSON_SLUG_SECOND
575
+ });
576
+
577
+ // src/seatLogs/personId.ts
578
+ var PERSON_ID_PATTERN = /^per-[a-z0-9]+-[a-z0-9]+(?:-\d+)?$/;
579
+ function isPersonId(v) {
580
+ return typeof v === "string" && PERSON_ID_PATTERN.test(v);
581
+ }
582
+ function indexOf(r, n) {
583
+ if (!Number.isFinite(r)) return 0;
584
+ return Math.min(n - 1, Math.max(0, Math.floor(r * n)));
585
+ }
586
+ function mintPersonId(wordlists = PERSON_SLUG_WORDLISTS, taken = [], random = Math.random) {
587
+ const F = wordlists?.first ?? [];
588
+ const S = wordlists?.second ?? [];
589
+ if (!F.length || !S.length) return null;
590
+ const used = /* @__PURE__ */ new Set();
591
+ for (const t of taken) if (t) used.add(t);
592
+ const pick = (list) => list[indexOf(random(), list.length)];
593
+ for (let i = 0; i < 200; i++) {
594
+ const slug = "per-" + pick(F) + "-" + pick(S);
595
+ if (!used.has(slug)) return slug;
596
+ }
597
+ for (const f of F) {
598
+ for (const t of S) {
599
+ const slug = "per-" + f + "-" + t;
600
+ if (!used.has(slug)) return slug;
601
+ }
602
+ }
603
+ for (let i = 0; i < 200; i++) {
604
+ const slug = "per-" + pick(F) + "-" + pick(S) + "-" + indexOf(random(), 1e3);
605
+ if (!used.has(slug)) return slug;
606
+ }
607
+ for (let num = 0; ; num++) {
608
+ for (const f of F) {
609
+ for (const t of S) {
610
+ const slug = "per-" + f + "-" + t + "-" + num;
611
+ if (!used.has(slug)) return slug;
612
+ }
613
+ }
614
+ }
615
+ }
616
+ function mintNewPersonId(taken = [], random = Math.random) {
617
+ return mintPersonId(PERSON_SLUG_WORDLISTS, taken, random);
618
+ }
619
+
620
+ // src/seatLogs/reader.ts
621
+ var SeatLogShapeError = class extends Error {
622
+ constructor(entryId, issues) {
623
+ super(`seat-logs: stored entry ${entryId ?? "(no id)"} does not match the contract: ${issues.join("; ")}`);
624
+ this.entryId = entryId;
625
+ this.issues = issues;
626
+ this.name = "SeatLogShapeError";
627
+ }
628
+ };
629
+ function strip(r) {
630
+ if (r === null || typeof r !== "object") return {};
631
+ const { _id: _ignored, ...rest } = r;
632
+ return rest;
633
+ }
634
+ function parseWith(schema, raw) {
635
+ const row = strip(raw);
636
+ const p = schema.safeParse(row);
637
+ if (p.success) return p.data;
638
+ throw new SeatLogShapeError(
639
+ typeof row.entry_id === "string" ? row.entry_id : null,
640
+ p.error.issues.map((i) => `${i.path.join(".") || "(row)"}: ${i.message}`)
641
+ );
642
+ }
643
+ var idForms = (id) => [.../* @__PURE__ */ new Set([id, id.toLowerCase()])];
644
+ var byEntryId = (a, b) => a.entry_id < b.entry_id ? -1 : a.entry_id > b.entry_id ? 1 : 0;
645
+ async function readLogs(db, collection, subjectType, subjectIds, parse, opts) {
646
+ const ids = [...new Set(subjectIds.filter((s) => typeof s === "string" && s))];
647
+ const out = /* @__PURE__ */ new Map();
648
+ if (!ids.length) return out;
649
+ const askedByKey = /* @__PURE__ */ new Map();
650
+ for (const id of ids) {
651
+ const k = id.toLowerCase();
652
+ askedByKey.set(k, [...askedByKey.get(k) ?? [], id]);
653
+ }
654
+ const raw = await db.collection(collection).find({ subject_type: subjectType, subject_id: { $in: ids.flatMap(idForms) } }).toArray();
655
+ for (const r of raw) {
656
+ let e;
657
+ try {
658
+ e = parse(r);
659
+ } catch (err) {
660
+ if (opts.invalid !== "skip" || !(err instanceof SeatLogShapeError)) throw err;
661
+ opts.onInvalidRow?.(err);
662
+ continue;
663
+ }
664
+ for (const asked of askedByKey.get(e.subject_id.toLowerCase()) ?? []) {
665
+ const list = out.get(asked) ?? [];
666
+ list.push(e);
667
+ out.set(asked, list);
668
+ }
669
+ }
670
+ for (const list of out.values()) list.sort(byEntryId);
671
+ return out;
672
+ }
673
+ function readSeatNameLogs(db, subjectIds, subjectType = "user", opts = {}) {
674
+ return readLogs(
675
+ db,
676
+ SEAT_NAMES_COLLECTION,
677
+ subjectType,
678
+ subjectIds,
679
+ (r) => parseWith(SeatNameEntrySchema, r),
680
+ opts
681
+ );
682
+ }
683
+ function readSeatContactLogs(db, subjectIds, subjectType = "user", opts = {}) {
684
+ return readLogs(
685
+ db,
686
+ SEAT_CONTACTS_COLLECTION,
687
+ subjectType,
688
+ subjectIds,
689
+ (r) => parseWith(SeatContactEntrySchema, r),
690
+ opts
691
+ );
692
+ }
693
+ export {
694
+ FLAT_NAME_ENTRY_ID,
695
+ PERSON_ID_PATTERN,
696
+ PERSON_SLUG_FIRST,
697
+ PERSON_SLUG_SECOND,
698
+ PERSON_SLUG_WORDLISTS,
699
+ SEAT_CONTACTS_COLLECTION,
700
+ SEAT_CONTACT_TYPES,
701
+ SEAT_LOG_SUBJECT_TYPES,
702
+ SEAT_NAMES_COLLECTION,
703
+ SEAT_NAME_ADD_TYPES,
704
+ SEAT_NAME_BLANK_REFUSAL,
705
+ SEAT_NAME_TYPES,
706
+ SeatContactEntrySchema,
707
+ SeatLogEventSchema,
708
+ SeatLogRefusal,
709
+ SeatLogShapeError,
710
+ SeatNameEntrySchema,
711
+ addSeatContact,
712
+ addSeatName,
713
+ canRetireSeatContact,
714
+ canonSeatContactValue,
715
+ correctSeatContact,
716
+ correctSeatName,
717
+ formatSeatPhone,
718
+ isPersonId,
719
+ liveSeatContacts,
720
+ liveSeatNames,
721
+ mintNewPersonId,
722
+ mintPersonId,
723
+ mintSeatLogEntryId,
724
+ pastSeatContacts,
725
+ pastSeatNames,
726
+ preferredSeatContact,
727
+ readSeatContactLogs,
728
+ readSeatNameLogs,
729
+ retireSeatContact,
730
+ retireSeatName,
731
+ seatContactKey,
732
+ seatDisplayNameEntry,
733
+ seatEmailProjection,
734
+ seatEmailRefusal,
735
+ seatNameProjection,
736
+ seatNameRows,
737
+ seatPhoneRefusal,
738
+ seedSeatNameLog,
739
+ setPreferredSeatContact,
740
+ setSeatDisplayName
741
+ };
742
+ //# sourceMappingURL=index.js.map