@ordinatio/entities 1.4.0 → 1.5.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 +4 -0
- package/dist/chunk-3VGJ4NFX.mjs +29 -0
- package/dist/constants-BwInbMWC.d.mts +11 -0
- package/dist/entity-notes/index.d.mts +19 -0
- package/dist/entity-notes/index.mjs +10 -0
- package/dist/entity-notes/prisma/index.d.mts +52 -0
- package/dist/entity-notes/prisma/index.mjs +279 -0
- package/dist/entity-notes/server/index.d.mts +153 -0
- package/dist/entity-notes/server/index.mjs +998 -0
- package/dist/types-B4DY5xj3.d.mts +123 -0
- package/package.json +17 -2
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).
|
|
@@ -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
|
+
};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
interface NoteLimits {
|
|
2
|
+
/** Longest note body after cleaning, in UTF-16 code units (the unit `String.length` and a text column's JavaScript value use; an emoji outside the basic plane counts as 2). */
|
|
3
|
+
maxBodyLength: number;
|
|
4
|
+
/** How many notes a list returns when the caller does not say. */
|
|
5
|
+
defaultPageSize: number;
|
|
6
|
+
/** The most notes one list call may return, whatever the caller asks for: a parent page lists them, so an unbounded page would slow it. */
|
|
7
|
+
maxPageSize: number;
|
|
8
|
+
}
|
|
9
|
+
declare const DEFAULT_NOTE_LIMITS: Readonly<NoteLimits>;
|
|
10
|
+
|
|
11
|
+
export { DEFAULT_NOTE_LIMITS as D, type NoteLimits as N };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export { D as DEFAULT_NOTE_LIMITS, N as NoteLimits } from '../constants-BwInbMWC.mjs';
|
|
2
|
+
|
|
3
|
+
/** Cleans a note body (see the file header). Not a string gives an empty string. */
|
|
4
|
+
declare function cleanNoteBody(body: unknown): string;
|
|
5
|
+
type NoteBodyCheck = {
|
|
6
|
+
ok: true;
|
|
7
|
+
body: string;
|
|
8
|
+
} | {
|
|
9
|
+
ok: false;
|
|
10
|
+
reason: 'empty' | 'too-long';
|
|
11
|
+
length: number;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Cleans the body and checks its length (1 to `maxLength`, default 10,000, in UTF-16 code units like the stored value). `maxLength` must be a positive whole number: anything
|
|
15
|
+
* else (NaN, 0, a negative, a fraction, Infinity) is a caller's mistake and the default applies, so a bad limit can never switch the cap off.
|
|
16
|
+
*/
|
|
17
|
+
declare function checkNoteBody(body: unknown, maxLength?: number): NoteBodyCheck;
|
|
18
|
+
|
|
19
|
+
export { type NoteBodyCheck, checkNoteBody, cleanNoteBody };
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { N as NoteStore, a as NoteRecord } from '../../types-B4DY5xj3.mjs';
|
|
2
|
+
|
|
3
|
+
interface PrismaNoteParentConfig {
|
|
4
|
+
/** The note model's NULLABLE column AND Prisma field that holds the id of this kind of parent, e.g. `contactId`. */
|
|
5
|
+
noteColumn: string;
|
|
6
|
+
/** Prisma delegate of the parent's model, e.g. `contact`. */
|
|
7
|
+
model: string;
|
|
8
|
+
/** SQL table of the parent, e.g. `Contact` (used in the share lock on the parent row). */
|
|
9
|
+
table: string;
|
|
10
|
+
/** The parent model's workspace column. Defaults to the note's. */
|
|
11
|
+
workspaceColumn?: string;
|
|
12
|
+
}
|
|
13
|
+
interface PrismaNoteStoreConfig {
|
|
14
|
+
/** Called each time the store needs the client (never at import), so a test can swap in a client with a bigger pool. */
|
|
15
|
+
client: () => PrismaLikeClient;
|
|
16
|
+
/** The workspace (organization, account, tenant) this store is built for. Every query is scoped by it. */
|
|
17
|
+
workspaceId: string;
|
|
18
|
+
/** Prisma delegate of the note model, e.g. `note`. */
|
|
19
|
+
noteModel: string;
|
|
20
|
+
/** SQL table of the note model, e.g. `Note` (used in the row locks). */
|
|
21
|
+
noteTable: string;
|
|
22
|
+
/** Workspace column on the note model, e.g. `organizationId`. */
|
|
23
|
+
workspaceColumn: string;
|
|
24
|
+
/** The kinds of parent a note can belong to, by kind name, e.g. `{ contact: { noteColumn: 'contactId', model: 'contact', table: 'Contact' } }`. At least one. */
|
|
25
|
+
parents: Record<string, PrismaNoteParentConfig>;
|
|
26
|
+
/** Column AND Prisma field of the note model for who wrote it (plain text). Default `authorId`. */
|
|
27
|
+
authorColumn?: string;
|
|
28
|
+
/** How long a transaction waits for any one lock before it throws (Postgres lock_timeout). Default 5000. */
|
|
29
|
+
lockWaitMs?: number;
|
|
30
|
+
/** Interactive transaction limits. Defaults: maxWait 10000, timeout 15000. */
|
|
31
|
+
transaction?: {
|
|
32
|
+
maxWait?: number;
|
|
33
|
+
timeout?: number;
|
|
34
|
+
};
|
|
35
|
+
/** TEST ONLY: runs inside `create` after the parent check and before the write, holding NO lock and no open transaction, so a test can delete the parent there. */
|
|
36
|
+
onBeforeNoteWrite?: () => Promise<void>;
|
|
37
|
+
}
|
|
38
|
+
/** The part of a transaction client the store uses. A real Prisma transaction client satisfies it; model delegates are looked up by name. */
|
|
39
|
+
interface PrismaLikeTx {
|
|
40
|
+
$executeRawUnsafe(query: string, ...values: unknown[]): Promise<unknown>;
|
|
41
|
+
$queryRawUnsafe(query: string, ...values: unknown[]): Promise<unknown>;
|
|
42
|
+
}
|
|
43
|
+
interface PrismaLikeClient extends PrismaLikeTx {
|
|
44
|
+
$transaction<R>(fn: (tx: PrismaLikeTx) => Promise<R>, options?: {
|
|
45
|
+
maxWait?: number;
|
|
46
|
+
timeout?: number;
|
|
47
|
+
}): Promise<R>;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
declare function createPrismaNoteStore(config: PrismaNoteStoreConfig): NoteStore<NoteRecord>;
|
|
51
|
+
|
|
52
|
+
export { type PrismaLikeClient, type PrismaLikeTx, type PrismaNoteParentConfig, type PrismaNoteStoreConfig, createPrismaNoteStore };
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
// src/entity-notes/prisma/identifiers.ts
|
|
2
|
+
var IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
3
|
+
var RESERVED = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype", "toString", "valueOf", "hasOwnProperty"]);
|
|
4
|
+
function assertIdentifier(value, what) {
|
|
5
|
+
if (typeof value !== "string" || !IDENTIFIER.test(value) || RESERVED.has(value)) {
|
|
6
|
+
throw new Error(`createPrismaNoteStore: ${what} must be a plain identifier (letters, digits and underscores, not starting with a digit), got ${JSON.stringify(value)}`);
|
|
7
|
+
}
|
|
8
|
+
return value;
|
|
9
|
+
}
|
|
10
|
+
function quote(identifier) {
|
|
11
|
+
return `"${identifier}"`;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// src/entity-notes/prisma/context.ts
|
|
15
|
+
var FIXED_COLUMNS = /* @__PURE__ */ new Set(["id", "body", "revision", "createdAt", "updatedAt", "deletedAt", "deletedBy"]);
|
|
16
|
+
function createContext(config) {
|
|
17
|
+
if (typeof config.client !== "function") throw new Error("createPrismaNoteStore: client must be a function that returns the Prisma client");
|
|
18
|
+
if (typeof config.workspaceId !== "string" || config.workspaceId === "") throw new Error("createPrismaNoteStore: workspaceId must be a non-empty string");
|
|
19
|
+
const workspaceColumn = assertIdentifier(config.workspaceColumn, "workspaceColumn");
|
|
20
|
+
const noteModel = assertIdentifier(config.noteModel, "noteModel");
|
|
21
|
+
const noteTable = assertIdentifier(config.noteTable, "noteTable");
|
|
22
|
+
const authorColumn = assertIdentifier(config.authorColumn ?? "authorId", "authorColumn");
|
|
23
|
+
if (FIXED_COLUMNS.has(workspaceColumn) || FIXED_COLUMNS.has(authorColumn) || workspaceColumn === authorColumn) {
|
|
24
|
+
throw new Error("createPrismaNoteStore: workspaceColumn and authorColumn must be different columns and must not be one of the fixed ones (id, body, revision, createdAt, updatedAt, deletedAt, deletedBy)");
|
|
25
|
+
}
|
|
26
|
+
const lockWaitMs = config.lockWaitMs ?? 5e3;
|
|
27
|
+
if (!Number.isInteger(lockWaitMs) || lockWaitMs <= 0) throw new Error("createPrismaNoteStore: lockWaitMs must be a positive integer");
|
|
28
|
+
const txOptions = { maxWait: config.transaction?.maxWait ?? 1e4, timeout: config.transaction?.timeout ?? 15e3 };
|
|
29
|
+
if (typeof config.parents !== "object" || config.parents === null) throw new Error("createPrismaNoteStore: parents must be an object with one entry per kind of parent");
|
|
30
|
+
const kinds = /* @__PURE__ */ new Map();
|
|
31
|
+
const taken = /* @__PURE__ */ new Set([workspaceColumn, authorColumn]);
|
|
32
|
+
for (const [kind, parent] of Object.entries(config.parents)) {
|
|
33
|
+
if (kind === "") throw new Error("createPrismaNoteStore: a parent kind must not be empty");
|
|
34
|
+
const noteColumn = assertIdentifier(parent?.noteColumn, `parents.${kind}.noteColumn`);
|
|
35
|
+
if (FIXED_COLUMNS.has(noteColumn) || taken.has(noteColumn)) throw new Error(`createPrismaNoteStore: parents.${kind}.noteColumn "${noteColumn}" is already used by another column (each kind needs its own column)`);
|
|
36
|
+
taken.add(noteColumn);
|
|
37
|
+
const model2 = assertIdentifier(parent.model, `parents.${kind}.model`);
|
|
38
|
+
const table = assertIdentifier(parent.table, `parents.${kind}.table`);
|
|
39
|
+
const parentWorkspace = assertIdentifier(parent.workspaceColumn ?? workspaceColumn, `parents.${kind}.workspaceColumn`);
|
|
40
|
+
kinds.set(kind, { kind, noteColumn, model: model2, workspaceColumn: parentWorkspace, sqlTable: quote(table), sqlWorkspaceColumn: quote(parentWorkspace) });
|
|
41
|
+
}
|
|
42
|
+
if (kinds.size === 0) throw new Error("createPrismaNoteStore: parents must name at least one kind of parent");
|
|
43
|
+
const model = (client, name) => {
|
|
44
|
+
const found = client[name];
|
|
45
|
+
if (typeof found !== "object" || found === null) throw new Error(`createPrismaNoteStore: the Prisma client has no model "${name}" (check the configuration)`);
|
|
46
|
+
return found;
|
|
47
|
+
};
|
|
48
|
+
return {
|
|
49
|
+
workspaceId: config.workspaceId,
|
|
50
|
+
workspaceColumn,
|
|
51
|
+
authorColumn,
|
|
52
|
+
sql: { noteTable: quote(noteTable), workspaceColumn: quote(workspaceColumn) },
|
|
53
|
+
txOptions,
|
|
54
|
+
beforeNoteWrite: config.onBeforeNoteWrite,
|
|
55
|
+
client: config.client,
|
|
56
|
+
parent: (kind) => kinds.get(kind),
|
|
57
|
+
model,
|
|
58
|
+
notes: (client) => model(client, noteModel),
|
|
59
|
+
noteWhere: (extra = {}) => ({ ...extra, [workspaceColumn]: config.workspaceId }),
|
|
60
|
+
toRecord(row) {
|
|
61
|
+
const fields = row;
|
|
62
|
+
for (const parent of kinds.values()) {
|
|
63
|
+
const parentId = fields[parent.noteColumn];
|
|
64
|
+
if (typeof parentId === "string" && parentId !== "") {
|
|
65
|
+
return {
|
|
66
|
+
id: fields.id,
|
|
67
|
+
parentKind: parent.kind,
|
|
68
|
+
parentId,
|
|
69
|
+
body: fields.body,
|
|
70
|
+
revision: fields.revision,
|
|
71
|
+
authorId: fields[authorColumn],
|
|
72
|
+
createdAt: fields.createdAt,
|
|
73
|
+
updatedAt: fields.updatedAt,
|
|
74
|
+
deletedAt: fields.deletedAt ?? null,
|
|
75
|
+
deletedBy: fields.deletedBy ?? null
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
throw new Error(`createPrismaNoteStore: note ${String(fields.id)} has none of the configured parent columns set`);
|
|
80
|
+
},
|
|
81
|
+
async limitLockWait(tx) {
|
|
82
|
+
await tx.$executeRawUnsafe(`SELECT set_config('lock_timeout', $1, true)`, `${lockWaitMs}ms`);
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// src/entity-notes/prisma/cursor.ts
|
|
88
|
+
var SHAPE = /^v1\.([A-Za-z0-9_-]+)$/;
|
|
89
|
+
var MIN_TIME = -621355968e5;
|
|
90
|
+
var MAX_TIME = 253402300799999;
|
|
91
|
+
function toBase64Url(text) {
|
|
92
|
+
const bytes = new TextEncoder().encode(text);
|
|
93
|
+
let binary = "";
|
|
94
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
95
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
96
|
+
}
|
|
97
|
+
function fromBase64Url(encoded) {
|
|
98
|
+
try {
|
|
99
|
+
const padded = encoded.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - encoded.length % 4) % 4);
|
|
100
|
+
const binary = atob(padded);
|
|
101
|
+
const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
|
|
102
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
103
|
+
} catch {
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
function encodeCursor(time, id) {
|
|
108
|
+
return `v1.${toBase64Url(JSON.stringify([time, id]))}`;
|
|
109
|
+
}
|
|
110
|
+
function decodeCursor(cursor) {
|
|
111
|
+
const match = SHAPE.exec(cursor);
|
|
112
|
+
if (!match) return null;
|
|
113
|
+
const json = fromBase64Url(match[1]);
|
|
114
|
+
if (json === null) return null;
|
|
115
|
+
let parsed;
|
|
116
|
+
try {
|
|
117
|
+
parsed = JSON.parse(json);
|
|
118
|
+
} catch {
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
if (!Array.isArray(parsed) || parsed.length !== 2) return null;
|
|
122
|
+
const [time, id] = parsed;
|
|
123
|
+
if (typeof time !== "number" || !Number.isInteger(time) || time < MIN_TIME || time > MAX_TIME) return null;
|
|
124
|
+
if (typeof id !== "string" || id.length === 0 || id.length > 255 || id.includes("\0")) return null;
|
|
125
|
+
return encodeCursor(time, id) === cursor ? { time, id } : null;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// src/entity-notes/prisma/reads.ts
|
|
129
|
+
var IDS_PER_QUERY = 1e4;
|
|
130
|
+
function chunksOf(items) {
|
|
131
|
+
const pieces = [];
|
|
132
|
+
for (let start = 0; start < items.length; start += IDS_PER_QUERY) pieces.push(items.slice(start, start + IDS_PER_QUERY));
|
|
133
|
+
return pieces;
|
|
134
|
+
}
|
|
135
|
+
function createNoteReads(context) {
|
|
136
|
+
const { noteWhere } = context;
|
|
137
|
+
const db = () => context.client();
|
|
138
|
+
const statusFilter = (status) => status === "live" ? null : { not: null };
|
|
139
|
+
return {
|
|
140
|
+
async get(id) {
|
|
141
|
+
const row = await context.notes(db()).findFirst({ where: noteWhere({ id }) });
|
|
142
|
+
return row ? context.toRecord(row) : null;
|
|
143
|
+
},
|
|
144
|
+
async list(query) {
|
|
145
|
+
let after = null;
|
|
146
|
+
if (query.cursor !== null) {
|
|
147
|
+
after = decodeCursor(query.cursor);
|
|
148
|
+
if (after === null) return { kind: "badCursor" };
|
|
149
|
+
}
|
|
150
|
+
const parent = context.parent(query.parent.kind);
|
|
151
|
+
if (!parent) return { kind: "page", notes: [], nextCursor: null };
|
|
152
|
+
const where = noteWhere({
|
|
153
|
+
[parent.noteColumn]: query.parent.id,
|
|
154
|
+
deletedAt: statusFilter(query.status),
|
|
155
|
+
...after ? { OR: [{ createdAt: { lt: new Date(after.time) } }, { createdAt: new Date(after.time), id: { lt: after.id } }] } : {}
|
|
156
|
+
});
|
|
157
|
+
const rows = await context.notes(db()).findMany({ where, orderBy: [{ createdAt: "desc" }, { id: "desc" }], take: query.limit + 1 });
|
|
158
|
+
const notes = rows.slice(0, query.limit).map((row) => context.toRecord(row));
|
|
159
|
+
const last = notes[notes.length - 1];
|
|
160
|
+
return { kind: "page", notes, nextCursor: rows.length > query.limit && last ? encodeCursor(last.createdAt.getTime(), last.id) : null };
|
|
161
|
+
},
|
|
162
|
+
async countByParent(kind, parentIds, status) {
|
|
163
|
+
const counts = new Map(parentIds.map((id) => [id, 0]));
|
|
164
|
+
const parent = context.parent(kind);
|
|
165
|
+
if (!parent) return counts;
|
|
166
|
+
for (const piece of chunksOf([...counts.keys()])) {
|
|
167
|
+
const grouped = await context.notes(db()).groupBy({
|
|
168
|
+
by: [parent.noteColumn],
|
|
169
|
+
where: noteWhere({ [parent.noteColumn]: { in: piece }, deletedAt: statusFilter(status) }),
|
|
170
|
+
_count: { _all: true }
|
|
171
|
+
});
|
|
172
|
+
for (const row of grouped) counts.set(row[parent.noteColumn], row._count._all);
|
|
173
|
+
}
|
|
174
|
+
return counts;
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// src/entity-notes/prisma/errors.ts
|
|
180
|
+
function hasCode(error, code, depth) {
|
|
181
|
+
if (typeof error !== "object" || error === null || depth > 4) return false;
|
|
182
|
+
const fields = error;
|
|
183
|
+
if (fields.code === code) return true;
|
|
184
|
+
return ["cause", "meta", "originalError", "driverAdapterError"].some((key) => hasCode(fields[key], code, depth + 1));
|
|
185
|
+
}
|
|
186
|
+
var isForeignKeyViolation = (error) => hasCode(error, "P2003", 0);
|
|
187
|
+
|
|
188
|
+
// src/entity-notes/prisma/writes.ts
|
|
189
|
+
function createNoteWrites(context) {
|
|
190
|
+
const { noteWhere, sql } = context;
|
|
191
|
+
const db = () => context.client();
|
|
192
|
+
const lockNote = async (tx, id) => (await tx.$queryRawUnsafe(`SELECT "id" FROM ${sql.noteTable} WHERE "id" = $1 AND ${sql.workspaceColumn} = $2 FOR UPDATE`, id, context.workspaceId)).length > 0;
|
|
193
|
+
const read = async (tx, id) => {
|
|
194
|
+
const row = await context.notes(tx).findFirst({ where: noteWhere({ id }) });
|
|
195
|
+
return row ? context.toRecord(row) : null;
|
|
196
|
+
};
|
|
197
|
+
return {
|
|
198
|
+
async create(parent, body, authorId) {
|
|
199
|
+
const kind = context.parent(parent.kind);
|
|
200
|
+
if (!kind) return { kind: "parentGone" };
|
|
201
|
+
const parentExists = async () => await context.model(db(), kind.model).findFirst({ where: { id: parent.id, [kind.workspaceColumn]: context.workspaceId }, select: { id: true } }) != null;
|
|
202
|
+
if (!await parentExists()) return { kind: "parentGone" };
|
|
203
|
+
if (context.beforeNoteWrite) await context.beforeNoteWrite();
|
|
204
|
+
try {
|
|
205
|
+
return await db().$transaction(async (tx) => {
|
|
206
|
+
await context.limitLockWait(tx);
|
|
207
|
+
const locked = await tx.$queryRawUnsafe(`SELECT "id" FROM ${kind.sqlTable} WHERE "id" = $1 AND ${kind.sqlWorkspaceColumn} = $2 FOR KEY SHARE`, parent.id, context.workspaceId);
|
|
208
|
+
if (locked.length === 0) return { kind: "parentGone" };
|
|
209
|
+
const stamp = /* @__PURE__ */ new Date();
|
|
210
|
+
const row = await context.notes(tx).create({
|
|
211
|
+
data: { ...noteWhere(), [kind.noteColumn]: parent.id, body, revision: 1, [context.authorColumn]: authorId, createdAt: stamp, updatedAt: stamp, deletedAt: null, deletedBy: null }
|
|
212
|
+
});
|
|
213
|
+
return { kind: "created", note: context.toRecord(row) };
|
|
214
|
+
}, context.txOptions);
|
|
215
|
+
} catch (error) {
|
|
216
|
+
if (isForeignKeyViolation(error)) return { kind: "parentGone" };
|
|
217
|
+
throw error;
|
|
218
|
+
}
|
|
219
|
+
},
|
|
220
|
+
async update(id, body, expectedRevision) {
|
|
221
|
+
return db().$transaction(async (tx) => {
|
|
222
|
+
await context.limitLockWait(tx);
|
|
223
|
+
if (!await lockNote(tx, id)) return { kind: "notFound" };
|
|
224
|
+
const before = await read(tx, id);
|
|
225
|
+
if (!before) return { kind: "notFound" };
|
|
226
|
+
if (before.deletedAt !== null) return { kind: "deleted" };
|
|
227
|
+
if (before.revision !== expectedRevision) return { kind: "conflict", current: before };
|
|
228
|
+
const { count } = await context.notes(tx).updateMany({
|
|
229
|
+
where: noteWhere({ id, revision: expectedRevision, deletedAt: null }),
|
|
230
|
+
data: { body, revision: expectedRevision + 1, updatedAt: /* @__PURE__ */ new Date() }
|
|
231
|
+
});
|
|
232
|
+
const after = await read(tx, id);
|
|
233
|
+
if (count === 0 || !after) return after ? after.deletedAt !== null ? { kind: "deleted" } : { kind: "conflict", current: after } : { kind: "notFound" };
|
|
234
|
+
return { kind: "updated", before, after };
|
|
235
|
+
}, context.txOptions);
|
|
236
|
+
},
|
|
237
|
+
async softDelete(id, actorId) {
|
|
238
|
+
return db().$transaction(async (tx) => {
|
|
239
|
+
await context.limitLockWait(tx);
|
|
240
|
+
if (!await lockNote(tx, id)) return { kind: "notFound" };
|
|
241
|
+
const before = await read(tx, id);
|
|
242
|
+
if (!before) return { kind: "notFound" };
|
|
243
|
+
if (before.deletedAt !== null) return { kind: "alreadyDeleted" };
|
|
244
|
+
const { count } = await context.notes(tx).updateMany({
|
|
245
|
+
where: noteWhere({ id, deletedAt: null }),
|
|
246
|
+
data: { deletedAt: /* @__PURE__ */ new Date(), deletedBy: actorId, updatedAt: before.updatedAt }
|
|
247
|
+
});
|
|
248
|
+
const after = await read(tx, id);
|
|
249
|
+
if (count === 0 || !after) return after ? { kind: "alreadyDeleted" } : { kind: "notFound" };
|
|
250
|
+
return { kind: "deleted", before, after };
|
|
251
|
+
}, context.txOptions);
|
|
252
|
+
},
|
|
253
|
+
async restore(id) {
|
|
254
|
+
return db().$transaction(async (tx) => {
|
|
255
|
+
await context.limitLockWait(tx);
|
|
256
|
+
if (!await lockNote(tx, id)) return { kind: "notFound" };
|
|
257
|
+
const before = await read(tx, id);
|
|
258
|
+
if (!before) return { kind: "notFound" };
|
|
259
|
+
if (before.deletedAt === null) return { kind: "notDeleted" };
|
|
260
|
+
const { count } = await context.notes(tx).updateMany({
|
|
261
|
+
where: { ...noteWhere({ id }), NOT: { deletedAt: null } },
|
|
262
|
+
data: { deletedAt: null, deletedBy: null, updatedAt: before.updatedAt }
|
|
263
|
+
});
|
|
264
|
+
const after = await read(tx, id);
|
|
265
|
+
if (count === 0 || !after) return after ? { kind: "notDeleted" } : { kind: "notFound" };
|
|
266
|
+
return { kind: "restored", before, after };
|
|
267
|
+
}, context.txOptions);
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// src/entity-notes/prisma/index.ts
|
|
273
|
+
function createPrismaNoteStore(config) {
|
|
274
|
+
const context = createContext(config);
|
|
275
|
+
return { ...createNoteReads(context), ...createNoteWrites(context) };
|
|
276
|
+
}
|
|
277
|
+
export {
|
|
278
|
+
createPrismaNoteStore
|
|
279
|
+
};
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { a as NoteRecord, b as NoteStatus, c as NoteParent, N as NoteStore } from '../../types-B4DY5xj3.mjs';
|
|
2
|
+
export { d as NoteCreateResult, e as NoteDeleteResult, f as NoteListQuery, g as NoteListResult, h as NoteRestoreResult, i as NoteUpdateResult } from '../../types-B4DY5xj3.mjs';
|
|
3
|
+
import { N as NoteLimits } from '../../constants-BwInbMWC.mjs';
|
|
4
|
+
|
|
5
|
+
/** Why a call did not do what was asked, with the context an app needs for its message. */
|
|
6
|
+
type NoteFailure<T extends NoteRecord> = {
|
|
7
|
+
reason: 'invalid-body';
|
|
8
|
+
problem: 'empty' | 'too-long';
|
|
9
|
+
length: number;
|
|
10
|
+
} | {
|
|
11
|
+
reason: 'invalid-parent';
|
|
12
|
+
}
|
|
13
|
+
/** The author or the actor is not a non-empty text id. */
|
|
14
|
+
| {
|
|
15
|
+
reason: 'invalid-actor';
|
|
16
|
+
}
|
|
17
|
+
/** `status` is neither `live` nor `deleted`. */
|
|
18
|
+
| {
|
|
19
|
+
reason: 'invalid-status';
|
|
20
|
+
} | {
|
|
21
|
+
reason: 'invalid-revision';
|
|
22
|
+
} | {
|
|
23
|
+
reason: 'invalid-cursor';
|
|
24
|
+
} | {
|
|
25
|
+
reason: 'parent-gone';
|
|
26
|
+
} | {
|
|
27
|
+
reason: 'not-found';
|
|
28
|
+
}
|
|
29
|
+
/** A deleted note cannot be edited: restore it first. */
|
|
30
|
+
| {
|
|
31
|
+
reason: 'deleted';
|
|
32
|
+
} | {
|
|
33
|
+
reason: 'already-deleted';
|
|
34
|
+
} | {
|
|
35
|
+
reason: 'not-deleted';
|
|
36
|
+
}
|
|
37
|
+
/** Someone saved this note since the editor loaded it: `current` is what is stored now. */
|
|
38
|
+
| {
|
|
39
|
+
reason: 'conflict';
|
|
40
|
+
current: T;
|
|
41
|
+
};
|
|
42
|
+
type NoteResult<T extends NoteRecord, V> = ({
|
|
43
|
+
ok: true;
|
|
44
|
+
} & V) | ({
|
|
45
|
+
ok: false;
|
|
46
|
+
} & NoteFailure<T>);
|
|
47
|
+
interface NoteListOptions {
|
|
48
|
+
/** Default `live`. */
|
|
49
|
+
status?: NoteStatus;
|
|
50
|
+
/** Default 50, at most 200 (the limits' page sizes); anything that is not a whole number of at least 1 gets the default. */
|
|
51
|
+
limit?: number;
|
|
52
|
+
/** An opaque cursor from `nextCursor` of an earlier page of the same listing. */
|
|
53
|
+
cursor?: string | null;
|
|
54
|
+
}
|
|
55
|
+
interface NoteService<T extends NoteRecord> {
|
|
56
|
+
/** Adds a note to a parent. `body` is cleaned; the stored text is the cleaned one. `authorId` must be a non-empty text (`invalid-actor` otherwise). */
|
|
57
|
+
add(parent: NoteParent, body: string, authorId: string): Promise<NoteResult<T, {
|
|
58
|
+
note: T;
|
|
59
|
+
}>>;
|
|
60
|
+
/** Edits a note that the editor loaded at `expectedRevision`: a stale revision is a `conflict` carrying the current note, and nothing changes. */
|
|
61
|
+
edit(id: string, body: string, expectedRevision: number): Promise<NoteResult<T, {
|
|
62
|
+
before: T;
|
|
63
|
+
after: T;
|
|
64
|
+
}>>;
|
|
65
|
+
/** Soft delete: the note is hidden from the live list and kept. `actorId` must be a non-empty text (`invalid-actor` otherwise). */
|
|
66
|
+
remove(id: string, actorId: string): Promise<NoteResult<T, {
|
|
67
|
+
before: T;
|
|
68
|
+
after: T;
|
|
69
|
+
}>>;
|
|
70
|
+
restore(id: string): Promise<NoteResult<T, {
|
|
71
|
+
before: T;
|
|
72
|
+
after: T;
|
|
73
|
+
}>>;
|
|
74
|
+
/** One note, a deleted one included (check `deletedAt`). */
|
|
75
|
+
get(id: string): Promise<NoteResult<T, {
|
|
76
|
+
note: T;
|
|
77
|
+
}>>;
|
|
78
|
+
/** One page of a parent's notes, newest first. An unknown `status` is `invalid-status`. */
|
|
79
|
+
list(parent: NoteParent, options?: NoteListOptions): Promise<NoteResult<T, {
|
|
80
|
+
notes: T[];
|
|
81
|
+
nextCursor: string | null;
|
|
82
|
+
}>>;
|
|
83
|
+
/** How many notes (live by default) each of these parents of one kind has: EXACTLY the asked ids appear (the service guarantees it, zero where the store says nothing); an id that is not a non-empty text is ignored; an empty list is an empty map. */
|
|
84
|
+
counts(kind: string, parentIds: string[], status?: NoteStatus): Promise<Map<string, number>>;
|
|
85
|
+
}
|
|
86
|
+
declare function createNoteService<T extends NoteRecord>(store: NoteStore<T>, suppliedLimits?: NoteLimits): NoteService<T>;
|
|
87
|
+
|
|
88
|
+
interface NoteContractRunner {
|
|
89
|
+
describe: (name: string, body: () => void) => void;
|
|
90
|
+
it: ((name: string, body: () => Promise<void>) => void) & {
|
|
91
|
+
skip?: (name: string, body: () => Promise<void>) => void;
|
|
92
|
+
};
|
|
93
|
+
expect: (value: unknown) => {
|
|
94
|
+
toBe(expected: unknown): void;
|
|
95
|
+
toEqual(expected: unknown): void;
|
|
96
|
+
toBeNull(): void;
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
interface NoteStoreHarness {
|
|
100
|
+
/** A fresh, empty workspace id. Every test uses its own, so tests never see each other's rows. */
|
|
101
|
+
newWorkspace(): Promise<string>;
|
|
102
|
+
/** The store for one workspace. Called repeatedly for the same id: it must give the same data. */
|
|
103
|
+
storeFor(workspace: string): NoteStore<NoteRecord>;
|
|
104
|
+
/**
|
|
105
|
+
* Creates a real parent of the given kind (a contact, a company ...) in the workspace and returns its id. `wantedId` is OPTIONAL: when given, a harness that can use that id for the
|
|
106
|
+
* parent returns it (so the contract can make a parent of another kind with the SAME id); a harness whose ids cannot be chosen ignores it and returns an id of its own, and the one
|
|
107
|
+
* check that needs the shared id then skips that part.
|
|
108
|
+
*/
|
|
109
|
+
addParent(workspace: string, kind: string, wantedId?: string): Promise<string>;
|
|
110
|
+
/**
|
|
111
|
+
* Deletes a parent with everything that points at it (its notes): what a database's cascading delete does. NOTE: the contract also passes ids that do not exist, such as 'missing',
|
|
112
|
+
* 'ghost-1' or 'nothing', for notes and for parents (a prefix of a real id, quotes too; never an empty text, a NUL or a lone surrogate, which the service refuses first): an adapter with
|
|
113
|
+
* uuid or integer id columns must answer them as "not found" instead of failing the cast.
|
|
114
|
+
*/
|
|
115
|
+
removeParent(workspace: string, kind: string, id: string): Promise<void>;
|
|
116
|
+
/**
|
|
117
|
+
* OPTIONAL test seam, for the parent-deleted-while-creating check (./contract-hooks; no other check uses it). Arms a ONE-SHOT hook that the next `create` runs AFTER it has checked that
|
|
118
|
+
* the parent exists and BEFORE the write (the write re-checks the parent, atomically, and inserts), so a test can delete the parent at exactly the dangerous moment. The hook is taken
|
|
119
|
+
* (cleared) BEFORE it is called and runs with no lock held and no transaction open: it may itself call any store method. A create stopped earlier by `parentGone` does not run the hook
|
|
120
|
+
* and leaves it armed (an adapter built as ONE `INSERT ... SELECT ... WHERE EXISTS` statement has no separate first check: its harness wrapper looks the parent up first, before arming, and
|
|
121
|
+
* returns `parentGone` itself without running the hook). Without it that check is shown as skipped when your runner has `it.skip`; if not, it will run and fail, so supply the hook.
|
|
122
|
+
*/
|
|
123
|
+
armBeforeNoteWrite?(hook: () => Promise<void>): void;
|
|
124
|
+
/** Removes everything the tests created. */
|
|
125
|
+
cleanup(): Promise<void>;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
interface MemoryNoteWorldOptions {
|
|
129
|
+
/** Default true. False removes the one-at-a-time chain so races become visible (for proving that concurrency checks can fail). */
|
|
130
|
+
serialise?: boolean;
|
|
131
|
+
/** Default true. False drops the parent re-check at write time (for proving that the deleted-parent check can fail). */
|
|
132
|
+
checkParentAtWrite?: boolean;
|
|
133
|
+
/** The clock; default `() => new Date()`. */
|
|
134
|
+
now?: () => Date;
|
|
135
|
+
/** Makes the id of each new note; default `note-000000001`, `note-000000002` ... (they sort in creation order). Pass random ids to prove that nothing depends on ids sorting in creation order. */
|
|
136
|
+
newId?: () => string;
|
|
137
|
+
}
|
|
138
|
+
interface MemoryNoteWorld {
|
|
139
|
+
store(workspace: string): NoteStore<NoteRecord>;
|
|
140
|
+
/** Registers a parent (a contact, a company ...) of a workspace and returns its id. */
|
|
141
|
+
addParent(workspace: string, kind: string, id?: string): string;
|
|
142
|
+
/** Removes a parent and every note of it, deleted ones included (what a database's cascading delete does). */
|
|
143
|
+
removeParent(workspace: string, kind: string, id: string): Promise<void>;
|
|
144
|
+
/** Arms a ONE-SHOT hook run by the next `create` IN THIS WORLD that gets past its first check, between that check and its write. */
|
|
145
|
+
armBeforeNoteWrite(hook: () => Promise<void>): void;
|
|
146
|
+
}
|
|
147
|
+
declare function createMemoryNoteWorld(options?: MemoryNoteWorldOptions): MemoryNoteWorld;
|
|
148
|
+
/** A harness over a fresh in-memory world, for running the contract suite against this store (a product's own tests can use it as a template for theirs). */
|
|
149
|
+
declare function createMemoryNoteHarness(options?: MemoryNoteWorldOptions): NoteStoreHarness;
|
|
150
|
+
|
|
151
|
+
declare function defineNoteStoreContract(api: NoteContractRunner, harness: NoteStoreHarness): void;
|
|
152
|
+
|
|
153
|
+
export { type MemoryNoteWorld, type MemoryNoteWorldOptions, type NoteContractRunner, type NoteFailure, type NoteListOptions, NoteParent, NoteRecord, type NoteResult, type NoteService, NoteStatus, NoteStore, type NoteStoreHarness, createMemoryNoteHarness, createMemoryNoteWorld, createNoteService, defineNoteStoreContract };
|