@htilabs/platform-common-models 0.39.0 → 0.41.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.
Files changed (48) hide show
  1. package/README.md +86 -0
  2. package/dist/age/index.cjs +136 -0
  3. package/dist/age/index.cjs.map +1 -0
  4. package/dist/age/index.d.cts +136 -0
  5. package/dist/age/index.d.ts +136 -0
  6. package/dist/age/index.js +105 -0
  7. package/dist/age/index.js.map +1 -0
  8. package/dist/index.cjs +159 -0
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +2 -1
  11. package/dist/index.d.ts +2 -1
  12. package/dist/index.js +150 -0
  13. package/dist/index.js.map +1 -1
  14. package/dist/share-rules/index.cjs +822 -0
  15. package/dist/share-rules/index.cjs.map +1 -0
  16. package/dist/share-rules/index.d.cts +804 -0
  17. package/dist/share-rules/index.d.ts +804 -0
  18. package/dist/share-rules/index.js +736 -0
  19. package/dist/share-rules/index.js.map +1 -0
  20. package/dist/sharing-ceiling/index.cjs +51 -0
  21. package/dist/sharing-ceiling/index.cjs.map +1 -1
  22. package/dist/sharing-ceiling/index.d.cts +87 -1
  23. package/dist/sharing-ceiling/index.d.ts +87 -1
  24. package/dist/sharing-ceiling/index.js +47 -0
  25. package/dist/sharing-ceiling/index.js.map +1 -1
  26. package/package.json +12 -1
  27. package/src/age/__tests__/ageFromDob.test.ts +192 -0
  28. package/src/age/ageFromDob.ts +269 -0
  29. package/src/age/index.ts +8 -0
  30. package/src/index.ts +4 -0
  31. package/src/shareRules/__tests__/caseShareLane.test.ts +259 -0
  32. package/src/shareRules/__tests__/magicLinkAddresses.test.ts +107 -0
  33. package/src/shareRules/__tests__/platformApps.test.ts +133 -0
  34. package/src/shareRules/__tests__/releaseTerms.test.ts +358 -0
  35. package/src/shareRules/__tests__/senderRoiPosture.test.ts +284 -0
  36. package/src/shareRules/__tests__/sharingMethods.test.ts +105 -0
  37. package/src/shareRules/caseShareLane.ts +289 -0
  38. package/src/shareRules/index.ts +31 -0
  39. package/src/shareRules/magicLinkAddresses.ts +185 -0
  40. package/src/shareRules/platformApps.ts +168 -0
  41. package/src/shareRules/releaseTerms.ts +359 -0
  42. package/src/shareRules/reportPurposes.ts +50 -0
  43. package/src/shareRules/senderRoiPosture.ts +296 -0
  44. package/src/shareRules/sharingMethods.ts +204 -0
  45. package/src/sharingCeiling/__tests__/threadLift.test.ts +353 -0
  46. package/src/sharingCeiling/coverage.ts +63 -0
  47. package/src/sharingCeiling/defaults.ts +106 -0
  48. package/src/sharingCeiling/index.ts +7 -0
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Which apps put a share recipient on the platform, and which app a team's
3
+ * shares land in — the two app-membership readings the magic-link and
4
+ * CaseShare-lane rules (./magicLinkAddresses.ts, ./caseShareLane.ts) stand on.
5
+ *
6
+ * Lifted unchanged from Thread `@thread/shared` @ thread develop f021be2:
7
+ * - `shareEdge.ts` L21-L125 — `RecipientPlatformSnapshot`,
8
+ * `recipientPlatformFromApps`, `recipientUsesApp`, `agencyIdKey` and their
9
+ * private helpers (th-a2dfb, Ava A7);
10
+ * - `teamLanding.ts` (whole file) — `teamLandingApp`, `teamLandsInPave`,
11
+ * `teamLandsInThread` (th-ng838.4 MINOR-1).
12
+ * They moved because the lifted rules import them; they are small and pure
13
+ * and read only `PLATFORM_TOOL` (this package). Behaviour and doc comments
14
+ * are Thread's.
15
+ *
16
+ * Pure: no mongoose, no I/O, no SOT import.
17
+ */
18
+
19
+ import {
20
+ PLATFORM_TOOL,
21
+ type PlatformToolValue,
22
+ } from "../constants/platform-auth.js";
23
+
24
+ // ─── On-platform by casework apps (shareEdge.ts L21-L125) ───────────────────
25
+
26
+ export interface RecipientPlatformSnapshot {
27
+ readonly recipientOnPlatform: boolean;
28
+ /**
29
+ * The recipient org's apps EXACTLY as read (non-empty strings, case kept —
30
+ * e.g. ["TRAIL", "THREAD"]): the audit basis the edge stores. It is NOT
31
+ * the on-platform test — an org on TRAIL alone has a non-empty basis and
32
+ * is off-platform (th-a2dfb). Read `recipientOnPlatform`.
33
+ */
34
+ readonly recipientOnPlatformBasis: string[];
35
+ }
36
+
37
+ /**
38
+ * The daily casework apps — the only apps that put a share recipient's
39
+ * inbox on the platform. The platform's network-reach rule (platform-prototype
40
+ * src/agencyhub.jsx L8708-8711 @ 0fa04c1, `networkReachFor`):
41
+ * thread / pave / leads, matched case-insensitively. Codes from
42
+ * `PLATFORM_TOOL`.
43
+ */
44
+ const CASEWORK_APPS: readonly PlatformToolValue[] = [
45
+ PLATFORM_TOOL.THREAD,
46
+ PLATFORM_TOOL.PAVE,
47
+ PLATFORM_TOOL.LEADS,
48
+ ];
49
+
50
+ /**
51
+ * ASCII whitespace only (space, tab, newline, vertical tab, form feed,
52
+ * carriage return) — the PCRE `\s` the shareable listing's Mongo query
53
+ * matches, so the JS predicate and the query agree exactly (PAVE trims the
54
+ * same set). A non-breaking space is NOT trimmed.
55
+ */
56
+ function trimAsciiWhitespace(s: string): string {
57
+ return s.replace(/^[ \t\n\v\f\r]+|[ \t\n\v\f\r]+$/g, "");
58
+ }
59
+
60
+ /** Matched trimmed and case-insensitively ("PAVE " and "pave" are PAVE). */
61
+ function isCaseworkApp(app: string): boolean {
62
+ return CASEWORK_APPS.some((c) => recipientUsesApp([app], c));
63
+ }
64
+
65
+ /**
66
+ * The org's apps as read: a list's non-empty strings, kept as written; a
67
+ * bare-string value (`"PAVE"`) counts as a one-item list; anything else is
68
+ * no apps.
69
+ */
70
+ function appsAsRead(apps: unknown): string[] {
71
+ const list: readonly unknown[] =
72
+ typeof apps === "string" ? [apps] : Array.isArray(apps) ? apps : [];
73
+ return list.filter((a): a is string => typeof a === "string" && a.length > 0);
74
+ }
75
+
76
+ /**
77
+ * Whether an ORGANIZATION's `apps` (read as {@link appsAsRead} reads them)
78
+ * include `app`, trimmed of ASCII whitespace and case-insensitively — the ONE
79
+ * agency app-membership test (the shareable listing, the A7 derivation and
80
+ * the CaseShare rule's LEADS-only agency reading all use it; th-fbb8e
81
+ * review). A TEAM's landing app is read strictly instead
82
+ * ({@link teamLandingApp}: the first entry, an exact uppercase PLATFORM_TOOL
83
+ * code).
84
+ */
85
+ export function recipientUsesApp(apps: unknown, app: string): boolean {
86
+ const want = app.toLowerCase();
87
+ return appsAsRead(apps).some(
88
+ (a) => trimAsciiWhitespace(a).toLowerCase() === want,
89
+ );
90
+ }
91
+
92
+ /**
93
+ * The key one agency (or team) id is compared under across its stored forms:
94
+ * a 24-hex id lower-cased (an ObjectId's hex and every hex string written from
95
+ * it agree), anything else exactly as given. The ONE 24-hex normaliser
96
+ * (th-fbb8e review).
97
+ */
98
+ export function agencyIdKey(id: unknown): string {
99
+ const s = String(id);
100
+ return /^[0-9a-fA-F]{24}$/.test(s) ? s.toLowerCase() : s;
101
+ }
102
+
103
+ /**
104
+ * Ava A7: "a magic-link recipient is a share recipient that is not using HTI
105
+ * Platform apps". th-a2dfb: the ROUTING rule — on-platform ⇔ the org uses at
106
+ * least one daily casework app (THREAD / PAVE / LEADS — trimmed, any case;
107
+ * a bare-string `apps` value is a one-item list), the
108
+ * platform's `networkReachFor` — so the picker's reach chip and the lane
109
+ * agree: an org on TRAIL / ECHO alone has no inbox to receive a CaseShare,
110
+ * reads Magic Link and rides the magic link.
111
+ *
112
+ * KNOWN DIVERGENCE (veto-able, pending a ruling): the monolith's share-edge
113
+ * derivation `_onPlatformFor` (HTI-LEADS-PAVE-Thread-prototype.html
114
+ * L343282-343299 over `_orgAppsMono` L343036 @ prototype 40f57adf) stamps
115
+ * the edge `value: apps.length > 0` over ALL daily apps, echo / trail
116
+ * included. Thread stamps `recipientOnPlatform` by the casework rule so the
117
+ * stamp matches the lane the share actually took; the basis keeps every app
118
+ * as read, so nothing the monolith records is lost.
119
+ *
120
+ * The EDGE records the derivation and its basis; the org is never marked
121
+ * ("derived from the org's apps_used, never typed on the org").
122
+ */
123
+ export function recipientPlatformFromApps(
124
+ apps: unknown,
125
+ ): RecipientPlatformSnapshot {
126
+ const basis = appsAsRead(apps);
127
+ return {
128
+ recipientOnPlatform: basis.some(isCaseworkApp),
129
+ recipientOnPlatformBasis: basis,
130
+ };
131
+ }
132
+
133
+ // ─── A team's landing app (teamLanding.ts) ──────────────────────────────────
134
+ //
135
+ // Canon lands a share in the receiving team's FIRST app:
136
+ // `_landApp = _landTeam.apps_used[0]` (monolith L340168-340207 @ prototype
137
+ // c2900116). Canon's intake resolver, though, picks a team that merely USES
138
+ // PAVE (`apps_used.indexOf("pave") >= 0`) — so a dual-app team listing PAVE
139
+ // second gets the preset in canon yet lands in Thread. Thread reads ONE
140
+ // predicate for both: a team is a PAVE intake-landing team only when its
141
+ // landing app (`apps[0]`) is `PAVE` (a recorded narrowing of canon's
142
+ // resolver, keeping its landing rule exact).
143
+ //
144
+ // Codes are the uppercase PLATFORM_TOOL codes the platform-db writers stamp;
145
+ // a lowercase `pave` is off-vocabulary and lands nowhere (th-ng838.2's strict
146
+ // reading).
147
+
148
+ /** The team's landing app — its first declared app code, or undefined. */
149
+ export function teamLandingApp(
150
+ apps: readonly unknown[] | null | undefined,
151
+ ): string | undefined {
152
+ const first = Array.isArray(apps) ? apps[0] : undefined;
153
+ return typeof first === "string" && first.length > 0 ? first : undefined;
154
+ }
155
+
156
+ /** True iff the team's landing app is PAVE (the intake-referral target). */
157
+ export function teamLandsInPave(
158
+ apps: readonly unknown[] | null | undefined,
159
+ ): boolean {
160
+ return teamLandingApp(apps) === PLATFORM_TOOL.PAVE;
161
+ }
162
+
163
+ /** True iff the team's landing app is THREAD (the cross-team inbox lane). */
164
+ export function teamLandsInThread(
165
+ apps: readonly unknown[] | null | undefined,
166
+ ): boolean {
167
+ return teamLandingApp(apps) === PLATFORM_TOOL.THREAD;
168
+ }
@@ -0,0 +1,359 @@
1
+ /**
2
+ * Lifted unchanged from Thread `@thread/shared` `shareReleaseTerms.ts` (the
3
+ * whole module, L1-L313) @ thread develop f021be2. Its Thread-only imports
4
+ * were cut as listed below the module note; Thread's note follows.
5
+ *
6
+ * THE RELEASE'S TERMS AT THE SHARE BOUNDARY — the pure rule, ONE copy
7
+ * (Next Steps declutter spec 2026-10-17, R19 / R21; v2.2 R66 / R67;
8
+ * Kickoff 07b step 6).
9
+ *
10
+ * - R19 (+R66) — the METHOD. A release lists the ways the client agreed
11
+ * their information may be sent (`approvedSharingMethods`, the
12
+ * `SHARING_METHOD` vocabulary a share's `method` uses). A share by a
13
+ * method the release does not list is REFUSED — the remedy is a renewal
14
+ * that adds the method (a signed release is never edited).
15
+ * - R21 (+R67) — the END DATE. A share never outlives its release (ruling
16
+ * E): a blank / no-time-limit expiry takes the release's end date; a
17
+ * later date is REFUSED (never capped silently).
18
+ *
19
+ * ## One implementation
20
+ *
21
+ * The server's doors (apps/api `helpers/share-release-terms.ts`, which keeps
22
+ * only the I/O: refusal codes, the drain's failedReason, the 422 reply) and
23
+ * the web composer (`ShareComposer` / `releaseTerms.ts` /
24
+ * `methodAvailability.ts`) both call THESE functions — the same shape as
25
+ * `shareRoiBasis.ts`. The composer had its own copy once, and the two drifted
26
+ * (pre-review M2 / M3 / L3, Kickoff 07b). Pure — no I/O, no logging.
27
+ *
28
+ * ## Exemptions
29
+ *
30
+ * As the prototype exempts every release question (`shareReleaseOf` /
31
+ * `shareReleaseMethodGaps`, monolith @ 31e3cf68 L344975-344987): an
32
+ * own-agency team (no release governs it — the ROI-basis ladder's rung 3,
33
+ * `isInternalIntakeReferral`) for both rules, and a reporting
34
+ * (legal-override) purpose (`isRoiWaiverExemptPurpose`, § 5.77) for the
35
+ * method rule. R21 binds only the methods the PLATFORM delivers (R76).
36
+ *
37
+ * ## Dependencies, cut from `@thread/shared` (the lift)
38
+ *
39
+ * - `SHARING_METHOD` / `SHARING_METHOD_LABELS` and
40
+ * `sharingMethodOfReleaseMethod` — moved to ./sharingMethods.ts.
41
+ * - `isRoiWaiverExemptPurpose` — moved to ./reportPurposes.ts.
42
+ * - `isInternalIntakeReferral` (Thread `constants/shareDeliveryKey.ts`
43
+ * L101-L122) — a two-line predicate, inlined below as
44
+ * `isSameAgencySend`, unchanged.
45
+ * - `ROI_BASIS_REASON.ROI_ON_FILE` (Thread `constants/ic.ts` L708) — the one
46
+ * basis REASON this rule reads, kept as the literal
47
+ * {@link ROI_BASIS_REASON_ROI_ON_FILE}; `roiBasis.reason` is typed
48
+ * `string` so either app's reason type passes.
49
+ *
50
+ * Pure — no mongoose, no I/O, no SOT import.
51
+ */
52
+
53
+ import { isRoiWaiverExemptPurpose } from "./reportPurposes.js";
54
+ import {
55
+ SHARING_METHOD,
56
+ SHARING_METHOD_LABELS,
57
+ sharingMethodOfReleaseMethod,
58
+ type SharingMethodValue,
59
+ } from "./sharingMethods.js";
60
+
61
+ /**
62
+ * The ROI-basis ladder's rung-1 REASON — "the send cites a live ROI" — the
63
+ * only reason under which a cited release binds a share
64
+ * ({@link operativeReleaseOf}). Thread's `ROI_BASIS_REASON.ROI_ON_FILE`
65
+ * (`constants/ic.ts` L708), which Thread maps to the basis `on_file`.
66
+ */
67
+ // CVC-331 convergence owed (Kickoff 12): this reason maps to Thread's basis
68
+ // `on_file`; the CVC-331 basis is `signed_release`. Kept as Thread's code in
69
+ // this lift.
70
+ export const ROI_BASIS_REASON_ROI_ON_FILE = "roi_on_file" as const;
71
+
72
+ /**
73
+ * Is this send addressed to the SENDER'S OWN agency? Thread's
74
+ * `isInternalIntakeReferral` (`constants/shareDeliveryKey.ts` L101-L122),
75
+ * unchanged: the `senderAgencyId.length > 0` guard keeps a caller that
76
+ * omitted BOTH ids from reading as "the same agency".
77
+ */
78
+ function isSameAgencySend(input: {
79
+ readonly senderAgencyId: string;
80
+ readonly recipientAgencyId: string;
81
+ }): boolean {
82
+ return (
83
+ input.senderAgencyId.length > 0 &&
84
+ input.senderAgencyId === input.recipientAgencyId
85
+ );
86
+ }
87
+
88
+
89
+ /**
90
+ * The methods the PLATFORM delivers (CVC-332 "brokered", R76): only these
91
+ * carry an end date. A recorded method (email, fax, …) is sent by the
92
+ * advocate themself — R21 does not reach it (R76's own `expires: null` rule
93
+ * is not built here).
94
+ */
95
+ const BROKERED_METHODS: ReadonlySet<string> = new Set([
96
+ SHARING_METHOD.CASE_SHARE,
97
+ SHARING_METHOD.MAGIC_LINK,
98
+ ]);
99
+
100
+ /** The fields of a release these rules read. */
101
+ export interface ReleaseTerms {
102
+ readonly approvedSharingMethods?: unknown;
103
+ readonly expirationDate?: unknown;
104
+ }
105
+
106
+ /** A share's method, canonical: an ABSENT method (legacy rows,
107
+ * `POST /shares`) is CaseShare. */
108
+ export function shareMethodOf(method: unknown): string {
109
+ return method === undefined || method === null || method === ""
110
+ ? SHARING_METHOD.CASE_SHARE
111
+ : String(method);
112
+ }
113
+
114
+ /** True for a method the platform delivers — the methods R21 binds. */
115
+ export function isBrokeredSharingMethod(method: unknown): boolean {
116
+ return BROKERED_METHODS.has(shareMethodOf(method));
117
+ }
118
+
119
+ /** A `SHARING_METHOD` value's words ("CaseShare", "Email", …). */
120
+ export function sharingMethodLabel(method: string): string {
121
+ return SHARING_METHOD_LABELS[method as SharingMethodValue] ?? method;
122
+ }
123
+
124
+ /** "A", "A and B", "A, B and C". */
125
+ export function releaseListWords(words: readonly string[]): string {
126
+ if (words.length <= 1) return words.join("");
127
+ return `${words.slice(0, -1).join(", ")} and ${words[words.length - 1]}`;
128
+ }
129
+
130
+ /**
131
+ * The share is exempt from EVERY release term: an own-agency send (no
132
+ * release governs it — the ladder's rung-3 predicate).
133
+ */
134
+ export function isReleaseTermsExemptRecipient(input: {
135
+ readonly senderAgencyId: string;
136
+ readonly recipientAgencyId: string;
137
+ }): boolean {
138
+ return isSameAgencySend(input);
139
+ }
140
+
141
+ /**
142
+ * The method rule does not apply to this purpose: a reporting
143
+ * (legal-override) purpose exercises no release term (§ 5.77).
144
+ */
145
+ export function isReleaseMethodExemptPurpose(
146
+ sharePurpose: string | null | undefined,
147
+ ): boolean {
148
+ return isRoiWaiverExemptPurpose(sharePurpose);
149
+ }
150
+
151
+ /**
152
+ * The OPERATIVE release of a share — the release whose terms bind it — or
153
+ * `undefined`. `release` is the cited release as the caller resolved it
154
+ * (followed through a renewal); it binds only when the ladder took it as the
155
+ * authority (rung 1 — a live release naming this recipient). An own-agency
156
+ * share is bound by no release (the prototype's `shareReleaseOf`: an
157
+ * internal team has none).
158
+ */
159
+ export function operativeReleaseOf<R extends ReleaseTerms>(input: {
160
+ readonly release: R | null | undefined;
161
+ readonly roiBasis: { readonly reason: string };
162
+ readonly senderAgencyId: string;
163
+ readonly recipientAgencyId: string;
164
+ }): R | undefined {
165
+ if (input.release === null || input.release === undefined) return undefined;
166
+ // CVC-331 convergence owed (Kickoff 12): `roi_on_file` (Thread basis
167
+ // `on_file`) is CVC-331 `signed_release`; Thread's code is kept.
168
+ if (input.roiBasis.reason !== ROI_BASIS_REASON_ROI_ON_FILE) return undefined;
169
+ // The ladder's own rung-3 predicate. Rung 1 runs before rung 3, so a
170
+ // release that happens to name the sender's own agency would otherwise
171
+ // bind an internal share the ladder would have read as `same_agency`.
172
+ if (
173
+ isReleaseTermsExemptRecipient({
174
+ senderAgencyId: input.senderAgencyId,
175
+ recipientAgencyId: input.recipientAgencyId,
176
+ })
177
+ ) {
178
+ return undefined;
179
+ }
180
+ return input.release;
181
+ }
182
+
183
+ /**
184
+ * The methods a release lists, or `null` when it lists none. An EMPTY (or
185
+ * absent) `approvedSharingMethods` names no method and restricts nothing —
186
+ * the prototype reads it so (`shareReleaseMethodGaps` /
187
+ * `shareAllowedMethods` filter on `env.methods.length`), and every release
188
+ * written before the method list existed carries `[]` (the schema default).
189
+ * OPEN ITEM: whether an empty list should instead refuse every method is a
190
+ * product ruling the record does not make. Every listed string counts — an
191
+ * unknown legacy value is still a listed method; it just never matches a
192
+ * method the platform offers. Returned in the SHARE-method space
193
+ * (`SHARING_METHOD`), whichever spelling the release stored.
194
+ */
195
+ export function releaseListedMethods(
196
+ release: ReleaseTerms | undefined,
197
+ ): readonly string[] | null {
198
+ const raw = release?.approvedSharingMethods;
199
+ if (!Array.isArray(raw)) return null;
200
+ // A release stores CVC-332 sending-method tokens (ROI Data Object § 4,
201
+ // ruling 5); one written before carries the old spellings. Both read into
202
+ // the share-method space a share's `method` uses (`thread_caseshare` and
203
+ // `case_share` → `case_share`), once each — so a renewal never refuses a
204
+ // share the old release allowed.
205
+ const listed: string[] = [];
206
+ for (const entry of raw as readonly unknown[]) {
207
+ const m = sharingMethodOfReleaseMethod(entry);
208
+ if (!listed.includes(m)) listed.push(m);
209
+ }
210
+ return listed.length === 0 ? null : listed;
211
+ }
212
+
213
+ /**
214
+ * R19 (+R66) — the refusal sentence when the operative release does not list
215
+ * the share's method, else `null`.
216
+ */
217
+ export function releaseMethodRefusal(input: {
218
+ readonly method: unknown;
219
+ /** The OPERATIVE release (`operativeReleaseOf`), or `undefined`. */
220
+ readonly release: ReleaseTerms | undefined;
221
+ readonly sharePurpose: string | null | undefined;
222
+ }): string | null {
223
+ const { release } = input;
224
+ if (release === undefined) return null;
225
+ if (isReleaseMethodExemptPurpose(input.sharePurpose)) return null;
226
+ const listed = releaseListedMethods(release);
227
+ if (listed === null) return null;
228
+ const method = shareMethodOf(input.method);
229
+ if (listed.includes(method)) return null;
230
+ const want = sharingMethodLabel(method);
231
+ return (
232
+ `The client's release for this recipient doesn't allow sending by ${want} — ` +
233
+ `the client agreed to ${releaseListWords(listed.map(sharingMethodLabel))}. Nothing was sent. ` +
234
+ `To send by ${want}, add it to the release by renewing it, or choose one of the methods it lists.`
235
+ );
236
+ }
237
+
238
+ const asDate = (v: unknown): Date | null => {
239
+ if (v === undefined || v === null || v === "") return null;
240
+ const d = new Date(v as string | number | Date);
241
+ return Number.isNaN(d.getTime()) ? null : d;
242
+ };
243
+
244
+ /** The UTC calendar day of an instant, `YYYY-MM-DD`. */
245
+ export const utcCalendarDay = (d: Date): string => d.toISOString().slice(0, 10);
246
+
247
+ /** The last instant of `d`'s UTC calendar day (`…T23:59:59.999Z`). */
248
+ export function endOfUtcDay(d: Date): Date {
249
+ return new Date(`${utcCalendarDay(d)}T23:59:59.999Z`);
250
+ }
251
+
252
+ /**
253
+ * The last instant a share under this release may run: the END of the
254
+ * release's end DAY, or `null` when the release has no end date (or there is
255
+ * no release). The release wizard stores its end as `D T00:00:00.000Z`
256
+ * (`RoiWizardHost` `toIsoDateTime`) while the composer stores a picked day as
257
+ * `D T23:59:59.999Z` (`ShareComposer` `toIsoExpirationDatetime`) — both mean
258
+ * "through day D", so the release is read as running through the whole day.
259
+ */
260
+ export function releaseEndOfDay(
261
+ release: ReleaseTerms | undefined,
262
+ ): Date | null {
263
+ const end = asDate(release?.expirationDate);
264
+ return end === null ? null : endOfUtcDay(end);
265
+ }
266
+
267
+ /** The release's end DAY, `YYYY-MM-DD`, or `null` (no end date / release). */
268
+ export function releaseEndDay(
269
+ release: ReleaseTerms | undefined,
270
+ ): string | null {
271
+ const end = releaseEndOfDay(release);
272
+ return end === null ? null : utcCalendarDay(end);
273
+ }
274
+
275
+ export type ShareExpiryDecision =
276
+ | {
277
+ readonly kind: "ok";
278
+ /** The share's effective end date; `null` = no end date. */
279
+ readonly expirationDate: Date | null;
280
+ /** `noTimeLimit` as it should now read beside the date. */
281
+ readonly noTimeLimit: boolean;
282
+ /** True when the date was taken from the release (R21). */
283
+ readonly fromRelease: boolean;
284
+ /**
285
+ * The latest instant anything delivered under this share may live —
286
+ * the end of the release's end day — or `null` when no release bounds
287
+ * it. A magic link's one-day floor never reaches past it.
288
+ */
289
+ readonly releaseEnd: Date | null;
290
+ }
291
+ | {
292
+ readonly kind: "refused";
293
+ readonly message: string;
294
+ /** The share's end day and the release's, `YYYY-MM-DD`. */
295
+ readonly shareDay: string;
296
+ readonly releaseDay: string;
297
+ };
298
+
299
+ /**
300
+ * R21 (+R67) — the share's effective end date under its operative release.
301
+ *
302
+ * - no operative release, or one with no end date → the share's own
303
+ * choice, unchanged (blank stays "no end date");
304
+ * - a recorded method (not platform-delivered, R76) → unchanged;
305
+ * - blank / `noTimeLimit` → the END of the release's end day, so the
306
+ * share lasts through that day;
307
+ * - on or before the release's end DAY → kept;
308
+ * - a later day → REFUSED. Never capped: a date the advocate picked is
309
+ * theirs, and silently moving it would hide that the share ends sooner
310
+ * than they chose.
311
+ *
312
+ * The comparison is by UTC CALENDAR DAY, never instant: the web stores the
313
+ * same day at different instants (`releaseEndOfDay`), so picking the
314
+ * release's own end day must be allowed.
315
+ */
316
+ export function shareExpiryUnderRelease(input: {
317
+ readonly method: unknown;
318
+ readonly expirationDate: unknown;
319
+ readonly noTimeLimit: unknown;
320
+ /** The OPERATIVE release (`operativeReleaseOf`), or `undefined`. */
321
+ readonly release: ReleaseTerms | undefined;
322
+ }): ShareExpiryDecision {
323
+ const noTimeLimit = input.noTimeLimit === true;
324
+ const own = noTimeLimit ? null : asDate(input.expirationDate);
325
+ const unbounded: ShareExpiryDecision = {
326
+ kind: "ok",
327
+ expirationDate: own,
328
+ noTimeLimit,
329
+ fromRelease: false,
330
+ releaseEnd: null,
331
+ };
332
+ if (!isBrokeredSharingMethod(input.method)) return unbounded;
333
+ const releaseEnd = releaseEndOfDay(input.release);
334
+ if (releaseEnd === null) return unbounded;
335
+ if (own === null) {
336
+ return {
337
+ kind: "ok",
338
+ expirationDate: releaseEnd,
339
+ noTimeLimit: false,
340
+ fromRelease: true,
341
+ releaseEnd,
342
+ };
343
+ }
344
+ const shareDay = utcCalendarDay(own);
345
+ const releaseDay = utcCalendarDay(releaseEnd);
346
+ if (shareDay > releaseDay) {
347
+ return {
348
+ kind: "refused",
349
+ shareDay,
350
+ releaseDay,
351
+ message:
352
+ `This share would end on ${shareDay}, after the ` +
353
+ `client's release for this recipient ends (${releaseDay}). ` +
354
+ `A share never outlives its release. Nothing was sent. Pick an end date on or ` +
355
+ `before the release's, or leave it blank to end with the release.`,
356
+ };
357
+ }
358
+ return { ...unbounded, releaseEnd };
359
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * The REPORT purposes — the share purposes the law compels, which no release
3
+ * requirement can gate (§ 5.77): `mandatory_reporting` and
4
+ * `authority_reporting`.
5
+ *
6
+ * Moved with the release-terms rule (./releaseTerms.ts), which exempts these
7
+ * purposes from the release's method term. A small pure constant, written as
8
+ * the two CVC-84 keys and typed against this package's `SharePurposeKey`, so
9
+ * a key renamed upstream fails the build here.
10
+ *
11
+ * Where it came from: Thread `@thread/shared` `constants/shareRoiWaiver.ts`
12
+ * L144-L168 @ thread develop f021be2 (`ROI_WAIVER_EXEMPT_PURPOSES`,
13
+ * `isRoiWaiverExemptPurpose`). Thread DERIVES the list from its
14
+ * `SHARE_PURPOSE_CONFIG[p].legalOverride` flag; that flag is Thread's own
15
+ * config, not in this package's CVC-84 SOT, so the list is written out here.
16
+ * It is byte-identical to Thread's derivation and to PAVE's
17
+ * `ROI_POSTURE_EXEMPT_PURPOSES` (`@pave/db/lookups/roiPosture.ts:129`).
18
+ * Thread's re-point keeps its derivation and pins it equal to this list.
19
+ *
20
+ * Pure: no mongoose, no I/O, no SOT import.
21
+ */
22
+
23
+ import type { SharePurposeKey } from "../generated/cvc-enums.js";
24
+
25
+ /** The purposes compelled by law (no release requirement applies). */
26
+ export const ROI_WAIVER_EXEMPT_PURPOSES: readonly SharePurposeKey[] = [
27
+ "mandatory_reporting",
28
+ "authority_reporting",
29
+ ];
30
+
31
+ const ROI_WAIVER_EXEMPT_PURPOSE_SET: ReadonlySet<string> = new Set(
32
+ ROI_WAIVER_EXEMPT_PURPOSES,
33
+ );
34
+
35
+ /**
36
+ * True when this purpose is compelled by law and no release requirement applies.
37
+ *
38
+ * An ABSENT purpose is NOT exempt. Every queued share written before the
39
+ * purpose dimension existed carries none, and reading absence as an exemption
40
+ * would retroactively excuse the entire back catalogue.
41
+ */
42
+ export function isRoiWaiverExemptPurpose(
43
+ purpose: string | undefined | null,
44
+ ): boolean {
45
+ return (
46
+ purpose !== undefined &&
47
+ purpose !== null &&
48
+ ROI_WAIVER_EXEMPT_PURPOSE_SET.has(purpose)
49
+ );
50
+ }