@zveltio/sdk 2.0.8 → 3.0.0-beta.100

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 (157) hide show
  1. package/README.md +17 -4
  2. package/dist/build/index.d.ts +77 -0
  3. package/dist/build/index.d.ts.map +1 -0
  4. package/dist/build/index.js +157 -0
  5. package/dist/client.d.ts +103 -7
  6. package/dist/client.d.ts.map +1 -1
  7. package/dist/client.js +129 -28
  8. package/dist/core.d.ts.map +1 -1
  9. package/dist/core.js +21 -3
  10. package/dist/crdt.d.ts.map +1 -1
  11. package/dist/crdt.js +11 -2
  12. package/dist/ddl/index.d.ts +173 -0
  13. package/dist/ddl/index.d.ts.map +1 -0
  14. package/dist/ddl/index.js +33 -0
  15. package/dist/errors.d.ts +58 -0
  16. package/dist/errors.d.ts.map +1 -0
  17. package/dist/errors.js +124 -0
  18. package/dist/extension/action-refusal.d.ts +27 -0
  19. package/dist/extension/action-refusal.d.ts.map +1 -0
  20. package/dist/extension/action-refusal.js +29 -0
  21. package/dist/extension/capabilities.d.ts +71 -0
  22. package/dist/extension/capabilities.d.ts.map +1 -0
  23. package/dist/extension/capabilities.js +79 -0
  24. package/dist/extension/dates.d.ts +7 -0
  25. package/dist/extension/dates.d.ts.map +1 -0
  26. package/dist/extension/dates.js +14 -0
  27. package/dist/extension/index.d.ts +1570 -10
  28. package/dist/extension/index.d.ts.map +1 -1
  29. package/dist/extension/index.js +17 -1
  30. package/dist/extension/jsonb.d.ts +62 -0
  31. package/dist/extension/jsonb.d.ts.map +1 -0
  32. package/dist/extension/jsonb.js +64 -0
  33. package/dist/extension/multipart.d.ts +58 -0
  34. package/dist/extension/multipart.d.ts.map +1 -0
  35. package/dist/extension/multipart.js +61 -0
  36. package/dist/extension/numeric.d.ts +94 -0
  37. package/dist/extension/numeric.d.ts.map +1 -0
  38. package/dist/extension/numeric.js +162 -0
  39. package/dist/extension/permission-gate.d.ts +52 -0
  40. package/dist/extension/permission-gate.d.ts.map +1 -0
  41. package/dist/extension/permission-gate.js +125 -0
  42. package/dist/extension/reserved-paths.d.ts +10 -0
  43. package/dist/extension/reserved-paths.d.ts.map +1 -0
  44. package/dist/extension/reserved-paths.js +23 -0
  45. package/dist/index.d.ts +4 -2
  46. package/dist/index.d.ts.map +1 -1
  47. package/dist/index.js +1 -0
  48. package/dist/local-store.d.ts +14 -1
  49. package/dist/local-store.d.ts.map +1 -1
  50. package/dist/local-store.js +93 -16
  51. package/dist/offline/index.d.ts +75 -0
  52. package/dist/offline/index.d.ts.map +1 -0
  53. package/dist/offline/index.js +251 -0
  54. package/dist/publish/index.d.ts +94 -0
  55. package/dist/publish/index.d.ts.map +1 -0
  56. package/dist/publish/index.js +153 -0
  57. package/dist/realtime.d.ts +25 -1
  58. package/dist/realtime.d.ts.map +1 -1
  59. package/dist/realtime.js +53 -5
  60. package/dist/rpc/index.d.ts +68 -0
  61. package/dist/rpc/index.d.ts.map +1 -0
  62. package/dist/rpc/index.js +63 -0
  63. package/dist/schema-codegen.d.ts +84 -0
  64. package/dist/schema-codegen.d.ts.map +1 -0
  65. package/dist/schema-codegen.js +503 -0
  66. package/dist/schema-watcher.d.ts +10 -2
  67. package/dist/schema-watcher.d.ts.map +1 -1
  68. package/dist/schema-watcher.js +26 -13
  69. package/dist/studio/index.d.ts +85 -0
  70. package/dist/studio/index.d.ts.map +1 -0
  71. package/dist/studio/index.js +183 -0
  72. package/dist/studio/slot-owner-registry.d.ts +13 -0
  73. package/dist/studio/slot-owner-registry.d.ts.map +1 -0
  74. package/dist/studio/slot-owner-registry.js +21 -0
  75. package/dist/svelte.d.ts +1 -1
  76. package/dist/svelte.d.ts.map +1 -1
  77. package/dist/svelte.js +4 -2
  78. package/dist/sync-manager.d.ts +49 -4
  79. package/dist/sync-manager.d.ts.map +1 -1
  80. package/dist/sync-manager.js +175 -24
  81. package/dist/testing/index.d.ts +121 -0
  82. package/dist/testing/index.d.ts.map +1 -0
  83. package/dist/testing/index.js +305 -0
  84. package/dist/testing/with-test-db.d.ts +119 -0
  85. package/dist/testing/with-test-db.d.ts.map +1 -0
  86. package/dist/testing/with-test-db.js +320 -0
  87. package/dist/tests/action-refusal.test.d.ts +2 -0
  88. package/dist/tests/action-refusal.test.d.ts.map +1 -0
  89. package/dist/tests/action-refusal.test.js +13 -0
  90. package/dist/tests/client.test.d.ts +2 -0
  91. package/dist/tests/client.test.d.ts.map +1 -0
  92. package/dist/tests/client.test.js +164 -0
  93. package/dist/tests/crdt-orset.test.d.ts +2 -0
  94. package/dist/tests/crdt-orset.test.d.ts.map +1 -0
  95. package/dist/tests/crdt-orset.test.js +23 -0
  96. package/dist/tests/local-store.test.js +44 -0
  97. package/dist/tests/migration-parse.test.d.ts +2 -0
  98. package/dist/tests/migration-parse.test.d.ts.map +1 -0
  99. package/dist/tests/migration-parse.test.js +17 -0
  100. package/dist/tests/multipart.test.d.ts +2 -0
  101. package/dist/tests/multipart.test.d.ts.map +1 -0
  102. package/dist/tests/multipart.test.js +37 -0
  103. package/dist/tests/offline-provider-crdt.test.d.ts +2 -0
  104. package/dist/tests/offline-provider-crdt.test.d.ts.map +1 -0
  105. package/dist/tests/offline-provider-crdt.test.js +206 -0
  106. package/dist/tests/realtime.test.d.ts +2 -0
  107. package/dist/tests/realtime.test.d.ts.map +1 -0
  108. package/dist/tests/realtime.test.js +220 -0
  109. package/dist/tests/reserved-paths.test.d.ts +2 -0
  110. package/dist/tests/reserved-paths.test.d.ts.map +1 -0
  111. package/dist/tests/reserved-paths.test.js +21 -0
  112. package/dist/tests/sync-manager.test.d.ts +2 -0
  113. package/dist/tests/sync-manager.test.d.ts.map +1 -0
  114. package/dist/tests/sync-manager.test.js +123 -0
  115. package/dist/tests/today-in.test.d.ts +2 -0
  116. package/dist/tests/today-in.test.d.ts.map +1 -0
  117. package/dist/tests/today-in.test.js +14 -0
  118. package/dist/tests/validate-manifest-actions.test.d.ts +2 -0
  119. package/dist/tests/validate-manifest-actions.test.d.ts.map +1 -0
  120. package/dist/tests/validate-manifest-actions.test.js +82 -0
  121. package/dist/tests/validate-manifest-dependencies.test.d.ts +2 -0
  122. package/dist/tests/validate-manifest-dependencies.test.d.ts.map +1 -0
  123. package/dist/tests/validate-manifest-dependencies.test.js +27 -0
  124. package/dist/tests/validate-manifest-forward-credentials.test.d.ts +2 -0
  125. package/dist/tests/validate-manifest-forward-credentials.test.d.ts.map +1 -0
  126. package/dist/tests/validate-manifest-forward-credentials.test.js +35 -0
  127. package/dist/tests/validate-sdui-data-endpoints.test.d.ts +2 -0
  128. package/dist/tests/validate-sdui-data-endpoints.test.d.ts.map +1 -0
  129. package/dist/tests/validate-sdui-data-endpoints.test.js +41 -0
  130. package/dist/tests/with-test-db.test.d.ts +2 -0
  131. package/dist/tests/with-test-db.test.d.ts.map +1 -0
  132. package/dist/tests/with-test-db.test.js +57 -0
  133. package/dist/types/index.d.ts.map +1 -1
  134. package/dist/utils.d.ts.map +1 -1
  135. package/dist/utils.js +3 -1
  136. package/dist/validate/index.d.ts +148 -0
  137. package/dist/validate/index.d.ts.map +1 -0
  138. package/dist/validate/index.js +887 -0
  139. package/dist/validate/migration-parse.d.ts +22 -0
  140. package/dist/validate/migration-parse.d.ts.map +1 -0
  141. package/dist/validate/migration-parse.js +11 -0
  142. package/dist/validate/shared-message-keys.d.ts +16 -0
  143. package/dist/validate/shared-message-keys.d.ts.map +1 -0
  144. package/dist/validate/shared-message-keys.js +227 -0
  145. package/package.json +56 -4
  146. package/dist/client/Auth.d.ts +0 -19
  147. package/dist/client/Auth.d.ts.map +0 -1
  148. package/dist/client/Auth.js +0 -45
  149. package/dist/client/QueryBuilder.d.ts +0 -17
  150. package/dist/client/QueryBuilder.d.ts.map +0 -1
  151. package/dist/client/QueryBuilder.js +0 -76
  152. package/dist/client/RealtimeClient.d.ts +0 -22
  153. package/dist/client/RealtimeClient.d.ts.map +0 -1
  154. package/dist/client/RealtimeClient.js +0 -96
  155. package/dist/client/ZveltioClient.d.ts +0 -20
  156. package/dist/client/ZveltioClient.d.ts.map +0 -1
  157. package/dist/client/ZveltioClient.js +0 -78
