@ordinatio/entities 1.3.0 → 1.4.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-ZWID3JLL.mjs +123 -0
- package/dist/companies/index.d.mts +60 -0
- package/dist/companies/index.mjs +24 -0
- package/dist/companies/prisma/index.d.mts +58 -0
- package/dist/companies/prisma/index.mjs +276 -0
- package/dist/companies/server/index.d.mts +167 -0
- package/dist/companies/server/index.mjs +1826 -0
- package/dist/constants-DV-gn6u8.d.mts +22 -0
- package/dist/types-CbfseUAS.d.mts +169 -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
|
+
### Companies Module (`@ordinatio/entities/companies`, experimental)
|
|
195
|
+
|
|
196
|
+
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).
|
|
197
|
+
|
|
194
198
|
### Tags Module (`@ordinatio/entities/tags`, experimental)
|
|
195
199
|
|
|
196
200
|
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.
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// src/companies/constants.ts
|
|
2
|
+
var DEFAULT_COMPANY_LIMITS = Object.freeze({
|
|
3
|
+
maxNameLength: 120,
|
|
4
|
+
maxRoleLength: 80,
|
|
5
|
+
maxWebsiteLength: 200,
|
|
6
|
+
maxPerWorkspace: 5e3,
|
|
7
|
+
maxMembersPerCompany: 1e3
|
|
8
|
+
});
|
|
9
|
+
var FREE_MAIL_DOMAINS = Object.freeze([
|
|
10
|
+
"126.com",
|
|
11
|
+
"163.com",
|
|
12
|
+
"aim.com",
|
|
13
|
+
"aol.com",
|
|
14
|
+
"comcast.net",
|
|
15
|
+
"duck.com",
|
|
16
|
+
"fastmail.com",
|
|
17
|
+
"gmail.com",
|
|
18
|
+
"gmx.com",
|
|
19
|
+
"gmx.net",
|
|
20
|
+
"googlemail.com",
|
|
21
|
+
"hey.com",
|
|
22
|
+
"hotmail.co.uk",
|
|
23
|
+
"hotmail.com",
|
|
24
|
+
"icloud.com",
|
|
25
|
+
"live.com",
|
|
26
|
+
"mac.com",
|
|
27
|
+
"mail.com",
|
|
28
|
+
"me.com",
|
|
29
|
+
"msn.com",
|
|
30
|
+
"outlook.com",
|
|
31
|
+
"pm.me",
|
|
32
|
+
"proton.me",
|
|
33
|
+
"protonmail.com",
|
|
34
|
+
"qq.com",
|
|
35
|
+
"sbcglobal.net",
|
|
36
|
+
"verizon.net",
|
|
37
|
+
"yahoo.co.uk",
|
|
38
|
+
"yahoo.com",
|
|
39
|
+
"yandex.com",
|
|
40
|
+
"ymail.com",
|
|
41
|
+
"zoho.com"
|
|
42
|
+
]);
|
|
43
|
+
|
|
44
|
+
// src/companies/name.ts
|
|
45
|
+
function cleanCompanyName(name) {
|
|
46
|
+
return name.trim().replace(/\s+/g, " ");
|
|
47
|
+
}
|
|
48
|
+
function companyNameKey(name) {
|
|
49
|
+
return cleanCompanyName(name).toLowerCase();
|
|
50
|
+
}
|
|
51
|
+
function checkCompanyName(name, maxLength = DEFAULT_COMPANY_LIMITS.maxNameLength) {
|
|
52
|
+
const cleaned = cleanCompanyName(name);
|
|
53
|
+
if (cleaned.length < 1) return { ok: false, reason: "empty", length: cleaned.length };
|
|
54
|
+
if (cleaned.length > maxLength) return { ok: false, reason: "too-long", length: cleaned.length };
|
|
55
|
+
return { ok: true, name: cleaned, key: companyNameKey(cleaned) };
|
|
56
|
+
}
|
|
57
|
+
function checkCompanyRole(role, maxLength = DEFAULT_COMPANY_LIMITS.maxRoleLength) {
|
|
58
|
+
const cleaned = cleanCompanyName(role ?? "");
|
|
59
|
+
if (cleaned.length === 0) return { ok: true, role: null };
|
|
60
|
+
if (cleaned.length > maxLength) return { ok: false, reason: "too-long", length: cleaned.length };
|
|
61
|
+
return { ok: true, role: cleaned };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// src/companies/domain.ts
|
|
65
|
+
var FREE_MAIL = new Set(FREE_MAIL_DOMAINS);
|
|
66
|
+
var HOST = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+(?:[a-z]{2,63}|xn--[a-z0-9-]{1,59})$/;
|
|
67
|
+
function normalizeHost(raw) {
|
|
68
|
+
let host = raw.replace(/\.$/, "");
|
|
69
|
+
if (host.startsWith("www.") && host.indexOf(".", 4) !== -1) host = host.slice(4);
|
|
70
|
+
return HOST.test(host) ? host : null;
|
|
71
|
+
}
|
|
72
|
+
function isFreeMailDomain(domain) {
|
|
73
|
+
return FREE_MAIL.has(domain.trim().toLowerCase());
|
|
74
|
+
}
|
|
75
|
+
function domainOfEmail(email) {
|
|
76
|
+
const parts = email.trim().split("@");
|
|
77
|
+
if (parts.length !== 2 || parts[0].length === 0 || /\s/.test(parts[0]) || /[\s/?#:\\]/.test(parts[1])) return null;
|
|
78
|
+
let ascii;
|
|
79
|
+
try {
|
|
80
|
+
ascii = new URL(`http://${parts[1]}`).hostname;
|
|
81
|
+
} catch {
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
return normalizeHost(ascii);
|
|
85
|
+
}
|
|
86
|
+
function checkCompanyWebsite(input, maxLength = DEFAULT_COMPANY_LIMITS.maxWebsiteLength) {
|
|
87
|
+
const typed = input.trim();
|
|
88
|
+
if (typed === "") return { ok: true, website: null, domain: null };
|
|
89
|
+
if (/\s/.test(typed)) return { ok: false, reason: "invalid" };
|
|
90
|
+
if (!/^https?:\/\//i.test(typed) && /^(?:[a-z][a-z0-9+.-]*:\/\/|(?:javascript|data|vbscript|mailto|file|ftp|tel|sms|blob|about):)/i.test(typed)) return { ok: false, reason: "invalid" };
|
|
91
|
+
if (!/^https?:\/\//i.test(typed) && /^[^/?#]*@/.test(typed)) return { ok: false, reason: "invalid" };
|
|
92
|
+
let url;
|
|
93
|
+
try {
|
|
94
|
+
url = new URL(/^https?:\/\//i.test(typed) ? typed : `https://${typed}`);
|
|
95
|
+
} catch {
|
|
96
|
+
return { ok: false, reason: "invalid" };
|
|
97
|
+
}
|
|
98
|
+
const host = url.hostname.replace(/\.$/, "");
|
|
99
|
+
const domain = host.endsWith(".") ? null : normalizeHost(host);
|
|
100
|
+
if (domain === null) return { ok: false, reason: "invalid" };
|
|
101
|
+
const website = `${url.protocol}//${host}${url.port ? `:${url.port}` : ""}${url.pathname === "/" ? "" : url.pathname}`;
|
|
102
|
+
if (website.length > maxLength) return { ok: false, reason: "too-long", length: website.length };
|
|
103
|
+
return { ok: true, website, domain };
|
|
104
|
+
}
|
|
105
|
+
function suggestCompanies(email, companies, exclude = []) {
|
|
106
|
+
const domain = domainOfEmail(email);
|
|
107
|
+
if (domain === null || isFreeMailDomain(domain)) return [];
|
|
108
|
+
const skip = new Set(exclude);
|
|
109
|
+
return companies.filter((c) => c.domain !== null && c.domain.trim().toLowerCase() === domain && !skip.has(c.id)).map((c) => c.id);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export {
|
|
113
|
+
DEFAULT_COMPANY_LIMITS,
|
|
114
|
+
FREE_MAIL_DOMAINS,
|
|
115
|
+
cleanCompanyName,
|
|
116
|
+
companyNameKey,
|
|
117
|
+
checkCompanyName,
|
|
118
|
+
checkCompanyRole,
|
|
119
|
+
isFreeMailDomain,
|
|
120
|
+
domainOfEmail,
|
|
121
|
+
checkCompanyWebsite,
|
|
122
|
+
suggestCompanies
|
|
123
|
+
};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
export { C as CompanyLimits, D as DEFAULT_COMPANY_LIMITS, F as FREE_MAIL_DOMAINS } from '../constants-DV-gn6u8.mjs';
|
|
2
|
+
|
|
3
|
+
/** Trims and collapses every run of whitespace (including tabs and no-break spaces) to one plain space. */
|
|
4
|
+
declare function cleanCompanyName(name: string): string;
|
|
5
|
+
/** The identity of a name inside one workspace: the cleaned name, lower-cased. Two names with the same key are the same company. */
|
|
6
|
+
declare function companyNameKey(name: string): string;
|
|
7
|
+
type CompanyNameCheck = {
|
|
8
|
+
ok: true;
|
|
9
|
+
name: string;
|
|
10
|
+
key: string;
|
|
11
|
+
} | {
|
|
12
|
+
ok: false;
|
|
13
|
+
reason: 'empty' | 'too-long';
|
|
14
|
+
length: number;
|
|
15
|
+
};
|
|
16
|
+
/** Cleans the name and checks its length (1 to `maxLength`, default 120, counted in UTF-16 code units like the stored value). */
|
|
17
|
+
declare function checkCompanyName(name: string, maxLength?: number): CompanyNameCheck;
|
|
18
|
+
type CompanyRoleCheck = {
|
|
19
|
+
ok: true;
|
|
20
|
+
role: string | null;
|
|
21
|
+
} | {
|
|
22
|
+
ok: false;
|
|
23
|
+
reason: 'too-long';
|
|
24
|
+
length: number;
|
|
25
|
+
};
|
|
26
|
+
/** A role is optional text: cleaned like a name, and an empty one means "no role" (null), never an empty string. */
|
|
27
|
+
declare function checkCompanyRole(role: string | null | undefined, maxLength?: number): CompanyRoleCheck;
|
|
28
|
+
|
|
29
|
+
declare function isFreeMailDomain(domain: string): boolean;
|
|
30
|
+
/** The domain of a plain address ("ann@taft.com" gives "taft.com"), or null when it is not one address with a usable domain. */
|
|
31
|
+
declare function domainOfEmail(email: string): string | null;
|
|
32
|
+
type CompanyWebsiteCheck = {
|
|
33
|
+
ok: true;
|
|
34
|
+
website: string;
|
|
35
|
+
domain: string;
|
|
36
|
+
} | {
|
|
37
|
+
ok: true;
|
|
38
|
+
website: null;
|
|
39
|
+
domain: null;
|
|
40
|
+
} | {
|
|
41
|
+
ok: false;
|
|
42
|
+
reason: 'invalid' | 'too-long';
|
|
43
|
+
length?: number;
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Normalises what a person typed into a website: empty means none. "taft.com", "www.Taft.com/about" and "https://taft.com/?x=1#top" are
|
|
47
|
+
* accepted ("https://" is added when there is no scheme); an address with spaces, another scheme, an email address, no dot in the host or an IP
|
|
48
|
+
* address is `invalid`; one longer than `maxLength` once normalised is `too-long`.
|
|
49
|
+
*/
|
|
50
|
+
declare function checkCompanyWebsite(input: string, maxLength?: number): CompanyWebsiteCheck;
|
|
51
|
+
/**
|
|
52
|
+
* The ids of the companies an email address suggests: those whose domain is exactly the address's domain. Never a free-mail domain, never a
|
|
53
|
+
* company the person already belongs to (`exclude`), in the order the companies were given.
|
|
54
|
+
*/
|
|
55
|
+
declare function suggestCompanies(email: string, companies: ReadonlyArray<{
|
|
56
|
+
id: string;
|
|
57
|
+
domain: string | null;
|
|
58
|
+
}>, exclude?: ReadonlyArray<string>): string[];
|
|
59
|
+
|
|
60
|
+
export { type CompanyNameCheck, type CompanyRoleCheck, type CompanyWebsiteCheck, checkCompanyName, checkCompanyRole, checkCompanyWebsite, cleanCompanyName, companyNameKey, domainOfEmail, isFreeMailDomain, suggestCompanies };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_COMPANY_LIMITS,
|
|
3
|
+
FREE_MAIL_DOMAINS,
|
|
4
|
+
checkCompanyName,
|
|
5
|
+
checkCompanyRole,
|
|
6
|
+
checkCompanyWebsite,
|
|
7
|
+
cleanCompanyName,
|
|
8
|
+
companyNameKey,
|
|
9
|
+
domainOfEmail,
|
|
10
|
+
isFreeMailDomain,
|
|
11
|
+
suggestCompanies
|
|
12
|
+
} from "../chunk-ZWID3JLL.mjs";
|
|
13
|
+
export {
|
|
14
|
+
DEFAULT_COMPANY_LIMITS,
|
|
15
|
+
FREE_MAIL_DOMAINS,
|
|
16
|
+
checkCompanyName,
|
|
17
|
+
checkCompanyRole,
|
|
18
|
+
checkCompanyWebsite,
|
|
19
|
+
cleanCompanyName,
|
|
20
|
+
companyNameKey,
|
|
21
|
+
domainOfEmail,
|
|
22
|
+
isFreeMailDomain,
|
|
23
|
+
suggestCompanies
|
|
24
|
+
};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { C as CompanyRecord, a as CompanyStore } from '../../types-CbfseUAS.mjs';
|
|
2
|
+
|
|
3
|
+
interface PrismaCompanyStoreConfig {
|
|
4
|
+
/** Called each time the store needs the client (never at import), so a test can swap in a client with a bigger pool. */
|
|
5
|
+
client: () => PrismaLikeClient;
|
|
6
|
+
/** The workspace (organization, account, tenant) this store is built for. Every query is scoped by it. */
|
|
7
|
+
workspaceId: string;
|
|
8
|
+
/** Prisma delegate of the company model, e.g. `company`. */
|
|
9
|
+
companyModel: string;
|
|
10
|
+
/** SQL table of the company model, e.g. `Company` (used in the row locks). */
|
|
11
|
+
companyTable: string;
|
|
12
|
+
/** Workspace column on the company model, e.g. `organizationId`. */
|
|
13
|
+
workspaceColumn: string;
|
|
14
|
+
/** Prisma delegate of the membership (join) model, e.g. `contactCompany`. */
|
|
15
|
+
memberModel: string;
|
|
16
|
+
/** SQL table of the membership model, e.g. `ContactCompany`. */
|
|
17
|
+
memberTable: string;
|
|
18
|
+
/** Prisma delegate of the model of the people who belong to companies, e.g. `contact`. */
|
|
19
|
+
personModel: string;
|
|
20
|
+
/** SQL table of the person model, e.g. `Contact` (used in the share lock on the person row). */
|
|
21
|
+
personTable: string;
|
|
22
|
+
/** The person model's workspace column. Defaults to the company's. */
|
|
23
|
+
personWorkspaceColumn?: string;
|
|
24
|
+
/** Column AND Prisma field on the membership model for the company id. Default `companyId`. */
|
|
25
|
+
companyIdColumn?: string;
|
|
26
|
+
/** Column AND Prisma field on the membership model for the person id. Default `personId`. */
|
|
27
|
+
personIdColumn?: string;
|
|
28
|
+
/** Column AND Prisma field on the membership model for the role (nullable text). Default `role`. */
|
|
29
|
+
roleColumn?: string;
|
|
30
|
+
/** Column AND Prisma field on the membership model for who added it. Default `addedBy`. */
|
|
31
|
+
addedByColumn?: string;
|
|
32
|
+
/** The advisory lock is on `prefix + workspaceId` (hashed by Postgres). Default `companies:`. Keep an old app's value so old and new servers serialise. */
|
|
33
|
+
lockKeyPrefix?: string;
|
|
34
|
+
/** How long a transaction waits for any one lock before it throws (Postgres lock_timeout). Default 5000. */
|
|
35
|
+
lockWaitMs?: number;
|
|
36
|
+
/** Interactive transaction limits. Defaults: maxWait 10000, timeout 15000. */
|
|
37
|
+
transaction?: {
|
|
38
|
+
maxWait?: number;
|
|
39
|
+
timeout?: number;
|
|
40
|
+
};
|
|
41
|
+
/** 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
|
+
onBeforeMemberWrite?: () => Promise<void>;
|
|
43
|
+
}
|
|
44
|
+
/** The part of a transaction client the store uses. A real Prisma transaction client satisfies it; model delegates are looked up by name. */
|
|
45
|
+
interface PrismaLikeTx {
|
|
46
|
+
$executeRawUnsafe(query: string, ...values: unknown[]): Promise<unknown>;
|
|
47
|
+
$queryRawUnsafe(query: string, ...values: unknown[]): Promise<unknown>;
|
|
48
|
+
}
|
|
49
|
+
interface PrismaLikeClient extends PrismaLikeTx {
|
|
50
|
+
$transaction<R>(fn: (tx: PrismaLikeTx) => Promise<R>, options?: {
|
|
51
|
+
maxWait?: number;
|
|
52
|
+
timeout?: number;
|
|
53
|
+
}): Promise<R>;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
declare function createPrismaCompanyStore<T extends CompanyRecord = CompanyRecord>(config: PrismaCompanyStoreConfig): CompanyStore<T>;
|
|
57
|
+
|
|
58
|
+
export { type PrismaCompanyStoreConfig, type PrismaLikeClient, type PrismaLikeTx, createPrismaCompanyStore };
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
// src/companies/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(`createPrismaCompanyStore: ${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/companies/prisma/context.ts
|
|
15
|
+
function createContext(config) {
|
|
16
|
+
if (typeof config.client !== "function") throw new Error("createPrismaCompanyStore: client must be a function that returns the Prisma client");
|
|
17
|
+
if (typeof config.workspaceId !== "string" || config.workspaceId === "") throw new Error("createPrismaCompanyStore: workspaceId must be a non-empty string");
|
|
18
|
+
const workspaceColumn = assertIdentifier(config.workspaceColumn, "workspaceColumn");
|
|
19
|
+
const companyModel = assertIdentifier(config.companyModel, "companyModel");
|
|
20
|
+
const companyTable = assertIdentifier(config.companyTable, "companyTable");
|
|
21
|
+
const memberModel = assertIdentifier(config.memberModel, "memberModel");
|
|
22
|
+
const memberTable = assertIdentifier(config.memberTable, "memberTable");
|
|
23
|
+
const personModel = assertIdentifier(config.personModel, "personModel");
|
|
24
|
+
const personTable = assertIdentifier(config.personTable, "personTable");
|
|
25
|
+
const personWorkspaceColumn = assertIdentifier(config.personWorkspaceColumn ?? workspaceColumn, "personWorkspaceColumn");
|
|
26
|
+
const companyIdColumn = assertIdentifier(config.companyIdColumn ?? "companyId", "companyIdColumn");
|
|
27
|
+
const personIdColumn = assertIdentifier(config.personIdColumn ?? "personId", "personIdColumn");
|
|
28
|
+
const roleColumn = assertIdentifier(config.roleColumn ?? "role", "roleColumn");
|
|
29
|
+
const addedByColumn = assertIdentifier(config.addedByColumn ?? "addedBy", "addedByColumn");
|
|
30
|
+
const lockKeyPrefix = config.lockKeyPrefix ?? "companies:";
|
|
31
|
+
const lockWaitMs = config.lockWaitMs ?? 5e3;
|
|
32
|
+
if (!Number.isInteger(lockWaitMs) || lockWaitMs <= 0) throw new Error("createPrismaCompanyStore: lockWaitMs must be a positive integer");
|
|
33
|
+
const lockKey = `${lockKeyPrefix}${config.workspaceId}`;
|
|
34
|
+
const txOptions = { maxWait: config.transaction?.maxWait ?? 1e4, timeout: config.transaction?.timeout ?? 15e3 };
|
|
35
|
+
const model = (client, name) => {
|
|
36
|
+
const found = client[name];
|
|
37
|
+
if (typeof found !== "object" || found === null) throw new Error(`createPrismaCompanyStore: the Prisma client has no model "${name}" (check the configuration)`);
|
|
38
|
+
return found;
|
|
39
|
+
};
|
|
40
|
+
return {
|
|
41
|
+
workspaceId: config.workspaceId,
|
|
42
|
+
workspaceColumn,
|
|
43
|
+
companyIdColumn,
|
|
44
|
+
personIdColumn,
|
|
45
|
+
roleColumn,
|
|
46
|
+
addedByColumn,
|
|
47
|
+
personWorkspaceColumn,
|
|
48
|
+
sql: { companyTable: quote(companyTable), workspaceColumn: quote(workspaceColumn), memberTable: quote(memberTable), personTable: quote(personTable), personWorkspaceColumn: quote(personWorkspaceColumn) },
|
|
49
|
+
txOptions,
|
|
50
|
+
beforeMemberWrite: config.onBeforeMemberWrite,
|
|
51
|
+
client: config.client,
|
|
52
|
+
model,
|
|
53
|
+
companies: (client) => model(client, companyModel),
|
|
54
|
+
members: (client) => model(client, memberModel),
|
|
55
|
+
people: (client) => model(client, personModel),
|
|
56
|
+
companyWhere: (extra = {}) => ({ ...extra, [workspaceColumn]: config.workspaceId }),
|
|
57
|
+
async limitLockWait(tx) {
|
|
58
|
+
await tx.$executeRawUnsafe(`SELECT set_config('lock_timeout', $1, true)`, `${lockWaitMs}ms`);
|
|
59
|
+
},
|
|
60
|
+
async lockWorkspace(tx) {
|
|
61
|
+
await tx.$executeRawUnsafe(`SELECT pg_advisory_xact_lock(hashtext($1))`, lockKey);
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// src/companies/prisma/errors.ts
|
|
67
|
+
function hasCode(error, code, depth) {
|
|
68
|
+
if (typeof error !== "object" || error === null || depth > 4) return false;
|
|
69
|
+
const fields = error;
|
|
70
|
+
if (fields.code === code) return true;
|
|
71
|
+
return ["cause", "meta", "originalError", "driverAdapterError"].some((key) => hasCode(fields[key], code, depth + 1));
|
|
72
|
+
}
|
|
73
|
+
var isUniqueViolation = (error) => hasCode(error, "P2002", 0);
|
|
74
|
+
var isForeignKeyViolation = (error) => hasCode(error, "P2003", 0);
|
|
75
|
+
|
|
76
|
+
// src/companies/prisma/reads.ts
|
|
77
|
+
var IDS_PER_QUERY = 1e4;
|
|
78
|
+
function chunksOf(items) {
|
|
79
|
+
const pieces = [];
|
|
80
|
+
for (let start = 0; start < items.length; start += IDS_PER_QUERY) pieces.push(items.slice(start, start + IDS_PER_QUERY));
|
|
81
|
+
return pieces;
|
|
82
|
+
}
|
|
83
|
+
function createCompanyReads(context) {
|
|
84
|
+
const { companyWhere } = context;
|
|
85
|
+
const db = () => context.client();
|
|
86
|
+
return {
|
|
87
|
+
async list() {
|
|
88
|
+
return await context.companies(db()).findMany({ where: companyWhere() });
|
|
89
|
+
},
|
|
90
|
+
async getMany(ids) {
|
|
91
|
+
const found = [];
|
|
92
|
+
for (const piece of chunksOf([...new Set(ids)])) found.push(...await context.companies(db()).findMany({ where: companyWhere({ id: { in: piece } }) }));
|
|
93
|
+
return found;
|
|
94
|
+
},
|
|
95
|
+
async findByKey(nameKey) {
|
|
96
|
+
return await context.companies(db()).findFirst({ where: companyWhere({ nameKey }) });
|
|
97
|
+
},
|
|
98
|
+
async get(id) {
|
|
99
|
+
return await context.companies(db()).findFirst({ where: companyWhere({ id }) });
|
|
100
|
+
},
|
|
101
|
+
async findByDomain(domain) {
|
|
102
|
+
if (domain === "") return [];
|
|
103
|
+
return await context.companies(db()).findMany({ where: companyWhere({ domain }) });
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// src/companies/prisma/members.ts
|
|
109
|
+
function createCompanyMembers(context, getMany) {
|
|
110
|
+
const db = () => context.client();
|
|
111
|
+
const { sql } = context;
|
|
112
|
+
const toMember = (row) => {
|
|
113
|
+
const fields = row;
|
|
114
|
+
return { companyId: fields[context.companyIdColumn], personId: fields[context.personIdColumn], role: fields[context.roleColumn] ?? null };
|
|
115
|
+
};
|
|
116
|
+
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;
|
|
120
|
+
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
|
+
return {
|
|
122
|
+
personExists: (personId) => personExists(db(), personId),
|
|
123
|
+
async addMember(companyId, personId, role, actorId, limits) {
|
|
124
|
+
if (!await companyExists(db(), companyId)) return { kind: "companyGone" };
|
|
125
|
+
if (!await personExists(db(), personId)) return { kind: "personGone" };
|
|
126
|
+
if (context.beforeMemberWrite) await context.beforeMemberWrite();
|
|
127
|
+
try {
|
|
128
|
+
return await db().$transaction(async (tx) => {
|
|
129
|
+
await context.limitLockWait(tx);
|
|
130
|
+
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);
|
|
132
|
+
if (person.length === 0) return { kind: "personGone" };
|
|
133
|
+
const members = context.members(tx);
|
|
134
|
+
const existing = await members.findFirst({ where: memberWhere(companyId, personId) });
|
|
135
|
+
if (existing) return { kind: "already", member: toMember(existing) };
|
|
136
|
+
if (await members.count({ where: { [context.companyIdColumn]: companyId } }) >= limits.maxMembers) return { kind: "memberLimit" };
|
|
137
|
+
const created = await members.create({ data: { ...memberWhere(companyId, personId), [context.roleColumn]: role, [context.addedByColumn]: actorId } });
|
|
138
|
+
return { kind: "added", member: toMember(created) };
|
|
139
|
+
}, context.txOptions);
|
|
140
|
+
} catch (error) {
|
|
141
|
+
if (isForeignKeyViolation(error)) return await companyExists(db(), companyId) ? { kind: "personGone" } : { kind: "companyGone" };
|
|
142
|
+
if (isUniqueViolation(error)) {
|
|
143
|
+
const existing = await context.members(db()).findFirst({ where: memberWhere(companyId, personId) });
|
|
144
|
+
if (existing) return { kind: "already", member: toMember(existing) };
|
|
145
|
+
}
|
|
146
|
+
throw error;
|
|
147
|
+
}
|
|
148
|
+
},
|
|
149
|
+
async setRole(companyId, personId, role) {
|
|
150
|
+
return db().$transaction(async (tx) => {
|
|
151
|
+
await context.limitLockWait(tx);
|
|
152
|
+
if (!await lockCompany(tx, companyId, "FOR KEY SHARE")) return { kind: "companyGone" };
|
|
153
|
+
if (!await lockMembership(tx, companyId, personId)) return { kind: "notMember" };
|
|
154
|
+
const members = context.members(tx);
|
|
155
|
+
const before = await members.findFirst({ where: memberWhere(companyId, personId) });
|
|
156
|
+
if (!before) return { kind: "notMember" };
|
|
157
|
+
await members.updateMany({ where: memberWhere(companyId, personId), data: { [context.roleColumn]: role } });
|
|
158
|
+
const after = await members.findFirst({ where: memberWhere(companyId, personId) });
|
|
159
|
+
return { kind: "updated", before: toMember(before), after: toMember(after) };
|
|
160
|
+
}, context.txOptions);
|
|
161
|
+
},
|
|
162
|
+
async removeMember(companyId, personId) {
|
|
163
|
+
return db().$transaction(async (tx) => {
|
|
164
|
+
await context.limitLockWait(tx);
|
|
165
|
+
if (!await lockCompany(tx, companyId, "FOR KEY SHARE")) return { kind: "companyGone" };
|
|
166
|
+
if (!await lockMembership(tx, companyId, personId)) return { kind: "notMember" };
|
|
167
|
+
const members = context.members(tx);
|
|
168
|
+
const member = await members.findFirst({ where: memberWhere(companyId, personId) });
|
|
169
|
+
if (!member) return { kind: "notMember" };
|
|
170
|
+
const { count } = await members.deleteMany({ where: memberWhere(companyId, personId) });
|
|
171
|
+
return count === 0 ? { kind: "notMember" } : { kind: "removed", member: toMember(member) };
|
|
172
|
+
}, context.txOptions);
|
|
173
|
+
},
|
|
174
|
+
async members(companyId) {
|
|
175
|
+
if (!await companyExists(db(), companyId)) return [];
|
|
176
|
+
return (await context.members(db()).findMany({ where: { [context.companyIdColumn]: companyId } })).map(toMember);
|
|
177
|
+
},
|
|
178
|
+
async companiesForPeople(personIds) {
|
|
179
|
+
const memberships = [];
|
|
180
|
+
for (const piece of chunksOf([...new Set(personIds)])) {
|
|
181
|
+
memberships.push(...(await context.members(db()).findMany({ where: { [context.personIdColumn]: { in: piece } } })).map(toMember));
|
|
182
|
+
}
|
|
183
|
+
const result = /* @__PURE__ */ new Map();
|
|
184
|
+
const companies = new Map((await getMany([...new Set(memberships.map((member) => member.companyId))])).map((company) => [company.id, company]));
|
|
185
|
+
for (const member of memberships) {
|
|
186
|
+
const company = companies.get(member.companyId);
|
|
187
|
+
if (!company) continue;
|
|
188
|
+
const list = result.get(member.personId) ?? [];
|
|
189
|
+
list.push({ company, role: member.role });
|
|
190
|
+
result.set(member.personId, list);
|
|
191
|
+
}
|
|
192
|
+
return result;
|
|
193
|
+
},
|
|
194
|
+
async memberCounts(ids) {
|
|
195
|
+
const companyIds = [];
|
|
196
|
+
const read = async (extra) => (await context.companies(db()).findMany({ where: context.companyWhere(extra), select: { id: true } })).map((row) => row.id);
|
|
197
|
+
if (ids === void 0) companyIds.push(...await read({}));
|
|
198
|
+
else for (const piece of chunksOf([...new Set(ids)])) companyIds.push(...await read({ id: { in: piece } }));
|
|
199
|
+
const counts = new Map(companyIds.map((id) => [id, 0]));
|
|
200
|
+
for (const piece of chunksOf(companyIds)) {
|
|
201
|
+
const grouped = await context.members(db()).groupBy({ by: [context.companyIdColumn], where: { [context.companyIdColumn]: { in: piece } }, _count: { _all: true } });
|
|
202
|
+
for (const row of grouped) counts.set(row[context.companyIdColumn], row._count._all);
|
|
203
|
+
}
|
|
204
|
+
return counts;
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// src/companies/prisma/writes.ts
|
|
210
|
+
function createCompanyWrites(context) {
|
|
211
|
+
const { companyWhere } = context;
|
|
212
|
+
const db = () => context.client();
|
|
213
|
+
return {
|
|
214
|
+
async create(input, limits) {
|
|
215
|
+
try {
|
|
216
|
+
return await db().$transaction(async (tx) => {
|
|
217
|
+
await context.limitLockWait(tx);
|
|
218
|
+
await context.lockWorkspace(tx);
|
|
219
|
+
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 } });
|
|
223
|
+
return { kind: "created", company };
|
|
224
|
+
}, context.txOptions);
|
|
225
|
+
} catch (error) {
|
|
226
|
+
if (isUniqueViolation(error)) return { kind: "duplicate" };
|
|
227
|
+
throw error;
|
|
228
|
+
}
|
|
229
|
+
},
|
|
230
|
+
async update(id, patch) {
|
|
231
|
+
try {
|
|
232
|
+
return await db().$transaction(async (tx) => {
|
|
233
|
+
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);
|
|
235
|
+
const companies = context.companies(tx);
|
|
236
|
+
const before = locked.length === 0 ? null : await companies.findFirst({ where: companyWhere({ id }) });
|
|
237
|
+
if (!before) return { kind: "notFound" };
|
|
238
|
+
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" };
|
|
240
|
+
const data = {};
|
|
241
|
+
if (patch.rename) Object.assign(data, { name: patch.rename.name, nameKey: patch.rename.nameKey });
|
|
242
|
+
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 }) });
|
|
245
|
+
return { kind: "updated", before, after };
|
|
246
|
+
}, context.txOptions);
|
|
247
|
+
} catch (error) {
|
|
248
|
+
if (isUniqueViolation(error)) return { kind: "duplicate" };
|
|
249
|
+
throw error;
|
|
250
|
+
}
|
|
251
|
+
},
|
|
252
|
+
async remove(id) {
|
|
253
|
+
return db().$transaction(async (tx) => {
|
|
254
|
+
await context.limitLockWait(tx);
|
|
255
|
+
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
|
+
if (locked.length === 0) return { kind: "notFound" };
|
|
257
|
+
const companies = context.companies(tx);
|
|
258
|
+
const company = await companies.findFirst({ where: companyWhere({ id }) });
|
|
259
|
+
if (!company) return { kind: "notFound" };
|
|
260
|
+
const memberCount = await context.members(tx).count({ where: { [context.companyIdColumn]: id } });
|
|
261
|
+
const { count } = await companies.deleteMany({ where: companyWhere({ id }) });
|
|
262
|
+
return count === 0 ? { kind: "notFound" } : { kind: "removed", company, memberCount };
|
|
263
|
+
}, context.txOptions);
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// src/companies/prisma/index.ts
|
|
269
|
+
function createPrismaCompanyStore(config) {
|
|
270
|
+
const context = createContext(config);
|
|
271
|
+
const reads = createCompanyReads(context);
|
|
272
|
+
return { ...reads, ...createCompanyWrites(context), ...createCompanyMembers(context, reads.getMany) };
|
|
273
|
+
}
|
|
274
|
+
export {
|
|
275
|
+
createPrismaCompanyStore
|
|
276
|
+
};
|