@rindle/api-server 0.1.0-rc.5

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,73 @@
1
+ # @rindle/api-server
2
+
3
+ Framework-neutral helpers for the application API server in daemon/serverless Rindle deployments.
4
+
5
+ Default public API paths:
6
+
7
+ - `POST /api/rindle/query`
8
+ - `POST /api/rindle/read`
9
+ - `POST /api/rindle/mutate`
10
+
11
+ `read` is the one-shot read path (`handleReadJson`): it parses a default `{ name, args }` body and
12
+ runs the query once for a server-rendered/SSR read, holding a short-lived lease (`readIdleTtlMs`)
13
+ unless the browser's follow-up `subscribe` lands first. `query` mints the subscription lease and
14
+ `mutate` runs named mutators.
15
+
16
+ The API server remains the application authority. It authenticates requests, optionally runs the
17
+ SDK authorizer hooks, resolves named queries to ASTs, and runs named mutators. The daemon only sees
18
+ approved ASTs and approved write/rejection records.
19
+
20
+ A query is defined **once** with `defineQuery` (in `@rindle/client`), co-located with the component
21
+ that reads it, and the same value is registered here. `registerQueries` turns the list of those
22
+ co-located queries into the server's query surface — it re-runs each query's validator on the
23
+ untrusted wire args and builds the authoritative AST, so client and server resolve a byte-identical
24
+ query:
25
+
26
+ ```ts
27
+ import { createRindleApiServer, registerQueries, defineApiMutators } from "@rindle/api-server";
28
+ import { HttpRindleDaemonClient } from "@rindle/daemon-client";
29
+ import { issuesPageQuery, myIssuesQuery } from "./components/IssueListItem.queries.ts";
30
+
31
+ const rindle = createRindleApiServer({
32
+ daemon: new HttpRindleDaemonClient({ baseUrl: "https://rindle.internal" }),
33
+ queries: registerQueries([issuesPageQuery, myIssuesQuery]),
34
+ mutators: defineApiMutators({
35
+ createIssue: (tx, args) => {
36
+ tx.exec("INSERT INTO issue (id, title) VALUES (?, ?)", [args.id, args.title]);
37
+ },
38
+ }),
39
+ authorizeQuery: ({ user }) => Boolean(user),
40
+ authorizeMutation: ({ user }) => Boolean(user),
41
+ });
42
+ ```
43
+
44
+ `registerQueries` forwards the request's authoritative `ApiContext` (`{ user, request }`) as a
45
+ context-scoped query's ctx, so a per-principal query (e.g. "my issues") is built from the server's
46
+ trusted identity — never a client-supplied arg.
47
+
48
+ When the server must **diverge** from the client — add a tenancy/auth filter the client can't see —
49
+ use `defineApiQueries`, which maps a name directly to a `(ctx, args)` resolver. Register a
50
+ server-specific query under the same name and it wins (both are plain `{ name → resolver }` maps, so
51
+ spread them together):
52
+
53
+ ```ts
54
+ import { defineApiQueries, registerQueries } from "@rindle/api-server";
55
+
56
+ const queries = {
57
+ ...registerQueries([issuesPageQuery, myIssuesQuery]),
58
+ ...defineApiQueries({
59
+ // SAME name as the client's issuesPage — the later spread wins, so this server-only resolver
60
+ // overrides it and adds a tenancy filter (the `where`) the client's query never carries.
61
+ issuesPage: (ctx, _args) => q.issue.where.tenantId(ctx.user).orderBy("id", "asc"),
62
+ }),
63
+ };
64
+ ```
65
+
66
+ There is no scope key. If two requests resolve to the same canonical AST, the daemon may dedupe
67
+ them because the result is the same. If tenant or user visibility matters, encode it into the AST.
68
+
69
+ The mutate handler also accepts `{ envelopes: [...] }` — an in-order batch (the client-side
70
+ `createQueuedMutationSender` from `@rindle/remote` flushes these) — and replies with an array.
71
+ Envelopes run strictly sequentially; a policy rejection still advances the daemon's lmid, so
72
+ later envelopes stay contiguous and keep applying. A daemon *error* fails the whole batch: the
73
+ client retries it and the daemon's mid dedup absorbs the already-applied prefix.
@@ -0,0 +1,256 @@
1
+ import type { Ast, MutationEnvelope, NamedQuery, Query } from "@rindle/client";
2
+ import type { DematerializeInput, DematerializeOutput, MaterializationPolicy, MaterializeInput, MaterializeOutput, MigrateInput, MigrateOutput, MutationRejection, MutationRejectionOutput, QueryOnceInput, QueryOnceOutput, RindleDaemonClient, RowChangeTxn, RowChangeTxnOutput, SqlStatement, SqlTxn, SqlTxnOutput, StreamMode, WireValue } from "@rindle/daemon-client";
3
+ export declare const DEFAULT_RINDLE_API_ROUTES: {
4
+ readonly query: "/api/rindle/query";
5
+ readonly read: "/api/rindle/read";
6
+ readonly mutate: "/api/rindle/mutate";
7
+ };
8
+ export type MaybePromise<T> = T | PromiseLike<T>;
9
+ export interface ApiContext<User> {
10
+ user: User;
11
+ request?: unknown;
12
+ }
13
+ export type ApiQueryResult = Ast | Query<any, any, any>;
14
+ export type ApiQuery<User, Args> = (ctx: ApiContext<User>, args: Args) => MaybePromise<ApiQueryResult>;
15
+ export type ApiQueries<User> = Record<string, ApiQuery<User, any>>;
16
+ export interface RunQueryInput<User> {
17
+ user: User;
18
+ name: string;
19
+ args: unknown;
20
+ query: ApiQuery<User, any>;
21
+ context: ApiContext<User>;
22
+ }
23
+ export type RunQuery<User> = (input: RunQueryInput<User>) => MaybePromise<ApiQueryResult>;
24
+ export interface AuthorizeQueryInput<User> {
25
+ user: User;
26
+ name: string;
27
+ args: unknown;
28
+ context: ApiContext<User>;
29
+ }
30
+ export interface AuthorizeMutationInput<User> {
31
+ user: User;
32
+ envelope: MutationEnvelope;
33
+ context: ApiContext<User>;
34
+ }
35
+ export type Authorizer<T> = (input: T) => MaybePromise<boolean | void>;
36
+ export interface MutationContext<User> {
37
+ user: User;
38
+ envelope: MutationEnvelope;
39
+ daemon: RindleDaemonClient;
40
+ request?: unknown;
41
+ }
42
+ export interface SqlMutationTx {
43
+ exec(sql: string, params?: WireValue[]): void;
44
+ readonly statements: readonly SqlStatement[];
45
+ }
46
+ export type ApiMutatorResult = void | SqlStatement[] | SqlTxn;
47
+ export type ApiMutator<User, Args> = (tx: SqlMutationTx, args: Args, ctx: MutationContext<User>) => MaybePromise<ApiMutatorResult>;
48
+ export type ApiMutators<User> = Record<string, ApiMutator<User, any>>;
49
+ export interface QueryLeaseRequest<User> {
50
+ user: User;
51
+ name: string;
52
+ args: unknown;
53
+ request?: unknown;
54
+ /** The browser's stable `clientId` (sent on the query POST) — the anonymous routing-key fallback
55
+ * when there is no authenticated subject and no session cookie (READ-ROUTER-DESIGN.md §1.5/§2.2).
56
+ * A routing HINT only, never authorization. */
57
+ clientId?: string;
58
+ }
59
+ export interface QueryLeaseResponse {
60
+ leaseToken: string;
61
+ materializationId: string;
62
+ queryKey?: string;
63
+ reused?: boolean;
64
+ /** The follower this lease lives on (READ-ROUTER-DESIGN.md §2.3) — the browser opens its
65
+ * subscription ws here. Absent ⇒ single-daemon (the client uses its static `wsUrl`). */
66
+ wsEndpoint?: string;
67
+ }
68
+ /** A one-shot SSR read of a named query (SSR-DESIGN.md §6): same `(name, args)` surface as a lease,
69
+ * but the daemon serializes the current view ONCE and registers no subscriber. */
70
+ export interface QueryReadRequest<User> {
71
+ user: User;
72
+ name: string;
73
+ args: unknown;
74
+ request?: unknown;
75
+ /** The browser's stable `clientId` — the anonymous routing-key fallback (see
76
+ * {@link QueryLeaseRequest.clientId}). Lets the SSR read co-locate on the follower the booting
77
+ * client's first subscribe will hit (READ-ROUTER-DESIGN.md §2.4). */
78
+ clientId?: string;
79
+ }
80
+ /** The assembled (nested-by-name) first-paint snapshot the server-side Store seeds + dehydrates
81
+ * (SSR-DESIGN.md §3.3). `rows` hydrate without an engine; `cvMin` is their watermark baseline. */
82
+ export interface QueryReadResponse {
83
+ rows: Array<{
84
+ cols: Record<string, unknown>;
85
+ [rel: string]: unknown;
86
+ }>;
87
+ cvMin?: number;
88
+ queryKey?: string;
89
+ /** The follower this read warmed (READ-ROUTER-DESIGN.md §2.4) — inject it into the SSR bootstrap
90
+ * so the booting client opens its ws to the same warm follower. Absent ⇒ single-daemon. */
91
+ wsEndpoint?: string;
92
+ }
93
+ export interface PushMutationRequest<User> {
94
+ user: User;
95
+ envelope: MutationEnvelope;
96
+ request?: unknown;
97
+ }
98
+ export interface PushMutationsRequest<User> {
99
+ user: User;
100
+ envelopes: MutationEnvelope[];
101
+ request?: unknown;
102
+ }
103
+ export type PushMutationResponse = {
104
+ accepted: true;
105
+ rejected: false;
106
+ output: SqlTxnOutput;
107
+ } | {
108
+ accepted: false;
109
+ rejected: true;
110
+ reason: string;
111
+ output?: unknown;
112
+ };
113
+ export interface RindleApiRoutes {
114
+ query: string;
115
+ read: string;
116
+ mutate: string;
117
+ }
118
+ /** A named query to keep permanently materialized (warm with zero subscribers). */
119
+ export interface PinnedQuery {
120
+ name: string;
121
+ args?: unknown;
122
+ }
123
+ /** The explicit fleet pin fan-out seam (READ-ROUTER-DESIGN.md §4.2). The api-server resolves each
124
+ * pin's authoritative AST under `pinUser` and hands the ready {@link MaterializeInput}s here; the
125
+ * implementation (the read router) fans EACH across all live followers. Distinct, on purpose, from
126
+ * a per-viewer `materialize` (which routes ONE) — a pin-assert always sprays ALL. */
127
+ export interface PinFanout {
128
+ assertPins(pins: readonly MaterializeInput[]): Promise<void>;
129
+ }
130
+ export interface RindleApiServerOptions<User> {
131
+ daemon: RindleDaemonClient;
132
+ queries?: ApiQueries<User>;
133
+ runQuery?: RunQuery<User>;
134
+ mutators?: ApiMutators<User>;
135
+ authorizeQuery?: Authorizer<AuthorizeQueryInput<User>>;
136
+ authorizeMutation?: Authorizer<AuthorizeMutationInput<User>>;
137
+ routes?: Partial<RindleApiRoutes>;
138
+ mode?: StreamMode;
139
+ materializationPolicy?: MaterializationPolicy | ((input: QueryLeaseRequest<User>) => MaybePromise<MaterializationPolicy>);
140
+ leaseTtlMs?: number;
141
+ /** Idle TTL (ms) the warm pipeline a one-shot SSR {@link RindleApiServer.readQuery read} leaves
142
+ * behind is held at (SSR-DESIGN.md §3.4) — it must comfortably cover page-load + client-boot +
143
+ * the follow-up live `subscribe` so the browser lands on a still-warm pipeline (the warm
144
+ * handoff). The TTL is NOT part of the dedup key (max-wins), so it only ever extends a shared
145
+ * query's window. Absent ⇒ the daemon's default idle TTL. */
146
+ readIdleTtlMs?: number;
147
+ subject?: string | ((input: QueryLeaseRequest<User>) => MaybePromise<string | undefined>);
148
+ /** The ANONYMOUS routing key forwarded to the read router (READ-ROUTER-DESIGN.md §2.2) — used by
149
+ * HRW placement when there is no authenticated `subject`. The router keys on `subject ?? this`;
150
+ * the resolved value rides `metadata.routingKey` to the daemon. Default: the browser-supplied
151
+ * `clientId` (from the query POST body). NOTE: the default cannot co-locate an ANONYMOUS SSR read
152
+ * with the booting client — an SSR server can't see the browser's localStorage `clientId`, so the
153
+ * two legs compute different keys and §2.4's warm handoff misses (still correct — just an extra
154
+ * first-touch materialize). For anonymous SSR co-location, set this to read a server-set session
155
+ * cookie from `input.request` (it rides the SSR request AND every browser request). A routing
156
+ * HINT only — never authorization. Ignored by a single (unrouted) daemon, which has nothing to
157
+ * route. */
158
+ routingKey?: string | ((input: QueryLeaseRequest<User>) => MaybePromise<string | undefined>);
159
+ /** The EXPLICIT fleet pin fan-out (READ-ROUTER-DESIGN.md §4.2 "push") — when set,
160
+ * {@link RindleApiServer.assertPins} fans each resolved pin across ALL live followers through it
161
+ * (e.g. `createRouterPinClient` from `@rindle/router`) instead of materializing each pin once on
162
+ * the (single) daemon. A per-viewer `materialize` always routes ONE; a pin-assert always fans
163
+ * ALL — never inferred from `policy.kind`. Absent ⇒ single-daemon behavior (one materialize per
164
+ * pin). */
165
+ pinFanout?: PinFanout;
166
+ /** Named queries to keep permanently materialized via {@link RindleApiServer.assertPins}.
167
+ * Each is materialized with a `pinned` policy (survives zero subscribers) so late joiners
168
+ * attach to an already-warm result. Pins are viewer-independent — resolved with `pinUser`. */
169
+ pinnedQueries?: PinnedQuery[];
170
+ /** The user context pins resolve under (pins are shared, so they should not depend on a
171
+ * per-viewer identity). Defaults to `undefined`. */
172
+ pinUser?: User;
173
+ }
174
+ export interface RindleApiServer<User> {
175
+ readonly routes: RindleApiRoutes;
176
+ createQueryLease(input: QueryLeaseRequest<User>): Promise<QueryLeaseResponse>;
177
+ /** (Re-)materialize every `pinnedQueries` entry with a pinned policy. Idempotent — the daemon
178
+ * dedupes by canonical query, so a re-assert reuses the existing materialization. Call it at
179
+ * startup and whenever the daemon restarts (e.g. from the daemon-client `onBootId` hook), since
180
+ * the daemon holds no durable materialization state. No-op when `pinnedQueries` is empty. */
181
+ assertPins(): Promise<void>;
182
+ pushMutation(input: PushMutationRequest<User>): Promise<PushMutationResponse>;
183
+ /** Apply an in-order batch (the client mutation queue's flush). Envelopes run strictly
184
+ * sequentially; a rejection still advances the daemon's lmid, so later envelopes in the
185
+ * batch stay contiguous and keep applying. A daemon ERROR throws for the whole batch —
186
+ * the client retries it and the daemon's mid dedup absorbs the already-applied prefix. */
187
+ pushMutations(input: PushMutationsRequest<User>): Promise<PushMutationResponse[]>;
188
+ /** One-shot SSR read (SSR-DESIGN.md §6): resolve `(name, args)` → AST (same authority path as a
189
+ * lease, `authorizeQuery` enforced), have the daemon serialize the current view once, and return
190
+ * the assembled rows for the loader to seed + dehydrate. Registers NO subscriber — a dropped
191
+ * render leaks nothing; the pipeline self-reclaims after the idle TTL ({@link
192
+ * RindleApiServerOptions.readIdleTtlMs}) unless the browser's follow-up `subscribe` lands first. */
193
+ readQuery(input: QueryReadRequest<User>): Promise<QueryReadResponse>;
194
+ handleQueryJson(body: unknown, context: ApiContext<User>): Promise<QueryLeaseResponse>;
195
+ /** Parse a default `{name, args}` read body and run {@link readQuery}. */
196
+ handleReadJson(body: unknown, context: ApiContext<User>): Promise<QueryReadResponse>;
197
+ /** Accepts `{envelope}` (one) or `{envelopes: [...]}` (an in-order batch → array reply). */
198
+ handleMutateJson(body: unknown, context: ApiContext<User>): Promise<PushMutationResponse | PushMutationResponse[]>;
199
+ }
200
+ export type RindleApiErrorCode = "bad-request" | "forbidden" | "not-found" | "rejected";
201
+ export declare class RindleApiError extends Error {
202
+ readonly code: RindleApiErrorCode;
203
+ readonly status: number;
204
+ constructor(code: RindleApiErrorCode, message: string, status: number);
205
+ }
206
+ /**
207
+ * A read/write-split `RindleDaemonClient` (READ-ROUTER-DESIGN.md §2.1). Writes
208
+ * (`executeSqlTxn` / `rejectMutation` / `applyRowChangeTxn` / `migrate`) go to the single
209
+ * write-master, UNCHANGED and never through the router; reads (`materialize` / `query` /
210
+ * `dematerialize`) go to the read router. Hand one of these to {@link createRindleApiServer} as
211
+ * `daemon` to point the reads leg at the router while writes stay on the master — no placement
212
+ * logic enters the api-server.
213
+ *
214
+ * ```ts
215
+ * const daemon = new SplitDaemonClient(
216
+ * new HttpRindleDaemonClient({ baseUrl: MASTER_URL, headers: writeAuth }), // writes → master
217
+ * new HttpRindleDaemonClient({ baseUrl: ROUTER_URL, headers: routerAuth }), // reads → router
218
+ * );
219
+ * ```
220
+ */
221
+ export declare class SplitDaemonClient implements RindleDaemonClient {
222
+ private readonly writes;
223
+ private readonly reads;
224
+ constructor(writes: RindleDaemonClient, reads: RindleDaemonClient);
225
+ executeSqlTxn(input: SqlTxn): Promise<SqlTxnOutput>;
226
+ rejectMutation(input: MutationRejection): Promise<MutationRejectionOutput>;
227
+ applyRowChangeTxn(input: RowChangeTxn): Promise<RowChangeTxnOutput>;
228
+ migrate(input: MigrateInput): Promise<MigrateOutput>;
229
+ materialize(input: MaterializeInput): Promise<MaterializeOutput>;
230
+ query(input: QueryOnceInput): Promise<QueryOnceOutput>;
231
+ dematerialize(input: DematerializeInput): Promise<DematerializeOutput>;
232
+ }
233
+ export declare function defineApiQueries<User, Q extends ApiQueries<User>>(queries: Q): Q;
234
+ /**
235
+ * Register a list of co-located client {@link NamedQuery `defineQuery`} values as the server's query
236
+ * surface — the bulk, no-boilerplate counterpart to {@link defineApiQueries}. Each query already
237
+ * carries its wire `name` and a `resolve` that re-runs its validator on the UNTRUSTED wire args and
238
+ * builds the authoritative `Query`, so the server just imports every co-located query and hands the
239
+ * list here. The same validated args build a byte-identical AST on both tiers.
240
+ *
241
+ * The query's AUTHORITATIVE {@link ApiContext} is forwarded as `resolve`'s ctx — so a context-scoped
242
+ * `defineQuery` (e.g. "my issues") is built from the server's trusted principal, never the client's.
243
+ * A context-free query simply ignores the extra argument.
244
+ *
245
+ * Use {@link defineApiQueries} instead (or in addition) only when the server must DIVERGE from the
246
+ * client — define a server-specific `defineQuery` with the same name and register that.
247
+ *
248
+ * ```ts
249
+ * queries: registerQueries<User>([issuesPageQuery, issueDetailQuery, recentCommentsQuery, usersQuery]),
250
+ * ```
251
+ */
252
+ export declare function registerQueries<User>(queries: readonly NamedQuery<any, any, any>[]): ApiQueries<User>;
253
+ export declare function defineApiMutators<User, M extends ApiMutators<User>>(mutators: M): M;
254
+ export declare function queryResultToAst(result: ApiQueryResult): Ast;
255
+ export declare function createRindleApiServer<User = unknown>(opts: RindleApiServerOptions<User>): RindleApiServer<User>;
256
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,gBAAgB,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AAC/E,OAAO,KAAK,EACV,kBAAkB,EAClB,mBAAmB,EACnB,qBAAqB,EACrB,gBAAgB,EAChB,iBAAiB,EACjB,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,uBAAuB,EACvB,cAAc,EACd,eAAe,EACf,kBAAkB,EAClB,YAAY,EACZ,kBAAkB,EAClB,YAAY,EACZ,MAAM,EACN,YAAY,EACZ,UAAU,EACV,SAAS,EACV,MAAM,uBAAuB,CAAC;AAE/B,eAAO,MAAM,yBAAyB;;;;CAI5B,CAAC;AAEX,MAAM,MAAM,YAAY,CAAC,CAAC,IAAI,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC;AAEjD,MAAM,WAAW,UAAU,CAAC,IAAI;IAC9B,IAAI,EAAE,IAAI,CAAC;IACX,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,MAAM,MAAM,cAAc,GAAG,GAAG,GAAG,KAAK,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;AACxD,MAAM,MAAM,QAAQ,CAAC,IAAI,EAAE,IAA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