@@ -1,34 +1,1570 @@
1
- import type { Hono } from 'hono';
2
- export interface ExtensionContext {
3
- db: any;
4
- auth: any;
5
- fieldTypeRegistry: FieldTypeRegistryAPI;
1
+ import type { Capability, MembersLockedFor } from './capabilities.js';
2
+ import type { Context, Hono } from 'hono';
3
+ import type { Kysely, RawBuilder } from 'kysely';
4
+ export { permissionGate } from './permission-gate.js';
5
+ export { ActionRefusal, ACTION_REFUSAL, type RefusalStatus } from './action-refusal.js';
6
+ export { todayIn } from './dates.js';
7
+ export { RESERVED_PATH_SEGMENTS, isReservedPath } from './reserved-paths.js';
8
+ export { readMultipart, MULTIPART_REQUIRED } from './multipart.js';
9
+ export { toJsonb } from './jsonb.js';
10
+ /**
11
+ * The prefix of a field an operator adds to a collection an extension owns
12
+ * (ADR 0012 amendment 2). Such a name is the operator's: an extension may not
13
+ * declare one, and its load never drops or alters one.
14
+ */
15
+ export declare const OPERATOR_FIELD_PREFIX = "my_";
16
+ export { isStorableNumeric, NumericConversionError, roundMoney, sumNumeric, toNumber, toNumberOrNull, toNumberSafe, } from './numeric.js';
17
+ /**
18
+ * One row-level-security condition, as `getRlsFilters` produces it and
19
+ * `applyRlsFilters` consumes it. Opaque in practice — an extension passes the
20
+ * array straight through rather than reading it.
21
+ */
22
+ export interface RlsFilter {
23
+ readonly field: string;
24
+ readonly condition: {
25
+ readonly op: string;
26
+ readonly value?: unknown;
27
+ };
28
+ }
29
+ /** What the data API answered a `ctx.internals` write: its HTTP status and JSON body. */
30
+ export interface DataApiAnswer {
31
+ status: number;
32
+ body: Record<string, unknown>;
33
+ }
34
+ /** One `ctx.internals.writeValidationRule` write; `collection` narrows a toggle or delete. */
35
+ export type ValidationRuleWrite = {
36
+ op: 'create';
37
+ rule: {
38
+ collection: string;
39
+ field_name: string;
40
+ rule_type: string;
41
+ rule_config?: unknown;
42
+ error_message: string;
43
+ nl_description?: string | null;
44
+ };
45
+ /**
46
+ * Whom the rule binds. Left out: an instance admin writes an instance rule
47
+ * (every tenant), a tenant admin a rule of the request's tenant. `'tenant'`
48
+ * lets an instance admin write one for the request's tenant; a tenant admin
49
+ * asking `'instance'` throws.
50
+ */
51
+ scope?: 'instance' | 'tenant';
52
+ } | {
53
+ op: 'setActive';
54
+ id: string;
55
+ is_active: boolean;
56
+ collection?: string;
57
+ } | {
58
+ op: 'delete';
59
+ id: string;
60
+ collection?: string;
61
+ };
62
+ /** One `ctx.internals.writeValidationRuleGroup` write. */
63
+ export type ValidationRuleGroupWrite = {
64
+ op: 'create';
65
+ group: {
66
+ name: string;
67
+ collection: string;
68
+ field_name: string;
69
+ description?: string | null;
70
+ logic?: 'AND' | 'OR';
71
+ rule_ids: string[];
72
+ is_active?: boolean;
73
+ };
74
+ } | {
75
+ op: 'delete';
76
+ id: string;
77
+ };
78
+ /** The query of `ctx.internals.listRecords`: `GET /api/data/:collection`'s own parameters. */
79
+ export interface DataApiReadQuery {
80
+ page?: number;
81
+ limit?: number;
82
+ sort?: string;
83
+ order?: 'asc' | 'desc';
84
+ /** The route's `?filter=` JSON, as an object or already serialized. */
85
+ filter?: Record<string, unknown> | string;
86
+ search?: string;
87
+ cursor?: string;
88
+ count?: 'exact' | 'none';
89
+ expand?: string;
90
+ }
91
+ /** What `ctx.internals.readScope` resolves: one caller's read gate on one collection. */
92
+ export interface ReadScope {
93
+ /** The physical table the alters and entity checks are registered against. */
94
+ readonly table: string;
95
+ /** Row policies, for a reader that renders them itself. */
96
+ readonly rls: RlsFilter[];
97
+ readonly columns: {
98
+ hidden: Set<string>;
99
+ readOnly: Set<string>;
100
+ };
101
+ /** An extension alter changes what this caller reads (see `admits`). */
102
+ readonly altersRestrict: boolean;
103
+ /** Alters + row policies onto a SELECT builder. Not for UPDATE/DELETE. */
104
+ query<Q>(qb: Q): Q;
105
+ /** The fetched rows entity access lets the caller `view`. */
106
+ keep<R>(rows: R[]): Promise<R[]>;
107
+ /** One row that did not come through `query` (a write's RETURNING): all three row gates in memory. */
108
+ admits(row: Record<string, unknown>): boolean | Promise<boolean>;
109
+ /** Column permissions onto one row. */
110
+ shape<R extends Record<string, unknown>>(row: R): R;
111
+ /** Whether the caller may read — and so filter, sort or join on — this column. */
112
+ readable(column: string): boolean;
113
+ }
114
+ /**
115
+ * The filter operators the engine's query compiler understands — the vocabulary
116
+ * `buildCondition` accepts.
117
+ *
118
+ * Declared here rather than in the engine because this is the file an extension
119
+ * author compiles against, and the engine imports it back (as it already does
120
+ * for `RlsFilter`). One list: a repeated one is how this codebase's dominant
121
+ * defect shape starts.
122
+ */
123
+ export type FilterOp = 'eq' | 'neq' | 'lt' | 'lte' | 'gt' | 'gte' | 'like' | 'ilike' | 'not_contains' | 'starts_with' | 'ends_with' | 'in' | 'not_in' | 'null' | 'not_null'
124
+ /** `location` only: `{ lat, lng, radius }`, radius in metres (ADR 0019). */
125
+ | 'near'
126
+ /** `location` only: `{ minLat, minLng, maxLat, maxLng }` (ADR 0019). */
127
+ | 'within';
128
+ /**
129
+ * The actor a data-path call is made on behalf of.
130
+ *
131
+ * Declared here for the same reason as `RlsFilter` and `FilterOp`: it is part
132
+ * of what `ctx.internals.checkAccess` asks an extension for, and the engine
133
+ * re-exports it rather than keeping a second copy.
134
+ */
135
+ export interface RequestUser {
136
+ id: string;
137
+ name: string;
138
+ role: string;
139
+ /** Present only for API-key auth — collection/action scopes. */
140
+ scopes?: unknown;
141
+ /** Present for session auth. */
142
+ email?: string;
143
+ /** API-key auth only: this key is exempt from row-level security. */
144
+ rlsBypass?: boolean;
145
+ /** API-key auth only: the `user` row authorship is recorded against. */
146
+ authorUserId?: string | null;
6
147
  }
7
148
  export interface FieldTypeRegistryAPI {
8
149
  register(definition: any): void;
9
150
  get(type: string): any;
10
151
  has(type: string): boolean;
11
152
  list(): string[];
153
+ /**
154
+ * Full list of registered field type definitions. Distinct from
155
+ * `list()` which returns just the type names — `getAll()` returns
156
+ * the registered metadata records (label, validators, default
157
+ * value, etc.). Used by AI/schema-generation tooling.
158
+ */
159
+ getAll(): Array<{
160
+ type: string;
161
+ [key: string]: any;
162
+ }>;
163
+ /** Coerce a value FROM the database representation INTO its TS shape. */
164
+ deserialize(type: string, value: any): any;
165
+ /** Coerce a value FROM its TS shape INTO the database representation. */
166
+ serialize(type: string, value: any): any;
167
+ }
168
+ /**
169
+ * Object storage settings, handed to extensions that declare the `storage`
170
+ * capability. `undefined` on `ExtensionConfig` means the instance has no object
171
+ * storage configured — degrade (keep metadata, skip the bytes), don't throw.
172
+ *
173
+ * Resolved from the same source the engine uses, which includes the admin's
174
+ * Studio settings. Reading `S3_*` from the environment instead misses that
175
+ * overlay entirely and sees an unconfigured instance.
176
+ */
177
+ export interface ObjectStorageConfig {
178
+ /** Endpoint origin, no trailing slash. */
179
+ readonly endpoint: string;
180
+ readonly region: string;
181
+ readonly bucket: string;
182
+ /** Public base URL for reads, when the deployment serves one. */
183
+ readonly publicUrl?: string;
184
+ readonly accessKeyId: string;
185
+ readonly secretAccessKey: string;
186
+ }
187
+ /**
188
+ * The configuration an extension may read — `ctx.config`.
189
+ *
190
+ * Use this instead of `process.env`. An in-process extension reading the
191
+ * environment gets the whole ENGINE environment (database credentials, the auth
192
+ * secret, the field-encryption key), which is both more than any extension
193
+ * needs and a way around the capability gate on `ctx.internals`.
194
+ *
195
+ * Values are live: read them when you need them rather than caching at module
196
+ * scope, because an administrator can change storage settings at runtime.
197
+ */
198
+ export interface ExtensionConfig {
199
+ /**
200
+ * This extension's own slice of the environment.
201
+ *
202
+ * Everything the deployment set as `ZVELTIO_EXT_<NAME>_<KEY>` appears here as
203
+ * `<KEY>`, and nothing else does. `search` reading `vars.MEILISEARCH_URL` gets
204
+ * `ZVELTIO_EXT_SEARCH_MEILISEARCH_URL`; it cannot see `DATABASE_URL`,
205
+ * `BETTER_AUTH_SECRET`, or another extension's keys.
206
+ *
207
+ * Use this instead of `process.env`, which from inside an in-process extension
208
+ * is the ENGINE's environment in full.
209
+ *
210
+ * Values are strings — coerce at the point of use, and treat a missing key as
211
+ * "not configured" rather than defaulting to something that half-works.
212
+ */
213
+ readonly vars: Readonly<Record<string, string>>;
214
+ readonly env: 'production' | 'development' | 'test';
215
+ readonly isProduction: boolean;
216
+ /** The engine's public base URL, when the deployment sets one. */
217
+ readonly publicUrl?: string;
218
+ /**
219
+ * Whether the instance has a field-encryption key configured. A boolean by
220
+ * design — to encrypt something use `ctx.internals.encryptSecret`, which is
221
+ * gated by the `secrets` capability. Extensions do not hold key material.
222
+ */
223
+ readonly encryptionConfigured: boolean;
224
+ readonly crossDomainAuth: boolean;
225
+ /** Permits plaintext LDAP binds. Development only. */
226
+ readonly allowInsecureLdap: boolean;
227
+ /** Present only with the `storage` capability, and only when configured. */
228
+ readonly objectStorage?: ObjectStorageConfig;
229
+ }
230
+ /**
231
+ * Context injected into every extension's `register()` call.
232
+ *
233
+ * The `DB` generic threads the extension's codegen'd database schema
234
+ * (`@zveltio/sdk/codegen` → `<ext>/.zveltio/db.d.ts`) through to `ctx.db`.
235
+ * Default `any` keeps legacy extensions compiling untouched. Migrated
236
+ * extensions get full Kysely autocomplete + typo detection.
237
+ */
238
+ /**
239
+ * `C` — the capabilities this extension declared, when it says so through
240
+ * `defineExtension`. It narrows `internals` to the members those capabilities
241
+ * unlock and `adminDb` to `db:admin`, so an undeclared capability is a compile
242
+ * error rather than a `CapabilityDeniedError` on the first request that needs
243
+ * it. Defaults to every capability: code that does not opt in keeps today's type.
244
+ */
245
+ export interface ExtensionContext<DB = any, C extends string = Capability> {
246
+ /**
247
+ * Kysely database instance (restricted — cannot query zv_* system tables).
248
+ * Typed via the `DB` generic; use `ZveltioExtension<MySchema>` to opt in.
249
+ *
250
+ * TENANT-SCOPED (since H-12): queries run against the current request/job
251
+ * tenant's transaction (so the `zveltio.current_tenant` GUC is set and
252
+ * FORCE-RLS rows are isolated), or the global pool outside any tenant context
253
+ * (boot/migrations). You no longer need `ctx.reqDb(c)` for isolation — `ctx.db`
254
+ * is safe by default. For explicit CROSS-tenant access, see `ctx.adminDb`.
255
+ */
256
+ db: Kysely<DB>;
257
+ /**
258
+ * Configuration this extension may read. Use it instead of `process.env` —
259
+ * see `ExtensionConfig`.
260
+ *
261
+ * Typed optional so partial/bootstrap contexts type-check; always present on
262
+ * the context the engine hands a loaded extension.
263
+ */
264
+ config?: ExtensionConfig;
265
+ /**
266
+ * Explicit CROSS-TENANT database handle (the global pool). Present ONLY when
267
+ * the manifest declares the `db:admin` permission — otherwise any query throws.
268
+ * Use for legitimately global operations (platform-wide reporting, backup).
269
+ * Declaring `db:admin` surfaces the cross-tenant access at review + install.
270
+ */
271
+ adminDb?: 'db:admin' extends C ? Kysely<DB> : never;
272
+ /**
273
+ * Per-request, tenant-scoped database. Returns the request's tenant
274
+ * transaction (so the `zveltio.current_tenant` GUC is set and FORCE-RLS rows
275
+ * are visible + isolated), wrapped in the same table-restriction guard as
276
+ * `ctx.db`. Pass the route's Hono context: `const db = ctx.reqDb(c)`.
277
+ * Throws when the request has no tenant transaction; `ctx.db` resolves the
278
+ * tenant wherever there is one.
279
+ *
280
+ * Always present on the context the engine hands to a loaded extension; typed
281
+ * optional only so partial/bootstrap contexts type-check. In a data handler
282
+ * use it directly — `ctx.reqDb(c)`.
283
+ */
284
+ reqDb?: (c: any) => Kysely<DB>;
285
+ /** Better-Auth instance — use `ctx.auth.api.getSession({ headers })` in route handlers. */
286
+ auth: any;
287
+ /** Field type registry — register custom field types here. */
288
+ fieldTypeRegistry: FieldTypeRegistryAPI;
289
+ /** Typed event bus — subscribe to record lifecycle events (insert/update/delete). */
290
+ events: any;
291
+ /** Check if a user has permission for a resource/action. */
292
+ checkPermission: (userId: string, resource: string, action: string) => Promise<boolean>;
293
+ /** Get all roles assigned to a user. */
294
+ getUserRoles: (userId: string) => Promise<string[]>;
295
+ /**
296
+ * DDLManager — schema-migration utilities for collections and fields
297
+ * (S4-08). See `@zveltio/sdk/ddl` for the interface. The engine owns the
298
+ * implementation; extensions use the instance handed in here. Typed as
299
+ * `any` at this layer (vs the SDK's DDLManager interface) so existing
300
+ * `ctx.DDLManager` call sites in the 50+ extensions don't break when
301
+ * upgrading; opt in to the typed surface with:
302
+ *
303
+ * import type { DDLManager } from '@zveltio/sdk/ddl';
304
+ * const ddl: DDLManager = ctx.DDLManager;
305
+ */
306
+ DDLManager: any;
307
+ /**
308
+ * Inter-extension service registry. Extensions publish services here for other
309
+ * extensions to consume. Stable public API — use this for cross-extension
310
+ * communication instead of direct imports.
311
+ */
312
+ services: ServiceRegistry;
313
+ /**
314
+ * Query-alter registry. Register a function per table that the data layer
315
+ * will call before executing SELECT queries on that table — typical uses
316
+ * are tenant isolation, soft-delete filtering, and column redaction.
317
+ *
318
+ * @example
319
+ * ctx.queryAlter.register({
320
+ * table: 'zvd_contacts',
321
+ * alter(qb, user) {
322
+ * if (user.isGod) return qb;
323
+ * return qb.where('tenant_id', '=', user.tenantId);
324
+ * },
325
+ * });
326
+ *
327
+ * Alters are scoped to the registering extension — removed automatically on
328
+ * unload / hot-reload. Today's scope: SELECT queries only.
329
+ */
330
+ queryAlter: QueryAlterScope;
331
+ /**
332
+ * Per-record authorization callbacks. Return `'deny'` to block access to
333
+ * a specific row; first deny across all extensions wins. See
334
+ * `EntityAccessScope` for an example.
335
+ */
336
+ entityAccess: EntityAccessScope;
337
+ /**
338
+ * Register a subsystem health check surfaced at `GET /api/health/deep` and
339
+ * `GET /api/health/<name>`. Use it to report the liveness of anything your
340
+ * extension owns (an external API, a worker, a provider):
341
+ *
342
+ * ctx.onHealthCheck('smtp', async () => {
343
+ * const ok = await pingSmtp();
344
+ * return { ok, detail: { host: SMTP_HOST } };
345
+ * });
346
+ *
347
+ * Checks are namespaced `ext:<yourExtension>:<name>` and cleared on reload.
348
+ * Mark `{ critical: true }` only if your extension being down should fail the
349
+ * engine's readiness probe (rarely — most extensions are optional).
350
+ */
351
+ onHealthCheck?: (name: string, run: () => Promise<{
352
+ ok: boolean;
353
+ error?: string;
354
+ detail?: Record<string, unknown>;
355
+ }> | {
356
+ ok: boolean;
357
+ error?: string;
358
+ detail?: Record<string, unknown>;
359
+ }, opts?: {
360
+ critical?: boolean;
361
+ }) => void;
362
+ /**
363
+ * Register a route on the engine's GLOBAL app, outside the extension's
364
+ * `/ext/<name>/` namespace. Use sparingly — most routes should live on
365
+ * the sub-app provided to `register()`. Valid cases:
366
+ *
367
+ * - Public CDN-style endpoints with stable user-facing URLs
368
+ * (e.g. `/share/:token` for shared file links).
369
+ * - User-deployed handlers whose path shape is dictated by the user
370
+ * (e.g. `/api/fn/:name` for edge functions).
371
+ *
372
+ * Extensions on `mountStrategy: 'subapp'` use this to keep specific
373
+ * routes at fixed root-relative paths even though the rest of the
374
+ * extension lives under `/ext/<name>/`. Public routes are re-registered
375
+ * on each engine rebuild — disabling the extension makes them disappear
376
+ * just like sub-app routes.
377
+ *
378
+ * @example
379
+ * ctx.registerPublicRoute({
380
+ * method: 'GET',
381
+ * path: '/share/:token',
382
+ * handler: async (c) => { ... },
383
+ * });
384
+ */
385
+ registerPublicRoute(spec: PublicRouteSpec): void;
386
+ /**
387
+ * Tell every engine replica, this one included, that something this
388
+ * extension caches changed. Engine 3.0.0-beta.90 and later; refused to a
389
+ * worker-isolated extension. See `ExtensionBroadcast`.
390
+ */
391
+ broadcast?: ExtensionBroadcast;
392
+ /**
393
+ * Engine-internal helpers. Stable across patch versions but may break across
394
+ * minor versions. First-party extensions only.
395
+ */
396
+ internals: Omit<ExtensionInternals<DB>, MembersLockedFor<C>>;
397
+ }
398
+ /**
399
+ * Engine-internal helpers passed via `ctx.internals.*`.
400
+ * Each field is the live engine singleton or function — extensions should never
401
+ * import these directly from `../../../packages/engine/src/...` paths.
402
+ */
403
+ export interface ExtensionInternals<DB = unknown> {
404
+ /**
405
+ * Insert one row into a collection table (`zvd_<name>`). The row goes
406
+ * through the engine's field pipeline first, as a `ctx.db` insert does: type
407
+ * validation, deserialization, field encryption and the collection's
408
+ * validation rules. Pass RAW values — do not deserialize or encrypt them
409
+ * yourself. A row the pipeline refuses throws and nothing is written.
410
+ */
411
+ dynamicInsert: (db: any, collection: string, values: Record<string, unknown>) => Promise<unknown>;
412
+ /**
413
+ * The three an extension needs to render a collection the way the engine's
414
+ * own data routes do: the access check, the column mask, and the filter
415
+ * compiler. `content/pages` renders arbitrary collections for a portal
416
+ * audience and has to apply exactly the rules `/api/data` applies —
417
+ * reimplementing them would be a second, quietly diverging copy of the
418
+ * authorisation path.
419
+ */
420
+ checkAccess: (db: Kysely<DB>, user: Pick<RequestUser, 'id' | 'scopes'> & {
421
+ role?: string;
422
+ }, collection: string, action: string) => Promise<boolean>;
423
+ applyColumnAccess: (record: Record<string, unknown>, access: {
424
+ hidden: Set<string>;
425
+ readOnly: Set<string>;
426
+ }) => Record<string, unknown>;
427
+ /**
428
+ * Compile one filter into a SQL condition, over the operators in `FilterOp`.
429
+ */
430
+ buildCondition: (key: string, condition: {
431
+ op: FilterOp;
432
+ value?: unknown;
433
+ }) => RawBuilder<boolean>;
434
+ /** Introspect a Postgres schema — returns tables, columns, types, indexes, FKs. */
435
+ introspectSchema: (db: any, schemaName?: string, excludePatterns?: string[], dryRun?: boolean) => Promise<any[]>;
436
+ /** Invalidate the cached validation rules for a collection. */
437
+ invalidateRulesCache: (collection: string) => void;
438
+ /**
439
+ * Evaluate a user-authored validation expression, safely.
440
+ *
441
+ * `refused` is distinct from `failed` on purpose: an expression the engine
442
+ * declines to run has not passed and has not failed, and a rule editor that
443
+ * reports either would be lying to whoever is writing the rule.
444
+ *
445
+ * Use this instead of `new Function` or `eval`. A Function body closes over
446
+ * the global scope, so an expression stored by any tenant admin could reach
447
+ * `process` and `Bun` from inside the engine process.
448
+ */
449
+ evaluateExpressionRule: (expression: string, value: unknown) => {
450
+ status: 'passed';
451
+ } | {
452
+ status: 'failed';
453
+ } | {
454
+ status: 'refused';
455
+ reason: string;
456
+ };
457
+ /**
458
+ * The same, for a `transition` rule: `value` is being written, `previous` is
459
+ * the stored value (`null` on create). Engine 3.0.0-beta.85 and later.
460
+ */
461
+ evaluateTransitionRule: (expression: string, value: unknown, previous: unknown) => {
462
+ status: 'passed';
463
+ } | {
464
+ status: 'failed';
465
+ } | {
466
+ status: 'refused';
467
+ reason: string;
468
+ };
469
+ /** Vet an expression before storing it. A `transition` rule also sees `previous`. */
470
+ checkValidationExpression: (expression: string, ruleType?: string) => {
471
+ ok: true;
472
+ } | {
473
+ ok: false;
474
+ reason: string;
475
+ };
476
+ /**
477
+ * Create, toggle or delete a validation rule. `ctx.db` only reads
478
+ * `zv_validation_rules`; this writes it as the engine for the caller the
479
+ * `/ext/*` gate admitted for `c`. An instance rule (`tenant_id` null) binds
480
+ * every tenant's writes and only an instance admin writes one; a tenant admin
481
+ * writes rules of the request's tenant only (the engine sets `tenant_id`),
482
+ * which add to the instance rules and never relax one, and toggles or deletes
483
+ * only those. Anyone else (an API key, a member) throws. Answers the stored
484
+ * row (the removed one for `delete`), or `null` when no rule the caller may
485
+ * write has that id. A `custom`, `nlp` or `transition` rule whose expression
486
+ * does not compile throws, as does a second instance rule with the same
487
+ * field, rule type and config (SQLSTATE 23505 on `errno`). Audited: an
488
+ * instance rule as an instance event, a tenant rule in its tenant. Engine
489
+ * 3.0.0-beta.88 and later.
490
+ */
491
+ writeValidationRule: (c: Context, write: ValidationRuleWrite) => Promise<Record<string, unknown> | null>;
492
+ /**
493
+ * Create or delete a rule group (`AND` / `OR` over a field's rules). Groups
494
+ * are instance-wide like the rules they combine, so the same caller rule
495
+ * applies: an instance admin only, written as the engine, audited. A second
496
+ * group with the same name on a collection throws (SQLSTATE 23505 on
497
+ * `errno`). Answers the stored row (the removed one for `delete`), or `null`
498
+ * when no group has that id. Engine 3.0.0-beta.88 and later.
499
+ */
500
+ writeValidationRuleGroup: (c: Context, write: ValidationRuleGroupWrite) => Promise<Record<string, unknown> | null>;
501
+ /**
502
+ * Run a callback inside a tenant transaction, outside any request.
503
+ *
504
+ * `ctx.reqDb(c)` covers request handlers. Background work — scheduled tasks,
505
+ * queue workers, fire-and-forget jobs — has no `c` and so had nothing: it ran
506
+ * on the engine's global pool with no tenant context at all. `data/export`
507
+ * and `data/import` documented that in a comment and called the fix a
508
+ * follow-up.
509
+ *
510
+ * The tenant must come from wherever the work was ENQUEUED; a job has no
511
+ * caller to inherit one from. Inside the callback the handle behaves exactly
512
+ * like a request's: the tenant GUC is set and `SET LOCAL ROLE` applied, so
513
+ * the isolation policies bind.
514
+ *
515
+ * Only the tenant the work already runs as — the request's, or the job's —
516
+ * is entered without a capability. Another tenant, or any tenant where none
517
+ * runs (load time, a timer), needs `tenant:enter` (or `db:admin`, which
518
+ * implies it); without it the promise rejects.
519
+ * A fire-and-forget job started from a handler keeps the handler's tenant.
520
+ *
521
+ * await ctx.internals.withTenantIsolation(tenantId, async (db) => {
522
+ * await db.selectFrom('zvd_things').selectAll().execute();
523
+ * });
524
+ */
525
+ withTenantIsolation: <T>(tenantId: string, fn: (db: Kysely<DB>) => Promise<T>) => Promise<T>;
526
+ /**
527
+ * The instance's own read policies, so an extension can honour them.
528
+ *
529
+ * `ctx.db` gives an extension the TENANT boundary — the Postgres policies
530
+ * bind, and rows from another company are unreachable. It gives nothing for
531
+ * the two access rules an operator writes inside a tenant: the RLS rules at
532
+ * `/api/rls`, which hide rows from a user, and the column permissions that
533
+ * hide a field from a role. Those live in the engine and, until now, only the
534
+ * engine could read them.
535
+ *
536
+ * So an extension serving the same data as a core route enforced strictly
537
+ * less, and nothing said so. `data/export` is the worked example: the engine's
538
+ * `/api/export` gained both guards, its own copy kept `selectAll()` inside a
539
+ * tenant transaction, and the Studio calls the extension. The fix was
540
+ * impossible to write on that side — not overlooked, unavailable.
541
+ *
542
+ * Ungated, deliberately. Every other guarded member of this bag grants
543
+ * authority; these only ever remove rows and columns from a result. An
544
+ * extension that cannot call them does not become safer, it becomes the
545
+ * loophole.
546
+ *
547
+ * const cols = await ctx.internals.getColumnAccess(coll, role);
548
+ * const q = ctx.internals.applyRlsFilters(base, filters);
549
+ */
550
+ /**
551
+ * Apply field encryption to a value the operator marked `encrypted: true`.
552
+ * No-op when `isEncrypted` is false, when the value is not a string, or when
553
+ * it is already encrypted.
554
+ *
555
+ * Not `encryptSecret`: that is gated behind the `secrets` capability, which
556
+ * also hands over `decryptSecret`. Writing a row correctly should not cost the
557
+ * power to read every stored secret — and that trade is why `data/import`
558
+ * stored marked columns in PLAINTEXT rather than declaring the capability.
559
+ *
560
+ * Throws when `FIELD_ENCRYPTION_KEY` is unset and the field is marked, which
561
+ * is the engine's posture on the same path: a column an operator marked
562
+ * sensitive is not silently downgraded.
563
+ */
564
+ maybeEncrypt: (value: unknown, isEncrypted: boolean) => Promise<unknown>;
565
+ /**
566
+ * The other half. Without it an extension can write a secret it cannot read
567
+ * back, so it stores plaintext instead — which is how a signing secret ends
568
+ * up readable by anyone with database access.
569
+ *
570
+ * Passes through values that do not carry the `enc:v1:` prefix, so adopting
571
+ * encryption on an existing column is safe: rows written before keep working,
572
+ * rows written after are encrypted at rest.
573
+ */
574
+ maybeDecrypt: (value: unknown, isEncrypted: boolean) => Promise<unknown>;
575
+ /**
576
+ * `role` is optional because the engine does not depend on it: the roles a
577
+ * policy matches come from `getUserRoles(user.id)`, and Better-Auth does not
578
+ * populate `role` on a session at all. The engine's own callers cast it in
579
+ * rather than having one. Demanding it here only made every extension invent
580
+ * a value the engine ignores.
581
+ */
582
+ getRlsFilters: (collection: string, user: {
583
+ id: string;
584
+ email?: string;
585
+ role?: string;
586
+ rlsBypass?: boolean;
587
+ authorUserId?: string | null;
588
+ }, authType: 'session' | 'api_key') => Promise<RlsFilter[]>;
589
+ /** Apply what `getRlsFilters` returned to a query builder. */
590
+ applyRlsFilters: <Q>(query: Q, filters: RlsFilter[]) => Q;
591
+ /**
592
+ * Columns this role may not read, and may not write.
593
+ *
594
+ * No db parameter: the host resolves the handle. Column permissions are
595
+ * instance configuration rather than tenant rows, so letting each extension
596
+ * pick a handle would only be a way to get it wrong.
597
+ */
598
+ getColumnAccess: (collection: string, role: string,
599
+ /**
600
+ * The acting user's id. Optional, and additive — omitting it means no
601
+ * exemption, which is the refusing direction, so an extension written
602
+ * against the two-argument form keeps working and keeps masking.
603
+ *
604
+ * Pass it to have the host resolve `data:view_all_columns` for that
605
+ * identity. That permission is how "god sees everything" is expressed for
606
+ * columns: `checkPermission` returns true for a god user before consulting
607
+ * any policy, and everything else is deny-by-default. Without the id there
608
+ * is no identity to resolve it for, so even a god is masked.
609
+ *
610
+ * For an API key pass the principal itself (`c.get('user')`): its bare
611
+ * `apikey:<id>` names no issuer, and a key's columns are bounded by its
612
+ * issuer's, so a bare key id sees none.
613
+ */
614
+ userId?: string | {
615
+ id: string;
616
+ authorUserId?: string | null;
617
+ }) => Promise<{
618
+ hidden: Set<string>;
619
+ readOnly: Set<string>;
620
+ }>;
621
+ /**
622
+ * The single role behind a user — what `getColumnAccess` keys on. Drawn from
623
+ * Casbin, the one source of roles: `god` (the instance attribute) > `member`
624
+ * (the `g <user> member *` row every account gets) > `public`. A user's full
625
+ * role set is `getUserRoles`.
626
+ */
627
+ resolveUserRole: (user: {
628
+ id?: string;
629
+ role?: string;
630
+ }) => Promise<string>;
631
+ /**
632
+ * The engine's whole read gate for one caller on one collection: row policies,
633
+ * extension query alters, entity-access checks (`view`) and column
634
+ * permissions, resolved together — what every engine read path uses. Prefer it
635
+ * to composing `getRlsFilters` + `getColumnAccess`, which leaves out the alters
636
+ * and entity checks another extension registered.
637
+ *
638
+ * const scope = await ctx.internals.readScope(coll, user, 'session');
639
+ * const rows = await scope.keep(await scope.query(db.selectFrom(t).selectAll()).execute());
640
+ * return rows.map(scope.shape);
641
+ */
642
+ readScope: (collection: string, user: {
643
+ id: string;
644
+ email?: string;
645
+ role?: string;
646
+ rlsBypass?: boolean;
647
+ }, authType: 'session' | 'api_key') => Promise<ReadScope>;
648
+ /**
649
+ * Write one record exactly as `POST /api/data/:collection` does — access check,
650
+ * column permissions, hooks, then revision, webhooks, flows and realtime — and
651
+ * answer with that route's status and JSON body (201 and the row on success).
652
+ *
653
+ * Acts as the caller the engine authenticated for `c`, the handler's own
654
+ * request context: session or API key, with the key's scopes and authorship.
655
+ * There is no way to name another identity. Throws outside that request (a
656
+ * job, a listener, a context kept from an earlier request). Needs `data:write`.
657
+ */
658
+ createRecord: (c: Context, collection: string, data: Record<string, unknown>) => Promise<DataApiAnswer>;
659
+ /**
660
+ * `PATCH /api/data/:collection/:id`, as `createRecord`: 404 for a row the
661
+ * caller cannot see, 403 for one they may not change. With `expect`, as
662
+ * `host.collections` `update`: the write happens only if each listed field
663
+ * currently holds one of the given values, checked on the locked row;
664
+ * otherwise 409, code `precondition_failed`.
665
+ */
666
+ updateRecord: (c: Context, collection: string, id: string, data: Record<string, unknown>, options?: {
667
+ expect?: UpdateExpect;
668
+ }) => Promise<DataApiAnswer>;
669
+ /** `DELETE /api/data/:collection/:id`, as `updateRecord`. */
670
+ deleteRecord: (c: Context, collection: string, id: string) => Promise<DataApiAnswer>;
671
+ /**
672
+ * Read one record exactly as `GET /api/data/:collection/:id` does — permission,
673
+ * RLS, column rules — as the same caller as `createRecord`. 200 and the record,
674
+ * 404 for one the caller cannot see. Throws outside the request.
675
+ *
676
+ * In one of the extension's `publicRoutes` the caller is the anonymous
677
+ * visitor: the tenant's `public` role, as `GET /api/data` serves it, whatever
678
+ * session the request carries; it holds no grant until an operator gives one.
679
+ * The request is charged once to the anonymous read rate limit; over it, the
680
+ * read throws the 429 (ADR 0020, 3.0.0-beta.99; it threw there before).
681
+ */
682
+ readRecord: (c: Context, collection: string, id: string) => Promise<DataApiAnswer>;
683
+ /** `GET /api/data/:collection` with the route's own query parameters, as `readRecord`. */
684
+ listRecords: (c: Context, collection: string, query?: DataApiReadQuery) => Promise<DataApiAnswer>;
685
+ /** Is this user an administrator of the current tenant? */
686
+ /**
687
+ * The tenant to add as an explicit `tenant_id =` beside the RLS policy, or
688
+ * `null` when one must not be added.
689
+ *
690
+ * The policy reads `tenant_id = ANY (…)` over an array the planner does not
691
+ * see until execution, so it cannot drive an ordered index scan: a read that
692
+ * filters and orders walks `created_at` and discards whatever the policy
693
+ * excludes. Measured on 300 000 rows: 46 ms, every row discarded to return 25.
694
+ *
695
+ * Performance only — the policy still decides what may be seen, and an
696
+ * equality can only narrow what it already allows. `null` whenever the reach
697
+ * is wider than one tenant, so the safe shape is:
698
+ *
699
+ * const t = ctx.internals.getSingleTenantId();
700
+ * if (t) q = q.where('tenant_id', '=', t);
701
+ */
702
+ getSingleTenantId: () => string | null;
703
+ /**
704
+ * Display names for a set of user ids, as `{ [id]: name }`. Ids with no row,
705
+ * or with a null name, are absent — render the id instead.
706
+ *
707
+ * Extensions cannot read the Better-Auth `user` table, and rendering "who
708
+ * asked for this" is a real need: `workflow/approvals` had been joining that
709
+ * table directly through a gap in the table guard. This hands over names and
710
+ * nothing else, so printing a name never requires a grant on a table that
711
+ * also holds emails and roles.
712
+ */
713
+ getUserNames: (userIds: string[]) => Promise<Record<string, string>>;
714
+ isTenantAdmin: (userId: string) => Promise<boolean>;
715
+ /**
716
+ * Facts about the tenant this work runs as, scoped by the engine — the path
717
+ * in place of raw SQL on `"user"`, `zv_tenant_users`, `zv_tenants`,
718
+ * `pg_class`, `zvd_permissions` and `zv_settings`, which `ctx.db` refuses.
719
+ */
720
+ /** People with a membership in force in the running tenant, and its owners/admins. */
721
+ countMembers: () => Promise<{
722
+ total: number;
723
+ admins: number;
724
+ }>;
725
+ /** Collection count, and a planner row estimate (`null` on a multi-tenant instance). */
726
+ getDataStats: () => Promise<{
727
+ collections: number;
728
+ records_estimate: number | null;
729
+ }>;
730
+ /** Role names granted in the running tenant or in every tenant. */
731
+ listRoles: () => Promise<string[]>;
732
+ /** A setting the instance marks public (`is_public`); `null` otherwise. */
733
+ getPublicSetting: (key: string) => Promise<unknown>;
734
+ /** Append to the audit log, as a row of the running tenant (instance-level where none runs). The engine stamps `metadata.extension` with the caller. */
735
+ audit: (event: {
736
+ type: string;
737
+ userId?: string;
738
+ resourceId?: string;
739
+ resourceType?: string;
740
+ metadata?: Record<string, unknown>;
741
+ ip?: string;
742
+ }) => Promise<void>;
743
+ /**
744
+ * Run `fn` acting as the system inside the running tenant, for the named
745
+ * collections (`['products']`, not `zvd_products`): collection permissions
746
+ * stand down for `ctx.db` during the call; tenant isolation and the table
747
+ * guard do not. Needs the `data:system` capability. Every call is audited
748
+ * with the extension, the user, the collections and `reason`.
749
+ */
750
+ asSystem: <T>(collections: readonly string[], fn: () => Promise<T>, opts?: {
751
+ reason?: string;
752
+ }) => Promise<T>;
753
+ /**
754
+ * Queue one of this extension's jobs from a handler of one of its
755
+ * `publicRoutes` — an inbound signed webhook verifies the signature, stores
756
+ * the raw event, enqueues, and the job does the writes through
757
+ * `host.collections` (ADR 0018). `c` is the handler's request context. The job
758
+ * lists the route in its manifest `fromPublicRoutes`; `input` must match its
759
+ * schema. The enqueue joins the request transaction: it rolls back with the
760
+ * request. The job has no author. Needs `data:system`; audited. Throws
761
+ * anywhere else. Absent before 3.0.0-beta.97.
762
+ */
763
+ enqueue?: (c: Context, job: string, input: unknown) => Promise<string>;
764
+ /**
765
+ * The running tenant's recent audit rows, newest first — never another
766
+ * tenant's, never instance-level events. `limit` defaults to 20, capped at
767
+ * 100. No `metadata` or `ip`. Needs the `audit:read` capability.
768
+ */
769
+ readAuditActivity: (query?: {
770
+ limit?: number;
771
+ eventType?: string;
772
+ resourceType?: string;
773
+ since?: Date | string;
774
+ }) => Promise<{
775
+ id: string;
776
+ event_type: string;
777
+ user_id: string | null;
778
+ resource_type: string | null;
779
+ resource_id: string | null;
780
+ created_at: Date;
781
+ }[]>;
782
+ /**
783
+ * How many of the running tenant's audit rows match, from `since` on. Same
784
+ * scope as `readAuditActivity`; a number, so ungated.
785
+ */
786
+ countAuditActivity: (query: {
787
+ since: Date | string;
788
+ eventType?: string;
789
+ resourceType?: string;
790
+ }) => Promise<number>;
791
+ /**
792
+ * Instance-level admin, as distinct from admin-within-a-tenant.
793
+ *
794
+ * `checkPermission(userId, 'admin', '*')` is TRUE for a delegated tenant
795
+ * owner inside their own domain — the `tenant_owner` policy is `('*','*','*')`
796
+ * there. That is the right answer for tenant-scoped screens and the wrong one
797
+ * for anything that reaches the instance: raw SQL, schema changes, role
798
+ * grants. Use this for those.
799
+ */
800
+ requireInstanceAdmin: (userId: string) => Promise<boolean>;
801
+ /** Run an Edge Function in the sandbox (used by developer/edge-functions). */
802
+ runEdgeFunction: (...args: any[]) => Promise<unknown>;
803
+ /** Cross-extension hook registry (e.g. trash purge, scheduled cleanups). */
804
+ extensionRegistry: any;
805
+ /** Queue an HTML→PDF render via the worker pool. */
806
+ generatePDFAsync: (html: string, options?: Record<string, unknown>) => Promise<unknown>;
807
+ /**
808
+ * Move a file to the trash bucket (soft delete with TTL): `(db, fileId, deletedBy)`.
809
+ * Only a file of the tenant the request or job runs as; outside one it rejects.
810
+ */
811
+ moveToTrash: (...args: any[]) => Promise<unknown>;
812
+ /** Enqueue an asynchronous DDL job (Ghost Tables, large alters). */
813
+ enqueueDDLJob: (...args: any[]) => Promise<unknown>;
814
+ /**
815
+ * Validate that a URL targets a public, non-internal address (SSRF safety).
816
+ * Synchronous — throws on a blocked URL and returns nothing. Safe to call from
817
+ * a sync context such as a zod `superRefine`. This checks only the literal
818
+ * host text; prefer {@link assertPublicUrl} wherever you can await.
819
+ */
820
+ validatePublicUrl: (url: string) => void;
821
+ /**
822
+ * DNS-aware SSRF check: everything `validatePublicUrl` does, plus rejecting
823
+ * hostnames that RESOLVE into private space (an attacker-owned name with an A
824
+ * record pointing at cloud metadata). MUST be awaited.
825
+ */
826
+ /**
827
+ * Resolves to the address to connect to, or null when there is nothing to pin
828
+ * (an IP literal, or a name that did not resolve). Ignoring the value keeps
829
+ * the previous behaviour; using it closes the DNS rebinding race, which is
830
+ * what the host's own `safeFetch` does.
831
+ */
832
+ assertPublicUrl: (url: string) => Promise<string | null>;
833
+ /**
834
+ * `fetch` with the SSRF guard applied where it has to be.
835
+ *
836
+ * Validating a URL before calling `fetch` is not enough on its own: fetch
837
+ * follows redirects, so a public host answering 302 to 169.254.169.254
838
+ * walks past a check performed on the original URL. This re-validates
839
+ * every redirect target, under a hop limit. Prefer it over `fetch` for
840
+ * any URL a user or a stored record can influence.
841
+ */
842
+ safeFetch: (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
843
+ /**
844
+ * SSRF guard for an admin-configured endpoint that is ALLOWED to be
845
+ * self-hosted (local Ollama on `http://localhost:11434`, an internal
846
+ * Meilisearch, on-prem object storage). Permits private ranges but rejects
847
+ * cloud-metadata hosts such as 169.254.169.254. Use this — NOT
848
+ * `validatePublicUrl` / `assertPublicUrl` — for provider "base URL" settings,
849
+ * otherwise every self-hosted deployment breaks. Synchronous; throws when
850
+ * the URL is blocked.
851
+ */
852
+ assertNonMetadataUrl: (url: string, label?: string) => void;
853
+ /** Send an in-app notification to a user (writes to zv_notifications system table). */
854
+ sendNotification: (db: any, input: {
855
+ user_id: string;
856
+ type?: string;
857
+ title: string;
858
+ message?: string;
859
+ data?: unknown;
860
+ }) => Promise<void>;
861
+ /**
862
+ * Sign in a user your extension has already verified (SSO bridge: LDAP,
863
+ * SAML, OIDC). The session is written by the engine's better-auth — its pool
864
+ * and, with Valkey, its session cache — so `auth.api.getSession` accepts the
865
+ * cookie; `ctx.db` cannot reach the `session` table. Refuses a deactivated
866
+ * user with an error whose `code` is `'account_disabled'`.
867
+ *
868
+ * `db` is your transaction: pass the one that provisioned the user. A user it
869
+ * created gets their session when it commits, and none if it rolls back.
870
+ * `replaceExisting` ends the user's other sessions once this one is written
871
+ * and your request commits. Returns the `Set-Cookie` header value for your
872
+ * Response. Needs `auth:session`.
873
+ */
874
+ createBetterAuthSession: (db: any, userId: string, opts?: {
875
+ ipAddress?: string;
876
+ userAgent?: string;
877
+ ttlSeconds?: number;
878
+ crossDomain?: boolean;
879
+ replaceExisting?: boolean;
880
+ }) => Promise<{
881
+ token: string;
882
+ setCookie: string;
883
+ }>;
884
+ /**
885
+ * Encrypt a secret (LDAP bind passwords, third-party API keys, …) with
886
+ * the engine's AES-256-GCM field encryption key (FIELD_ENCRYPTION_KEY).
887
+ * Output is prefixed with `enc:v1:`, so calling this on an already-
888
+ * encrypted value is a no-op. Throws if FIELD_ENCRYPTION_KEY is unset;
889
+ * extensions should refuse the write rather than persist plaintext.
890
+ */
891
+ encryptSecret: (plaintext: string) => Promise<string>;
892
+ /**
893
+ * HMAC-SHA256 under the instance auth secret, hex encoded. A compatibility
894
+ * surface for `auth/scim`'s stored bearer-token hashes — not a general MAC.
895
+ */
896
+ deriveTokenHash: (raw: string) => Promise<string>;
897
+ /**
898
+ * Quoted, formula-safe CSV cell. Ungated: a pure string function with no
899
+ * authority. Every extension that exports CSV was writing its own escaping,
900
+ * and quoting alone does not stop a spreadsheet executing a cell that starts
901
+ * with `=`.
902
+ */
903
+ csvCell: (value: unknown) => string;
904
+ /** Rows → CSV document, using `csvCell` for every cell. */
905
+ recordsToCsv: (records: Record<string, unknown>[]) => string;
906
+ /**
907
+ * Reverse of `encryptSecret`. Returns the plaintext if the value has
908
+ * the `enc:v1:` prefix; otherwise returns the value as-is so reads of
909
+ * legacy unencrypted rows still work during a rolling encryption rollout.
910
+ */
911
+ decryptSecret: (value: string) => Promise<string>;
912
+ /**
913
+ * Delete a user exactly as `DELETE /api/users/:id` does: revoke their
914
+ * sessions (database AND cache), drop their grants, delete the row and audit
915
+ * `user.deleted` with `who`. `db` is the handle the row delete and the audit
916
+ * row run on — pass your transaction so they commit with it. Resolves `false`
917
+ * when there is no such user. Needs the `auth:users` capability.
918
+ *
919
+ * `actorUserId` must be a real user id (the audit column references "user");
920
+ * a non-user actor — a SCIM token, the erased subject — goes in `actor`.
921
+ */
922
+ deleteUser: (db: unknown, userId: string, who: {
923
+ actorUserId?: string | null;
924
+ actor?: string;
925
+ reason: string;
926
+ metadata?: Record<string, unknown>;
927
+ }) => Promise<boolean>;
928
+ /**
929
+ * End every session a user has, in the database AND the cache — `ctx.db`
930
+ * cannot reach either. Needs the `auth:users` capability.
931
+ */
932
+ revokeUserSessions: (userId: string) => Promise<void>;
933
+ /**
934
+ * What the engine's own tables hold about a user — profile, their audit
935
+ * rows in every tenant and at instance level, notifications, the API keys
936
+ * they created (names, never secrets) and their approval requests — for a
937
+ * data-subject access request. `null` when there is no such user. Needs the
938
+ * `auth:users` capability.
939
+ */
940
+ exportUserData: (userId: string) => Promise<{
941
+ profile: {
942
+ id: string;
943
+ name: string | null;
944
+ email: string;
945
+ created_at: string;
946
+ } | null;
947
+ audit_log: Array<{
948
+ action: string;
949
+ collection: string | null;
950
+ record_id: string | null;
951
+ created_at: string;
952
+ }>;
953
+ notifications: Array<{
954
+ title: string;
955
+ message: string | null;
956
+ type: string | null;
957
+ is_read: boolean;
958
+ created_at: string;
959
+ }>;
960
+ api_keys: Array<{
961
+ name: string;
962
+ key_prefix: string | null;
963
+ scopes: unknown;
964
+ created_at: string;
965
+ }>;
966
+ approval_requests: Array<{
967
+ id: string;
968
+ collection: string;
969
+ record_id: string | null;
970
+ status: string;
971
+ requested_at: string;
972
+ }>;
973
+ } | null>;
974
+ /**
975
+ * `false` stops the user signing in by ANY method (password, magic link,
976
+ * passkey, OAuth, SSO) and revokes their sessions; `true` lets them back in
977
+ * with the credentials they had. Instance-wide: a user has one sign-in, not
978
+ * one per tenant. `db` is your transaction — pass the one that may already
979
+ * have written the user's row. Needs the `auth:users` capability.
980
+ *
981
+ * A ban records your extension as its source (`"user".ban_source =
982
+ * 'ext:<your name>'`, taken by the host, not from you). Banning an account
983
+ * that is already banned keeps the first source. `true` lifts ANY ban,
984
+ * an administrator's included — kept for extensions written before
985
+ * `liftOwnBan`; to undo your own ban, use `liftOwnBan`.
986
+ */
987
+ setUserActive: (db: unknown, userId: string, active: boolean) => Promise<void>;
988
+ /**
989
+ * Lift the user's ban only if YOUR extension placed it (through
990
+ * `setUserActive(…, false)`); resolves whether it did. A ban an
991
+ * administrator, another extension or raw SQL placed stays. Needs the
992
+ * `auth:users` capability.
993
+ */
994
+ liftOwnBan: (db: unknown, userId: string) => Promise<boolean>;
995
+ /** Whether at most one tenant exists — then every user belongs to it. Ungated. */
996
+ isSingleTenantInstance: () => Promise<boolean>;
997
+ /**
998
+ * The account for `email` (case-insensitive), created when there is none:
999
+ * verified, no password, never god, in no tenant. Works while
1000
+ * self-registration is off. Inside `withTenantIsolation` it is created in
1001
+ * that transaction, and a rollback takes it back. An account that already
1002
+ * exists comes back only if the running tenant has a claim to it: a member
1003
+ * here with no power elsewhere beyond plain membership, any account but god
1004
+ * and the instance admins on a single-tenant instance, or a bare record (no
1005
+ * credential, membership or grant). Anyone else is `account_exists`: they join
1006
+ * through an invitation, which proves they control the address.
1007
+ */
1008
+ provisionUser: (input: {
1009
+ email: string;
1010
+ name?: string;
1011
+ }) => Promise<{
1012
+ user: ProvisionedUser;
1013
+ created: boolean;
1014
+ }>;
1015
+ /**
1016
+ * Users of the running tenant — a membership there, lapsed included — or
1017
+ * every user on a single-tenant instance (`membership: null`). By creation
1018
+ * order; `limit` defaults to 100, at most 1000.
1019
+ */
1020
+ listTenantUsers: (db: unknown, query?: {
1021
+ email?: string;
1022
+ userId?: string;
1023
+ limit?: number;
1024
+ offset?: number;
1025
+ }) => Promise<Array<ProvisionedUser & {
1026
+ membership: TenantMembershipInfo | null;
1027
+ }>>;
1028
+ /**
1029
+ * Rename or re-address a user the running tenant ALONE holds: a membership
1030
+ * here (any user on a single-tenant instance), not god, not an instance admin,
1031
+ * no membership or grant in any other tenant (`user_not_owned` otherwise).
1032
+ * `db` is your transaction.
1033
+ */
1034
+ updateUserProfile: (db: unknown, userId: string, patch: {
1035
+ name?: string;
1036
+ email?: string;
1037
+ }) => Promise<ProvisionedUser>;
1038
+ /**
1039
+ * Make the user a `member` (default) or `viewer` of the running tenant, or
1040
+ * switch between the two, with the matching tenant role. Dates are kept: a
1041
+ * membership that ended is not reopened. An `owner`/`admin` is refused.
1042
+ */
1043
+ addTenantMember: (db: unknown, userId: string, role?: 'member' | 'viewer') => Promise<'added' | 'role_changed' | 'unchanged'>;
1044
+ /**
1045
+ * Remove the user from the running tenant with every role they hold in it.
1046
+ * `orphaned`: no tenant and nothing else holds the account now — deleting it
1047
+ * (`deleteUser`, `auth:users`) is your call. `inForceAnywhere`: a membership
1048
+ * in force remains in some tenant. An owner or admin of the tenant (in the
1049
+ * default tenant, an instance admin) is refused, `role_not_allowed`.
1050
+ */
1051
+ removeTenantMember: (db: unknown, userId: string) => Promise<{
1052
+ removed: boolean;
1053
+ orphaned: boolean;
1054
+ inForceAnywhere: boolean;
1055
+ }>;
1056
+ /**
1057
+ * Set when the user's membership of the running tenant ends: `'now'`, an
1058
+ * ISO-8601 instant, or `null` (open-ended). `ifInForce` changes only a
1059
+ * membership in force; `ifValidTo` only one whose end is still exactly that
1060
+ * value. `null` when the user is no member here. An owner or admin is
1061
+ * refused, `role_not_allowed`.
1062
+ */
1063
+ setTenantMembershipEnd: (db: unknown, userId: string, validTo: string | null, guard?: {
1064
+ ifInForce?: boolean;
1065
+ ifValidTo?: string | null;
1066
+ }) => Promise<{
1067
+ changed: boolean;
1068
+ previousValidTo: string | null;
1069
+ validTo: string | null;
1070
+ inForceAnywhere: boolean;
1071
+ } | null>;
1072
+ }
1073
+ /** A user as `ctx.internals` identity provisioning returns it. */
1074
+ export interface ProvisionedUser {
1075
+ id: string;
1076
+ email: string;
1077
+ name: string;
1078
+ emailVerified: boolean;
1079
+ createdAt: string;
1080
+ updatedAt: string;
1081
+ }
1082
+ /** A user's membership of the running tenant. */
1083
+ export interface TenantMembershipInfo {
1084
+ role: 'owner' | 'admin' | 'member' | 'viewer';
1085
+ validFrom: string;
1086
+ /** `null`: open-ended. */
1087
+ validTo: string | null;
1088
+ inForce: boolean;
1089
+ }
1090
+ /**
1091
+ * Entity-access scope handed to each extension via `ctx.entityAccess`.
1092
+ *
1093
+ * Use this for row-level authorization that cannot be expressed via roles
1094
+ * alone: "only the owner can view this", "drafts editable only by author",
1095
+ * "manager can approve only their direct reports", etc.
1096
+ *
1097
+ * Semantics: first `deny` wins. If no checks are registered for a table,
1098
+ * access is allowed (no extension cares about it).
1099
+ *
1100
+ * @example
1101
+ * ctx.entityAccess.register({
1102
+ * table: 'zvd_payroll',
1103
+ * async check(record, user, op) {
1104
+ * if (user.roles.includes('hr')) return 'allow';
1105
+ * if (op === 'view' && record.user_id === user.id) return 'allow';
1106
+ * return 'deny';
1107
+ * },
1108
+ * });
1109
+ *
1110
+ * Scoped to the registering extension — automatically cleaned up on unload.
1111
+ */
1112
+ export interface EntityAccessScope {
1113
+ register(def: {
1114
+ table: string;
1115
+ check: (record: any, user: any, op: 'view' | 'update' | 'delete') => ('allow' | 'deny') | Promise<'allow' | 'deny'>;
1116
+ }): void;
1117
+ list(): Array<{
1118
+ table: string;
1119
+ }>;
1120
+ unregisterAll(): void;
1121
+ }
1122
+ /**
1123
+ * Query-alter scope handed to each extension via `ctx.queryAlter`.
1124
+ *
1125
+ * Each call to `register({ table, alter })` is automatically tagged with the
1126
+ * registering extension's name so it can be cleaned up on unload — extensions
1127
+ * don't manage that lifecycle themselves.
1128
+ */
1129
+ export interface QueryAlterScope {
1130
+ register(def: {
1131
+ /** Table name to attach the alter to (typically `zvd_<collection>`). */
1132
+ table: string;
1133
+ /**
1134
+ * Mutates the Kysely query builder before execution. Must return a chained
1135
+ * builder. `qb` and `user` are typed `any` in the SDK so extensions don't
1136
+ * need to depend on engine internals; cast as needed.
1137
+ */
1138
+ alter: (qb: any, user: any) => any;
1139
+ }): void;
1140
+ list(): Array<{
1141
+ table: string;
1142
+ }>;
1143
+ unregisterAll(): void;
12
1144
  }
13
- export interface ZveltioExtension {
1145
+ /**
1146
+ * Inter-extension service registry.
1147
+ *
1148
+ * Extensions publish services here for other extensions to consume — a Drupal-style
1149
+ * services container. Services are keyed by string names (e.g. `'ai.providers'`,
1150
+ * `'crm.contacts.lookup'`). Consumers should treat `get()` returning `null` as a
1151
+ * recoverable signal (the providing extension is not active) and either skip the
1152
+ * feature or surface a clear error to the user.
1153
+ *
1154
+ * Extensions MUST NOT directly import from other extensions — communication goes
1155
+ * exclusively through this registry.
1156
+ *
1157
+ * The instance passed to each extension via `ctx.services` is **scoped to that
1158
+ * extension** — anything `register()`-ed through it is automatically attributed
1159
+ * to the extension and gets cleaned up on unload (disable / hot-reload).
1160
+ * `register()` is idempotent within a scope (replaces on duplicate), so an
1161
+ * extension's `register()` can safely run multiple times during hot-reload.
1162
+ */
1163
+ /**
1164
+ * A manifest `dependencies` / `optionalDependencies` entry. A required one must be
1165
+ * installed for this extension to load; an optional one need not be — its
1166
+ * services then read as `null`. Either way, the extensions named in these two
1167
+ * lists are the only ones whose services `ctx.services` hands this one.
1168
+ */
1169
+ export interface ManifestDependency {
14
1170
  name: string;
1171
+ minVersion?: string;
1172
+ }
1173
+ /**
1174
+ * Cross-replica messages, scoped to the extension that holds them: `publish`
1175
+ * sends under its name and `on` hears only its own, so no extension can speak
1176
+ * for another or for the engine.
1177
+ *
1178
+ * Meant for invalidation — "firm X's providers changed, read them again" — not
1179
+ * for data: send an id, let each replica read the rest from the database.
1180
+ */
1181
+ export interface ExtensionBroadcast {
1182
+ /**
1183
+ * Deliver `data` to this extension's `on(name)` handlers on every replica,
1184
+ * this one included, once the current transaction commits (at once outside
1185
+ * one; never after a rollback). Each handler runs in the publisher's tenant
1186
+ * transaction, so `ctx.db` there is that tenant's. Rejects a `name` outside
1187
+ * `[A-Za-z0-9._:-]{1,64}` and a message over the bus limit (~7.9 KB of JSON).
1188
+ * Delivery is at most once: see `onMissed`.
1189
+ */
1190
+ publish(name: string, data?: unknown): Promise<void>;
1191
+ /** Run `handler` for each `name` message; it receives `data` as JSON gave it back. */
1192
+ on(name: string, handler: (data: unknown) => void | Promise<void>): () => void;
1193
+ /**
1194
+ * Run `handler` when this replica may have missed messages (its bus
1195
+ * connection came back), outside any tenant: drop every cache the messages
1196
+ * keep fresh.
1197
+ */
1198
+ onMissed(handler: () => void | Promise<void>): () => void;
1199
+ }
1200
+ export interface ServiceRegistry {
1201
+ /**
1202
+ * Publish a service under a name, which must be `<this extension's name>.<x>`.
1203
+ * Idempotent: re-registering the same name from the same extension replaces.
1204
+ * Throws if a different extension already owns that name.
1205
+ */
1206
+ register<T = unknown>(name: string, value: T): void;
1207
+ /** Remove a service this extension previously registered. No-op if not owned. */
1208
+ unregister(name: string): void;
1209
+ /**
1210
+ * Get a service. Returns `null` if not registered (an optional dependency
1211
+ * that is not installed). Throws if its owner is not this extension or one in
1212
+ * its manifest `dependencies` / `optionalDependencies`.
1213
+ */
1214
+ get<T = unknown>(name: string): T | null;
1215
+ /** Check if a service is registered. Throws as `get` does for an undeclared owner. */
1216
+ has(name: string): boolean;
1217
+ /**
1218
+ * Wait for a service to be registered. Resolves immediately if already there.
1219
+ * Rejects after `timeoutMs` (default 30s) if never registered.
1220
+ */
1221
+ waitFor<T = unknown>(name: string, timeoutMs?: number): Promise<T>;
1222
+ /** List all registered service names — useful for debugging. */
1223
+ list(): string[];
1224
+ }
1225
+ /**
1226
+ * Pre-write hook payloads.
1227
+ *
1228
+ * Subscribe via `ctx.events.onBefore('record.beforeInsert', handler)`. The
1229
+ * handler is async and receives a mutable payload. Call:
1230
+ * - `payload.mutate({ ... })` to merge fields into the in-flight write —
1231
+ * subsequent handlers and the data layer see the patched values.
1232
+ * - `payload.abort('reason')` to reject the write — the HTTP response
1233
+ * becomes 422 with code `EXT_HOOK_ABORTED` and the reason in the body.
1234
+ *
1235
+ * Hooks run sequentially in registration order. Throwing a non-abort error
1236
+ * surfaces as 500.
1237
+ */
1238
+ export interface BeforeInsertPayload {
1239
+ collection: string;
1240
+ data: Record<string, unknown>;
1241
+ userId: string;
1242
+ abort(reason: string): never;
1243
+ mutate(patch: Record<string, unknown>): void;
1244
+ }
1245
+ export interface BeforeUpdatePayload {
1246
+ collection: string;
1247
+ id: string;
1248
+ before: Record<string, unknown>;
1249
+ patch: Record<string, unknown>;
1250
+ userId: string;
1251
+ abort(reason: string): never;
1252
+ mutate(patch: Record<string, unknown>): void;
1253
+ }
1254
+ export interface BeforeDeletePayload {
1255
+ collection: string;
1256
+ id: string;
1257
+ record: Record<string, unknown>;
1258
+ userId: string;
1259
+ abort(reason: string): never;
1260
+ }
1261
+ /**
1262
+ * Native scheduled task. Extensions declare these via `ZveltioExtension.schedules()`.
1263
+ *
1264
+ * Specify exactly ONE timing field:
1265
+ * - `intervalMs`: re-run every N milliseconds.
1266
+ * - `at`: run once a day at `{ hour, minute }` (server's local timezone).
1267
+ * - `cron`: reserved for future cron-expression support; currently logged
1268
+ * as unsupported and the schedule is skipped.
1269
+ *
1270
+ * Every invocation persists to the `zv_extension_schedule_runs` table with
1271
+ * status `running` → (`ok` | `failed` | `dlq`). `failed` rows trigger another
1272
+ * attempt up to `retry.maxAttempts`; the final failed attempt is recorded as
1273
+ * `dlq` (dead letter — admin can replay manually).
1274
+ *
1275
+ * Cross-instance: NOT yet coordinated. Multiple engine replicas will each run
1276
+ * the same schedule until distributed locking lands.
1277
+ */
1278
+ export interface ExtensionSchedule<DB = any> {
1279
+ /** Stable name, unique within this extension. Used as the persistence key. */
1280
+ name: string;
1281
+ intervalMs?: number;
1282
+ at?: {
1283
+ hour: number;
1284
+ minute: number;
1285
+ };
1286
+ cron?: string;
1287
+ /** Async work to perform. `runId` is the row id in zv_extension_schedule_runs. */
1288
+ handler: (ctx: ExtensionContext<DB>, runId: string) => Promise<void>;
1289
+ retry?: {
1290
+ maxAttempts?: number;
1291
+ backoffMs?: number;
1292
+ };
1293
+ /** Reserved — single-engine assumption today. Documented behaviour. */
1294
+ singleton?: boolean;
1295
+ /**
1296
+ * Run once per active tenant where this extension is active, each run inside
1297
+ * that tenant's transaction, so `ctx.db` sees that tenant's rows. Without it
1298
+ * the handler runs once with no tenant in scope, and a table under tenant RLS
1299
+ * answers for the root tenant only. A tenant that fails does not stop the
1300
+ * others; the run then fails naming it, and a retry runs every tenant again,
1301
+ * so the handler must be safe to repeat.
1302
+ */
1303
+ perTenant?: boolean;
1304
+ }
1305
+ /**
1306
+ * Spec for a route registered on the engine's global app via
1307
+ * `ctx.registerPublicRoute()`. See the `registerPublicRoute` field on
1308
+ * `ExtensionContext` for usage guidance.
1309
+ */
1310
+ export interface PublicRouteSpec {
1311
+ method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'ALL';
1312
+ /** Absolute path on the global app, e.g. `'/share/:token'`. */
1313
+ path: string;
1314
+ /** Hono handler — receives the Context, returns a Response (or via c.json). */
1315
+ handler: (c: any) => any;
1316
+ }
1317
+ /**
1318
+ * Mount strategy for the extension's Hono routes (S3-01).
1319
+ *
1320
+ * - `'global'` (default, legacy): the `register(app, ctx)` callback receives
1321
+ * the engine's global Hono app. Extension owns full URL paths and typically
1322
+ * mounts under `/api/<feature>`. Routes cannot be cleanly de-registered at
1323
+ * runtime — disabling the extension requires an app rebuild.
1324
+ *
1325
+ * - `'subapp'`: the `register(subApp, ctx)` callback receives a per-extension
1326
+ * Hono instance. The engine mounts it at `/ext/<extension-name>` so the
1327
+ * extension's routes appear under that prefix. Disable/enable is cheap
1328
+ * (next rebuild drops the sub-app); no cross-extension URL collisions.
1329
+ * New extensions should use this. Migrating an existing extension is
1330
+ * lock-step with updating its Studio bundle URL calls.
1331
+ */
1332
+ export type MountStrategy = 'global' | 'subapp';
1333
+ /** The interface every Zveltio extension must implement. */
1334
+ /**
1335
+ * The interface every Zveltio extension implements.
1336
+ *
1337
+ * @example Untyped (legacy / new extensions before codegen)
1338
+ * const ext: ZveltioExtension = { ... }
1339
+ *
1340
+ * @example Typed via codegen (S4-01 + S4-02)
1341
+ * import type { ExtensionSchema as DB } from './.zveltio/db.js';
1342
+ * const ext: ZveltioExtension<DB> = {
1343
+ * async register(app, ctx) {
1344
+ * // ctx.db is Kysely<DB> — full autocomplete on table + column names
1345
+ * const items = await ctx.db.selectFrom('zv_my_items').selectAll().execute();
1346
+ * }
1347
+ * };
1348
+ */
1349
+ export interface ZveltioExtension<DB = any, C extends string = Capability> {
1350
+ /** Unique name — must match manifest.json `name` exactly (e.g. `'hr/employees'`). */
1351
+ name: string;
1352
+ /** Category shown in the marketplace (e.g. `'hr'`, `'finance'`, `'content'`). */
15
1353
  category: string;
16
- register: (app: Hono, ctx: ExtensionContext) => Promise<void>;
1354
+ /**
1355
+ * How the engine mounts the extension's routes. Defaults to `'global'` for
1356
+ * backward compatibility with existing extensions. New extensions should
1357
+ * declare `'subapp'`. See `MountStrategy` for details.
1358
+ */
1359
+ mountStrategy?: MountStrategy;
1360
+ /**
1361
+ * Called once when the extension is activated.
1362
+ * Register Hono routes, subscribe to events, etc.
1363
+ */
1364
+ register: (app: Hono, ctx: ExtensionContext<DB, C>) => Promise<void>;
1365
+ /** Register custom Studio field types contributed by this extension. */
17
1366
  registerFieldTypes?: (registry: FieldTypeRegistryAPI) => void;
1367
+ /** Return absolute paths to SQL migration files, run in order on first activation. */
18
1368
  getMigrations?: () => string[];
1369
+ /**
1370
+ * Return the list of scheduled tasks. Called once after `register()`. The
1371
+ * engine's cron runner picks them up and starts polling.
1372
+ */
1373
+ schedules?: () => ExtensionSchedule<DB>[];
1374
+ /**
1375
+ * Called when the extension is disabled or the server shuts down.
1376
+ * Close database connections, clear timers, etc.
1377
+ * Note: Hono routes cannot be de-registered at runtime — they persist until restart.
1378
+ */
1379
+ cleanup?: () => Promise<void>;
1380
+ /**
1381
+ * The implementations of the manifest's `actions`, by name — one each, and no
1382
+ * more: the engine refuses to load an extension whose two lists differ. The
1383
+ * engine serves each at `POST /ext/<name>/actions/<action>`: it checks the
1384
+ * declared permission, validates the body against the declared `input`, and
1385
+ * runs the function with that body inside the request's transaction. A throw
1386
+ * fails the request and rolls back everything the action wrote.
1387
+ */
1388
+ actions?: Record<string, ExtensionAction>;
1389
+ /**
1390
+ * The implementations of the manifest's `jobs`, by name — one each, and no
1391
+ * more, as for `actions`. An action enqueues one (`ActionHost.enqueue`) inside
1392
+ * its request transaction, so a job whose action failed never runs. The engine
1393
+ * runs it after that commits, out of any request, in the enqueuing tenant; a
1394
+ * throw fails the run, which is retried as the manifest's `retry` says.
1395
+ */
1396
+ jobs?: Record<string, ExtensionJob>;
1397
+ }
1398
+ /**
1399
+ * One action: business logic over the input the engine validated. Returns the
1400
+ * response's `result`; throws `ActionRefusal` to answer the caller with a 4xx.
1401
+ */
1402
+ export type ExtensionAction = (input: unknown, host: ActionHost) => Promise<unknown>;
1403
+ /**
1404
+ * How an action reaches data: the data API, as the caller, inside the request's
1405
+ * transaction — permissions, RLS, column rules, hooks and audit are the route's.
1406
+ * Only the collections the manifest declares for the action: `reads` for
1407
+ * `read`/`list`, `writes` for `insert`/`update`/`delete` (which also need
1408
+ * `data:write`). A refused write throws with the data API's status, and the
1409
+ * request fails with it.
1410
+ */
1411
+ export interface ActionHost {
1412
+ collections: HostCollections;
1413
+ /**
1414
+ * The IANA zone "today" means for the request's tenant: the tenant's own
1415
+ * setting, else the instance's, else `UTC`. Pair with `todayIn`.
1416
+ */
1417
+ timezone: string;
1418
+ /**
1419
+ * Queue one of the jobs this action's manifest entry lists in `enqueues`, with
1420
+ * an `input` its schema accepts — anything else throws. Written in the request
1421
+ * transaction: the job exists only if the request commits. Needs `data:system`.
1422
+ * Resolves to the job's id.
1423
+ */
1424
+ enqueue(job: string, input: unknown): Promise<string>;
1425
+ /**
1426
+ * Run an action of an extension this one depends on (ADR 0014). The calling
1427
+ * action's manifest entry lists it in `calls` as `<extension>.<action>`; the
1428
+ * engine checks the caller holds that action's permission, validates `input`
1429
+ * against its schema, and runs it in the same request transaction, its writes
1430
+ * carrying the called extension's name. Resolves to what the action returns; a
1431
+ * refusal it throws reaches the caller unchanged. An action run this way cannot
1432
+ * run another. Absent on engines before 3.0.0-beta.94.
1433
+ */
1434
+ actions?: {
1435
+ run(extension: string, action: string, input: unknown): Promise<unknown>;
1436
+ };
1437
+ }
1438
+ /** The data API, through `ActionHost` or `JobHost`, for the collections the manifest declares. */
1439
+ export interface HostCollections {
1440
+ /** The record, or `null` when the caller cannot see one with this id. */
1441
+ read(collection: string, id: string): Promise<Record<string, unknown> | null>;
1442
+ /** `GET /api/data/:collection`'s body: `{ records, … }`. */
1443
+ list(collection: string, query?: DataApiReadQuery): Promise<Record<string, unknown>>;
1444
+ insert(collection: string, data: Record<string, unknown>): Promise<Record<string, unknown>>;
1445
+ /**
1446
+ * With `expect`, the update happens only if the row's current value of each
1447
+ * listed field is one of the given values — checked on the row locked for the
1448
+ * write, so a concurrent update waits and is then tested against the new row.
1449
+ * Otherwise it throws with status 409, code `precondition_failed`. Each field
1450
+ * must be one the caller can read.
1451
+ */
1452
+ update(collection: string, id: string, data: Record<string, unknown>, options?: {
1453
+ expect?: UpdateExpect;
1454
+ }): Promise<Record<string, unknown>>;
1455
+ delete(collection: string, id: string): Promise<void>;
1456
+ }
1457
+ /**
1458
+ * A precondition on an update: field name to the values it may currently hold.
1459
+ * Values compare as text (`String(value)`), `null` as SQL NULL.
1460
+ */
1461
+ export type UpdateExpect = Record<string, readonly (string | number | boolean | null)[]>;
1462
+ /** One job: work over the input the engine validated when it was enqueued. */
1463
+ export type ExtensionJob = (input: unknown, host: JobHost) => Promise<void>;
1464
+ /**
1465
+ * How a job reaches data. A job has no caller: it acts as the extension, with
1466
+ * exactly the job's declared `reads` (read) and `writes` (create, update,
1467
+ * delete) — the data API's checks, as for an API key holding those scopes — in
1468
+ * the tenant it was enqueued in, in a transaction of its own. Rows it writes are
1469
+ * authored by the user whose action enqueued it.
1470
+ */
1471
+ export interface JobHost {
1472
+ collections: HostCollections;
1473
+ /** As `ActionHost.timezone`, for the tenant that enqueued the job. */
1474
+ timezone: string;
19
1475
  }
20
1476
  export interface StudioExtensionAPI {
21
1477
  registerRoute(route: StudioRoute): void;
22
1478
  registerFieldType(ft: StudioFieldType): void;
1479
+ registerAssetPreview(handler: AssetPreviewHandler): void;
1480
+ /**
1481
+ * Register a component into a named slot in core Studio (S3-03).
1482
+ * Slot names are stable strings declared by core (e.g. `dashboard.widgets`,
1483
+ * `collections.list.toolbar`). See the developer guide for the full list.
1484
+ */
1485
+ registerSlot(name: string, contribution: SlotContribution): void;
1486
+ /**
1487
+ * Drupal-style `hook_form_alter` for Studio forms (S3-02). The hook
1488
+ * receives a `form` object with `addField`, `hideField`, `reorder`,
1489
+ * `addValidator`. Form IDs are stable strings (e.g. `core:user-edit`,
1490
+ * `collection:zvd_contacts:edit`).
1491
+ */
1492
+ registerFormAlter(formId: string, hook: FormAlterHook): void;
23
1493
  engineUrl: string;
24
1494
  }
1495
+ /** S3-03: a single slot contribution. */
1496
+ export interface SlotContribution {
1497
+ /** Svelte component to render. */
1498
+ component: any;
1499
+ /**
1500
+ * Lower runs first. Default 100. Two contributions with the same
1501
+ * priority render in registration order.
1502
+ */
1503
+ priority?: number;
1504
+ /**
1505
+ * Optional predicate. If returns false, the contribution is skipped.
1506
+ * `ctx` carries whatever the slot host passes (typically `{ user }`).
1507
+ */
1508
+ visible?: (ctx: Record<string, unknown>) => boolean;
1509
+ /** Optional props passed to the component. */
1510
+ props?: Record<string, unknown>;
1511
+ }
1512
+ /** S3-02: signature of a form-alter hook. */
1513
+ export type FormAlterHook = (form: FormAlterAPI, ctx: Record<string, unknown>) => void;
1514
+ /** S3-02: the surface form-alter hooks operate on. */
1515
+ export interface FormAlterAPI {
1516
+ addField(spec: {
1517
+ after?: string;
1518
+ before?: string;
1519
+ field: FormField;
1520
+ }): void;
1521
+ hideField(name: string): void;
1522
+ reorder(order: string[]): void;
1523
+ addValidator(fieldName: string, validator: (value: unknown) => string | null): void;
1524
+ readonly fields: ReadonlyArray<FormField>;
1525
+ }
1526
+ /** S3-02: minimal form schema shape consumed by alters + renderers. */
1527
+ export interface FormSchema {
1528
+ /** Stable form id; matched by `registerFormAlter`. */
1529
+ id: string;
1530
+ /** Fields in render order. */
1531
+ fields: FormField[];
1532
+ /** Free-form metadata renderers may inspect. */
1533
+ meta?: Record<string, unknown>;
1534
+ }
1535
+ /** S3-02: a single form field as seen by alters. */
1536
+ export interface FormField {
1537
+ name: string;
1538
+ type: string;
1539
+ label?: string;
1540
+ required?: boolean;
1541
+ hidden?: boolean;
1542
+ options?: Array<string | {
1543
+ value: string;
1544
+ label: string;
1545
+ }>;
1546
+ validators?: Array<(value: unknown) => string | null>;
1547
+ /** Anything else the renderer needs. Renderers + alters share this loosely. */
1548
+ [k: string]: unknown;
1549
+ }
25
1550
  export interface StudioRoute {
26
1551
  path: string;
27
1552
  component: any;
28
- label: string;
29
- icon: string;
30
- category: string;
1553
+ /** Sidebar label. Optional — when omitted, the route exists for routing
1554
+ * but doesn't surface in the nav (use together with `hidden` for purely
1555
+ * programmatic child routes). */
1556
+ label?: string;
1557
+ icon?: string;
1558
+ /** Sidebar group key. Optional; extensions that don't care about
1559
+ * grouping can leave it off. */
1560
+ category?: string;
31
1561
  children?: StudioRoute[];
1562
+ /** Display under a custom heading instead of the default category. Used
1563
+ * by extensions that want a localized group label (e.g. "Trasabilitate"). */
1564
+ parent?: string;
1565
+ /** Hide from the sidebar even when label is set. Useful for detail
1566
+ * pages (`/items/:id`) that are reachable via in-app navigation. */
1567
+ hidden?: boolean;
32
1568
  }
33
1569
  export interface StudioFieldType {
34
1570
  type: string;
@@ -42,5 +1578,29 @@ export interface StudioFieldType {
42
1578
  default: any;
43
1579
  }>;
44
1580
  }
1581
+ export interface AssetPreviewHandler {
1582
+ match: (asset: {
1583
+ url: string;
1584
+ name?: string;
1585
+ mimeType?: string;
1586
+ }) => boolean;
1587
+ component: any;
1588
+ }
1589
+ /**
1590
+ * Declare an extension together with the capabilities it uses, so `ctx` is typed
1591
+ * by them (roadmap R8). The list must match `permissions` in manifest.json —
1592
+ * the manifest is what the engine enforces and an administrator approves;
1593
+ * `zveltio extension validate` reports a difference.
1594
+ *
1595
+ * export default defineExtension(['secrets'], { name, category, register });
1596
+ *
1597
+ * Returns the extension unchanged, with the list attached as `capabilities`.
1598
+ */
1599
+ /** `ZveltioExtension`'s own default schema type, without spelling it again. */
1600
+ type DefaultExtensionDB = ZveltioExtension extends ZveltioExtension<infer D> ? D : never;
1601
+ export declare function defineExtension<const C extends readonly Capability[], DB = DefaultExtensionDB>(capabilities: C, extension: ZveltioExtension<DB, C[number]>): ZveltioExtension<DB, C[number]> & {
1602
+ readonly capabilities: C;
1603
+ };
45
1604
  export type { Hono };
1605
+ export * from './capabilities.js';
46
1606
  //# sourceMappingURL=index.d.ts.map