@mistriwork/mistri 1.0.0-rc.52 → 1.0.0-rc.53

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.
Files changed (42) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +1 -1
  3. package/dist/docs/status.md +3 -3
  4. package/dist/embed/react/headless.js +1 -1
  5. package/dist/embed/react/index.js +1 -1
  6. package/dist/server/app/appSearchRuntime.d.ts +9 -0
  7. package/dist/server/app/appSearchRuntime.js +21 -3
  8. package/dist/server/cli/apps.d.ts +2 -0
  9. package/dist/server/cli/apps.js +14 -0
  10. package/dist/server/cli/mistriMain.js +13 -1
  11. package/dist/server/cli/reindex.js +15 -2
  12. package/dist/server/stores/commandStores.d.ts +6 -1
  13. package/dist/server/stores/commandStores.js +2 -1
  14. package/dist/server/tenant/tenantAdministration.js +2 -1
  15. package/dist/server/tenant/tenantAuthenticatedHttp.js +3 -1
  16. package/dist/server/tenant/tenantBackstopOwner.d.ts +20 -0
  17. package/dist/server/tenant/tenantBackstopOwner.js +37 -0
  18. package/dist/server/tenant/tenantConnections.d.ts +23 -2
  19. package/dist/server/tenant/tenantConnections.js +39 -3
  20. package/dist/server/tenant/tenantEnrollment.d.ts +8 -0
  21. package/dist/server/tenant/tenantEnrollment.js +40 -4
  22. package/dist/server/tenant/tenantLive.d.ts +6 -0
  23. package/dist/server/tenant/tenantLive.js +18 -1
  24. package/dist/server/tenant/tenantLocalAccess.js +16 -2
  25. package/dist/server/tenant/tenantNames.d.ts +1 -1
  26. package/dist/server/tenant/tenantPostgresCatalog.d.ts +14 -0
  27. package/dist/server/tenant/tenantPostgresCatalog.js +45 -0
  28. package/dist/server/tenant/tenantReadSource.d.ts +4 -187
  29. package/dist/server/tenant/tenantReadSource.js +110 -693
  30. package/dist/server/tenant/tenantReadSourceShared.d.ts +213 -0
  31. package/dist/server/tenant/tenantReadSourceShared.js +176 -0
  32. package/dist/server/tenant/tenantReadSourceSqlite.d.ts +6 -0
  33. package/dist/server/tenant/tenantReadSourceSqlite.js +498 -0
  34. package/dist/server/tenant/tenantSearch.d.ts +2 -30
  35. package/dist/server/tenant/tenantSearch.js +17 -2
  36. package/dist/server/tenant/tenantStartup.js +13 -2
  37. package/dist/server/tenant/tenantSupportOperations.js +2 -1
  38. package/dist/server/tenant/tenantValidationRecord.js +2 -0
  39. package/dist/server/tenant/tenantWriteSource.d.ts +8 -1
  40. package/dist/server/tenant/tenantWriteSource.js +79 -14
  41. package/dist/ssr/render.js +1 -1
  42. package/package.json +4 -4
