@chatwarden/core 0.1.11 → 0.1.12

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/src/links.ts ADDED
@@ -0,0 +1,80 @@
1
+ // `cw.links` (K5 design 5.1): "this kit id is that outside id", one small table for the outside-system adapters (Coop jobs, EOS sanctions,
2
+ // EOS report keys and one polling cursor). Rows are ids and one short state word, never text: no chat line, handle, reason or outside
3
+ // account id is written here, and a check pins the value shapes.
4
+
5
+ /** The systems a link can belong to: a closed list. */
6
+ export const LINK_SYSTEMS = ['coop-report', 'eos-sanction', 'eos-report', 'eos-cursor'] as const;
7
+ export type LinkSystem = (typeof LINK_SYSTEMS)[number];
8
+
9
+ /**
10
+ * One link row.
11
+ * @experimental
12
+ */
13
+ export interface LinkRow {
14
+ system: LinkSystem;
15
+ /** A kit id or a key derived from outside data (never an outside account id): 1..128 characters of A-Z a-z 0-9 _ . : # -. */
16
+ ref: string;
17
+ /** The outside system's id for it (a Coop report uuid, an EOS referenceId, an ISO cursor): 1..128 characters of the same set. */
18
+ external: string;
19
+ /** One short word: 'sent', 'decided', 'active', 'removed', 'filed', 'skipped'. 1..32 characters of a-z _ . */
20
+ state: string;
21
+ /** Epoch ms, from the kit's clock. */
22
+ at: number;
23
+ }
24
+
25
+ /** The longest ref or external. */
26
+ export const LINK_VALUE_MAX = 128;
27
+ /** The longest state. */
28
+ export const LINK_STATE_MAX = 32;
29
+ /** `list` takes at most this many rows; the default is {@link LINK_LIST_DEFAULT}. */
30
+ export const LINK_LIST_MAX = 500;
31
+ export const LINK_LIST_DEFAULT = 100;
32
+
33
+ const VALUE_RE = /^[A-Za-z0-9_.:#-]+$/;
34
+ const STATE_RE = /^[a-z_.]+$/;
35
+
36
+ /** True for a system on the closed list. */
37
+ export function isLinkSystem(value: unknown): value is LinkSystem {
38
+ return typeof value === 'string' && (LINK_SYSTEMS as readonly string[]).includes(value);
39
+ }
40
+
41
+ /** True for a `ref` or `external` value: 1..128 characters of the allowed set. */
42
+ export function isLinkValue(value: unknown): value is string {
43
+ return typeof value === 'string' && value.length >= 1 && value.length <= LINK_VALUE_MAX && VALUE_RE.test(value);
44
+ }
45
+
46
+ /**
47
+ * Check a row's shape. Throws `TypeError` for a value that is not an object and `RangeError` for a field outside its shape; the message
48
+ * names the field and never the value.
49
+ */
50
+ export function checkLinkRow(row: LinkRow): void {
51
+ if (typeof row !== 'object' || row === null || Array.isArray(row)) throw new TypeError('a link row is an object');
52
+ if (!isLinkSystem(row.system)) throw new RangeError('link system is not one of the known systems');
53
+ if (!isLinkValue(row.ref)) throw new RangeError(`link ref must be 1 to ${LINK_VALUE_MAX} characters of A-Z a-z 0-9 _ . : # -`);
54
+ if (!isLinkValue(row.external)) throw new RangeError(`link external must be 1 to ${LINK_VALUE_MAX} characters of A-Z a-z 0-9 _ . : # -`);
55
+ if (typeof row.state !== 'string' || row.state.length < 1 || row.state.length > LINK_STATE_MAX || !STATE_RE.test(row.state)) {
56
+ throw new RangeError(`link state must be 1 to ${LINK_STATE_MAX} characters of a-z _ .`);
57
+ }
58
+ if (typeof row.at !== 'number' || !Number.isFinite(row.at) || row.at < 0) throw new RangeError('link at must be a finite non-negative number');
59
+ }
60
+
61
+ /** The default and the clamp of `list`'s limit: a fraction is floored, a non-number or NaN is the default. */
62
+ export function linkLimit(limit: unknown): number {
63
+ if (typeof limit !== 'number' || Number.isNaN(limit)) return LINK_LIST_DEFAULT;
64
+ return Math.min(LINK_LIST_MAX, Math.max(1, Math.floor(limit)));
65
+ }
66
+
67
+ /** True when the store has all four link methods. */
68
+ export function hasLinkMethods(store: {
69
+ getLink?: unknown;
70
+ putLink?: unknown;
71
+ listLinks?: unknown;
72
+ purgeLinks?: unknown;
73
+ }): boolean {
74
+ return (
75
+ typeof store.getLink === 'function' &&
76
+ typeof store.putLink === 'function' &&
77
+ typeof store.listLinks === 'function' &&
78
+ typeof store.purgeLinks === 'function'
79
+ );
80
+ }
package/src/retention.ts CHANGED
@@ -195,6 +195,7 @@ function checkWindow(name: string, ms: number): void {
195
195
  * permanent, or timed and not yet ended before that cutoff, and not revoked (that row stops a second appeal). An open appeal is never
196
196
  * deleted or cleared; but one whose sanction rows this pass removed (or that has none) is first mooted, so it ends up decided-like. Blocked names: `at < now - blockedNamesMs` (30 days by default).
197
197
  * A store without the appeal or blocked-name methods has none of these.
198
+ * - links (`cw.links`): `at < now - reportsMs` (90 days by default), every system. A store without the link methods has none.
198
199
  * - notices: withdrawn, or a seen warning / report outcome, with `createdAt < now - noticesMs`; or
199
200
  * `until < now - noticesMs`. A notice for a permanent or running sanction is kept while it applies (agrees with
200
201
  * `NoticeService.record`), and an unseen warning is kept until it is seen or withdrawn. The four message kinds: seen, as a report outcome;
@@ -237,6 +238,8 @@ export async function purge(
237
238
  checkWindow('blockedNamesMs', p.blockedNamesMs);
238
239
  return store.transaction(() => {
239
240
  const reports = store.purgeReports(now - p.reportsMs, now - p.badFaithMs);
241
+ // Link rows (`cw.links`) are ids only and outlive the report they name by no useful time: the same clock as reports. Not counted in the result. A live row (an active EOS sanction, the EOS cursor) is kept by the store whatever its age.
242
+ store.purgeLinks?.(now - p.reportsMs);
240
243
  const ai = store.purgeAi?.(now - p.reportsMs, now - p.aiOutcomesMs, now - p.aiExamplesMs) ?? { reads: 0, outcomes: 0 };
241
244
  return {
242
245
  reports,
package/src/sanctions.ts CHANGED
@@ -49,6 +49,23 @@ const REF_ATTEMPTS = 5;
49
49
  /** No I, L, O, 0 or 1: a player reads the code aloud or types it from a screenshot. */
50
50
  const REF_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
51
51
 
52
+ /**
53
+ * Reads a player-typed reference code: trims, ignores case, accepts a bare five characters as `M-` plus them. Returns the canonical
54
+ * `M-XXXXX`, or null for anything else (a wrong length, an ambiguous character I, L, O, 0 or 1, another prefix). A non-string is a
55
+ * `TypeError`. Pure.
56
+ * @experimental
57
+ */
58
+ export function normalizeRefCode(text: string): string | null {
59
+ if (typeof text !== 'string') throw new TypeError('a reference code is a string');
60
+ const t = text.trim();
61
+ // ASCII only before upper-casing: a few non-ASCII letters (a long s) upper-case into a valid one.
62
+ const m = /^(?:[Mm]-)?([A-Za-z0-9]{5})$/.exec(t);
63
+ const code = m?.[1]?.toUpperCase();
64
+ if (code === undefined) return null;
65
+ for (const ch of code) if (!REF_ALPHABET.includes(ch)) return null;
66
+ return `M-${code}`;
67
+ }
68
+
52
69
  /**
53
70
  * The key to `SanctionInput.startsAt`. It is exported from this module only, never from the package index, so only code inside the kit (the
54
71
  * appeals service) can hold it; a public caller passing a start time is refused with a `RangeError`.
package/src/staffViews.ts CHANGED
@@ -208,6 +208,39 @@ export function listSanctionGroups(store: Store, subjects: SubjectIndex, q: Sanc
208
208
  };
209
209
  }
210
210
 
211
+ /** How many of the newest groups the by-ref fallback reads for a store with no `sanctionGroupByRef`. */
212
+ export const BY_REF_FALLBACK_GROUPS = 1000;
213
+
214
+ /**
215
+ * One group's staff view with its canonical person, found by a normalised ref code (`M-XXXXX`), or null. A store with
216
+ * `sanctionGroupByRef` answers from its index; one without is read through the newest {@link BY_REF_FALLBACK_GROUPS} groups.
217
+ * Built from the group's SUBJECT row only: an IP row is never read.
218
+ */
219
+ export function sanctionByRef(store: Store, subjects: SubjectIndex, code: string, now: number): PersonSanctionView | null {
220
+ const view = (r: SanctionRow): PersonSanctionView => ({ ...sanctionGroupView(r, now), person: subjects.canonical(r.value) });
221
+ if (typeof store.sanctionGroupByRef === 'function') {
222
+ const groupId = store.sanctionGroupByRef(code);
223
+ if (groupId === null) return null;
224
+ const row = store.listSubjectSanctions({ groupId, limit: 5 }).find((r) => r.groupId === groupId && r.refCode === code);
225
+ return row === undefined ? null : view(row);
226
+ }
227
+ let before: { startsAt: number; id: string } | null = null;
228
+ let seen = 0;
229
+ while (seen < BY_REF_FALLBACK_GROUPS) {
230
+ const page = store.listSubjectSanctions({
231
+ limit: Math.min(200, BY_REF_FALLBACK_GROUPS - seen),
232
+ ...(before === null ? {} : { before: before.startsAt, beforeId: before.id }),
233
+ });
234
+ const hit = page.find((r) => r.refCode === code);
235
+ if (hit !== undefined) return view(hit);
236
+ const last = page[page.length - 1];
237
+ if (last === undefined || page.length < Math.min(200, BY_REF_FALLBACK_GROUPS - seen)) return null;
238
+ seen += page.length;
239
+ before = { startsAt: last.startsAt, id: last.id };
240
+ }
241
+ return null;
242
+ }
243
+
211
244
  // ---------------------------------------------------------------------------
212
245
  // The reporter's record
213
246
  // ---------------------------------------------------------------------------
package/src/types.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  import type { AIExample, AIRead, AISignal } from './ai/types.js';
5
5
  import type { AppealStatus } from './appeals.js';
6
6
  import type { AuditListQuery, AuditRow } from './audit.js';
7
+ import type { LinkRow, LinkSystem } from './links.js';
7
8
  import type { NameReason } from './names.js';
8
9
  import type { PolicyLayer } from './profile.js';
9
10
  import type { RuleRef } from './rules.js';
@@ -216,6 +217,8 @@ export interface SanctionListQuery {
216
217
  /** Keyset cursor: only rows older than this (`startsAt` below it, or equal with an id below `beforeId`). `beforeId` without `before` is ignored. */
217
218
  before?: number;
218
219
  beforeId?: string;
220
+ /** Only the rows of this sanction group (its subject row: an IP row is never listed). Optional, additive (0.1.12). */
221
+ groupId?: string;
219
222
  /** Clamped to 1..200 (a fraction is floored). */
220
223
  limit: number;
221
224
  }
@@ -883,6 +886,15 @@ export interface Store {
883
886
  */
884
887
  sanctionRefCode(groupId: string): string | null;
885
888
 
889
+ /**
890
+ * OPTIONAL (0.1.12, `@experimental`). The sanction group that holds this exact ref code (`M-` plus five characters, already
891
+ * normalised: upper case), or null. Revoked and ended groups are found: the code never changes. A store that implements it MUST also honour
892
+ * `SanctionListQuery.groupId` (`cw.sanctions.byRef` reads the group's rows with it; a store that ignores the filter returns other groups'
893
+ * rows and the code is silently missed). A store without it makes
894
+ * `cw.sanctions.byRef` read the newest 1 000 groups through {@link Store.listSubjectSanctions} instead.
895
+ */
896
+ sanctionGroupByRef?(refCode: string): string | null;
897
+
886
898
  /**
887
899
  * The person a sanction group is about and the rule it cites, for the `sanction.revoked` event: the group's SUBJECT row
888
900
  * (its IP row is not a person) and its stored rule text (`'1'`.., `'uncovered'`, or null on a row written before rules
@@ -1398,6 +1410,29 @@ export interface Store {
1398
1410
  /** OPTIONAL. Delete names with `at < before` (a row exactly on the line is kept); returns how many. */
1399
1411
  purgeBlockedNames?(before: number): number;
1400
1412
 
1413
+ // Links (K5 design 5.1, `cw.links`). OPTIONAL: a store without all four has `cw.links.supported` false, and an adapter that needs links
1414
+ // refuses it at construction. SYNCHRONOUS (like notices); they run inside `transaction` and are undone with it. They take a row the
1415
+ // facade has already validated, keep it as it is and return copies. A link write is not a queue change: it does not move the change token.
1416
+
1417
+ /** OPTIONAL (`@experimental`). The row for `(system, ref)`, a copy, or null. */
1418
+ getLink?(system: LinkSystem, ref: string): LinkRow | null;
1419
+
1420
+ /** OPTIONAL (`@experimental`). Insert the row, or replace the one with the same `(system, ref)`. */
1421
+ putLink?(row: LinkRow): void;
1422
+
1423
+ /**
1424
+ * OPTIONAL (`@experimental`). The `system`'s rows, oldest `at` first and then by `ref` (code point order), only this `state` when given,
1425
+ * at most `limit` (floored, clamped to 1..500; NaN is 1). The state filter applies before the limit. Copies.
1426
+ */
1427
+ listLinks?(system: LinkSystem, q: { state?: string; limit: number }): LinkRow[];
1428
+
1429
+ /**
1430
+ * OPTIONAL (`@experimental`). Delete rows with `at < before` (a row exactly on the line is kept); returns how many. A row that says it is live
1431
+ * is never deleted by age: an `eos-sanction` row in state `active` (a lift long after the push must still find it) and every `eos-cursor`
1432
+ * row. Once such a row is marked `removed` (or `failed`) its `at` is new and it ages out like any other.
1433
+ */
1434
+ purgeLinks?(before: number): number;
1435
+
1401
1436
  // Staff audit trail. SYNCHRONOUS on purpose (like sanctions). The trail also holds the rows `closeGap` and the term
1402
1437
  // editor write; none of these methods ever returns the json columns those carry (they may hold term text).
1403
1438