@12-apps/tenant 1.0.0 → 1.1.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/ADOPTING.md CHANGED
@@ -112,6 +112,73 @@ const port: TenantPort<Status, Tx> = {
112
112
  - **`bySlug` resolves the tenant's current slug only.** A former slug you keep
113
113
  for redirects is not answered here.
114
114
 
115
+ ### The tenant tree (opt-in)
116
+
117
+ A tenant may sit under another (ownership only, any depth: a company above its
118
+ units, a unit above its venues). **The tree is optional.** A host with no tree
119
+ passes no `tree` and gets no `tenant.tree` (`createApiTenant` leaves the key
120
+ out); a host written for a release before the tree boots unchanged, since none
121
+ of the tree's methods is on the tenant port. A host that wants it passes its
122
+ own port as `tree`, and then all four members are required and checked at
123
+ startup (`TenantConfigError`, key `tree.<method>`):
124
+
125
+ ```ts
126
+ const tree: TenantTreePort<Tx> = {
127
+ treeNode: (id, tx) => …, // on tx when given: { id, parentId, path } | null — one read
128
+ treeAncestors: (id, tx) => …, // on tx when given: the node and every node above it — one read
129
+ treeDescendants: (id, tx) => …, // on tx when given: the node and every node below it — one read
130
+ moveSubtree: (move, tx) => …, // a planned move ON tx — lock, then ONE rewrite; rows written
131
+ };
132
+ const tenant = createApiTenant({ ...config, port, tree });
133
+ ```
134
+
135
+ Store three columns on your tenant row: the parent's id (NULL for a standalone
136
+ tenant), the **materialized path** and, if you want one, your own unit code.
137
+ The package computes and validates every path; you store it and apply what it
138
+ plans.
139
+
140
+ - **The path** is `/<root id>/…/<own id>/`; a standalone tenant's is
141
+ `/<own id>/`, so backfilling an existing table makes every row a root.
142
+ Ids must not contain `/`.
143
+ - **`treeAncestors(id)`**: ONE read of the rows whose ids are the segments of
144
+ the tenant's own path (a primary-key read; nothing recurses).
145
+ - **`treeDescendants(id)`**: ONE read of the rows whose path starts with the
146
+ tenant's own, served by an index on the path. With a byte-ordered collation
147
+ (Postgres `COLLATE "C"`) the prefix is exactly the range
148
+ `path >= p AND path < p-minus-its-last-"/" || '0'`.
149
+ - **`moveSubtree(move, tx)`**, on the caller's transaction:
150
+ 1. **Lock** every row of the subtree AND the new parent `FOR UPDATE`, in ONE
151
+ global order that never changes (by id). Two crossing moves (A under B
152
+ while B goes under A) then wait on each other instead of deadlocking.
153
+ 2. **Rewrite** in ONE statement: replace the prefix `move.fromPath` with
154
+ `move.toPath` on every row under it and re-point the row `move.id` at
155
+ `move.parentId`, ONLY while that row's path is still `fromPath` and the
156
+ parent's is still `parentPath`. Answer the rows written; 0 tells the
157
+ package the tree moved under its plan, and it refuses the move by name
158
+ (`moved`).
159
+ - **A new unit reads its parent's path `FOR SHARE`** (an insert trigger, or
160
+ your writer). With the move's lock above, an insert under a moving tenant
161
+ either waits for the move and takes the moved path, or commits first and the
162
+ move's rewrite (a later statement) moves it too. Without both locks a unit
163
+ can keep a stale prefix, and a stale prefix names the wrong ancestors.
164
+ - **Hold the row to its path** in the database too: a path that names the row
165
+ once and last, and is `/<own id>/` exactly when there is no parent, so no
166
+ writer can store a cycle. Such a check does not hold the path's PREFIX to
167
+ the parent's path; only the port's writes keep that true, so write the tree
168
+ through them.
169
+
170
+ `tenant.tree` answers `parentOf`, `rootOf`, `ancestorsOf`, `descendantsOf` (one
171
+ port call each, at any depth; each takes your transaction optionally) and
172
+ `move(id, parentId, tx)`, which runs its reads and its write in your
173
+ transaction (required) and refuses a cycle (`TenantTreeError`, code `cycle`)
174
+ before anything is written.
175
+
176
+ A grant across a tree is your authorization's business, not the package's.
177
+ Keep it distinguishable from a grant on the parent tenant itself: a scope that
178
+ names "the tenants below X" must never be the same string as X's own. And
179
+ wherever you gather the holders of grants by scope, gather the WHOLE chain
180
+ above a tenant, not only its parent.
181
+
115
182
  ### The schema and the migration