@@ -0,0 +1,213 @@
1
+ import { type SandboxRecord } from './tenantSandboxStore.js';
2
+ import { type ScopedReads, type WriteTransaction } from '@mistriwork/engine/adapters/adapter.js';
3
+ import { type RowScope } from '@mistriwork/engine/shared/rowScope.js';
4
+ import { type TenantMembershipEvidence, type TenantMembershipLookup, type TenantMembershipRecord } from './tenantMembership.js';
5
+ import { type TenantOwnershipSnapshot } from './tenantOwnership.js';
6
+ import type { PlatformMembershipEvidence, PlatformMembershipLookup, PlatformMembershipRecord } from './tenantPlatform.js';
7
+ import { type TenantServiceEvidence } from './tenantServiceModel.js';
8
+ import { type TenantPublicEvidence, type TenantPublicLookup, type TenantPublicResolution } from './tenantPublicRead.js';
9
+ import type { SupportMembershipEvidence } from './tenantSupportLease.js';
10
+ import { type TenantMembershipListLookup } from './tenantStore.js';
11
+ import { type TenantAddresses, type TenantAddressesLookup, type TenantProfileLookup, type ActiveTenant, type ActiveTenantsQuery, type TenantIntakeEvidence, type TenantIntakeLookup, type TenantIntakeTenantLookup, type TenantIntakeResolution } from './tenantIntakeModel.js';
12
+ import type { TenantValue } from '@mistriwork/engine/shared/queryOperands.js';
13
+ import { type TenantLinkEvidence, type TenantLinkLookup, type TenantLinkResolution } from './tenantLinkModel.js';
14
+ import { type DueTimer, type DueTimersQuery } from './tenantDueTimers.js';
15
+ import { type TenantNamePlan } from './tenantNames.js';
16
+ import { type RecordActivityQuery, type RecordHistoryQuery, type StoredRecordChange } from '../../adapters/history/recordHistory.js';
17
+ import { type InboxQuery, type StoredNotice } from '../../adapters/inbox/inbox.js';
18
+ import { type BrandingLogoQuery, type BrandingQuery, type StoredBranding, type StoredBrandingLogo } from '../../adapters/branding/branding.js';
19
+ /** One person's email switch in one inbox: the same names an inbox read takes. */
20
+ export interface EmailSwitchQuery {
21
+ readonly app: string;
22
+ readonly recipient: string;
23
+ }
24
+ export declare function assertEmailSwitchQuery(query: EmailSwitchQuery): void;
25
+ /** Private pinned source, not a public credential or session/deployment issuer. */
26
+ /** A discovery's tenants, as a sandbox lookup takes them: tenant ids, at most a discovery's worth. */
27
+ export declare function sandboxLookup(tenants: unknown): readonly string[];
28
+ export interface TenantReadSource {
29
+ readonly ownership: TenantOwnershipSnapshot;
30
+ readMembership(lookup: TenantMembershipLookup): Promise<TenantMembershipRecord | null>;
31
+ readMemberships(lookup: TenantMembershipListLookup): Promise<readonly TenantMembershipRecord[]>;
32
+ assertCurrent(evidence: TenantMembershipEvidence): Promise<void>;
33
+ scopeReads(evidence: TenantMembershipEvidence, rows: RowScope): Promise<ScopedReads>;
34
+ /** The reader `scopeReads` binds, composed by the same rule, without the
35
+ * snapshot `scopeReads` checks the membership in first. Nothing is read
36
+ * until an operation runs, and every operation revalidates the evidence in
37
+ * its own snapshot before its SQL, so no row is read on evidence that
38
+ * snapshot did not find current. For an owner that also revalidates before
39
+ * it releases anything (tenantReadRuntime.ts). */
40
+ bindReads(evidence: TenantMembershipEvidence, rows: RowScope): Promise<ScopedReads>;
41
+ /** Several reads in one snapshot: the evidence revalidated once at its start,
42
+ * then every operation `work` asks for on that same snapshot, one after
43
+ * another, and none once it has returned. The snapshot is the fence each of
44
+ * `bindReads`' operations has, shared: what they read is one state, and it is
45
+ * the state the membership was found current in. For an answer that is only
46
+ * advice — which commands a record offers — and that its command asks again
47
+ * when it runs (tenantCommandAvailability.ts). */
48
+ withReads<T>(evidence: TenantMembershipEvidence, rows: RowScope, work: (reads: ScopedReads) => T | Promise<T>): Promise<T>;
49
+ /** `work`, with every operation of `bindReads`' readers for this evidence that it asks, while it runs, on one
50
+ * snapshot: opened at the first of them, the evidence revalidated in it once, held until `work` has returned and
51
+ * every read begun on it has settled, then ended. A composed record page, a page's boot, a post-write refresh asked
52
+ * many reads of one context at once, and each took a snapshot of its own — its BEGIN, its LOCK and its membership,
53
+ * its COMMIT, and a reader of the pool beside the others (tenantReadRuntime.ts `together`). What they read is then
54
+ * one state, the one the membership was found current in, as `withReads`' is. A read that wants a replica, and any
55
+ * asked once `work` has returned, takes its own snapshot as before. Where reads are not pooled (SQLite), `work`. */
56
+ together<T>(evidence: TenantMembershipEvidence, work: () => Promise<T>): Promise<T>;
57
+ /** `together`, and where its snapshot was opened and the catalog's attestation stands, the release fence in the
58
+ * message that ends it (PostgresReadSnapshot.finish): once `work` has returned and every read on the snapshot has
59
+ * settled, its COMMIT and this evidence's membership in a fresh snapshot of its own, one round trip where the
60
+ * COMMIT and assertCurrent's own snapshot were three. A membership that no longer holds refuses. `fenced` says
61
+ * whether it rode; where it did not — nothing was read, the attestation was due, `work` failed, SQLite — the
62
+ * caller fences as before. */
63
+ togetherFenced<T>(evidence: TenantMembershipEvidence, work: () => Promise<T>): Promise<{
64
+ value: T;
65
+ fenced: boolean;
66
+ }>;
67
+ /** The platform realm's twins: its membership, its revalidation, and reads
68
+ * under the platform scope (across tenants, unnamed tables denied). */
69
+ readPlatformMembership(lookup: PlatformMembershipLookup): Promise<PlatformMembershipRecord | null>;
70
+ assertPlatformCurrent(evidence: PlatformMembershipEvidence): Promise<void>;
71
+ scopePlatformReads(evidence: PlatformMembershipEvidence, rows: RowScope): Promise<ScopedReads>;
72
+ /** `scopePlatformReads` without its snapshot, as `bindReads` is `scopeReads`
73
+ * without one: every operation revalidates the platform membership in its
74
+ * own snapshot before its SQL, for an owner that fences again before it
75
+ * releases anything (tenantPlatformReadRuntime.ts). */
76
+ bindPlatformReads(evidence: PlatformMembershipEvidence, rows: RowScope): Promise<ScopedReads>;
77
+ /** `withReads` for the platform realm, under the platform scope. */
78
+ withPlatformReads<T>(evidence: PlatformMembershipEvidence, rows: RowScope, work: (reads: ScopedReads) => T | Promise<T>): Promise<T>;
79
+ /** A support session's twins ("enter as dealer"): its revalidation, and reads
80
+ * under the dealer's own scope. The fence is the support row itself, with its
81
+ * parent platform membership, `@platform` and the dealer — never a member
82
+ * membership, which an operator inside a dealer does not have. The scope is
83
+ * the dealer's, composed by the same rule a member's is, so a session can
84
+ * never read more than that one rule allows. */
85
+ assertSupportCurrent(evidence: SupportMembershipEvidence): Promise<void>;
86
+ scopeSupportReads(evidence: SupportMembershipEvidence, rows: RowScope): Promise<ScopedReads>;
87
+ /** Public intake's resolution, in one snapshot: the active tenant whose
88
+ * profile row alone holds the address, else the platform when it is active.
89
+ * Reads the profile by the policy's column only; admits nobody. */
90
+ resolveIntake(lookup: TenantIntakeLookup): Promise<TenantIntakeResolution>;
91
+ /** A token's public verb's placement, in one snapshot: the token's own
92
+ * tenant when it and the platform are both active, else refused — never
93
+ * triage, and never another tenant, whatever the request says. */
94
+ resolveIntakeByTenant(lookup: TenantIntakeTenantLookup): Promise<TenantIntakeResolution>;
95
+ /** A visitor's placement, in one snapshot: the active tenant whose profile
96
+ * row alone holds the address (or the mapped host's tenant, when active),
97
+ * with `@platform` active too; else null, whatever the reason, so no
98
+ * address is answered differently from another. Admits nobody. */
99
+ resolvePublic(lookup: TenantPublicLookup): Promise<TenantPublicResolution | null>;
100
+ /** A visitor's placement re-resolved in a snapshot of its own: the release fence. */
101
+ assertPublicCurrent(evidence: TenantPublicEvidence): Promise<void>;
102
+ /** Reads under a visitor's scope (tenantPublicRead.ts composePublicReadScope),
103
+ * as `bindReads` is a member's: every operation re-resolves the address in
104
+ * its own snapshot and requires the same tenant at the same versions before
105
+ * its SQL, so a rotated address or a suspended tenant reads nothing more. */
106
+ bindPublicReads(evidence: TenantPublicEvidence, rows: RowScope): Promise<ScopedReads>;
107
+ /** Reads for a public command's lookup in a tenant's intake (tenantIntake.ts): the submission read as the
108
+ * visitor it is (tenantPublicRead.ts intakeVisitor), under the same scope and the same fence as
109
+ * `bindPublicReads`. Triage is refused: it lands in no tenant, so no tenant's rows are its to look up. */
110
+ bindIntakeReads(evidence: TenantIntakeEvidence, rows: RowScope): Promise<ScopedReads>;
111
+ /** Reads under a tenant service's scope (tenantServiceModel.ts composeServiceScope), as `bindReads` is a
112
+ * member's: the source recomposes the scope from the evidence (never a caller's predicate), and every
113
+ * operation re-reads the service anchors in its own snapshot and requires the same tenant and platform at
114
+ * the same versions, inside the attempt's window. A platform place is refused: it runs outside any tenant. */
115
+ bindServiceReads(evidence: TenantServiceEvidence, rows: RowScope): Promise<ScopedReads>;
116
+ /** A capability link's placement, in one snapshot: the live link by this App and its id alone — the one read a
117
+ * tenant App's shared door makes before it knows the tenant — with its tenant and `@platform` each active; else
118
+ * null, whatever the reason. Admits nobody: the door checks the token or session against the tenant it names. */
119
+ resolveLink(lookup: TenantLinkLookup): Promise<TenantLinkResolution | null>;
120
+ /** Reads under a link's scope (tenantLinkModel.ts composeLinkScope): its one record within its tenant. Every
121
+ * operation re-reads the anchors and the link row in its own snapshot and requires the same tenant at the same
122
+ * versions, inside the request's window, with the link still live: a revoke or a suspension reads nothing more. */
123
+ bindLinkReads(evidence: TenantLinkEvidence, rows: RowScope): Promise<ScopedReads>;
124
+ /** What these tenants are called: each one's profile row said by the App's
125
+ * template for that resource (tenantNames.ts), for the ids a caller already
126
+ * holds. Reads the profile's key and the name's columns only; admits nobody. */
127
+ readTenantNames(lookup: TenantNamesLookup): Promise<Readonly<Record<string, string>>>;
128
+ /** A tenant's own intake and public addresses, by the policy's columns, in
129
+ * one snapshot: each only when its profile row holds one of an
130
+ * address's shape that resolves back to this tenant alone. For the tenant's
131
+ * own lease to show; admits nobody. */
132
+ readTenantAddresses(lookup: TenantAddressesLookup): Promise<TenantAddresses>;
133
+ /** The columns of a tenant's profile row its members read (`auth.tenancy.shared`), by column, once per request:
134
+ * the platform's own read of the row (as the names and addresses are), no App resource read and no grant. Those
135
+ * columns and nothing else of the row; a missing row reads as every column null. Admits nobody. */
136
+ readTenantProfile(lookup: TenantProfileLookup): Promise<Readonly<Record<string, TenantValue>>>;
137
+ /** A job attempt's anchors, in one snapshot: the named tenant's row and
138
+ * `@platform`, each its version while active, else null. With no tenant
139
+ * (the platform's own time job), `@platform` alone. Admits nobody. */
140
+ readServiceAnchors(tenantId: string | null): Promise<Readonly<{
141
+ tenantVersion: string | null;
142
+ platformVersion: string | null;
143
+ }>>;
144
+ /** The tenants active now, by id: whom a job at times per tenant runs for.
145
+ * Given `zone`, a shared profile column, each also carries that column off
146
+ * its row (null where it has none): the zone its slots keep. Each attempt is
147
+ * admitted again on its own tenant's row. Admits nobody. */
148
+ readActiveTenants(options?: ActiveTenantsQuery): Promise<readonly ActiveTenant[]>;
149
+ /** A machine timer's due records across the active tenants, a page at a
150
+ * time, each with the tenant its owner column names, read off the row here
151
+ * (tenantDueTimers.ts). A plan, as readActiveTenants is: each run is
152
+ * admitted again on its own tenant's row. Admits nobody. */
153
+ readDueTimers(query: DueTimersQuery): Promise<readonly DueTimer[]>;
154
+ /** The sandboxes whose dev clock reads ahead (tenantSandboxClock.ts), none where the store was never
155
+ * provisioned: which tenants' timers the sweep also reads on their own clock. A live tenant has no row
156
+ * there, so none is ever among them. Admits nobody. */
157
+ readSandboxClocks(): Promise<readonly SandboxRecord[]>;
158
+ /** Which of these tenants are sandboxes, for discovery to mark them to their members: none where the
159
+ * store was never provisioned. Admits nobody. */
160
+ readSandboxes(tenants: readonly string[]): Promise<ReadonlySet<string>>;
161
+ /** One record's stored history, by its store key — a tenant-owned record's
162
+ * carries its owner (adapters/history/recordHistory.ts). Admits nobody: the
163
+ * caller has read the record in the reader's own context first. */
164
+ readRecordHistory(query: RecordHistoryQuery): Promise<StoredRecordChange[]>;
165
+ /** A dashboard feed's stored rows (recordActivity.ts). Admits nobody: the
166
+ * caller names the context's own tenant in `owners`, or none for the
167
+ * platform realm, and reads each record the rows name in that context. */
168
+ readRecordActivity(query: RecordActivityQuery): Promise<StoredRecordChange[]>;
169
+ /** One person's notices in one inbox (tenantInbox.ts). Admits nobody: the caller names the lease's own inbox. */
170
+ readInbox(query: InboxQuery): Promise<StoredNotice[]>;
171
+ /** Whether one person asked an inbox for no email: the outbox's switch, read on the reader (inboxMail.ts). */
172
+ readEmailOff(query: EmailSwitchQuery): Promise<boolean>;
173
+ /** One tenant's saved branding in one App, or null (adapters/branding). */
174
+ readBranding(query: BrandingQuery): Promise<StoredBranding | null>;
175
+ /** One logo of an App by the hash of its bytes. */
176
+ readBrandingLogo(query: BrandingLogoQuery): Promise<StoredBrandingLogo | null>;
177
+ close(): Promise<void>;
178
+ }
179
+ /** The tenant an address names, when that tenant is active, else the platform.
180
+ * The platform's own row first: while it is not active nothing is taken,
181
+ * whatever the address, so no address is answered differently from another. */
182
+ export declare function intakeResolution(tenantId: string | undefined, anchor: (id: string) => string | null): TenantIntakeResolution;
183
+ /** The token's tenant when it and the platform are both active; refused otherwise, as no token is triaged. */
184
+ export declare function intakeResolutionByTenant(tenantId: string, anchor: (id: string) => string | null): TenantIntakeResolution;
185
+ /** The profile's record-name template, as the App's catalog serves it, and the tenants to name. */
186
+ export interface TenantNamesLookup {
187
+ readonly template: string | undefined;
188
+ readonly tenants: readonly string[];
189
+ }
190
+ /** The lookup's plan and its ids, or undefined when there is nothing to read. */
191
+ export declare function namesLookup(owned: TenantOwnershipSnapshot, lookup: TenantNamesLookup): {
192
+ plan: TenantNamePlan;
193
+ tenants: string[];
194
+ } | undefined;
195
+ export declare const sources: WeakSet<TenantReadSource>;
196
+ /** Only frozen factory objects can supply source authority. WeakSet lookup does
197
+ * not inspect properties, so lookalikes, getters and proxies never execute. */
198
+ export declare function captureTenantReadSource(input: TenantReadSource): TenantReadSource;
199
+ /** A batch's reads in the shape a command's records take, for the one caller
200
+ * that asks a command's questions without its transaction (availability): it
201
+ * reads, and every way of writing refuses. */
202
+ export declare function advisoryRecords(reads: ScopedReads): WriteTransaction;
203
+ export declare const refusedBefore: (error: unknown) => Promise<never>;
204
+ /** The reader a batch is handed (`withReads`): each operation's arguments
205
+ * captured, run on the batch's snapshot as it is asked, and refused once the
206
+ * batch has returned. Asked together, they leave together: the PostgreSQL
207
+ * reader pipelines, so the `when` of every command a record offers is one
208
+ * round trip, where one after another each was its own (SQLite runs them in
209
+ * turn on its one handle either way). The first failure is every later
210
+ * operation's, as one transaction's is. A database failure is mapped where
211
+ * it happens, so what `work` itself throws stays its own; `own` hears which
212
+ * that was. */
213
+ export declare function readBatch<T>(bound: ScopedReads, active: () => void, work: (reads: ScopedReads) => T | Promise<T>, own: (error: unknown) => void): Promise<T>;
@@ -0,0 +1,176 @@
1
+ // What a tenant read source is, whichever dialect serves it: the interface, the lookups both sources answer the same
2
+ // way (names, intake resolution, sandbox rows, email switch), the refusal checks run before a batch, and the probe that
3
+ // captures a source for the admission checks. The PostgreSQL source (tenantReadSource.ts) and the SQLite one
4
+ // (tenantReadSourceSqlite.ts) are built on it.
5
+ import {} from './tenantSandboxStore.js';
6
+ import { Refusal } from '@mistriwork/engine/adapters/adapter.js';
7
+ import {} from '@mistriwork/engine/shared/rowScope.js';
8
+ import { captureTenantData, denyTenant, denyTenantFor, recordRefusalCause, TenantContextError, tenantRecord, } from '@mistriwork/engine/server/evidence.js';
9
+ import { parseTenantSelector, } from './tenantMembership.js';
10
+ import {} from './tenantOwnership.js';
11
+ import {} from './tenantServiceModel.js';
12
+ import {} from './tenantPublicRead.js';
13
+ import { provideTenantSourceProbe } from './tenantSourceIdentity.js';
14
+ import {} from './tenantStore.js';
15
+ import {} from './tenantIntakeModel.js';
16
+ import { PLATFORM_TENANT_ID } from './tenantPlatform.js';
17
+ import {} from './tenantLinkModel.js';
18
+ import {} from './tenantDueTimers.js';
19
+ import { TENANT_NAMES_MAX, tenantNamePlan } from './tenantNames.js';
20
+ import {} from '../../adapters/history/recordHistory.js';
21
+ import {} from '../../adapters/inbox/inbox.js';
22
+ import {} from '../../adapters/branding/branding.js';
23
+ export function assertEmailSwitchQuery(query) {
24
+ tenantRecord(query, ['app', 'recipient']);
25
+ if (typeof query.app !== 'string' || !query.app || typeof query.recipient !== 'string' || !query.recipient)
26
+ throw new Refusal('Invalid notification read.');
27
+ }
28
+ /** Private pinned source, not a public credential or session/deployment issuer. */
29
+ /** A discovery's tenants, as a sandbox lookup takes them: tenant ids, at most a discovery's worth. */
30
+ export function sandboxLookup(tenants) {
31
+ if (!Array.isArray(tenants) || tenants.length > 256)
32
+ return denyTenant();
33
+ return Object.freeze(tenants.map((id) => parseTenantSelector([id])));
34
+ }
35
+ /** The tenant an address names, when that tenant is active, else the platform.
36
+ * The platform's own row first: while it is not active nothing is taken,
37
+ * whatever the address, so no address is answered differently from another. */
38
+ export function intakeResolution(tenantId, anchor) {
39
+ const platform = anchor(PLATFORM_TENANT_ID);
40
+ if (platform === null)
41
+ return denyTenant();
42
+ const version = tenantId === undefined ? null : anchor(tenantId);
43
+ return tenantId !== undefined && version !== null
44
+ ? { tenantId, tenantVersion: version, platformVersion: platform }
45
+ : { tenantId: PLATFORM_TENANT_ID, tenantVersion: platform, platformVersion: platform };
46
+ }
47
+ /** The token's tenant when it and the platform are both active; refused otherwise, as no token is triaged. */
48
+ export function intakeResolutionByTenant(tenantId, anchor) {
49
+ const platform = anchor(PLATFORM_TENANT_ID);
50
+ const version = platform === null ? null : anchor(tenantId);
51
+ if (platform === null || version === null)
52
+ return denyTenant();
53
+ return { tenantId, tenantVersion: version, platformVersion: platform };
54
+ }
55
+ /** The lookup's plan and its ids, or undefined when there is nothing to read. */
56
+ export function namesLookup(owned, lookup) {
57
+ const value = captureTenantData(lookup);
58
+ if (!Array.isArray(value.tenants) ||
59
+ value.tenants.length > TENANT_NAMES_MAX ||
60
+ (value.template !== undefined && typeof value.template !== 'string'))
61
+ return denyTenant();
62
+ const tenants = [...new Set(value.tenants.filter((id) => id !== PLATFORM_TENANT_ID))];
63
+ for (const id of tenants)
64
+ parseTenantSelector([id]);
65
+ const plan = tenantNamePlan(owned, value.template);
66
+ return plan && tenants.length ? { plan, tenants } : undefined;
67
+ }
68
+ export const sources = new WeakSet();
69
+ /** Only frozen factory objects can supply source authority. WeakSet lookup does
70
+ * not inspect properties, so lookalikes, getters and proxies never execute. */
71
+ export function captureTenantReadSource(input) {
72
+ if (!sources.has(input))
73
+ return denyTenant();
74
+ return input;
75
+ }
76
+ provideTenantSourceProbe('read', captureTenantReadSource);
77
+ /** A batch's reads in the shape a command's records take, for the one caller
78
+ * that asks a command's questions without its transaction (availability): it
79
+ * reads, and every way of writing refuses. */
80
+ export function advisoryRecords(reads) {
81
+ const refuse = async () => {
82
+ throw new Refusal('Availability reads; it never writes.');
83
+ };
84
+ return Object.freeze({
85
+ query: (request) => reads.query(request),
86
+ count: (table, filter) => reads.count(table, filter),
87
+ ...(reads.aggregate ? { aggregate: (request) => reads.aggregate(request) } : {}),
88
+ insert: refuse,
89
+ update: refuse,
90
+ remove: refuse,
91
+ });
92
+ }
93
+ /* A read refused before it ran — its arguments not plain data, the source
94
+ closed — is one fixed sentence to its caller, and keeps why for the
95
+ operator (refusalReport.ts), where a fresh denial in its place said
96
+ nothing on stderr at all. */
97
+ export const refusedBefore = (error) => Promise.reject(recordRefusalCause(new TenantContextError(), error));
98
+ /** The reader a batch is handed (`withReads`): each operation's arguments
99
+ * captured, run on the batch's snapshot as it is asked, and refused once the
100
+ * batch has returned. Asked together, they leave together: the PostgreSQL
101
+ * reader pipelines, so the `when` of every command a record offers is one
102
+ * round trip, where one after another each was its own (SQLite runs them in
103
+ * turn on its one handle either way). The first failure is every later
104
+ * operation's, as one transaction's is. A database failure is mapped where
105
+ * it happens, so what `work` itself throws stays its own; `own` hears which
106
+ * that was. */
107
+ export async function readBatch(bound, active, work, own) {
108
+ const running = new Set();
109
+ let failure;
110
+ const operations = {
111
+ finish: async () => {
112
+ await Promise.allSettled([...running]);
113
+ if (failure)
114
+ throw failure.error;
115
+ },
116
+ };
117
+ let open = true;
118
+ const run = (args, call) => {
119
+ let captured;
120
+ try {
121
+ if (!open)
122
+ throw recordRefusalCause(new TenantContextError(), "A batch's read was asked after the batch had returned.");
123
+ active();
124
+ captured = captureTenantData(args);
125
+ }
126
+ catch (error) {
127
+ return refusedBefore(error);
128
+ }
129
+ if (failure)
130
+ return Promise.reject(failure.error);
131
+ const operation = (async () => {
132
+ try {
133
+ const result = await call(...captured);
134
+ active();
135
+ return result;
136
+ }
137
+ catch (error) {
138
+ try {
139
+ return denyTenantFor(error);
140
+ }
141
+ catch (mapped) {
142
+ failure ??= { error: mapped };
143
+ throw mapped;
144
+ }
145
+ }
146
+ })();
147
+ running.add(operation);
148
+ void operation.then(() => running.delete(operation), () => running.delete(operation));
149
+ return operation;
150
+ };
151
+ const reads = Object.freeze({
152
+ query: (request) => run([request], (value) => bound.query(value)),
153
+ count: (table, filter, limit) => run([table, filter, limit], (id, value, boundLimit) => bound.count(id, value, boundLimit)),
154
+ runView: (view, offset) => run([view, offset], (value, boundOffset) => bound.runView(value, boundOffset)),
155
+ countView: (view, limit) => run([view, limit], (value, boundLimit) => bound.countView(value, boundLimit)),
156
+ runBreakdown: (breakdown, offset) => run([breakdown, offset], (value, boundOffset) => bound.runBreakdown(value, boundOffset)),
157
+ countBreakdown: (breakdown, limit) => run([breakdown, limit], (value, boundLimit) => bound.countBreakdown(value, boundLimit)),
158
+ /* A sum or a group, captured and run on the batch's snapshot as `count` is. */
159
+ ...(bound.aggregate
160
+ ? { aggregate: (request) => run([request], (value) => bound.aggregate(value)) }
161
+ : {}),
162
+ });
163
+ let result;
164
+ try {
165
+ result = await work(reads);
166
+ }
167
+ catch (error) {
168
+ open = false;
169
+ own(error);
170
+ await operations.finish().catch(() => { });
171
+ throw error;
172
+ }
173
+ open = false;
174
+ await operations.finish();
175
+ return result;
176
+ }
@@ -0,0 +1,6 @@
1
+ import { type TenantOwnershipSnapshot } from './tenantOwnership.js';
2
+ import { type TenantStoreBinding } from './tenantStore.js';
3
+ import { type TenantReadSource } from './tenantReadSourceShared.js';
4
+ /** Opens once, read-only. Every operation owns a serialized read snapshot on
5
+ * that exact handle; no registry lookup, request-time migration or writer exists. */
6
+ export declare function openSqliteTenantReadSource(existingPath: string, ownership: TenantOwnershipSnapshot, store: TenantStoreBinding, now?: () => number): TenantReadSource;