@12-apps/tenant 0.0.0-stage → 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.
@@ -0,0 +1,94 @@
1
+ /**
2
+ * `@12-apps/tenant/server` — the backend factory.
3
+ *
4
+ * `createApiTenant` takes the WHOLE config: the status set, the ids, the copy
5
+ * packs and the tenant port, every one required. It validates them before it
6
+ * returns, so a host missing a piece fails when it boots, with the missing key
7
+ * named (`TenantConfigError`), instead of adopting somebody else's values.
8
+ *
9
+ * Framework-neutral, the report-builder doctrine: routes are plain
10
+ * descriptors and `@12-apps/tenant/hono` mounts them. This slice ships the
11
+ * shape, the validation, the readings and the transaction-bound status move;
12
+ * the lifecycle, the purge and the export add their routes and behaviour on
13
+ * top of the same config.
14
+ */
15
+ import type { TenantCoreConfig } from '../config';
16
+ import { createReadings, frozenCopy, type DeepReadonly, type TenantReadings } from '../core';
17
+ import type { TenantPort, TenantRecord, TenantTreePort } from '../port';
18
+ import { createTenantTree, type TenantTree } from '../tree';
19
+ import { validateCoreConfig, validatePort, validateTreePort } from '../validate';
20
+
21
+ export { TenantConfigError } from '../validate';
22
+
23
+ /** A framework-neutral route: the Hono adapter mounts each one as given. */
24
+ export interface TenantRoute {
25
+ method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
26
+ /** Relative to wherever the host mounts the package. */
27
+ path: string;
28
+ handler(request: Request): Promise<Response>;
29
+ }
30
+
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
+ */
35
+ export interface TenantServerConfig<S extends string = string, Tx = unknown>
36
+ extends TenantCoreConfig<S> {
37
+ /** The host's tenant row, reached only through this port. */
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>;
44
+ }
45
+
46
+ export interface ApiTenant<S extends string = string, Tx = unknown> extends TenantReadings<S> {
47
+ /** The validated config's data parts (statuses, ids, copy), deep-frozen copies. */
48
+ config: DeepReadonly<TenantCoreConfig<S>>;
49
+ /** The host's tenant port, as given. */
50
+ port: TenantPort<S, Tx>;
51
+ /** The tenant tree, read and moved through `config.tree`; absent when none was given. */
52
+ tree?: TenantTree<Tx>;
53
+ /** The package's routes, in mount order. None yet: the lifecycle slice adds them. */
54
+ routes: readonly TenantRoute[];
55
+ /** The tenant, read through the port, on `tx` when given. */
56
+ byId(id: string, tx?: Tx): Promise<TenantRecord<S> | null>;
57
+ /**
58
+ * Move the tenant's status from `from` to `to` on the CALLER's transaction:
59
+ * true when it moved. Both must be statuses of the host's set; the port's
60
+ * compare-and-set runs on `tx`, so a later refusal in the same transaction
61
+ * rolls the move back.
62
+ */
63
+ setStatusIf(id: string, from: S, to: S, tx: Tx): Promise<boolean>;
64
+ }
65
+
66
+ export function createApiTenant<S extends string, Tx = unknown>(
67
+ config: TenantServerConfig<S, Tx>,
68
+ ): ApiTenant<S, Tx> {
69
+ validateCoreConfig(config);
70
+ validatePort((config as { port?: unknown }).port);
71
+ const treePort = (config as { tree?: unknown }).tree;
72
+ if (treePort !== undefined) validateTreePort(treePort);
73
+ const data = frozenCopy({ statuses: config.statuses, ids: config.ids, copy: config.copy });
74
+ const known = new Set<string>(data.statuses.all);
75
+ const { port } = config;
76
+ return {
77
+ ...createReadings(data),
78
+ config: data,
79
+ port,
80
+ ...(config.tree === undefined ? {} : { tree: createTenantTree(config.tree) }),
81
+ routes: Object.freeze([]),
82
+ byId: (id, tx) => port.byId(id, tx),
83
+ setStatusIf: (id, from, to, tx) => {
84
+ for (const [key, status] of [['from', from], ['to', to]] as const) {
85
+ if (!known.has(status)) {
86
+ return Promise.reject(
87
+ new RangeError(`@12-apps/tenant: setStatusIf "${key}" is "${status}", which statuses.all does not list.`),
88
+ );
89
+ }
90
+ }
91
+ return port.setStatusIf(id, from, to, tx);
92
+ },
93
+ };
94
+ }
@@ -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
+ }
@@ -0,0 +1,223 @@
1
+ /**
2
+ * Startup validation: every factory runs these before it returns, so a host
3
+ * that forgot a piece of config fails when it boots, with the missing key
4
+ * named, rather than on the first request that needed it.
5
+ *
6
+ * The checks read the config as `unknown` on purpose: a host written in plain
7
+ * JavaScript, or one that casts, gets the same answer as a typed one.
8
+ */
9
+ import {
10
+ TENANT_COPY_SHAPE,
11
+ type TenantCoreConfig,
12
+ type TenantIds,
13
+ } from './config';
14
+ import { TENANT_PORT_METHODS, TENANT_TREE_PORT_METHODS, type TenantPort, type TenantTreePort } from './port';
15
+
16
+ /** Thrown at startup when the config is missing a piece or carries a bad one. */
17
+ export class TenantConfigError extends Error {
18
+ /** The dotted path of the offending key (`ids.refusals.gone`). */
19
+ readonly key: string;
20
+
21
+ constructor(key: string, problem: string) {
22
+ super(`@12-apps/tenant: config "${key}" ${problem}.`);
23
+ this.name = 'TenantConfigError';
24
+ this.key = key;
25
+ }
26
+ }
27
+
28
+ type Bag = Record<string, unknown>;
29
+
30
+ function isBag(value: unknown): value is Bag {
31
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
32
+ }
33
+
34
+ function requireBag(value: unknown, key: string): Bag {
35
+ if (value === undefined || value === null) {
36
+ throw new TenantConfigError(key, 'is required and missing');
37
+ }
38
+ if (!isBag(value)) throw new TenantConfigError(key, 'must be an object');
39
+ return value;
40
+ }
41
+
42
+ function requireString(value: unknown, key: string): string {
43
+ if (value === undefined || value === null) {
44
+ throw new TenantConfigError(key, 'is required and missing');
45
+ }
46
+ if (typeof value !== 'string' || value.trim() === '') {
47
+ throw new TenantConfigError(key, 'must be a non-empty string');
48
+ }
49
+ return value;
50
+ }
51
+
52
+ function requireDistinct(values: Record<string, string>, key: string): void {
53
+ const seen = new Map<string, string>();
54
+ for (const [name, value] of Object.entries(values)) {
55
+ const first = seen.get(value);
56
+ if (first !== undefined) {
57
+ throw new TenantConfigError(
58
+ `${key}.${name}`,
59
+ `repeats the value "${value}" already given to ${key}.${first}`,
60
+ );
61
+ }
62
+ seen.set(value, name);
63
+ }
64
+ }
65
+
66
+ /** A non-empty list of distinct non-empty strings, as a set. */
67
+ function requireStatusList(value: unknown, key: string): Set<string> {
68
+ if (value === undefined || value === null) {
69
+ throw new TenantConfigError(key, 'is required and missing');
70
+ }
71
+ if (!Array.isArray(value) || value.length === 0) {
72
+ throw new TenantConfigError(key, 'must be a non-empty array');
73
+ }
74
+ const seen = new Set<string>();
75
+ value.forEach((status, index) => {
76
+ const name = requireString(status, `${key}[${index}]`);
77
+ if (seen.has(name)) throw new TenantConfigError(`${key}[${index}]`, `repeats "${name}"`);
78
+ seen.add(name);
79
+ });
80
+ return seen;
81
+ }
82
+
83
+ function validateClosableFrom(value: unknown, known: Set<string>, named: Record<string, string>): void {
84
+ const closable = requireStatusList(value, 'statuses.closableFrom');
85
+ for (const name of closable) {
86
+ if (!known.has(name)) {
87
+ throw new TenantConfigError('statuses.closableFrom', `names "${name}", which statuses.all does not list`);
88
+ }
89
+ if (name === named.closing || name === named.closed) {
90
+ throw new TenantConfigError('statuses.closableFrom', `names "${name}", a status a close cannot start from`);
91
+ }
92
+ }
93
+ }
94
+
95
+ function validateStatuses(value: unknown): void {
96
+ const statuses = requireBag(value, 'statuses');
97
+ const known = requireStatusList(statuses.all, 'statuses.all');
98
+ const named: Record<string, string> = {};
99
+ for (const role of ['active', 'closing', 'closed'] as const) {
100
+ const name = requireString(statuses[role], `statuses.${role}`);
101
+ if (!known.has(name)) {
102
+ throw new TenantConfigError(`statuses.${role}`, `names "${name}", which statuses.all does not list`);
103
+ }
104
+ named[role] = name;
105
+ }
106
+ requireDistinct(named, 'statuses');
107
+ validateClosableFrom(statuses.closableFrom, known, named);
108
+ }
109
+
110
+ const ID_GROUPS = {
111
+ refusals: [
112
+ 'closing',
113
+ 'closed',
114
+ 'readOnly',
115
+ 'gone',
116
+ 'reasonTooShort',
117
+ 'nameMismatch',
118
+ 'alreadyClosing',
119
+ 'notActive',
120
+ 'closingBlocked',
121
+ 'purged',
122
+ 'notClosing',
123
+ 'exportNeedsPerson',
124
+ 'exportNotFound',
125
+ 'exportExpired',
126
+ ],
127
+ audit: [
128
+ 'closeScheduled',
129
+ 'closeReopened',
130
+ 'closePurged',
131
+ 'afterCloseFailed',
132
+ 'exportRequested',
133
+ 'exportDownloaded',
134
+ ],
135
+ notifications: ['closingScheduled', 'closingWeek', 'closingDay', 'reopened', 'exportReady'],
136
+ permissions: ['close'],
137
+ } as const satisfies { [G in keyof TenantIds]: readonly (keyof TenantIds[G])[] };
138
+
139
+ function validateIdGroup(value: unknown, group: string, names: readonly string[]): void {
140
+ const bag = requireBag(value, `ids.${group}`);
141
+ const values = Object.fromEntries(
142
+ names.map((name) => [name, requireString(bag[name], `ids.${group}.${name}`)]),
143
+ );
144
+ // Two acts sharing one id would be indistinguishable to whoever reads it.
145
+ requireDistinct(values, `ids.${group}`);
146
+ }
147
+
148
+ function validateIds(value: unknown): void {
149
+ const ids = requireBag(value, 'ids');
150
+ for (const [group, names] of Object.entries(ID_GROUPS)) validateIdGroup(ids[group], group, names);
151
+ }
152
+
153
+ function requireSentence(value: unknown, key: string): void {
154
+ if (value === undefined || value === null) {
155
+ throw new TenantConfigError(key, 'is required and missing');
156
+ }
157
+ if (typeof value !== 'function') {
158
+ throw new TenantConfigError(key, 'must be a function that writes the whole sentence');
159
+ }
160
+ }
161
+
162
+ function validatePack(value: unknown, tag: string): void {
163
+ const pack = requireBag(value, `copy.locales.${tag}`);
164
+ for (const [copyKey, kind] of Object.entries(TENANT_COPY_SHAPE)) {
165
+ const key = `copy.locales.${tag}.${copyKey}`;
166
+ if (kind === 'text') requireString(pack[copyKey], key);
167
+ else requireSentence(pack[copyKey], key);
168
+ }
169
+ }
170
+
171
+ function validateCopy(value: unknown): void {
172
+ const copy = requireBag(value, 'copy');
173
+ const locales = requireBag(copy.locales, 'copy.locales');
174
+ const tags = Object.keys(locales);
175
+ if (tags.length === 0) {
176
+ throw new TenantConfigError('copy.locales', 'must hold at least one locale pack');
177
+ }
178
+ for (const tag of tags) validatePack(locales[tag], tag);
179
+ const fallback = requireString(copy.defaultLocale, 'copy.defaultLocale');
180
+ if (!tags.includes(fallback)) {
181
+ throw new TenantConfigError('copy.defaultLocale', `names "${fallback}", which copy.locales does not hold`);
182
+ }
183
+ }
184
+
185
+ /** Validate what both halves share. Throws {@link TenantConfigError}. */
186
+ export function validateCoreConfig(config: unknown): asserts config is TenantCoreConfig {
187
+ const bag = requireBag(config, 'config');
188
+ validateStatuses(bag.statuses);
189
+ validateIds(bag.ids);
190
+ validateCopy(bag.copy);
191
+ }
192
+
193
+ /** Validate the tenant port: every member present and a function. */
194
+ export function validatePort(value: unknown): asserts value is TenantPort {
195
+ const port = requireBag(value, 'port');
196
+ for (const method of TENANT_PORT_METHODS) {
197
+ if (port[method] === undefined || port[method] === null) {
198
+ throw new TenantConfigError(`port.${method}`, 'is required and missing');
199
+ }
200
+ if (typeof port[method] !== 'function') {
201
+ throw new TenantConfigError(`port.${method}`, 'must be a function');
202
+ }
203
+ }
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
+ }