@ordinatio/entities 1.4.0 → 1.6.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/README.md CHANGED
@@ -191,6 +191,10 @@ await app.entities.createNote({ entityType: 'client', entityId: 'client-123', co
191
191
  | `getNotes(db, options)` | Query | List notes with cursor pagination |
192
192
  | `deleteNote(db, noteId, entityId)` | Mutation | Delete a note |
193
193
 
194
+ ### Notes Module (`@ordinatio/entities/notes`, experimental)
195
+
196
+ Pure, zero-dependency helpers for notes on any record (a person, a company), on their own subpath so a browser component can import them (no Prisma, zod or Node modules): `DEFAULT_NOTE_LIMITS` (body length 10,000, page sizes 50 and 200) and the body rule `cleanNoteBody` / `checkNoteBody`: a note is multi-line plain text; cleaning normalises line endings to `\n`, removes NUL and other control characters, the byte-order mark, lone surrogates and (for safety) the bidirectional override and isolate controls, drops trailing horizontal whitespace on every line, collapses runs of blank lines to one, removes leading blank lines and trailing whitespace of the whole note, while KEEPING indentation (including the first line's), joiners, variation selectors and every script's real text; it never truncates (a body that is too long is refused as `too-long`, an empty one as `empty`) and is idempotent. Length is counted in UTF-16 code units; a `maxLength` that is not a positive whole number falls back to the default, so a bad limit can never switch the cap off. The server entry `@ordinatio/entities/notes/server` adds the store interface (`NoteStore`, built per workspace), the service (`createNoteService`: add, edit with a compare-and-set revision so two editors never overwrite each other, soft delete and restore, newest-first keyset paging, counts for many parents; anything a person can cause comes back as a result, never a throw; only a store answer the service does not know, or a store that itself fails, throws) an in-memory reference store (`createMemoryNoteWorld`, `createMemoryNoteHarness`) and the store contract suite `defineNoteStoreContract(runner, harness)` (framework-agnostic: pass your runner's `describe`/`it`/`expect`) that any storage adapter must pass: the single-note rules (exact body, compare-and-set edits and their precedence, soft delete and restore, removing a parent), the list rules (newest first on `(createdAt, id)` with notes of one millisecond neither repeated nor skipped, exact pages, paging by position, bad cursors, counts for 5,000 ids), the tenancy rules, the simultaneous-callers rules (run them against a database with a connection pool of at least 10) and the parent-removed-while-creating checks (they need the harness's `armBeforeNoteWrite` and are shown as skipped without it when your runner has `it.skip`). Notes made in the same millisecond are forced only in the in-memory run: on a real database add a test of your own with an identical `createdAt`. Ties are ordered by `id` descending in plain code-unit order, so an adapter whose database collation orders ids differently must compare ids with a binary collation. The suite makes hundreds of sequential calls (it creates 120 notes in one check, walks 30-note listings and counts 5,000 ids), so give your runner a generous per-test timeout when you run it against a database over a network. On a further entry, `@ordinatio/entities/notes/prisma` (also EXPERIMENTAL): `createPrismaNoteStore(config)`, a ready-made `NoteStore` for a Prisma client on Postgres, so an app writes configuration instead of storage code. It holds the generic storage rules: the parent row share-locked (`FOR KEY SHARE`) while a note is inserted, the note row locked `FOR UPDATE` in edit, delete and restore with `before` and `after` read in the same transaction, a bounded lock wait that THROWS on timeout (the lock key is Postgres' `lock_timeout`), a conditional write on revision and not-deleted, explicit timestamps from the app's clock (milliseconds exactly; `updatedAt` is set by the store on EVERY write, so an `@updatedAt` attribute can never move it on delete or restore), a foreign-key failure read as `parentGone`, a keyset list on `(createdAt, id)` with `take limit + 1` and a strictly parsed cursor (`v1.` + base64url of the position; junk, whitespace, padding or an out-of-range time is `badCursor`), and counts for many parents in pieces of 10,000 ids with every asked id present. The configuration names your client (as a getter), the note model and table, the workspace column, the author column (default `authorId`) and, per kind of parent, the note's nullable parent column plus the parent's model and table (a note belongs to exactly one parent, set through that column); every name that reaches SQL is checked once and double-quoted, values are always bound. Its REQUIREMENTS are documented at the top of `src/entity-notes/prisma/types.ts` (foreign keys from the parent columns with ON DELETE CASCADE, plain text columns, `timestamp(3)`, ids ordered by the database like code units, such as lowercase cuids, no `@map` on the columns the SQL names, READ COMMITTED). It does not import `@prisma/client`. **Prove it on YOUR database** by running `defineNoteStoreContract` against it with a harness of your own (at least ten connections, a per-test timeout of 60 seconds or more, and an `armBeforeNoteWrite` wired to the `onBeforeNoteWrite` configuration callback, which must be one-shot). This package runs the same contract against the store over an in-memory Prisma stand-in, which proves the query logic but not locking. (The older `createNote` / `updateNote` / `getNotes` / `deleteNote` above are System 1701's own notes and are unrelated to this module.)
197
+
194
198
  ### Companies Module (`@ordinatio/entities/companies`, experimental)
195
199
 
196
200
  Pure, zero-dependency helpers for companies, on their own subpath so a browser component can import them (no Prisma, zod or Node modules): `companyNameKey` / `cleanCompanyName` / `checkCompanyName` (the case-insensitive identity of a name; **pinned to its first shipped behaviour** because apps store the key in a unique column; legal suffixes such as "LLC" are deliberately NOT stripped), `checkCompanyRole` (an optional role text; empty means none), `checkCompanyWebsite` (normalises what a person typed: http or https only; scheme, host, a non-default port and the path are kept, credentials, query and fragment dropped; and derives the `domain`), `domainOfEmail`, `isFreeMailDomain` with the `FREE_MAIL_DOMAINS` list, `suggestCompanies` (which companies an email address suggests: exact domain match only, never a free-mail domain, never one the person is already in; a suggestion is only ever an offer) and `DEFAULT_COMPANY_LIMITS`. Matching uses the exact normalised host (one leading `www.` removed) and no public-suffix list on purpose. On the separate server entry `@ordinatio/entities/companies/server` (EXPERIMENTAL until a second product has used it): the `CompanyStore` interface (built per workspace, so the package never sees a tenant id; atomic, typed, limit-aware operations), `createCompanyService(store, limits?)` (the company rules over any store: validate and clean names and websites and derive the domain, create and find-or-create, rename, set or clear the website, remove (reporting how many people were detached), read companies back sorted, and manage who belongs to a company: add a member (an existing member is reported as `added: false`, never an error, and never counts against the member limit), change or clear a role, remove a member, list a company's members, fetch the companies of many people in one call, count the members of every company in one call, and suggest companies for an email address (`suggest(email, personId?)`: companies whose domain is exactly the address's domain, never for a free-mail address, never one the person already belongs to, only ever an offer); every outcome a user can cause is a typed `{ ok: false, reason, ... }` result and a store result it does not know throws) and an in-memory reference store (`createMemoryCompanyWorld`, with `addPerson` / `removePerson` and a hook for deleting a company or person in the middle of an add). The store contract suite `defineCompanyStoreContract(runner, harness)` (framework-agnostic: pass your runner's `describe`/`it`/`expect`) states the rules observable through the interface so any storage adapter can prove it follows them; this release holds the company rules (create, duplicate, limit, key kept apart from name, website and domain together, update precedence, remove, the reads, `findByDomain`, member counts) and the membership rules (`personExists`, `addMember` with its order of refusals and the member limit, `setRole`, `removeMember`, `members`, `companiesForPeople`, member counts, what removing a company or a person does to memberships), the tenancy rules (another workspace is invisible and untouched, limits count per workspace) and the simultaneous-callers rules (ten callers at once cannot overshoot a limit, double-add or double-remove, or leave a membership behind; run them against a database with a connection pool of at least 10), `createMemoryCompanyHarness` runs it on the reference store (with `serialise: false` its races become visible, which proves that twelve of the sixteen simultaneous-callers checks can fail) and the delete-while-adding checks (they need the harness's `armBeforeMemberWrite` and are shown as skipped without it when your runner has `it.skip`). The suite is complete. On a further entry, `@ordinatio/entities/companies/prisma` (also EXPERIMENTAL): `createPrismaCompanyStore(config)`, a ready-made `CompanyStore` for a Prisma client on Postgres, so an app writes configuration instead of storage code. It holds the generic storage rules: a per-workspace advisory lock around the company limit (the lock key prefix is configurable), lock waits that THROW on timeout, the company row locked `FOR NO KEY UPDATE` in an update (a rename takes the stronger lock anyway, because the key is in a unique index) and `FOR UPDATE` in a remove (which reports the members detached, counted in the same transaction), the member limit enforced together with the insert under the company row lock with the person row share-locked, foreign-key-abort handling (a membership written for a company or person deleted a moment ago becomes `companyGone` or `personGone`), and every list cut into queries of 10,000 ids. The configuration names your client (as a getter), the company, membership and person models and tables, the workspace column and, optionally, the membership columns. Its REQUIREMENTS are documented at the top of `src/companies/prisma/types.ts` (a unique index on (workspace, key), plain `text` columns, foreign keys with ON DELETE CASCADE from the membership table to the company and the person, no `@map` on the columns the raw SQL names). It does not import `@prisma/client`. **Prove it on YOUR database** by running `defineCompanyStoreContract` against it with a harness of your own (with at least ten connections available; `armBeforeMemberWrite` is wired to the `onBeforeMemberWrite` configuration callback and must be one-shot). Against a real database over a network connection, give the runner a generous test timeout (the checks make many round trips, and one reads 40,000 ids).
@@ -199,6 +203,22 @@ Pure, zero-dependency helpers for companies, on their own subpath so a browser c
199
203
 
200
204
  Pure, zero-dependency helpers for tags, on their own subpath so a browser component can import them without pulling in the rest of the package (no Prisma, zod or Node modules): `tagNameKey` / `cleanTagName` / `checkTagName` (the case-insensitive identity of a name; **pinned to its first shipped behaviour** because apps store the key in a unique column), `TAG_COLORS` / `isTagColor` / `resolveTagColor`, `DEFAULT_TAG_LIMITS` (name length 40, 50 changes per save, 15 pinned, 500 per workspace: defaults, a store takes them as arguments), and the picker helpers `describeTagChanges`, `tagSetKey`, `rebaseSelection`, `mergeTagOptions`. The `./schemas` and `./errors` subpaths exist only in the workspace (source) exports map and are not part of the published package yet. On the separate server entry `@ordinatio/entities/tags/server` (EXPERIMENTAL until a second product has used it): the `TagStore` interface (built per workspace, so the package never sees a tenant id; atomic, typed, limit-aware operations), `createTagService(store, limits?)` (the tag rules over any store: validate and clean names and colours, create and find-or-create, rename/recolour/pin, remove, apply only the changes a user made to one item's tags, and read tags back sorted; every outcome a user can cause is a typed `{ ok: false, reason, ... }` result with the context an app needs for its message, and a store result it does not know throws; a store that throws is not caught, so an app that must never fail a page, such as a sidebar of pinned tags, wraps that one call itself; `pinned()` asks the store for the first `maxPinned` pinned tags, so make `listPinned` return them in a stable order such as by name), `planTagChanges`, an in-memory reference store (`createMemoryTagWorld`, `createMemoryTagHarness`) and the store contract suite `defineTagStoreContract` that any storage adapter must pass (framework-agnostic: pass your runner's `describe`/`it`/`expect`). On a further entry, `@ordinatio/entities/tags/prisma` (also EXPERIMENTAL): `createPrismaTagStore(config)`, a ready-made `TagStore` for a Prisma client on Postgres, so an app writes configuration instead of storage code. It holds the generic storage rules: a per-workspace advisory lock around the two limits (the lock key prefix is configurable, so an app can keep an older key), lock waits that THROW on timeout in create, pin and update (a remove and a link write start no explicit lock of their own, so they wait only on locks other transactions hold, bounded only if those transactions are), `FOR UPDATE` on the tag row in an update (which briefly serialises with the key-share lock a concurrent link insert takes on the same tag), `createManyAndReturn` and `DELETE ... RETURNING` so `added` and `removed` come from rows really written, and foreign-key-abort handling (a link to a tag or item deleted a moment ago becomes `tagGone` or `targetGone`, decided by a fresh read after the aborted transaction). The configuration names your client (as a getter, called each time the store needs the client), the tag model and table, the workspace column, and per taggable kind the join model, table and columns and the item model; every name that reaches SQL is checked once and double-quoted, values are always bound. It needs Prisma 5.14 or later and unique and foreign-key constraints in your database (listed at the top of its `types.ts`) and does not import `@prisma/client`. **Prove it on YOUR database** by running `defineTagStoreContract` against it with a harness of your own (with at least ten connections available): the contract, not the unit tests of this package, is what shows the SQL, the locks and the foreign keys behave. Pin this package's exact version while the server entry is experimental: adding a required store method or a contract rule can break an adapter that passed before. The concurrency tests are meaningful only against a real store: run them against your database with a connection pool of at least 10. **Adapters and mappers must treat an unknown result `kind` or reason as an error**, never as success: adding a kind is a breaking change for an exhaustive switch.
201
205
 
206
+ ### Soft delete (Trash), 1.6.0
207
+
208
+ Three OPT-IN options, all off by default: a consumer that sets none of them gets exactly the queries and SQL of 1.5.0 (pinned by the snapshot tests `src/companies/prisma/off-baseline.test.ts`, `src/tags/prisma/off-baseline.test.ts` and `src/entity-notes/prisma/off-baseline.test.ts`, which were recorded on 1.5.0 before any change). Every column name is checked like every other name that reaches SQL.
209
+
210
+ 1. **Companies** (`createPrismaCompanyStore`): `softDelete: { column, byColumn, updatedAtColumn? }` on the company table, and `personSoftDeleteColumn` on the person table. With `softDelete` set the store is a `TrashableCompanyStore` (the overloads type it so: pass the config as an inline object literal, or cast the result; a config held in a variable typed `PrismaCompanyStoreConfig` has `softDelete` optional, so TypeScript picks the plain `CompanyStore` overload even though the trash methods exist at run time) with `trash(id, actorId)`, `restore(id)`, `listTrashed()` and `getAny(id)`. All plain reads and writes (`list`, `get`, `getMany`, `findByKey`, `findByDomain`, `update`, the member methods, `memberCounts`) see LIVE companies only; the create-time limit counts trashed companies too. `trash` and `restore` run in one transaction with a bounded lock wait, take the company row `FOR UPDATE` (so they also wait for and block `setRole` and `removeMember`), then compare-and-set on the column: `trashed` / `restored` with `before` and `after`, or `notFound`, `alreadyTrashed`, `notTrashed`. `updatedAtColumn`, when set, is written back to its existing value so an `@updatedAt` cannot move it. `personSoftDeleteColumn` makes `personExists`, the `addMember` person check and its `FOR KEY SHARE` SQL, `members()` and `memberCounts` ignore trashed people.
211
+ 2. **Tags** (`PrismaTagTarget`): `softDeleteColumn` per target kind. A trashed item counts as gone (`targetGone`) for tagging and untagging; counts and tag lists are not filtered.
212
+ 3. **Notes** (`createPrismaNoteStore` parents): `softDeleteColumn` per parent kind. A trashed parent is `parentGone` for a new note.
213
+
214
+ **Results and failures.** `CompanyCreateResult` and `CompanyUpdateResult` gain `{ kind: 'inTrash'; id }`: the unique index is NOT made partial, so a trashed company keeps its name key, and a create or rename onto it reports `inTrash` with that company's id (a live holder is still `duplicate`; the unique-violation race path re-reads the key with the live term off and reports the same). `findByKey` stays live-only, so `findOrCreate` falls through to `create` and returns `inTrash`, never the trashed row as found. The service maps it to `{ ok: false, reason: 'in-trash', id }` in `create`, `update` and `findOrCreate`; its `trash(id, actorId)`, `restore(id)`, `listTrashed()` and `getAny(id)` return `already-trashed`, `not-trashed` or `not-found` as needed, and `{ ok: false, reason: 'unsupported' }` WITHOUT touching the store when the store has no `trash` function (a plain 1.5.0 `CompanyStore` keeps working). A new result kind can break a consumer's exhaustive `switch`: re-run your type check when you upgrade.
215
+
216
+ **`remove` is still the hard delete**, of a live or a trashed company (the purge path); it takes no live term.
217
+
218
+ **Locks.** Company trash uses `FOR UPDATE`. For a person or a note parent this package only filters on the column: a plain `UPDATE ... SET deletedAt` takes `FOR NO KEY UPDATE`, which does not conflict with the `FOR KEY SHARE` that `addMember` and note creation take, so a race can leave a membership or note on a freshly trashed row (benign: it shows after Restore). Callers that trash a person or a note parent should take `SELECT ... FOR UPDATE` on the row first.
219
+
220
+ **Contract suite and in-memory store.** `createMemoryCompanyHarness({ softDelete: true })` gives a Trash-capable reference store and sets the harness flag `supportsTrash`; `defineCompanyStoreContract` runs its Trash rules (hiding, `alreadyTrashed` / `notTrashed`, `inTrash` versus `duplicate`, `remove` as hard delete, tenancy, ten simultaneous trashes give one `trashed`, ten restores one `restored`) only for a harness that sets `supportsTrash: true`; existing harnesses are unchanged.
221
+
202
222
  ### Contacts Module
203
223
 
204
224
  | Function | Type | Description |
@@ -0,0 +1,29 @@
1
+ // src/entity-notes/constants.ts
2
+ var DEFAULT_NOTE_LIMITS = Object.freeze({
3
+ maxBodyLength: 1e4,
4
+ defaultPageSize: 50,
5
+ maxPageSize: 200
6
+ });
7
+
8
+ // src/entity-notes/body.ts
9
+ var NEVER_TEXT = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F\uFEFF\u202A-\u202E\u2066-\u2069]/g;
10
+ var HSPACE = "[ \\t\\u00A0\\u1680\\u2000-\\u200A\\u202F\\u205F\\u3000]";
11
+ var TRAILING_HSPACE = new RegExp(`${HSPACE}+(?=\\n)`, "g");
12
+ var LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
13
+ function cleanNoteBody(body) {
14
+ if (typeof body !== "string") return "";
15
+ return body.replace(/\r\n?/g, "\n").replace(NEVER_TEXT, "").replace(LONE_SURROGATE, "").replace(TRAILING_HSPACE, "").replace(/\n{3,}/g, "\n\n").replace(/^\n+/, "").trimEnd();
16
+ }
17
+ function checkNoteBody(body, maxLength = DEFAULT_NOTE_LIMITS.maxBodyLength) {
18
+ const limit = Number.isInteger(maxLength) && maxLength >= 1 ? maxLength : DEFAULT_NOTE_LIMITS.maxBodyLength;
19
+ const cleaned = cleanNoteBody(body);
20
+ if (cleaned.length < 1) return { ok: false, reason: "empty", length: 0 };
21
+ if (cleaned.length > limit) return { ok: false, reason: "too-long", length: cleaned.length };
22
+ return { ok: true, body: cleaned };
23
+ }
24
+
25
+ export {
26
+ DEFAULT_NOTE_LIMITS,
27
+ cleanNoteBody,
28
+ checkNoteBody
29
+ };
@@ -1,4 +1,4 @@
1
- import { C as CompanyRecord, a as CompanyStore } from '../../types-CbfseUAS.mjs';
1
+ import { C as CompanyRecord, T as TrashableCompanyStore, a as CompanyStore } from '../../types-BJl_PZDf.mjs';
2
2
 
3
3
  interface PrismaCompanyStoreConfig {
4
4
  /** Called each time the store needs the client (never at import), so a test can swap in a client with a bigger pool. */
@@ -38,6 +38,20 @@ interface PrismaCompanyStoreConfig {
38
38
  maxWait?: number;
39
39
  timeout?: number;
40
40
  };
41
+ /**
42
+ * OPTIONAL soft delete (the Trash) of companies. Names columns of the COMPANY table (plain identifiers, same name as the Prisma field): `column` is a nullable
43
+ * timestamp (NULL = live), `byColumn` a nullable text column for who trashed it, `updatedAtColumn` (optional) the model's `@updatedAt` column, which `trash` and
44
+ * `restore` write back to its existing value so the trash itself does not move it (when omitted the key is not written: a model with `@updatedAt` may bump it).
45
+ * When set: reads, `update` and the membership methods see LIVE companies only, name collisions with a trashed company are reported as `inTrash`, the store gains
46
+ * `trash`/`restore`/`listTrashed`/`getAny`, and `remove` stays a hard delete of a company in ANY state. When unset the store is exactly the 1.5.0 store.
47
+ */
48
+ softDelete?: {
49
+ column: string;
50
+ byColumn: string;
51
+ updatedAtColumn?: string;
52
+ };
53
+ /** OPTIONAL: the nullable timestamp column of the PERSON table that marks a trashed person. When set, `personExists`, `addMember`, `members` and `memberCounts` treat a trashed person as absent. */
54
+ personSoftDeleteColumn?: string;
41
55
  /** TEST ONLY: runs inside `addMember` after the existence checks and before the write, holding NO lock and no open transaction, so a test can delete a company or person there. */
42
56
  onBeforeMemberWrite?: () => Promise<void>;
43
57
  }
@@ -53,6 +67,10 @@ interface PrismaLikeClient extends PrismaLikeTx {
53
67
  }): Promise<R>;
54
68
  }
55
69
 
70
+ /** With `softDelete` configured the store also has `trash`, `restore`, `listTrashed` and `getAny`; without it the store is exactly the 1.5.0 `CompanyStore`. */
71
+ declare function createPrismaCompanyStore<T extends CompanyRecord = CompanyRecord>(config: PrismaCompanyStoreConfig & {
72
+ softDelete: NonNullable<PrismaCompanyStoreConfig['softDelete']>;
73
+ }): TrashableCompanyStore<T>;
56
74
  declare function createPrismaCompanyStore<T extends CompanyRecord = CompanyRecord>(config: PrismaCompanyStoreConfig): CompanyStore<T>;
57
75
 
58
76
  export { type PrismaCompanyStoreConfig, type PrismaLikeClient, type PrismaLikeTx, createPrismaCompanyStore };
@@ -27,6 +27,12 @@ function createContext(config) {
27
27
  const personIdColumn = assertIdentifier(config.personIdColumn ?? "personId", "personIdColumn");
28
28
  const roleColumn = assertIdentifier(config.roleColumn ?? "role", "roleColumn");
29
29
  const addedByColumn = assertIdentifier(config.addedByColumn ?? "addedBy", "addedByColumn");
30
+ const softDelete = config.softDelete ? {
31
+ column: assertIdentifier(config.softDelete.column, "softDelete.column"),
32
+ byColumn: assertIdentifier(config.softDelete.byColumn, "softDelete.byColumn"),
33
+ updatedAtColumn: config.softDelete.updatedAtColumn === void 0 ? void 0 : assertIdentifier(config.softDelete.updatedAtColumn, "softDelete.updatedAtColumn")
34
+ } : void 0;
35
+ const personSoftDeleteColumn = config.personSoftDeleteColumn === void 0 ? void 0 : assertIdentifier(config.personSoftDeleteColumn, "personSoftDeleteColumn");
30
36
  const lockKeyPrefix = config.lockKeyPrefix ?? "companies:";
31
37
  const lockWaitMs = config.lockWaitMs ?? 5e3;
32
38
  if (!Number.isInteger(lockWaitMs) || lockWaitMs <= 0) throw new Error("createPrismaCompanyStore: lockWaitMs must be a positive integer");
@@ -46,6 +52,9 @@ function createContext(config) {
46
52
  addedByColumn,
47
53
  personWorkspaceColumn,
48
54
  sql: { companyTable: quote(companyTable), workspaceColumn: quote(workspaceColumn), memberTable: quote(memberTable), personTable: quote(personTable), personWorkspaceColumn: quote(personWorkspaceColumn) },
55
+ softDelete,
56
+ personSoftDeleteColumn,
57
+ liveSql: { company: softDelete ? ` AND ${quote(softDelete.column)} IS NULL` : "", person: personSoftDeleteColumn ? ` AND ${quote(personSoftDeleteColumn)} IS NULL` : "" },
49
58
  txOptions,
50
59
  beforeMemberWrite: config.onBeforeMemberWrite,
51
60
  client: config.client,
@@ -54,6 +63,8 @@ function createContext(config) {
54
63
  members: (client) => model(client, memberModel),
55
64
  people: (client) => model(client, personModel),
56
65
  companyWhere: (extra = {}) => ({ ...extra, [workspaceColumn]: config.workspaceId }),
66
+ companyWhereLive: (extra = {}) => ({ ...extra, [workspaceColumn]: config.workspaceId, ...softDelete ? { [softDelete.column]: null } : {} }),
67
+ companyWhereAny: (extra = {}) => ({ ...extra, [workspaceColumn]: config.workspaceId }),
57
68
  async limitLockWait(tx) {
58
69
  await tx.$executeRawUnsafe(`SELECT set_config('lock_timeout', $1, true)`, `${lockWaitMs}ms`);
59
70
  },
@@ -81,26 +92,26 @@ function chunksOf(items) {
81
92
  return pieces;
82
93
  }
83
94
  function createCompanyReads(context) {
84
- const { companyWhere } = context;
95
+ const { companyWhereLive } = context;
85
96
  const db = () => context.client();
86
97
  return {
87
98
  async list() {
88
- return await context.companies(db()).findMany({ where: companyWhere() });
99
+ return await context.companies(db()).findMany({ where: companyWhereLive() });
89
100
  },
90
101
  async getMany(ids) {
91
102
  const found = [];
92
- for (const piece of chunksOf([...new Set(ids)])) found.push(...await context.companies(db()).findMany({ where: companyWhere({ id: { in: piece } }) }));
103
+ for (const piece of chunksOf([...new Set(ids)])) found.push(...await context.companies(db()).findMany({ where: companyWhereLive({ id: { in: piece } }) }));
93
104
  return found;
94
105
  },
95
106
  async findByKey(nameKey) {
96
- return await context.companies(db()).findFirst({ where: companyWhere({ nameKey }) });
107
+ return await context.companies(db()).findFirst({ where: companyWhereLive({ nameKey }) });
97
108
  },
98
109
  async get(id) {
99
- return await context.companies(db()).findFirst({ where: companyWhere({ id }) });
110
+ return await context.companies(db()).findFirst({ where: companyWhereLive({ id }) });
100
111
  },
101
112
  async findByDomain(domain) {
102
113
  if (domain === "") return [];
103
- return await context.companies(db()).findMany({ where: companyWhere({ domain }) });
114
+ return await context.companies(db()).findMany({ where: companyWhereLive({ domain }) });
104
115
  }
105
116
  };
106
117
  }
@@ -114,9 +125,9 @@ function createCompanyMembers(context, getMany) {
114
125
  return { companyId: fields[context.companyIdColumn], personId: fields[context.personIdColumn], role: fields[context.roleColumn] ?? null };
115
126
  };
116
127
  const memberWhere = (companyId, personId) => ({ [context.companyIdColumn]: companyId, [context.personIdColumn]: personId });
117
- const companyExists = async (client, companyId) => await context.companies(client).findFirst({ where: context.companyWhere({ id: companyId }), select: { id: true } }) != null;
118
- const personExists = async (client, personId) => await context.people(client).findFirst({ where: { id: personId, [context.personWorkspaceColumn]: context.workspaceId }, select: { id: true } }) != null;
119
- const lockCompany = async (tx, companyId, mode) => (await tx.$queryRawUnsafe(`SELECT "id" FROM ${sql.companyTable} WHERE "id" = $1 AND ${sql.workspaceColumn} = $2 ${mode}`, companyId, context.workspaceId)).length > 0;
128
+ const companyExists = async (client, companyId) => await context.companies(client).findFirst({ where: context.companyWhereLive({ id: companyId }), select: { id: true } }) != null;
129
+ const personExists = async (client, personId) => await context.people(client).findFirst({ where: { id: personId, [context.personWorkspaceColumn]: context.workspaceId, ...context.personSoftDeleteColumn ? { [context.personSoftDeleteColumn]: null } : {} }, select: { id: true } }) != null;
130
+ const lockCompany = async (tx, companyId, mode) => (await tx.$queryRawUnsafe(`SELECT "id" FROM ${sql.companyTable} WHERE "id" = $1 AND ${sql.workspaceColumn} = $2${context.liveSql.company} ${mode}`, companyId, context.workspaceId)).length > 0;
120
131
  const lockMembership = async (tx, companyId, personId) => (await tx.$queryRawUnsafe(`SELECT 1 FROM ${sql.memberTable} WHERE ${quote(context.companyIdColumn)} = $1 AND ${quote(context.personIdColumn)} = $2 FOR UPDATE`, companyId, personId)).length > 0;
121
132
  return {
122
133
  personExists: (personId) => personExists(db(), personId),
@@ -128,7 +139,7 @@ function createCompanyMembers(context, getMany) {
128
139
  return await db().$transaction(async (tx) => {
129
140
  await context.limitLockWait(tx);
130
141
  if (!await lockCompany(tx, companyId, "FOR NO KEY UPDATE")) return { kind: "companyGone" };
131
- const person = await tx.$queryRawUnsafe(`SELECT "id" FROM ${sql.personTable} WHERE "id" = $1 AND ${sql.personWorkspaceColumn} = $2 FOR KEY SHARE`, personId, context.workspaceId);
142
+ const person = await tx.$queryRawUnsafe(`SELECT "id" FROM ${sql.personTable} WHERE "id" = $1 AND ${sql.personWorkspaceColumn} = $2${context.liveSql.person} FOR KEY SHARE`, personId, context.workspaceId);
132
143
  if (person.length === 0) return { kind: "personGone" };
133
144
  const members = context.members(tx);
134
145
  const existing = await members.findFirst({ where: memberWhere(companyId, personId) });
@@ -173,6 +184,15 @@ function createCompanyMembers(context, getMany) {
173
184
  },
174
185
  async members(companyId) {
175
186
  if (!await companyExists(db(), companyId)) return [];
187
+ if (context.personSoftDeleteColumn) {
188
+ const memberTable = sql.memberTable;
189
+ const rows = await db().$queryRawUnsafe(
190
+ `SELECT m.* FROM ${memberTable} m JOIN ${sql.personTable} p ON p."id" = m.${quote(context.personIdColumn)} AND p.${sql.personWorkspaceColumn} = $2 AND p.${quote(context.personSoftDeleteColumn)} IS NULL WHERE m.${quote(context.companyIdColumn)} = $1`,
191
+ companyId,
192
+ context.workspaceId
193
+ );
194
+ return rows.map(toMember);
195
+ }
176
196
  return (await context.members(db()).findMany({ where: { [context.companyIdColumn]: companyId } })).map(toMember);
177
197
  },
178
198
  async companiesForPeople(personIds) {
@@ -193,11 +213,20 @@ function createCompanyMembers(context, getMany) {
193
213
  },
194
214
  async memberCounts(ids) {
195
215
  const companyIds = [];
196
- const read = async (extra) => (await context.companies(db()).findMany({ where: context.companyWhere(extra), select: { id: true } })).map((row) => row.id);
216
+ const read = async (extra) => (await context.companies(db()).findMany({ where: context.companyWhereLive(extra), select: { id: true } })).map((row) => row.id);
197
217
  if (ids === void 0) companyIds.push(...await read({}));
198
218
  else for (const piece of chunksOf([...new Set(ids)])) companyIds.push(...await read({ id: { in: piece } }));
199
219
  const counts = new Map(companyIds.map((id) => [id, 0]));
200
220
  for (const piece of chunksOf(companyIds)) {
221
+ if (context.personSoftDeleteColumn) {
222
+ const rows = await db().$queryRawUnsafe(
223
+ `SELECT c."id" AS "companyId", COUNT(p."id")::int AS "n" FROM ${sql.companyTable} c LEFT JOIN ${sql.memberTable} m ON m.${quote(context.companyIdColumn)} = c."id" LEFT JOIN ${sql.personTable} p ON p."id" = m.${quote(context.personIdColumn)} AND p.${sql.personWorkspaceColumn} = $2 AND p.${quote(context.personSoftDeleteColumn)} IS NULL WHERE c."id" = ANY($1::text[]) AND c.${sql.workspaceColumn} = $2${context.softDelete ? ` AND c.${quote(context.softDelete.column)} IS NULL` : ""} GROUP BY c."id"`,
224
+ piece,
225
+ context.workspaceId
226
+ );
227
+ for (const row of rows) counts.set(row.companyId, Number(row.n));
228
+ continue;
229
+ }
201
230
  const grouped = await context.members(db()).groupBy({ by: [context.companyIdColumn], where: { [context.companyIdColumn]: { in: piece } }, _count: { _all: true } });
202
231
  for (const row of grouped) counts.set(row[context.companyIdColumn], row._count._all);
203
232
  }
@@ -206,9 +235,73 @@ function createCompanyMembers(context, getMany) {
206
235
  };
207
236
  }
208
237
 
238
+ // src/companies/prisma/trash.ts
239
+ function createCompanyTrash(context) {
240
+ const soft = context.softDelete;
241
+ if (!soft) throw new Error("createCompanyTrash: softDelete is not configured");
242
+ const { companyWhereAny } = context;
243
+ const db = () => context.client();
244
+ const lock = async (tx, id) => (await tx.$queryRawUnsafe(`SELECT "id" FROM ${context.sql.companyTable} WHERE "id" = $1 AND ${context.sql.workspaceColumn} = $2 FOR UPDATE`, id, context.workspaceId)).length > 0;
245
+ const read = async (tx, id) => await context.companies(tx).findFirst({ where: companyWhereAny({ id }) });
246
+ const isTrashed = (row) => row[soft.column] != null;
247
+ const keepUpdatedAt = (before) => soft.updatedAtColumn ? { [soft.updatedAtColumn]: before[soft.updatedAtColumn] } : {};
248
+ return {
249
+ async trash(id, actorId) {
250
+ return db().$transaction(async (tx) => {
251
+ await context.limitLockWait(tx);
252
+ if (!await lock(tx, id)) return { kind: "notFound" };
253
+ const before = await read(tx, id);
254
+ if (!before) return { kind: "notFound" };
255
+ if (isTrashed(before)) return { kind: "alreadyTrashed" };
256
+ const { count } = await context.companies(tx).updateMany({
257
+ where: companyWhereAny({ id, [soft.column]: null }),
258
+ data: { [soft.column]: /* @__PURE__ */ new Date(), [soft.byColumn]: actorId, ...keepUpdatedAt(before) }
259
+ });
260
+ const after = await read(tx, id);
261
+ if (count === 0 || !after) return after ? { kind: "alreadyTrashed" } : { kind: "notFound" };
262
+ return { kind: "trashed", before, after };
263
+ }, context.txOptions);
264
+ },
265
+ async restore(id) {
266
+ return db().$transaction(async (tx) => {
267
+ await context.limitLockWait(tx);
268
+ if (!await lock(tx, id)) return { kind: "notFound" };
269
+ const before = await read(tx, id);
270
+ if (!before) return { kind: "notFound" };
271
+ if (!isTrashed(before)) return { kind: "notTrashed" };
272
+ const { count } = await context.companies(tx).updateMany({
273
+ where: { ...companyWhereAny({ id }), NOT: { [soft.column]: null } },
274
+ data: { [soft.column]: null, [soft.byColumn]: null, ...keepUpdatedAt(before) }
275
+ });
276
+ const after = await read(tx, id);
277
+ if (count === 0 || !after) return after ? { kind: "notTrashed" } : { kind: "notFound" };
278
+ return { kind: "restored", before, after };
279
+ }, context.txOptions);
280
+ },
281
+ async listTrashed() {
282
+ return await context.companies(db()).findMany({ where: companyWhereAny({ [soft.column]: { not: null } }), orderBy: { [soft.column]: "desc" } });
283
+ },
284
+ async getAny(id) {
285
+ return await context.companies(db()).findFirst({ where: companyWhereAny({ id }) });
286
+ }
287
+ };
288
+ }
289
+
209
290
  // src/companies/prisma/writes.ts
210
291
  function createCompanyWrites(context) {
211
- const { companyWhere } = context;
292
+ const { companyWhereLive, companyWhereAny } = context;
293
+ const soft = context.softDelete;
294
+ const keySelect = soft ? { id: true, [soft.column]: true } : { id: true };
295
+ const collision = (owner) => {
296
+ if (!owner) return null;
297
+ const fields = owner;
298
+ return soft && fields[soft.column] != null ? { kind: "inTrash", id: fields.id } : { kind: "duplicate" };
299
+ };
300
+ const afterViolation = async (nameKey, exceptId) => {
301
+ if (!soft || nameKey === void 0) return { kind: "duplicate" };
302
+ const owner = await context.companies(db()).findFirst({ where: companyWhereAny(exceptId === void 0 ? { nameKey } : { nameKey, NOT: { id: exceptId } }), select: keySelect });
303
+ return collision(owner) ?? { kind: "duplicate" };
304
+ };
212
305
  const db = () => context.client();
213
306
  return {
214
307
  async create(input, limits) {
@@ -217,13 +310,14 @@ function createCompanyWrites(context) {
217
310
  await context.limitLockWait(tx);
218
311
  await context.lockWorkspace(tx);
219
312
  const companies = context.companies(tx);
220
- if (await companies.count({ where: companyWhere() }) >= limits.maxCompanies) return { kind: "limit" };
221
- if (await companies.findFirst({ where: companyWhere({ nameKey: input.nameKey }), select: { id: true } })) return { kind: "duplicate" };
222
- const company = await companies.create({ data: { ...companyWhere(), name: input.name, nameKey: input.nameKey, website: input.website, domain: input.domain } });
313
+ if (await companies.count({ where: companyWhereAny() }) >= limits.maxCompanies) return { kind: "limit" };
314
+ const taken = collision(await companies.findFirst({ where: companyWhereAny({ nameKey: input.nameKey }), select: keySelect }));
315
+ if (taken) return taken;
316
+ const company = await companies.create({ data: { ...companyWhereAny(), name: input.name, nameKey: input.nameKey, website: input.website, domain: input.domain } });
223
317
  return { kind: "created", company };
224
318
  }, context.txOptions);
225
319
  } catch (error) {
226
- if (isUniqueViolation(error)) return { kind: "duplicate" };
320
+ if (isUniqueViolation(error)) return afterViolation(input.nameKey);
227
321
  throw error;
228
322
  }
229
323
  },
@@ -231,21 +325,24 @@ function createCompanyWrites(context) {
231
325
  try {
232
326
  return await db().$transaction(async (tx) => {
233
327
  await context.limitLockWait(tx);
234
- const locked = await tx.$queryRawUnsafe(`SELECT "id" FROM ${context.sql.companyTable} WHERE "id" = $1 AND ${context.sql.workspaceColumn} = $2 FOR NO KEY UPDATE`, id, context.workspaceId);
328
+ const locked = await tx.$queryRawUnsafe(`SELECT "id" FROM ${context.sql.companyTable} WHERE "id" = $1 AND ${context.sql.workspaceColumn} = $2${context.liveSql.company} FOR NO KEY UPDATE`, id, context.workspaceId);
235
329
  const companies = context.companies(tx);
236
- const before = locked.length === 0 ? null : await companies.findFirst({ where: companyWhere({ id }) });
330
+ const before = locked.length === 0 ? null : await companies.findFirst({ where: companyWhereLive({ id }) });
237
331
  if (!before) return { kind: "notFound" };
238
332
  if (patch.rename === void 0 && patch.website === void 0) return { kind: "updated", before, after: { ...before } };
239
- if (patch.rename && await companies.findFirst({ where: companyWhere({ nameKey: patch.rename.nameKey, NOT: { id } }), select: { id: true } })) return { kind: "duplicate" };
333
+ if (patch.rename) {
334
+ const taken = collision(await companies.findFirst({ where: companyWhereAny({ nameKey: patch.rename.nameKey, NOT: { id } }), select: keySelect }));
335
+ if (taken) return taken;
336
+ }
240
337
  const data = {};
241
338
  if (patch.rename) Object.assign(data, { name: patch.rename.name, nameKey: patch.rename.nameKey });
242
339
  if (patch.website) Object.assign(data, { website: patch.website.website, domain: patch.website.domain });
243
- await companies.updateMany({ where: companyWhere({ id }), data });
244
- const after = await companies.findFirst({ where: companyWhere({ id }) });
340
+ await companies.updateMany({ where: companyWhereLive({ id }), data });
341
+ const after = await companies.findFirst({ where: companyWhereLive({ id }) });
245
342
  return { kind: "updated", before, after };
246
343
  }, context.txOptions);
247
344
  } catch (error) {
248
- if (isUniqueViolation(error)) return { kind: "duplicate" };
345
+ if (isUniqueViolation(error)) return afterViolation(patch.rename?.nameKey, id);
249
346
  throw error;
250
347
  }
251
348
  },
@@ -255,10 +352,10 @@ function createCompanyWrites(context) {
255
352
  const locked = await tx.$queryRawUnsafe(`SELECT "id" FROM ${context.sql.companyTable} WHERE "id" = $1 AND ${context.sql.workspaceColumn} = $2 FOR UPDATE`, id, context.workspaceId);
256
353
  if (locked.length === 0) return { kind: "notFound" };
257
354
  const companies = context.companies(tx);
258
- const company = await companies.findFirst({ where: companyWhere({ id }) });
355
+ const company = await companies.findFirst({ where: companyWhereAny({ id }) });
259
356
  if (!company) return { kind: "notFound" };
260
357
  const memberCount = await context.members(tx).count({ where: { [context.companyIdColumn]: id } });
261
- const { count } = await companies.deleteMany({ where: companyWhere({ id }) });
358
+ const { count } = await companies.deleteMany({ where: companyWhereAny({ id }) });
262
359
  return count === 0 ? { kind: "notFound" } : { kind: "removed", company, memberCount };
263
360
  }, context.txOptions);
264
361
  }
@@ -269,7 +366,8 @@ function createCompanyWrites(context) {
269
366
  function createPrismaCompanyStore(config) {
270
367
  const context = createContext(config);
271
368
  const reads = createCompanyReads(context);
272
- return { ...reads, ...createCompanyWrites(context), ...createCompanyMembers(context, reads.getMany) };
369
+ const store = { ...reads, ...createCompanyWrites(context), ...createCompanyMembers(context, reads.getMany) };
370
+ return context.softDelete ? { ...store, ...createCompanyTrash(context) } : store;
273
371
  }
274
372
  export {
275
373
  createPrismaCompanyStore
@@ -1,5 +1,5 @@
1
- import { C as CompanyRecord, b as CompanyMemberRecord, P as PersonCompany, a as CompanyStore } from '../../types-CbfseUAS.mjs';
2
- export { c as CompanyAddMemberResult, d as CompanyCreateLimits, e as CompanyCreateResult, f as CompanyMemberLimits, g as CompanyRemoveMemberResult, h as CompanyRemoveResult, i as CompanySetRoleResult, j as CompanyUpdatePatch, k as CompanyUpdateResult, l as CompanyWebsite } from '../../types-CbfseUAS.mjs';
1
+ import { C as CompanyRecord, b as CompanyMemberRecord, P as PersonCompany, a as CompanyStore } from '../../types-BJl_PZDf.mjs';
2
+ export { c as CompanyAddMemberResult, d as CompanyCreateLimits, e as CompanyCreateResult, f as CompanyMemberLimits, g as CompanyRemoveMemberResult, h as CompanyRemoveResult, i as CompanyRestoreResult, j as CompanySetRoleResult, k as CompanyTrashResult, l as CompanyUpdatePatch, m as CompanyUpdateResult, n as CompanyWebsite, T as TrashableCompanyStore } from '../../types-BJl_PZDf.mjs';
3
3
  import { C as CompanyLimits } from '../../constants-DV-gn6u8.mjs';
4
4
 
5
5
  /** Why a call did not do what was asked, with the context an app needs for its message. */
@@ -22,10 +22,27 @@ type CompanyFailure = {
22
22
  reason: 'member-limit';
23
23
  } | {
24
24
  reason: 'duplicate';
25
+ }
26
+ /** The name belongs to a company in the Trash (`id`); only with a soft-delete store. */
27
+ | {
28
+ reason: 'in-trash';
29
+ id: string;
25
30
  } | {
26
31
  reason: 'limit';
27
32
  } | {
28
33
  reason: 'not-found';
34
+ }
35
+ /** Trash only: the company is already in the Trash. */
36
+ | {
37
+ reason: 'already-trashed';
38
+ }
39
+ /** Restore only: the company is not in the Trash. */
40
+ | {
41
+ reason: 'not-trashed';
42
+ }
43
+ /** The store has no Trash (it is not a `TrashableCompanyStore`); nothing was asked of it. */
44
+ | {
45
+ reason: 'unsupported';
29
46
  };
30
47
  type CompanyResult<V> = ({
31
48
  ok: true;
@@ -69,6 +86,24 @@ interface CompanyService<T extends CompanyRecord> {
69
86
  company: T;
70
87
  memberCount: number;
71
88
  }>>;
89
+ /** Moves a company to the Trash. `unsupported` (and no store call) when the store has no Trash. `actorId` is stored with the trash. */
90
+ trash(id: string, actorId: string): Promise<CompanyResult<{
91
+ before: T;
92
+ after: T;
93
+ }>>;
94
+ /** Takes a company out of the Trash. `unsupported` when the store has no Trash. */
95
+ restore(id: string): Promise<CompanyResult<{
96
+ before: T;
97
+ after: T;
98
+ }>>;
99
+ /** The companies in the Trash, most recently trashed first. `unsupported` when the store has no Trash. */
100
+ listTrashed(): Promise<CompanyResult<{
101
+ companies: T[];
102
+ }>>;
103
+ /** A company in ANY state (live or trashed). `unsupported` when the store has no Trash. */
104
+ getAny(id: string): Promise<CompanyResult<{
105
+ company: T;
106
+ }>>;
72
107
  /**
73
108
  * Adds a person to a company. A person who is already a member is NOT an error: the result is `added: false` with the membership as it is
74
109
  * (its role is untouched: changing a role is `setRole`). An empty role means none.
@@ -136,6 +171,11 @@ interface CompanyStoreHarness {
136
171
  * not, they will run and fail, so supply the hook.
137
172
  */
138
173
  armBeforeMemberWrite?(hook: () => Promise<void>): void;
174
+ /**
175
+ * OPTIONAL. True when `storeFor` returns a `TrashableCompanyStore` (trash, restore, listTrashed, getAny; trashed companies hidden from reads, `inTrash` on name collisions,
176
+ * `remove` a hard delete in any state). Only then does the suite run its Trash rules; every existing harness leaves it out and sees no change.
177
+ */
178
+ supportsTrash?: boolean;
139
179
  /** Removes everything the tests created. */
140
180
  cleanup(): Promise<void>;
141
181
  }
@@ -143,6 +183,12 @@ interface CompanyStoreHarness {
143
183
  interface MemoryCompanyWorldOptions {
144
184
  /** Default true. False removes the one-at-a-time chain so races become visible (for proving that concurrency tests can fail). */
145
185
  serialise?: boolean;
186
+ /**
187
+ * Default false (the store is exactly the 1.5.0 one). True gives the stores of this world a Trash (they are `TrashableCompanyStore`s): trashed companies are hidden from
188
+ * every read and write except `getAny`, `listTrashed`, `trash`, `restore` and `remove`; a name taken by a trashed company is `inTrash` (create, update), by a live one `duplicate`;
189
+ * the limit on creates counts trashed companies too; `remove` stays a hard delete of a company in either state.
190
+ */
191
+ softDelete?: boolean;
146
192
  }
147
193
  interface MemoryCompanyWorld {
148
194
  store(workspace: string): CompanyStore<CompanyRecord>;