116
183
 
117
184
  - Copy the partial into your schema folder with
package/README.md CHANGED
@@ -15,6 +15,12 @@ This first release ships the **contract** every later behaviour extends:
15
15
  `bySlug`, `byId(id, tx?)`, `setStatusIf(id, from, to, tx)`,
16
16
  `clearProfile(tx, id)`, `timeZone(id)`. Its writes run on the caller's
17
17
  transaction;
18
+ - the **tenant tree**, OPT-IN: a tenant under a parent, any depth, on a
19
+ materialized path the package computes and validates, through a `tree` port
20
+ of its own (`treeNode`, `treeAncestors`, `treeDescendants`,
21
+ `moveSubtree(move, tx)`); `parentOf`, `rootOf`, `ancestorsOf`, `descendantsOf`
22
+ (one port call each) and a subtree `move` that refuses a cycle. A host that
23
+ passes no `tree` gets no `tenant.tree`;
18
24
  - `createApiTenant` and `createWebTenant`, which validate all of it at startup
19
25
  and keep a deep-frozen copy of the data;
20
26
  - the package's own tables, `tenant_closings` and `tenant_data_exports`, as a
@@ -27,8 +33,8 @@ in later releases on top of the same config. How to adopt it: [ADOPTING.md](./AD
27
33
 
28
34
  | Import | What | Needs |
29
35
  |---|---|---|
30
- | `@12-apps/tenant` | config types, `TenantPort`, `TenantConfigError`, the validators | nothing |
31
- | `@12-apps/tenant/server` | `createApiTenant` | nothing |
36
+ | `@12-apps/tenant` | config types, `TenantPort`, `TenantConfigError`, the validators, the tree (`createTenantTree`, the path helpers, `TenantTreeError`) | nothing |
37
+ | `@12-apps/tenant/server` | `createApiTenant` (with `tenant.tree` when a `tree` port is given) | nothing |
32
38
  | `@12-apps/tenant/hono` | `mountTenant(app, tenant)` | `hono` |
33
39
  | `@12-apps/tenant/react` | `createWebTenant` | nothing yet |
34
40
  | `@12-apps/tenant/manifest` | the wiring manifest (`db`) | `@12-apps/wiring` (types) |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@12-apps/tenant",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "sideEffects": false,
package/src/index.ts CHANGED
@@ -20,6 +20,26 @@ export {
20
20
  type TenantRefusalCodes,
21
21
  type TenantStatusSet,
22
22
  } from './config';
23
- export { TENANT_PORT_METHODS, type TenantPort, type TenantRecord } from './port';
24
- export { TenantConfigError, validateCoreConfig, validatePort } from './validate';
23
+ export {
24
+ TENANT_PORT_METHODS,
25
+ TENANT_TREE_PORT_METHODS,
26
+ type TenantPort,
27
+ type TenantRecord,
28
+ type TenantTreeMove,
29
+ type TenantTreeNode,
30
+ } from './port';
31
+ export {
32
+ TenantTreeError,
33
+ childPath,
34
+ createTenantTree,
35
+ depthOf,
36
+ isWithin,
37
+ parsePath,
38
+ rootPath,
39
+ validateNode,
40
+ type TenantTree,
41
+ type TenantTreeErrorCode,
42
+ type TenantTreePort,
43
+ } from './tree';
44
+ export { TenantConfigError, validateCoreConfig, validatePort, validateTreePort } from './validate';
25
45
  export type { DeepReadonly, TenantReadings, TenantRefusalKind } from './core';
package/src/port.ts CHANGED
@@ -4,7 +4,8 @@
4
4
  * The tenant row, its slugs and its domains stay the host's. The package never
5
5
  * maps them (Prisma refuses two models on one table, and a shared partial has
6
6
  * no foreign key into a host table), so it asks the host through these five
7
- * functions instead. Every one is required.
7
+ * functions instead. Every one is required. (The tenant tree has a port of its
8
+ * own, `TenantTreePort`, optional as a whole.)
8
9
  *
9
10
  * TRANSACTIONS. Every lifecycle step changes the tenant row and the package's
10
11
  * own rows together: a close flips the status, recounts the blockers (one
@@ -25,6 +26,44 @@ export interface TenantRecord<S extends string = string> {
25
26
  status: S;
26
27
  }
27
28
 
29
+ /**
30
+ * One tenant's place in the tenant tree, as the host stores it.
31
+ *
32
+ * The tree is ownership only (a company above its units, a unit above its
33
+ * venues), of any depth. `path` is the materialized path the package computes
34
+ * (`/<root id>/…/<own id>/`), so no tree read recurses.
35
+ */
36
+ export interface TenantTreeNode {
37
+ /** The host's tenant id. */
38
+ id: string;
39
+ /** The tenant directly above, or null for a standalone tenant (a root). */
40
+ parentId: string | null;
41
+ /** `/<root id>/…/<own id>/`; a root's is `/<own id>/`. */
42
+ path: string;
43
+ }
44
+
45
+ /**
46
+ * A subtree move, planned and validated by the package. The host first locks
47
+ * the subtree and the new parent (ADOPTING.md, "The tenant tree (opt-in)"), then
48
+ * rewrites in ONE statement: every path starting with `fromPath` has that
49
+ * prefix replaced by `toPath`, and the row `id` is re-pointed at `parentId`.
50
+ */
51
+ export interface TenantTreeMove {
52
+ /** The tenant that moves, everything below it moving with it. */
53
+ id: string;
54
+ /** Its new parent, or null to make it a root. */
55
+ parentId: string | null;
56
+ /**
57
+ * The new parent's path as the package read it (null with no parent). The
58
+ * host applies the move only while the parent's path still is this.
59
+ */
60
+ parentPath: string | null;
61
+ /** The moving tenant's path before the move: the prefix replaced. */
62
+ fromPath: string;
63
+ /** Its path after the move: the replacement prefix. */
64
+ toPath: string;
65
+ }
66
+
28
67
  /**
29
68
  * `Tx` is the host's transaction client. The package never opens one itself:
30
69
  * it hands back whatever the host gave it, so the host's own writes and the
@@ -69,3 +108,44 @@ export const TENANT_PORT_METHODS = [
69
108
  'clearProfile',
70
109
  'timeZone',
71
110
  ] as const satisfies readonly (keyof TenantPort)[];
111
+
112
+ /**
113
+ * The tenant TREE's port: OPTIONAL as a whole, and every member required when
114
+ * it is given (`createApiTenant`'s `tree`). A host with no tree passes none and
115
+ * gets no `tenant.tree`; a host written against a release before the tree
116
+ * boots unchanged. Same transaction rule as the tenant port: the one write
117
+ * takes the caller's `tx`, required; the reads take it optionally.
118
+ */
119
+ export interface TenantTreePort<Tx = unknown> {
120
+ /**
121
+ * One tenant's node, ONE read. Null when none exists. Read inside
122
+ * `tx` when one is given, so a move's plan sees what its write will.
123
+ */
124
+ treeNode(id: string, tx?: Tx): Promise<TenantTreeNode | null>;
125
+ /**
126
+ * The tenant and every tenant above it, in ONE read (the ids are
127
+ * the segments of its own path). Any order; empty when the tenant is unknown.
128
+ */
129
+ treeAncestors(id: string, tx?: Tx): Promise<TenantTreeNode[]>;
130
+ /**
131
+ * The tenant and every tenant below it at any depth, in ONE
132
+ * indexed prefix read on the path. Any order; empty when the tenant is unknown.
133
+ */
134
+ treeDescendants(id: string, tx?: Tx): Promise<TenantTreeNode[]>;
135
+ /**
136
+ * Apply a planned move inside the caller's transaction (required: a write
137
+ * never runs outside it): lock the subtree and the new parent, then ONE
138
+ * rewrite statement (ADOPTING.md, "The tenant tree (opt-in)"). Answers the rows
139
+ * written. 0 means the tree changed since the plan (the subtree is no longer
140
+ * at `fromPath`, or the parent no longer at `parentPath`): nothing written.
141
+ */
142
+ moveSubtree(move: TenantTreeMove, tx: Tx): Promise<number>;
143
+ }
144
+
145
+ /** The tree port's members, in a fixed order: what startup validation checks when a tree is given. */
146
+ export const TENANT_TREE_PORT_METHODS = [
147
+ 'treeNode',
148
+ 'treeAncestors',
149
+ 'treeDescendants',
150
+ 'moveSubtree',
151
+ ] as const satisfies readonly (keyof TenantTreePort)[];
@@ -14,8 +14,9 @@
14
14
  */
15
15
  import type { TenantCoreConfig } from '../config';
16
16
  import { createReadings, frozenCopy, type DeepReadonly, type TenantReadings } from '../core';
17
- import type { TenantPort, TenantRecord } from '../port';
18
- import { validateCoreConfig, validatePort } from '../validate';
17
+ import type { TenantPort, TenantRecord, TenantTreePort } from '../port';
18
+ import { createTenantTree, type TenantTree } from '../tree';
19
+ import { validateCoreConfig, validatePort, validateTreePort } from '../validate';
19
20
 
20
21
  export { TenantConfigError } from '../validate';
21
22
 
@@ -27,11 +28,19 @@ export interface TenantRoute {
27
28
  handler(request: Request): Promise<Response>;
28
29
  }
29
30
 
30
- /** Everything `createApiTenant` needs. Nothing is optional. */
31
+ /**
32
+ * Everything `createApiTenant` needs. Nothing is optional but the tenant tree,
33
+ * an opt-in feature: give `tree` and every one of its members is required.
34
+ */
31
35
  export interface TenantServerConfig<S extends string = string, Tx = unknown>
32
36
  extends TenantCoreConfig<S> {
33
37
  /** The host's tenant row, reached only through this port. */
34
38
  port: TenantPort<S, Tx>;
39
+ /**
40
+ * The tenant tree's port (a tenant under a parent, any depth). Left out, the
41
+ * host has no tree and `tenant.tree` is absent.
42
+ */
43
+ tree?: TenantTreePort<Tx>;
35
44
  }
36
45
 
37
46
  export interface ApiTenant<S extends string = string, Tx = unknown> extends TenantReadings<S> {
@@ -39,6 +48,8 @@ export interface ApiTenant<S extends string = string, Tx = unknown> extends Tena
39
48
  config: DeepReadonly<TenantCoreConfig<S>>;
40
49
  /** The host's tenant port, as given. */
41
50
  port: TenantPort<S, Tx>;
51
+ /** The tenant tree, read and moved through `config.tree`; absent when none was given. */
52
+ tree?: TenantTree<Tx>;
42
53
  /** The package's routes, in mount order. None yet: the lifecycle slice adds them. */
43
54
  routes: readonly TenantRoute[];
44
55
  /** The tenant, read through the port, on `tx` when given. */
@@ -57,6 +68,8 @@ export function createApiTenant<S extends string, Tx = unknown>(
57
68
  ): ApiTenant<S, Tx> {
58
69
  validateCoreConfig(config);
59
70
  validatePort((config as { port?: unknown }).port);
71
+ const treePort = (config as { tree?: unknown }).tree;
72
+ if (treePort !== undefined) validateTreePort(treePort);
60
73
  const data = frozenCopy({ statuses: config.statuses, ids: config.ids, copy: config.copy });
61
74
  const known = new Set<string>(data.statuses.all);
62
75
  const { port } = config;
@@ -64,6 +77,7 @@ export function createApiTenant<S extends string, Tx = unknown>(
64
77
  ...createReadings(data),
65
78
  config: data,
66
79
  port,
80
+ ...(config.tree === undefined ? {} : { tree: createTenantTree(config.tree) }),
67
81
  routes: Object.freeze([]),
68
82
  byId: (id, tx) => port.byId(id, tx),
69
83
  setStatusIf: (id, from, to, tx) => {
@@ -0,0 +1,147 @@
1
+ /**
2
+ * The tenant tree: ownership of any depth (a company above its units, a unit
3
+ * above its venues), read and moved through the tenant port only. The package
4
+ * owns no tenant row: it computes and validates every path, refuses a cycle
5
+ * and plans a move; the host stores the paths and applies the plan.
6
+ *
7
+ * Every read is ONE port call at any depth (`parentOf`, `rootOf` read the
8
+ * tenant's own node; `ancestorsOf` and `descendantsOf` one indexed read each).
9
+ * A move is two node reads and ONE write that rewrites the whole subtree.
10
+ *
11
+ * Participation (a tenant selling inside another tenant's space) is not a
12
+ * parent: the tree is ownership only.
13
+ */
14
+ import type { TenantTreeMove, TenantTreeNode, TenantTreePort } from '../port';
15
+
16
+ export type { TenantTreePort } from '../port';
17
+ import {
18
+ TenantTreeError,
19
+ assertSegment,
20
+ depthOf,
21
+ isWithin,
22
+ movedPath,
23
+ validateNode,
24
+ } from './path';
25
+
26
+ export {
27
+ TenantTreeError,
28
+ childPath,
29
+ depthOf,
30
+ isWithin,
31
+ parsePath,
32
+ rootPath,
33
+ validateNode,
34
+ type TenantTreeErrorCode,
35
+ } from './path';
36
+
37
+
38
+ /**
39
+ * Every read takes the host's transaction optionally (to read what a write in
40
+ * it will see); the move takes it REQUIRED: the package never opens one, and
41
+ * never writes outside the caller's.
42
+ */
43
+ export interface TenantTree<Tx = unknown> {
44
+ /** The tenant directly above `id`, or null for a root. One port call. */
45
+ parentOf(id: string, tx?: Tx): Promise<string | null>;
46
+ /** The root of `id`'s tree (`id` itself for a root). One port call. */
47
+ rootOf(id: string, tx?: Tx): Promise<string>;
48
+ /** Every tenant above `id`, nearest first; empty for a root. One port call. */
49
+ ancestorsOf(id: string, tx?: Tx): Promise<TenantTreeNode[]>;
50
+ /** Every tenant below `id` at any depth, shallowest first; `id` excluded. One port call. */
51
+ descendantsOf(id: string, tx?: Tx): Promise<TenantTreeNode[]>;
52
+ /**
53
+ * Move `id`, with everything below it, under `parentId` (null: make it a
54
+ * root), inside the caller's transaction: the plan's two reads and the
55
+ * write all run in `tx`. Refuses a cycle before anything is written; answers
56
+ * the rows the host rewrote. Throws `moved` when the tree changed under the
57
+ * plan.
58
+ */
59
+ move(id: string, parentId: string | null, tx: Tx): Promise<number>;
60
+ }
61
+
62
+ async function nodeOf<Tx>(
63
+ port: TenantTreePort<Tx>,
64
+ id: string,
65
+ tx: Tx | undefined,
66
+ ): Promise<{ node: TenantTreeNode; ids: string[] }> {
67
+ assertSegment(id);
68
+ const node = await port.treeNode(id, tx);
69
+ if (node === null) throw new TenantTreeError('unknown-tenant', `no tenant "${id}"`);
70
+ return { node, ids: validateNode(node) };
71
+ }
72
+
73
+ /** Shallowest first, then by id, so equal depths answer in a stable order. */
74
+ function byDepth(a: TenantTreeNode, b: TenantTreeNode): number {
75
+ return depthOf(a.path) - depthOf(b.path) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
76
+ }
77
+
78
+ /** The read's nodes, each validated; refuses a read that lost its own tenant. */
79
+ function checked(id: string, nodes: readonly TenantTreeNode[]): TenantTreeNode[] {
80
+ nodes.forEach(validateNode);
81
+ if (!nodes.some((node) => node.id === id)) {
82
+ throw new TenantTreeError('unknown-tenant', `no tenant "${id}"`);
83
+ }
84
+ return [...nodes].sort(byDepth);
85
+ }
86
+
87
+ export function createTenantTree<Tx = unknown>(port: TenantTreePort<Tx>): TenantTree<Tx> {
88
+ return {
89
+ async parentOf(id, tx) {
90
+ return (await nodeOf(port, id, tx)).node.parentId;
91
+ },
92
+
93
+ async rootOf(id, tx) {
94
+ const { ids } = await nodeOf(port, id, tx);
95
+ return ids[0] as string;
96
+ },
97
+
98
+ async ancestorsOf(id, tx) {
99
+ assertSegment(id);
100
+ const nodes = checked(id, await port.treeAncestors(id, tx));
101
+ const self = nodes[nodes.length - 1] as TenantTreeNode;
102
+ // Exactly the ids the tenant's own path names above it, no more, no fewer.
103
+ const above = validateNode(self).slice(0, -1);
104
+ const ancestors = nodes.filter((node) => node.id !== id);
105
+ if (ancestors.length !== above.length || ancestors.some((node, index) => node.id !== above[index])) {
106
+ throw new TenantTreeError('corrupt-path', `the ancestors read for "${id}" disagree with "${self.path}"`);
107
+ }
108
+ return ancestors.reverse();
109
+ },
110
+
111
+ async descendantsOf(id, tx) {
112
+ assertSegment(id);
113
+ const nodes = checked(id, await port.treeDescendants(id, tx));
114
+ const self = nodes[0] as TenantTreeNode;
115
+ if (self.id !== id || nodes.some((node) => !isWithin(node.path, self.path))) {
116
+ throw new TenantTreeError('corrupt-path', `the descendants read for "${id}" left "${self.path}"`);
117
+ }
118
+ return nodes.slice(1);
119
+ },
120
+
121
+ async move(id, parentId, tx) {
122
+ const { node } = await nodeOf(port, id, tx);
123
+ let parentPath: string | null = null;
124
+ if (parentId !== null) {
125
+ if (parentId === id) throw new TenantTreeError('cycle', `"${id}" cannot be its own parent`);
126
+ const parent = (await nodeOf(port, parentId, tx)).node;
127
+ if (isWithin(parent.path, node.path)) {
128
+ throw new TenantTreeError('cycle', `"${id}" cannot move under "${parentId}", which sits below it`);
129
+ }
130
+ parentPath = parent.path;
131
+ }
132
+ const plan: TenantTreeMove = {
133
+ id,
134
+ parentId,
135
+ parentPath,
136
+ fromPath: node.path,
137
+ toPath: movedPath(id, parentPath),
138
+ };
139
+ if (plan.toPath === plan.fromPath) return 0; // already there
140
+ const written = await port.moveSubtree(plan, tx);
141
+ if (written === 0) {
142
+ throw new TenantTreeError('moved', `the tree changed while "${id}" was moving; nothing was written`);
143
+ }
144
+ return written;
145
+ },
146
+ };
147
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * The materialized path of the tenant tree: pure, no I/O.
3
+ *
4
+ * A path is `/` + each id from the root down to the tenant itself, each
5
+ * followed by `/`: a root's is `/<id>/`, a unit's `/<root>/<id>/`. Because it
6
+ * ends in `/`, "this tenant and everything below it" is exactly the paths that
7
+ * START with its path, which a host serves with one indexed prefix (or range)
8
+ * read; and every ancestor's id is one of its segments, which a host serves
9
+ * with one primary-key read. Nothing ever recurses.
10
+ */
11
+ import type { TenantTreeNode } from '../port';
12
+
13
+ /** Why a tree operation was refused. */
14
+ export type TenantTreeErrorCode =
15
+ /** An id is not a valid path segment (empty, or containing `/`). */
16
+ | 'invalid-id'
17
+ /** No tenant has the id. */
18
+ | 'unknown-tenant'
19
+ /** The host returned a node whose path does not agree with its own row. */
20
+ | 'corrupt-path'
21
+ /** The move would make a tenant its own ancestor. */
22
+ | 'cycle'
23
+ /** The tree changed between the plan and the write: nothing was written. */
24
+ | 'moved';
25
+
26
+ /** Thrown when a tree read or move is refused; `code` says why. */
27
+ export class TenantTreeError extends Error {
28
+ readonly code: TenantTreeErrorCode;
29
+
30
+ constructor(code: TenantTreeErrorCode, message: string) {
31
+ super(`@12-apps/tenant: ${message}`);
32
+ this.name = 'TenantTreeError';
33
+ this.code = code;
34
+ }
35
+ }
36
+
37
+ /** Refuse an id that cannot be a path segment. */
38
+ export function assertSegment(id: string): void {
39
+ if (typeof id !== 'string' || id.length === 0 || id.includes('/')) {
40
+ throw new TenantTreeError('invalid-id', `"${String(id)}" cannot be a tenant id in a tree path`);
41
+ }
42
+ }
43
+
44
+ /** The path of a root (a standalone tenant): `/<id>/`. */
45
+ export function rootPath(id: string): string {
46
+ assertSegment(id);
47
+ return `/${id}/`;
48
+ }
49
+
50
+ /** The path of `id` placed directly under a tenant whose path is `parentPath`. */
51
+ export function childPath(parentPath: string, id: string): string {
52
+ parsePath(parentPath);
53
+ assertSegment(id);
54
+ return `${parentPath}${id}/`;
55
+ }
56
+
57
+ /**
58
+ * A path's ids, root first. Refuses a malformed path, and one naming the same
59
+ * id twice (a cycle cannot be written down as a path).
60
+ */
61
+ export function parsePath(path: string): string[] {
62
+ if (typeof path !== 'string' || !/^\/(?:[^/]+\/)+$/u.test(path)) {
63
+ throw new TenantTreeError('corrupt-path', `"${String(path)}" is not a tree path`);
64
+ }
65
+ const ids = path.slice(1, -1).split('/');
66
+ if (new Set(ids).size !== ids.length) {
67
+ throw new TenantTreeError('corrupt-path', `"${path}" names a tenant twice`);
68
+ }
69
+ return ids;
70
+ }
71
+
72
+ /** How deep a path sits: 0 for a root. */
73
+ export function depthOf(path: string): number {
74
+ return parsePath(path).length - 1;
75
+ }
76
+
77
+ /** Whether `path` is `ancestorPath` itself or anywhere below it. */
78
+ export function isWithin(path: string, ancestorPath: string): boolean {
79
+ return path.startsWith(ancestorPath);
80
+ }
81
+
82
+ /**
83
+ * Hold a node the host returned to its own row: the path parses, ends in the
84
+ * node's own id, and its second-to-last segment is the node's parent (none
85
+ * for a root). Answers the path's ids, root first.
86
+ */
87
+ export function validateNode(node: TenantTreeNode): string[] {
88
+ const ids = parsePath(node.path);
89
+ const own = ids[ids.length - 1];
90
+ const parent = ids.length > 1 ? ids[ids.length - 2] : null;
91
+ if (own !== node.id || parent !== node.parentId) {
92
+ throw new TenantTreeError(
93
+ 'corrupt-path',
94
+ `tenant "${node.id}" (parent ${JSON.stringify(node.parentId)}) has the path "${node.path}"`,
95
+ );
96
+ }
97
+ return ids;
98
+ }
99
+
100
+ /** The new path prefix of a subtree that moves under `parentPath` (null: becomes a root). */
101
+ export function movedPath(id: string, parentPath: string | null): string {
102
+ return parentPath === null ? rootPath(id) : childPath(parentPath, id);
103
+ }
package/src/validate.ts CHANGED
@@ -11,7 +11,7 @@ import {
11
11
  type TenantCoreConfig,
12
12
  type TenantIds,
13
13
  } from './config';
14
- import { TENANT_PORT_METHODS, type TenantPort } from './port';
14
+ import { TENANT_PORT_METHODS, TENANT_TREE_PORT_METHODS, type TenantPort, type TenantTreePort } from './port';
15
15
 
16
16
  /** Thrown at startup when the config is missing a piece or carries a bad one. */
17
17
  export class TenantConfigError extends Error {
@@ -202,3 +202,22 @@ export function validatePort(value: unknown): asserts value is TenantPort {
202
202
  }
203
203
  }
204
204
  }
205
+
206
+ /**
207
+ * The tenant tree's port, when the host gives one: every member required. Left
208
+ * out (`undefined`), there is no tree and nothing to check; anything else that
209
+ * is not a port with all four members fails at startup, named.
210
+ */
211
+ export function validateTreePort(value: unknown): asserts value is TenantTreePort {
212
+ if (value === null || !isBag(value)) {
213
+ throw new TenantConfigError('tree', 'must be the tree port object, or be left out');
214
+ }
215
+ for (const method of TENANT_TREE_PORT_METHODS) {
216
+ if (value[method] === undefined || value[method] === null) {
217
+ throw new TenantConfigError(`tree.${method}`, 'is required and missing');
218
+ }
219
+ if (typeof value[method] !== 'function') {
220
+ throw new TenantConfigError(`tree.${method}`, 'must be a function');
221
+ }
222
+ }
223
+ }