@feltdb/feltkit 0.0.0-stage → 0.1.1
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 +21 -0
- package/README.md +22 -2
- package/bin/feltkit.js +3 -0
- package/dist/app.d.ts +151 -0
- package/dist/app.js +130 -0
- package/dist/app.js.map +1 -0
- package/dist/cli/deploy.d.ts +8 -0
- package/dist/cli/deploy.js +125 -0
- package/dist/cli/deploy.js.map +1 -0
- package/dist/cli/main.d.ts +9 -0
- package/dist/cli/main.js +365 -0
- package/dist/cli/main.js.map +1 -0
- package/dist/cli/output.d.ts +18 -0
- package/dist/cli/output.js +87 -0
- package/dist/cli/output.js.map +1 -0
- package/dist/client/index.d.ts +125 -0
- package/dist/client/index.js +306 -0
- package/dist/client/index.js.map +1 -0
- package/dist/dashboard/assets/index-BLnBFDJs.css +1 -0
- package/dist/dashboard/assets/index-CxJGCspE.js +15 -0
- package/dist/dashboard/index.html +16 -0
- package/dist/errors.d.ts +31 -0
- package/dist/errors.js +54 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +12 -0
- package/dist/index.js.map +1 -0
- package/dist/react/index.d.ts +40 -0
- package/dist/react/index.js +85 -0
- package/dist/react/index.js.map +1 -0
- package/dist/runtime/activity.d.ts +97 -0
- package/dist/runtime/activity.js +99 -0
- package/dist/runtime/activity.js.map +1 -0
- package/dist/runtime/authority.d.ts +78 -0
- package/dist/runtime/authority.js +176 -0
- package/dist/runtime/authority.js.map +1 -0
- package/dist/runtime/changes.d.ts +34 -0
- package/dist/runtime/changes.js +85 -0
- package/dist/runtime/changes.js.map +1 -0
- package/dist/runtime/context.d.ts +51 -0
- package/dist/runtime/context.js +2 -0
- package/dist/runtime/context.js.map +1 -0
- package/dist/runtime/data.d.ts +139 -0
- package/dist/runtime/data.js +374 -0
- package/dist/runtime/data.js.map +1 -0
- package/dist/runtime/environment.d.ts +36 -0
- package/dist/runtime/environment.js +62 -0
- package/dist/runtime/environment.js.map +1 -0
- package/dist/runtime/instance.d.ts +77 -0
- package/dist/runtime/instance.js +230 -0
- package/dist/runtime/instance.js.map +1 -0
- package/dist/runtime/loader.d.ts +11 -0
- package/dist/runtime/loader.js +99 -0
- package/dist/runtime/loader.js.map +1 -0
- package/dist/runtime/projects.d.ts +51 -0
- package/dist/runtime/projects.js +139 -0
- package/dist/runtime/projects.js.map +1 -0
- package/dist/runtime/runtime.d.ts +178 -0
- package/dist/runtime/runtime.js +448 -0
- package/dist/runtime/runtime.js.map +1 -0
- package/dist/runtime/services.d.ts +177 -0
- package/dist/runtime/services.js +418 -0
- package/dist/runtime/services.js.map +1 -0
- package/dist/runtime/sessions.d.ts +55 -0
- package/dist/runtime/sessions.js +107 -0
- package/dist/runtime/sessions.js.map +1 -0
- package/dist/schema.d.ts +56 -0
- package/dist/schema.js +44 -0
- package/dist/schema.js.map +1 -0
- package/dist/server/admin.d.ts +115 -0
- package/dist/server/admin.js +326 -0
- package/dist/server/admin.js.map +1 -0
- package/dist/server/http.d.ts +19 -0
- package/dist/server/http.js +99 -0
- package/dist/server/http.js.map +1 -0
- package/dist/server/index.d.ts +52 -0
- package/dist/server/index.js +296 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/mcp.d.ts +12 -0
- package/dist/server/mcp.js +77 -0
- package/dist/server/mcp.js.map +1 -0
- package/dist/server/project.d.ts +60 -0
- package/dist/server/project.js +331 -0
- package/dist/server/project.js.map +1 -0
- package/dist/server/public.d.ts +14 -0
- package/dist/server/public.js +15 -0
- package/dist/server/public.js.map +1 -0
- package/dist/testing/index.d.ts +20 -0
- package/dist/testing/index.js +64 -0
- package/dist/testing/index.js.map +1 -0
- package/package.json +84 -4
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Identity and authority.
|
|
3
|
+
*
|
|
4
|
+
* One policy — the application's roles → permissions — is evaluated by AppPort's own
|
|
5
|
+
* `permissionAuthorizer` (so `tasks.*` and `*` mean exactly what AppPort says they
|
|
6
|
+
* mean) and enforced at every execution boundary:
|
|
7
|
+
*
|
|
8
|
+
* FeltKit functions (HTTP, dashboard, tests) → Authority.authorize()
|
|
9
|
+
* AppPort capability dispatch (/appport, MCP) → the same Authorizer, given to createApplication
|
|
10
|
+
* AppPort Services effects (Files) → ServiceAuthorizer adapter below
|
|
11
|
+
*
|
|
12
|
+
* Roles are resolved at decision time from the principal, so changing the policy
|
|
13
|
+
* applies to the next call on every interface.
|
|
14
|
+
*/
|
|
15
|
+
import { permissionAuthorizer } from "@appport/sdk";
|
|
16
|
+
import { grantsPermission } from "@appport/authorization";
|
|
17
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
18
|
+
import { FeltKitError } from "../errors.js";
|
|
19
|
+
export function normalizePrincipal(input) {
|
|
20
|
+
if (!input || typeof input.id !== "string" || !input.id.trim())
|
|
21
|
+
throw new FeltKitError("INVALID_ARGUMENT", "A principal needs an id.");
|
|
22
|
+
const type = input.type ?? "user";
|
|
23
|
+
if (!["user", "agent", "service"].includes(type))
|
|
24
|
+
throw new FeltKitError("INVALID_ARGUMENT", `Unknown principal type "${type}".`);
|
|
25
|
+
if (!Array.isArray(input.roles))
|
|
26
|
+
throw new FeltKitError("INVALID_ARGUMENT", "A principal needs a roles array.");
|
|
27
|
+
return {
|
|
28
|
+
id: input.id,
|
|
29
|
+
type,
|
|
30
|
+
roles: [...input.roles],
|
|
31
|
+
...(input.displayName ? { displayName: input.displayName } : {}),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export function toAppPortPrincipal(principal) {
|
|
35
|
+
return {
|
|
36
|
+
id: principal.id,
|
|
37
|
+
type: principal.type === "agent" ? "application" : principal.type,
|
|
38
|
+
...(principal.displayName ? { displayName: principal.displayName } : {}),
|
|
39
|
+
attributes: { roles: principal.roles, feltkitType: principal.type },
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
export function fromAppPortPrincipal(principal) {
|
|
43
|
+
if (!principal)
|
|
44
|
+
return null;
|
|
45
|
+
const attributes = (principal.attributes ?? {});
|
|
46
|
+
const roles = Array.isArray(attributes.roles) ? attributes.roles.filter((r) => typeof r === "string") : [];
|
|
47
|
+
const type = (typeof attributes.feltkitType === "string" ? attributes.feltkitType : principal.type === "application" ? "agent" : principal.type);
|
|
48
|
+
return { id: principal.id, type: ["user", "agent", "service"].includes(type) ? type : "service", roles, ...(principal.displayName ? { displayName: principal.displayName } : {}) };
|
|
49
|
+
}
|
|
50
|
+
export class Authority {
|
|
51
|
+
roles;
|
|
52
|
+
policyVersion;
|
|
53
|
+
/** The AppPort authorizer. Every boundary evaluates through it. */
|
|
54
|
+
authorizer;
|
|
55
|
+
#applicationId;
|
|
56
|
+
constructor(applicationId, roles = {}) {
|
|
57
|
+
this.#applicationId = applicationId;
|
|
58
|
+
this.roles = Object.freeze(Object.fromEntries(Object.entries(roles).map(([k, v]) => [k, Object.freeze([...v])])));
|
|
59
|
+
this.policyVersion = createHash("sha256").update(JSON.stringify(Object.entries(this.roles).sort())).digest("hex").slice(0, 12);
|
|
60
|
+
this.authorizer = permissionAuthorizer({
|
|
61
|
+
resolvePermissions: (request) => this.permissionsFor(fromAppPortPrincipal(request.principal ?? request.session?.principal)),
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
permissionsFor(principal) {
|
|
65
|
+
if (!principal)
|
|
66
|
+
return [];
|
|
67
|
+
const granted = new Set();
|
|
68
|
+
for (const role of principal.roles)
|
|
69
|
+
for (const permission of this.roles[role] ?? [])
|
|
70
|
+
granted.add(permission);
|
|
71
|
+
return [...granted];
|
|
72
|
+
}
|
|
73
|
+
/** Permissions an `access` declaration requires. */
|
|
74
|
+
static required(access) {
|
|
75
|
+
return access === "public" || access === "authenticated" ? [] : [access];
|
|
76
|
+
}
|
|
77
|
+
async authorize(input) {
|
|
78
|
+
const decisionId = `dec_${randomUUID()}`;
|
|
79
|
+
const granted = this.permissionsFor(input.principal);
|
|
80
|
+
const required = Authority.required(input.access);
|
|
81
|
+
const base = { required: required[0] ?? "", granted, decisionId, policyVersion: this.policyVersion };
|
|
82
|
+
if (input.access !== "public" && !input.principal) {
|
|
83
|
+
return { ...base, allowed: false, code: "UNAUTHORIZED", reason: "Authentication is required" };
|
|
84
|
+
}
|
|
85
|
+
const decision = await this.authorizer.authorize({
|
|
86
|
+
capability: { name: input.target.name, version: input.target.version ?? 1 },
|
|
87
|
+
required,
|
|
88
|
+
...(input.principal ? { principal: toAppPortPrincipal(input.principal) } : {}),
|
|
89
|
+
input: input.input,
|
|
90
|
+
transport: input.transport,
|
|
91
|
+
applicationId: this.#applicationId,
|
|
92
|
+
...(input.requestId ? { requestId: input.requestId } : {}),
|
|
93
|
+
});
|
|
94
|
+
if (decision.allowed)
|
|
95
|
+
return { ...base, allowed: true };
|
|
96
|
+
return { ...base, allowed: false, code: decision.code, ...(decision.reason ? { reason: decision.reason } : {}) };
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* The ServiceAuthorizer given to AppPort Services' ServiceGateway. Services pass a
|
|
100
|
+
* subject id only; FeltKit resolves the full principal for the invocation that
|
|
101
|
+
* caused the effect (bound by `runId`) and evaluates the same policy.
|
|
102
|
+
*/
|
|
103
|
+
serviceAuthorizer(resolve, onDecision) {
|
|
104
|
+
return {
|
|
105
|
+
authorize: async (request) => {
|
|
106
|
+
const principal = resolve(request.context.run_id);
|
|
107
|
+
const matches = principal !== null && principal.id === request.subject.id && request.tenant_id === this.#applicationId;
|
|
108
|
+
const owner = OWNED_BY_ATTRIBUTE[request.capability];
|
|
109
|
+
const ownerValue = owner ? request.resource.attributes?.[owner] : undefined;
|
|
110
|
+
const notOwner = owner !== undefined && ownerValue !== request.subject.id;
|
|
111
|
+
const decision = matches && !notOwner
|
|
112
|
+
? await this.authorize({
|
|
113
|
+
access: request.capability,
|
|
114
|
+
principal,
|
|
115
|
+
target: { name: request.capability, version: request.capability_version },
|
|
116
|
+
transport: "service",
|
|
117
|
+
requestId: request.request_id,
|
|
118
|
+
})
|
|
119
|
+
: null;
|
|
120
|
+
const result = {
|
|
121
|
+
decision_id: decision?.decisionId ?? `dec_${randomUUID()}`,
|
|
122
|
+
allowed: decision?.allowed ?? false,
|
|
123
|
+
capability: request.capability,
|
|
124
|
+
tenant_id: request.tenant_id,
|
|
125
|
+
application_id: request.application_id,
|
|
126
|
+
subject: request.subject,
|
|
127
|
+
resource: request.resource,
|
|
128
|
+
...(decision?.allowed
|
|
129
|
+
? {}
|
|
130
|
+
: {
|
|
131
|
+
reason: decision?.reason ??
|
|
132
|
+
(matches && notOwner
|
|
133
|
+
? `${request.capability} is limited to the principal named by "${owner}" (${String(ownerValue)}); it is ${request.subject.id}`
|
|
134
|
+
: "No FeltKit invocation is bound to this service request"),
|
|
135
|
+
}),
|
|
136
|
+
policy_version: this.policyVersion,
|
|
137
|
+
evaluated_at: Date.now(),
|
|
138
|
+
};
|
|
139
|
+
onDecision?.(result);
|
|
140
|
+
return result;
|
|
141
|
+
},
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Service resources that belong to one principal. The service names the owner in a
|
|
147
|
+
* resource attribute; FeltKit allows the effect only when that owner is the caller.
|
|
148
|
+
* There is deliberately no override permission: a wildcard grant such as
|
|
149
|
+
* "notifications.*" must not expose other people's notifications.
|
|
150
|
+
*/
|
|
151
|
+
const OWNED_BY_ATTRIBUTE = {
|
|
152
|
+
"notifications.read": "recipient",
|
|
153
|
+
"notifications.update": "recipient",
|
|
154
|
+
"notifications.delete": "recipient",
|
|
155
|
+
};
|
|
156
|
+
export function authContext(authority, principal) {
|
|
157
|
+
const grants = (granted, permission) => grantsPermission(granted, permission);
|
|
158
|
+
const permissions = Object.freeze(authority.permissionsFor(principal));
|
|
159
|
+
return Object.freeze({
|
|
160
|
+
principal,
|
|
161
|
+
permissions,
|
|
162
|
+
has: (permission) => grants([...permissions], permission),
|
|
163
|
+
require(permission) {
|
|
164
|
+
if (!principal)
|
|
165
|
+
throw new FeltKitError("UNAUTHORIZED", "Authentication is required");
|
|
166
|
+
if (!grants([...permissions], permission))
|
|
167
|
+
throw new FeltKitError("FORBIDDEN", `Missing permission: ${permission}`);
|
|
168
|
+
},
|
|
169
|
+
requirePrincipal() {
|
|
170
|
+
if (!principal)
|
|
171
|
+
throw new FeltKitError("UNAUTHORIZED", "Authentication is required");
|
|
172
|
+
return principal;
|
|
173
|
+
},
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
//# sourceMappingURL=authority.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"authority.js","sourceRoot":"","sources":["../../src/runtime/authority.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAAE,oBAAoB,EAAmB,MAAM,cAAc,CAAC;AACrE,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAG1D,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAErD,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAuB5C,MAAM,UAAU,kBAAkB,CAAC,KAAiC;IAClE,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,CAAC,EAAE,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,IAAI,EAAE;QAAE,MAAM,IAAI,YAAY,CAAC,kBAAkB,EAAE,0BAA0B,CAAC,CAAC;IACvI,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,IAAI,MAAM,CAAC;IAClC,IAAI,CAAC,CAAC,MAAM,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC;QAAE,MAAM,IAAI,YAAY,CAAC,kBAAkB,EAAE,2BAA2B,IAAI,IAAI,CAAC,CAAC;IAClI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC;QAAE,MAAM,IAAI,YAAY,CAAC,kBAAkB,EAAE,k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gBAAE,MAAM,IAAI,YAAY,CAAC,WAAW,EAAE,uBAAuB,UAAU,EAAE,CAAC,CAAC;QACtH,CAAC;QACD,gBAAgB;YACd,IAAI,CAAC,SAAS;gBAAE,MAAM,IAAI,YAAY,CAAC,cAAc,EAAE,4BAA4B,CAAC,CAAC;YACrF,OAAO,SAAS,CAAC;QACnB,CAAC;KACF,CAAC,CAAC;AACL,CAAC"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The change feed, read from FeltDB's own operation journal.
|
|
3
|
+
*
|
|
4
|
+
* Collection subscriptions on the local runtime do not observe writes committed
|
|
5
|
+
* through `db.transaction` (which is how FeltKit mutations and AppPort Services
|
|
6
|
+
* write), so FeltKit does not rely on them. Instead it watches the instance's
|
|
7
|
+
* sequence (`getSequence()`, synchronous and cheap) and reads the committed
|
|
8
|
+
* operations since the last position (`exportOperations(since)`). Every write path
|
|
9
|
+
* on the instance — functions, capabilities, services, the dashboard — appears here.
|
|
10
|
+
*
|
|
11
|
+
* Guarantee: within one server process, every committed write produces a change
|
|
12
|
+
* event naming its collection, at least once, within roughly one poll interval.
|
|
13
|
+
*/
|
|
14
|
+
import type { StateFirstDB } from "@feltdb/core";
|
|
15
|
+
export interface ChangeEvent {
|
|
16
|
+
/** Journal position after these changes. */
|
|
17
|
+
sequence: number;
|
|
18
|
+
collections: string[];
|
|
19
|
+
at: string;
|
|
20
|
+
}
|
|
21
|
+
export type ChangeListener = (event: ChangeEvent) => void;
|
|
22
|
+
export declare class ChangeFeed {
|
|
23
|
+
#private;
|
|
24
|
+
lastError: string | null;
|
|
25
|
+
constructor(db: StateFirstDB, options?: {
|
|
26
|
+
intervalMs?: number;
|
|
27
|
+
});
|
|
28
|
+
get position(): number;
|
|
29
|
+
start(): void;
|
|
30
|
+
stop(): void;
|
|
31
|
+
subscribe(listener: ChangeListener): () => void;
|
|
32
|
+
/** Check the journal now (called after commits for low latency, and on a timer). */
|
|
33
|
+
check(): Promise<void>;
|
|
34
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
export class ChangeFeed {
|
|
2
|
+
#db;
|
|
3
|
+
#listeners = new Set();
|
|
4
|
+
#intervalMs;
|
|
5
|
+
#position;
|
|
6
|
+
#timer;
|
|
7
|
+
#running = null;
|
|
8
|
+
#pending = false;
|
|
9
|
+
lastError = null;
|
|
10
|
+
constructor(db, options = {}) {
|
|
11
|
+
this.#db = db;
|
|
12
|
+
this.#intervalMs = options.intervalMs ?? 150;
|
|
13
|
+
this.#position = safeSequence(db);
|
|
14
|
+
}
|
|
15
|
+
get position() {
|
|
16
|
+
return this.#position;
|
|
17
|
+
}
|
|
18
|
+
start() {
|
|
19
|
+
if (this.#timer)
|
|
20
|
+
return;
|
|
21
|
+
this.#timer = setInterval(() => void this.check(), this.#intervalMs);
|
|
22
|
+
this.#timer.unref();
|
|
23
|
+
}
|
|
24
|
+
stop() {
|
|
25
|
+
if (this.#timer)
|
|
26
|
+
clearInterval(this.#timer);
|
|
27
|
+
this.#timer = undefined;
|
|
28
|
+
}
|
|
29
|
+
subscribe(listener) {
|
|
30
|
+
this.#listeners.add(listener);
|
|
31
|
+
return () => this.#listeners.delete(listener);
|
|
32
|
+
}
|
|
33
|
+
/** Check the journal now (called after commits for low latency, and on a timer). */
|
|
34
|
+
check() {
|
|
35
|
+
if (this.#running) {
|
|
36
|
+
this.#pending = true;
|
|
37
|
+
return this.#running;
|
|
38
|
+
}
|
|
39
|
+
this.#running = this.#check().finally(() => {
|
|
40
|
+
this.#running = null;
|
|
41
|
+
if (this.#pending) {
|
|
42
|
+
this.#pending = false;
|
|
43
|
+
void this.check();
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
return this.#running;
|
|
47
|
+
}
|
|
48
|
+
async #check() {
|
|
49
|
+
const sequence = safeSequence(this.#db);
|
|
50
|
+
if (sequence <= this.#position)
|
|
51
|
+
return;
|
|
52
|
+
const since = this.#position;
|
|
53
|
+
let collections;
|
|
54
|
+
try {
|
|
55
|
+
const operations = await this.#db.exportOperations(since);
|
|
56
|
+
collections = [...new Set(operations.filter((op) => op.sequence > since).map((op) => op.collection))];
|
|
57
|
+
this.lastError = null;
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
// The journal could not be read (for example after compaction). Report the
|
|
61
|
+
// position change without names; subscribers treat that as "anything changed".
|
|
62
|
+
this.lastError = error.message;
|
|
63
|
+
collections = ["*"];
|
|
64
|
+
}
|
|
65
|
+
this.#position = sequence;
|
|
66
|
+
const event = { sequence, collections, at: new Date().toISOString() };
|
|
67
|
+
for (const listener of this.#listeners) {
|
|
68
|
+
try {
|
|
69
|
+
listener(event);
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
/* a broken subscriber must not stop delivery to others */
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function safeSequence(db) {
|
|
78
|
+
try {
|
|
79
|
+
return db.getSequence();
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return 0;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
//# sourceMappingURL=changes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"changes.js","sourceRoot":"","sources":["../../src/runtime/changes.ts"],"names":[],"mappings":"AAwBA,MAAM,OAAO,UAAU;IACZ,GAAG,CAAe;IAClB,UAAU,GAAG,IAAI,GAAG,EAAkB,CAAC;IACvC,WAAW,CAAS;IAC7B,SAAS,CAAS;IAClB,MAAM,CAA6B;IACnC,QAAQ,GAAyB,IAAI,CAAC;IACtC,QAAQ,GAAG,KAAK,CAAC;IACjB,SAAS,GAAkB,IAAI,CAAC;IAEhC,YAAY,EAAgB,EAAE,UAAmC,EAAE;QACjE,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC;QACd,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,UAAU,IAAI,GAAG,CAAC;QAC7C,IAAI,CAAC,SAAS,GA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X,CAAC;AACH,CAAC"}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a query or mutation handler receives.
|
|
3
|
+
*/
|
|
4
|
+
import type { StateFirstDB } from "@feltdb/core";
|
|
5
|
+
import type { AuthContext } from "./authority.js";
|
|
6
|
+
import type { DatabaseReader, DatabaseWriter } from "./data.js";
|
|
7
|
+
import type { ConfigurationReader, ConfigurationWriter, FilesReader, FilesWriter, NotificationsReader, NotificationsWriter } from "./services.js";
|
|
8
|
+
export interface Logger {
|
|
9
|
+
info(message: string, fields?: Record<string, unknown>): void;
|
|
10
|
+
warn(message: string, fields?: Record<string, unknown>): void;
|
|
11
|
+
error(message: string, fields?: Record<string, unknown>): void;
|
|
12
|
+
}
|
|
13
|
+
export interface EnvironmentInfo {
|
|
14
|
+
name: string;
|
|
15
|
+
production: boolean;
|
|
16
|
+
}
|
|
17
|
+
export interface QueryCtx {
|
|
18
|
+
/** Read-only. Queries cannot write. */
|
|
19
|
+
readonly db: DatabaseReader;
|
|
20
|
+
readonly auth: AuthContext;
|
|
21
|
+
readonly services: {
|
|
22
|
+
readonly files: FilesReader;
|
|
23
|
+
readonly notifications: NotificationsReader;
|
|
24
|
+
readonly configuration: ConfigurationReader;
|
|
25
|
+
};
|
|
26
|
+
readonly environment: EnvironmentInfo;
|
|
27
|
+
readonly requestId: string;
|
|
28
|
+
readonly log: Logger;
|
|
29
|
+
}
|
|
30
|
+
export interface MutationCtx {
|
|
31
|
+
/** Writes are buffered and commit atomically when the handler returns. */
|
|
32
|
+
readonly db: DatabaseWriter;
|
|
33
|
+
readonly auth: AuthContext;
|
|
34
|
+
/** Service effects commit on their own; they are not part of the mutation's transaction. */
|
|
35
|
+
readonly services: {
|
|
36
|
+
readonly files: FilesWriter;
|
|
37
|
+
readonly notifications: NotificationsWriter;
|
|
38
|
+
readonly configuration: ConfigurationWriter;
|
|
39
|
+
};
|
|
40
|
+
readonly environment: EnvironmentInfo;
|
|
41
|
+
readonly requestId: string;
|
|
42
|
+
readonly log: Logger;
|
|
43
|
+
/**
|
|
44
|
+
* Escape hatch: this environment's FeltDB instance. Writes made here are not
|
|
45
|
+
* validated, not part of the mutation's transaction, and not shown as the
|
|
46
|
+
* mutation's writes in the activity log. Prefer ctx.db.
|
|
47
|
+
*/
|
|
48
|
+
readonly unsafe: {
|
|
49
|
+
readonly feltdb: StateFirstDB;
|
|
50
|
+
};
|
|
51
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.js","sourceRoot":"","sources":["../../src/runtime/context.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `ctx.db`: the thinnest correct layer over FeltDB.
|
|
3
|
+
*
|
|
4
|
+
* Reads map one-to-one onto FeltDB:
|
|
5
|
+
* get → collection.get(id)
|
|
6
|
+
* find → collection.find(equalityFilter, { orderBy, limit })
|
|
7
|
+
* query → db.query({ collection, where, orderBy, limit, cursor }) (bounded page)
|
|
8
|
+
* count → collection.find(filter).length
|
|
9
|
+
*
|
|
10
|
+
* Writes in a mutation are buffered and committed as ONE FeltDB atomic transaction
|
|
11
|
+
* when the handler returns:
|
|
12
|
+
* - inserts are `requireAbsent` creates,
|
|
13
|
+
* - updates and deletes carry `ifVersion` = the version this mutation observed,
|
|
14
|
+
* - records the mutation read with `get` but did not write become preconditions.
|
|
15
|
+
* If anything the mutation read by id changed before commit, FeltDB rejects the whole
|
|
16
|
+
* transaction and nothing is written (CONFLICT). If the handler throws, nothing is
|
|
17
|
+
* written. Reads inside a mutation see the mutation's own pending writes.
|
|
18
|
+
*
|
|
19
|
+
* Reads through `find`/`query`/`count` are fenced with FeltDB read bases: the basis
|
|
20
|
+
* for the read's equality predicate is captured before the read and re-checked at
|
|
21
|
+
* commit, so a concurrent insert, update, or delete of any record matching it (a
|
|
22
|
+
* phantom included) fails the commit with CONFLICT. Range clauses widen the fence to
|
|
23
|
+
* their equality-only superset: extra conflicts, never missed ones. A read with no
|
|
24
|
+
* equality clause fences the collection's change marker (see COLLECTION_MARKERS),
|
|
25
|
+
* which detects every commit made through a Writer, but not writes made through the
|
|
26
|
+
* `ctx.unsafe.feltdb` escape hatch.
|
|
27
|
+
*
|
|
28
|
+
* Not provided: a consistent snapshot across reads within one call. A mutation that
|
|
29
|
+
* only reads commits nothing, so nothing is checked; queries are not fenced.
|
|
30
|
+
*/
|
|
31
|
+
import type { StateFirstDB } from "@feltdb/core";
|
|
32
|
+
import type { CollectionDefinition } from "../app.js";
|
|
33
|
+
import { type Doc, type InferShape, type ShapeInput, type Simplify } from "../schema.js";
|
|
34
|
+
type AnyDoc = Record<string, unknown> & {
|
|
35
|
+
id: string;
|
|
36
|
+
__version: number;
|
|
37
|
+
};
|
|
38
|
+
export type CollectionRef<S extends ShapeInput = ShapeInput> = CollectionDefinition<S> | string;
|
|
39
|
+
type DocOf<C> = C extends CollectionDefinition<infer S> ? Doc<S> : AnyDoc;
|
|
40
|
+
type FieldsOf<C> = C extends CollectionDefinition<infer S> ? Simplify<InferShape<S>> : Record<string, unknown>;
|
|
41
|
+
export interface OrderBy {
|
|
42
|
+
field: string;
|
|
43
|
+
direction: "asc" | "desc";
|
|
44
|
+
}
|
|
45
|
+
export interface WhereClause {
|
|
46
|
+
field: string;
|
|
47
|
+
eq?: unknown;
|
|
48
|
+
neq?: unknown;
|
|
49
|
+
lt?: unknown;
|
|
50
|
+
lte?: unknown;
|
|
51
|
+
gt?: unknown;
|
|
52
|
+
gte?: unknown;
|
|
53
|
+
}
|
|
54
|
+
export interface FindOptions {
|
|
55
|
+
orderBy?: OrderBy[];
|
|
56
|
+
limit?: number;
|
|
57
|
+
}
|
|
58
|
+
export interface QueryRequest {
|
|
59
|
+
where?: WhereClause[];
|
|
60
|
+
orderBy?: OrderBy[];
|
|
61
|
+
limit: number;
|
|
62
|
+
cursor?: string;
|
|
63
|
+
}
|
|
64
|
+
export interface QueryPage<T> {
|
|
65
|
+
records: T[];
|
|
66
|
+
nextCursor?: string;
|
|
67
|
+
exhausted: boolean;
|
|
68
|
+
}
|
|
69
|
+
export interface DatabaseReader {
|
|
70
|
+
get<C extends CollectionRef>(collection: C, id: string): Promise<DocOf<C> | null>;
|
|
71
|
+
find<C extends CollectionRef>(collection: C, filter?: Partial<FieldsOf<C> & {
|
|
72
|
+
id: string;
|
|
73
|
+
}>, options?: FindOptions): Promise<DocOf<C>[]>;
|
|
74
|
+
query<C extends CollectionRef>(collection: C, request: QueryRequest): Promise<QueryPage<DocOf<C>>>;
|
|
75
|
+
count<C extends CollectionRef>(collection: C, filter?: Partial<FieldsOf<C>>): Promise<number>;
|
|
76
|
+
}
|
|
77
|
+
export interface DatabaseWriter extends DatabaseReader {
|
|
78
|
+
/** Create a record. Returns its id. */
|
|
79
|
+
insert<C extends CollectionRef>(collection: C, value: FieldsOf<C>): Promise<string>;
|
|
80
|
+
/** Merge fields into an existing record. Returns the record as it will be committed. */
|
|
81
|
+
patch<C extends CollectionRef>(collection: C, id: string, fields: Partial<FieldsOf<C>>): Promise<DocOf<C>>;
|
|
82
|
+
/** Replace an existing record's fields. */
|
|
83
|
+
replace<C extends CollectionRef>(collection: C, id: string, value: FieldsOf<C>): Promise<DocOf<C>>;
|
|
84
|
+
delete<C extends CollectionRef>(collection: C, id: string): Promise<void>;
|
|
85
|
+
}
|
|
86
|
+
export interface CommittedWrite {
|
|
87
|
+
collection: string;
|
|
88
|
+
id: string;
|
|
89
|
+
op: "insert" | "update" | "delete";
|
|
90
|
+
/** Version the write was conditioned on (updates and deletes). */
|
|
91
|
+
expectedVersion?: number;
|
|
92
|
+
}
|
|
93
|
+
export interface CommitResult {
|
|
94
|
+
transactionId: string;
|
|
95
|
+
writes: CommittedWrite[];
|
|
96
|
+
commitRevision?: number;
|
|
97
|
+
revisionId?: string;
|
|
98
|
+
operationIds: string[];
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Per-collection change markers. Every commit through a Writer touches the marker of
|
|
102
|
+
* each collection it writes (unguarded, so concurrent writers never conflict on it).
|
|
103
|
+
* A read with no equality clause fences the marker, because FeltDB fences only
|
|
104
|
+
* predicates that name at least one field.
|
|
105
|
+
*/
|
|
106
|
+
export declare const COLLECTION_MARKERS = "_feltkit_collections";
|
|
107
|
+
export declare class CollectionResolver {
|
|
108
|
+
private readonly collections;
|
|
109
|
+
constructor(collections: ReadonlyMap<string, CollectionDefinition>);
|
|
110
|
+
resolve(ref: CollectionRef): CollectionDefinition;
|
|
111
|
+
}
|
|
112
|
+
export declare function newId(): string;
|
|
113
|
+
/** Read-only access. Every collection read is recorded so subscribers can be invalidated. */
|
|
114
|
+
export declare class Reader implements DatabaseReader {
|
|
115
|
+
protected readonly db: StateFirstDB;
|
|
116
|
+
protected readonly resolver: CollectionResolver;
|
|
117
|
+
readonly reads: Set<string>;
|
|
118
|
+
constructor(db: StateFirstDB, resolver: CollectionResolver);
|
|
119
|
+
protected track(ref: CollectionRef): CollectionDefinition;
|
|
120
|
+
get(ref: CollectionRef, id: string): Promise<any>;
|
|
121
|
+
find(ref: CollectionRef, filter?: Record<string, unknown>, options?: FindOptions): Promise<any[]>;
|
|
122
|
+
query(ref: CollectionRef, request: QueryRequest): Promise<QueryPage<any>>;
|
|
123
|
+
count(ref: CollectionRef, filter?: Record<string, unknown>): Promise<number>;
|
|
124
|
+
}
|
|
125
|
+
/** Mutation access: reads see pending writes; writes commit together. */
|
|
126
|
+
export declare class Writer extends Reader implements DatabaseWriter {
|
|
127
|
+
#private;
|
|
128
|
+
get pendingCount(): number;
|
|
129
|
+
get(ref: CollectionRef, id: string): Promise<any>;
|
|
130
|
+
find(ref: CollectionRef, filter?: Record<string, unknown>, options?: FindOptions): Promise<any[]>;
|
|
131
|
+
query(ref: CollectionRef, request: QueryRequest): Promise<QueryPage<any>>;
|
|
132
|
+
insert(ref: CollectionRef, value: Record<string, unknown>): Promise<string>;
|
|
133
|
+
patch(ref: CollectionRef, id: string, fields: Record<string, unknown>): Promise<any>;
|
|
134
|
+
replace(ref: CollectionRef, id: string, value: Record<string, unknown>): Promise<any>;
|
|
135
|
+
delete(ref: CollectionRef, id: string): Promise<void>;
|
|
136
|
+
/** Commit every pending write in one FeltDB transaction. */
|
|
137
|
+
commit(transactionId: string): Promise<CommitResult>;
|
|
138
|
+
}
|
|
139
|
+
export {};
|