@autonoma-ai/sdk 0.2.1-canary.aa1079f → 0.2.2

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.
@@ -1,21 +1,24 @@
1
- /** Minimal SQL executor — wrap your DB connection (pg Pool, Prisma, Drizzle, etc.) into this. */
2
- interface SQLExecutor {
3
- /** Execute a SQL query with parameterized values. Returns rows as plain objects. */
4
- query<T = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<T[]>;
5
- /**
6
- * Execute a block within a transaction.
7
- * The callback receives an executor scoped to the transaction.
8
- * If the callback throws, the transaction is rolled back.
9
- */
10
- transaction<T>(fn: (tx: SQLExecutor) => Promise<T>): Promise<T>;
11
- }
1
+ import { ZodTypeAny, z } from 'zod';
2
+
3
+ /**
4
+ * Public types for the Autonoma SDK.
5
+ *
6
+ * The SDK is now factory-driven: every model the dashboard can create
7
+ * comes from a registered factory, and each factory carries a Zod input
8
+ * schema (and optional ref schema). There is no SQL introspection, no
9
+ * SQL fallback, and no executor on `HandlerConfig`. Factories that need
10
+ * DB access use whatever client the host already has.
11
+ */
12
+
12
13
  interface SchemaInfo {
13
14
  models: ModelInfo[];
15
+ /** Always emitted as `[]` in factory-driven mode; kept for wire-shape symmetry. */
14
16
  edges: FKEdge[];
17
+ /** Always emitted as `[]` in factory-driven mode; kept for wire-shape symmetry. */
15
18
  relations: SchemaRelation[];
16
19
  scopeField: string;
17
20
  }
18
- /** Maps a parent's relation field name to the child model and its FK */
21
+ /** Wire-shape relic emitted as an empty array in factory-driven mode. */
19
22
  interface SchemaRelation {
20
23
  parentModel: string;
21
24
  childModel: string;
@@ -24,6 +27,7 @@ interface SchemaRelation {
24
27
  }
25
28
  interface ModelInfo {
26
29
  name: string;
30
+ /** Cosmetic — snake_case of `name`; the dashboard renders it for display only. */
27
31
  tableName: string;
28
32
  fields: FieldInfo[];
29
33
  }
@@ -34,6 +38,7 @@ interface FieldInfo {
34
38
  isId: boolean;
35
39
  hasDefault: boolean;
36
40
  }
41
+ /** Wire-shape relic — emitted as an empty array in factory-driven mode. */
37
42
  interface FKEdge {
38
43
  from: string;
39
44
  to: string;
@@ -41,20 +46,6 @@ interface FKEdge {
41
46
  foreignField: string;
42
47
  nullable: boolean;
43
48
  }
44
- interface ResolvedEntitySpec {
45
- count: number;
46
- fields: Record<string, unknown>[];
47
- batch?: boolean;
48
- }
49
- interface CreateContext {
50
- testRunId: string;
51
- refs: Record<string, Record<string, unknown>[]>;
52
- }
53
- /** Scenario sent inline in the `up` request body */
54
- interface ScenarioDefinition {
55
- /** Nested tree: model name → array of node objects with nested children */
56
- create: Record<string, Record<string, unknown>[]>;
57
- }
58
49
  interface SdkInfo {
59
50
  language: string;
60
51
  orm: string;
@@ -63,42 +54,59 @@ interface SdkInfo {
63
54
  interface FactoryContext {
64
55
  /** All refs created so far, keyed by model name */
65
56
  refs: Record<string, Record<string, unknown>[]>;
66
- /** The SQL executor (for factories that need direct DB access) */
67
- executor: SQLExecutor;
68
- /** The detected or fallback scope value */
57
+ /** Logical scope value or testRunId fallback (kept for backwards-compat). */
69
58
  scenarioName: string;
70
59
  /** Unique ID for this test run */
71
60
  testRunId: string;
72
61
  }
73
- interface FactoryDefinition {
74
- /** Create a single entity. Receives pre-resolved fields (temp IDs already replaced). Must return at least { id }. */
75
- create: (data: Record<string, unknown>, ctx: FactoryContext) => Promise<Record<string, unknown>>;
76
- /** Optional teardown per record. If omitted, falls back to SQL DELETE. */
77
- teardown?: (record: Record<string, unknown>, ctx: FactoryContext) => Promise<void>;
78
- }
79
- type FactoryRegistry = Record<string, FactoryDefinition>;
62
+ /**
63
+ * Factory definition.
64
+ *
65
+ * The two type parameters are bound to the Zod schemas you pass in:
66
+ * - `TInput extends ZodTypeAny` the create input. `data` arrives
67
+ * already validated and typed as `z.infer<TInput>`, so your factory
68
+ * body doesn't need a manual `z.infer<...>` annotation.
69
+ * - `TRef extends ZodTypeAny` — the shape your `create` returns and
70
+ * `teardown` later receives. When `refSchema` is omitted, `TRef`
71
+ * widens to a generic `{ id; ... }` record so old factories keep
72
+ * compiling without a refSchema.
73
+ *
74
+ * Bind both at the call site by writing `defineFactory({...})` — TS
75
+ * infers the generics from the schema instances.
76
+ */
77
+ interface FactoryDefinition<TInput extends ZodTypeAny = ZodTypeAny, TRef extends ZodTypeAny | undefined = undefined> {
78
+ /**
79
+ * Create a single entity. Receives the validated input (parsed by
80
+ * `inputSchema`) and must return at least `{ id }`. When `refSchema`
81
+ * is set, the return type is constrained to `z.input<TRef>` so the
82
+ * teardown signature lines up exactly.
83
+ */
84
+ create: (data: z.infer<TInput>, ctx: FactoryContext) => Promise<RefRecord<TRef>> | RefRecord<TRef>;
85
+ /**
86
+ * Optional teardown per record. Receives whatever `create` returned —
87
+ * validated through `refSchema` first when one is registered. If
88
+ * omitted the model is left alone on `down`. There is no SQL fallback.
89
+ */
90
+ teardown?: (record: TRef extends ZodTypeAny ? z.infer<TRef> : Record<string, unknown> & {
91
+ id: string | number;
92
+ }, ctx: FactoryContext) => Promise<void> | void;
93
+ /** Required Zod schema for the create input — drives both validation and discover. */
94
+ inputSchema: TInput;
95
+ /** Optional Zod schema for the record returned by `create` (validated on teardown). */
96
+ refSchema?: TRef;
97
+ }
98
+ type RefRecord<TRef extends ZodTypeAny | undefined> = TRef extends ZodTypeAny ? z.input<TRef> : Record<string, unknown> & {
99
+ id: string | number;
100
+ };
101
+ type FactoryRegistry = Record<string, FactoryDefinition<any, any>>;
80
102
  interface HandlerConfig {
81
- /** SQL executor wrapping your database connection */
82
- executor: SQLExecutor;
83
103
  /** Scope field name (camelCase), e.g., 'organizationId' */
84
104
  scopeField: string;
85
- /** Database dialect. Defaults to 'postgres'. */
86
- dialect?: 'postgres' | 'mysql' | 'sqlite';
87
- /** DB schema name. Defaults to 'public' for Postgres. */
88
- dbSchema?: string;
89
- /**
90
- * Map scenario model names to DB table names.
91
- * Keys are model names (PascalCase), values are DB table names.
92
- * If omitted, auto-detected from information_schema with PascalCase inference.
93
- */
94
- tableNameMap?: Record<string, string>;
95
- /** Tables to exclude from introspection. Defaults to ['_prisma_migrations']. */
96
- excludeTables?: string[];
97
105
  /** Shared secret — known by both you and Autonoma. Used to verify HMAC signatures on incoming requests. */
98
106
  sharedSecret: string;
99
107
  /** Internal secret — only you know this. Used to sign the refs JWT token. Autonoma never sees it. */
100
108
  signingSecret: string;
101
- /** Factory definitions per model. If a factory exists for a model, it is used instead of raw SQL INSERT. */
109
+ /** Factory definitions per model. Required: every model the dashboard sends in `create` must have one. */
102
110
  factories?: FactoryRegistry;
103
111
  allowProduction?: boolean;
104
112
  /**
@@ -118,7 +126,7 @@ interface HandlerConfig {
118
126
  * Can modify the auth result before it is returned to the caller.
119
127
  */
120
128
  afterUp?: (context: HookContext, authResult: AuthResult) => Promise<AuthResult> | AuthResult;
121
- /** SDK identity metadata. Server and ORM adapters populate this. */
129
+ /** SDK identity metadata. Server adapters populate this. */
122
130
  sdk?: Partial<SdkInfo>;
123
131
  }
124
132
  interface AuthContext {
@@ -185,4 +193,4 @@ declare function topoSort(nodes: string[], edges: FKEdge[]): TopoSortResult;
185
193
  */
186
194
  declare function findDeferrableEdge(cycle: string[], edges: FKEdge[]): FKEdge | null;
187
195
 
188
- export { type AuthContext as A, type CreateContext as C, type DiscoverResponse as D, type FactoryDefinition as F, type HandlerConfig as H, type ModelInfo as M, type ResolvedEntitySpec as R, type SchemaInfo as S, type TopoSortResult as T, type UpResponse as U, type HandlerRequest as a, type HandlerResponse as b, type SQLExecutor as c, type ScenarioDefinition as d, type AuthCookie as e, type AuthResult as f, type DownResponse as g, type FKEdge as h, type FactoryContext as i, type FactoryRegistry as j, type FieldInfo as k, type HookContext as l, type SchemaRelation as m, type SdkInfo as n, findDeferrableEdge as o, topoSort as t };
196
+ export { type AuthContext as A, type DiscoverResponse as D, type FactoryRegistry as F, type HandlerConfig as H, type ModelInfo as M, type SchemaInfo as S, type TopoSortResult as T, type UpResponse as U, type HandlerRequest as a, type HandlerResponse as b, type FactoryDefinition as c, type AuthCookie as d, type AuthResult as e, type DownResponse as f, type FKEdge as g, type FactoryContext as h, type FieldInfo as i, type HookContext as j, type SchemaRelation as k, type SdkInfo as l, findDeferrableEdge as m, topoSort as t };
package/dist/graph.d.ts CHANGED
@@ -1 +1,2 @@
1
- export { h as FKEdge, T as TopoSortResult, o as findDeferrableEdge, t as topoSort } from './graph-OB0ohy_v.js';
1
+ export { g as FKEdge, T as TopoSortResult, m as findDeferrableEdge, t as topoSort } from './graph-Bh_9SEer.js';
2
+ import 'zod';
package/dist/index.d.ts CHANGED
@@ -1,6 +1,25 @@
1
- import { H as HandlerConfig, a as HandlerRequest, b as HandlerResponse, S as SchemaInfo, c as SQLExecutor, d as ScenarioDefinition, R as ResolvedEntitySpec, C as CreateContext, M as ModelInfo, F as FactoryDefinition } from './graph-OB0ohy_v.js';
2
- export { A as AuthContext, e as AuthCookie, f as AuthResult, D as DiscoverResponse, g as DownResponse, h as FKEdge, i as FactoryContext, j as FactoryRegistry, k as FieldInfo, l as HookContext, m as SchemaRelation, n as SdkInfo, U as UpResponse, o as findDeferrableEdge, t as topoSort } from './graph-OB0ohy_v.js';
1
+ import { H as HandlerConfig, a as HandlerRequest, b as HandlerResponse, F as FactoryRegistry, S as SchemaInfo, c as FactoryDefinition } from './graph-Bh_9SEer.js';
2
+ export { A as AuthContext, d as AuthCookie, e as AuthResult, D as DiscoverResponse, f as DownResponse, g as FKEdge, h as FactoryContext, i as FieldInfo, j as HookContext, M as ModelInfo, k as SchemaRelation, l as SdkInfo, U as UpResponse, m as findDeferrableEdge, t as topoSort } from './graph-Bh_9SEer.js';
3
+ import { ZodTypeAny } from 'zod';
3
4
 
5
+ /**
6
+ * Request routing for discover / up / down protocol actions.
7
+ *
8
+ * Factory-driven design: every model in `body.create` must have a
9
+ * registered factory. The SDK uses each factory's `inputSchema` (Zod)
10
+ * to validate inputs and to build the `discover` schema. Ordering for
11
+ * `up` and `down` comes from the create payload's `_alias` / `_ref`
12
+ * graph (see `payload-topo.ts`); there is no SQL introspection.
13
+ */
14
+
15
+ /**
16
+ * Substitute built-in tokens in field values: {{testRunId}}, {{index}},
17
+ * {{cycle(a,b,c)}}. Defense-in-depth: the test runner should substitute
18
+ * recipe variables before calling /up, but if a literal {{…}} slips
19
+ * through we fail loudly with UNRESOLVED_TOKEN rather than INSERT the
20
+ * raw string.
21
+ */
22
+ declare function resolveTokens(value: unknown, testRunId: string, index: number): unknown;
4
23
  declare const PROTOCOL_VERSION: string;
5
24
  declare function handleRequest(config: HandlerConfig, req: HandlerRequest): Promise<HandlerResponse>;
6
25
 
@@ -11,6 +30,13 @@ interface RefsPayload {
11
30
  refs: Record<string, Record<string, unknown>[]>;
12
31
  testRunId: string;
13
32
  environment: string;
33
+ /**
34
+ * Captured at `up` time so `down` can topo-sort teardown without
35
+ * re-parsing the create payload. Optional — older tokens omitted it
36
+ * and `down` falls back to refs-key insertion order.
37
+ */
38
+ aliasDependencies?: Record<string, string[]>;
39
+ aliasOwnerModel?: Record<string, string>;
14
40
  }
15
41
  /**
16
42
  * Sign refs into a JWT-like token (header.payload.signature).
@@ -28,50 +54,84 @@ declare function verifyRefs(token: string, secret: string): RefsPayload;
28
54
  */
29
55
  declare function fingerprint(value: unknown): string;
30
56
 
31
- /** A create operation produced by the tree resolver */
32
57
  interface CreateOp {
33
58
  model: string;
34
59
  fields: Record<string, unknown>;
35
60
  tempId: string;
36
- batch: boolean;
37
61
  }
38
- /**
39
- * A deferred FK update — emitted when a _ref points to a node that hasn't
40
- * been created yet (circular dependency). Resolved after all creates.
41
- */
42
- interface DeferredUpdate {
43
- /** Temp ID of the record that needs to be updated */
44
- targetTempId: string;
45
- /** Model name of the record to update */
46
- model: string;
47
- /** Field on the record that holds the deferred FK */
48
- field: string;
49
- /** Alias that will resolve to the FK value once created */
50
- refAlias: string;
51
- }
52
- /** Result of resolving a tree scenario */
53
62
  interface ResolvedTree {
54
63
  ops: CreateOp[];
55
- deferredUpdates: DeferredUpdate[];
56
- aliases: Map<string, string>;
57
- }
58
- /** A resolved reference to another node's id */
59
- interface RefNode {
60
- _ref: string;
64
+ /** alias → temp id assigned to the entity declaring that alias. */
65
+ aliases: Record<string, string>;
66
+ /** alias → model name, used by teardown to pick the right factory. */
67
+ aliasOwnerModel: Record<string, string>;
68
+ /** alias → list of aliases the owner depends on (may include unknowns). */
69
+ aliasDependencies: Record<string, string[]>;
61
70
  }
62
71
  /**
63
- * Resolve a nested scenario tree into an ordered list of create operations.
72
+ * Topo-sort a create payload into an ordered list of `CreateOp`.
73
+ *
74
+ * `create` is the dashboard's nested map `{ model: [entity, ...] }`.
75
+ * Each entity is an object; `_alias` (declared by dependency targets)
76
+ * and `_ref` (declared by dependents, anywhere in the field tree) are
77
+ * the only reserved keys.
78
+ *
79
+ * Throws INVALID_BODY if the payload references an alias that is never
80
+ * declared, or if the alias graph contains a cycle.
81
+ */
82
+ declare function resolvePayloadTree(create: Record<string, unknown>): ResolvedTree;
83
+ /**
84
+ * Order models for teardown.
85
+ *
86
+ * With `aliasDependencies` available (newer refs tokens carry it), we
87
+ * run the same Kahn's topo sort over models — derived from aggregating
88
+ * each alias's dependencies — and return the *reverse* topo so children
89
+ * are torn down before parents.
90
+ *
91
+ * Without it (older refs tokens), fall back to reversing the insertion
92
+ * order of `refs` keys, which is what the SDK always did for factory
93
+ * teardown.
94
+ */
95
+ declare function computeTeardownOrder(refs: Record<string, unknown[]>, aliasDependencies?: Record<string, string[]>, aliasOwnerModel?: Record<string, string>): string[];
96
+
97
+ /**
98
+ * Build the SDK's wire-shape schema from registered factories.
99
+ *
100
+ * The dashboard's `discover` response carries a `schema` block listing
101
+ * every model the host can create. With the old SDK that came from
102
+ * `information_schema` queries; with this one it comes from each
103
+ * factory's `inputSchema` (a Zod schema).
104
+ *
105
+ * The mapping from a Zod type to the dashboard's coarse type string is
106
+ * intentionally lossy — the dashboard only branches on a handful of
107
+ * categories (`string`, `integer`, `boolean`, `timestamp`, ...) and
108
+ * treats everything else as opaque JSON.
109
+ */
110
+
111
+ /**
112
+ * Map a Zod schema to the SDK's coarse type string.
113
+ *
114
+ * Unknown schemas fall back to `string` — the conservative default the
115
+ * dashboard renders as a free-form text input.
116
+ */
117
+ declare function fieldTypeFromZod(schema: ZodTypeAny): string;
118
+ /**
119
+ * Build the SDK's discover-time schema from registered factories.
64
120
  *
65
- * Walks depth-first. Parent-child FKs are wired automatically.
66
- * Handles both directions:
67
- * - FK on child (Application.organizationId Organization): set child FK to parent ID
68
- * - FK on parent (Member.userId User): create child first, set parent FK to child ID
121
+ * `edges` and `relations` are emitted as empty arrays. They were
122
+ * populated from FK introspection in the old design; here the create
123
+ * payload's `_alias` / `_ref` graph carries equivalent information at
124
+ * request time, so the static schema doesn't need them.
125
+ */
126
+ declare function buildSchemaFromFactories(factories: FactoryRegistry, scopeField: string): SchemaInfo;
127
+ /**
128
+ * Serialise a `SchemaInfo` to the JSON shape the dashboard expects.
69
129
  *
70
- * Circular FK cycles (e.g. Application.mainBranchId Branch.applicationId) are handled
71
- * transparently: the nullable FK is omitted on the first create and emitted as a
72
- * DeferredUpdate to be applied via UPDATE after all records exist.
130
+ * Field names in the wire JSON are camelCase (`isRequired`, not
131
+ * `is_required`); kept here so both halves of the discover response
132
+ * live in one place.
73
133
  */
74
- declare function resolveTree(create: Record<string, Record<string, unknown>[]>, schema: SchemaInfo): ResolvedTree;
134
+ declare function schemaToWire(schema: SchemaInfo): Record<string, unknown>;
75
135
 
76
136
  interface CheckResult {
77
137
  valid: boolean;
@@ -87,117 +147,48 @@ interface CheckError {
87
147
  message: string;
88
148
  fix?: string;
89
149
  }
150
+ interface CheckScenario {
151
+ /** Flat map: model name → list of entity payloads (with `_alias` / `_ref`). */
152
+ create: Record<string, Record<string, unknown>[]>;
153
+ }
90
154
  /**
91
- * Dry-run a scenario against a real database.
92
- * Runs the full up down cycle and returns structured errors.
155
+ * Dry-run a scenario through the same handler the dashboard hits. Runs
156
+ * `up` then `down` and returns structured errors if either fails.
93
157
  */
94
- declare function checkScenario(executor: SQLExecutor, scenario: ScenarioDefinition, options?: {
95
- scopeField: string;
96
- dialect?: HandlerConfig['dialect'];
97
- dbSchema?: string;
98
- tableNameMap?: Record<string, string>;
158
+ declare function checkScenario(factories: FactoryRegistry, scenario: CheckScenario, options?: {
159
+ scopeField?: string;
99
160
  sharedSecret?: string;
100
161
  signingSecret?: string;
101
162
  auth?: HandlerConfig['auth'];
102
163
  }): Promise<CheckResult>;
103
- /**
104
- * Check multiple scenarios sequentially.
105
- */
106
- declare function checkAllScenarios(executor: SQLExecutor, scenarios: ScenarioDefinition[], options?: {
107
- scopeField: string;
108
- dialect?: HandlerConfig['dialect'];
109
- dbSchema?: string;
110
- tableNameMap?: Record<string, string>;
111
- sharedSecret?: string;
112
- signingSecret?: string;
113
- auth?: HandlerConfig['auth'];
114
- }): Promise<CheckResult[]>;
115
-
116
- /** Database dialect abstraction — generates dialect-specific SQL strings. */
117
- interface Dialect {
118
- readonly name: 'postgres' | 'mysql' | 'sqlite';
119
- /** Parameter placeholder for index (1-based). Postgres: $1, MySQL/SQLite: ? */
120
- param(index: number): string;
121
- /** Quote an identifier. Postgres: "name", MySQL: `name` */
122
- quoteId(name: string): string;
123
- /** Whether INSERT ... RETURNING is supported */
124
- readonly supportsReturning: boolean;
125
- /** SQL to list all base tables in a schema/database */
126
- tablesSQL(schema: string): string;
127
- /** SQL to list all columns for all tables in a schema/database */
128
- columnsSQL(schema: string): string;
129
- /** SQL to list primary key columns */
130
- primaryKeysSQL(schema: string): string;
131
- /** SQL to list foreign key relationships */
132
- foreignKeysSQL(schema: string): string;
133
- /** SQL to list enum types and their values */
134
- enumsSQL(schema: string): string;
135
- }
136
- declare function getDialect(name?: 'postgres' | 'mysql' | 'sqlite'): Dialect;
137
-
138
- /** Internal result including name mapping tables */
139
- interface IntrospectionResult {
140
- schema: SchemaInfo;
141
- /** model name → DB table name */
142
- tableMap: Map<string, string>;
143
- /** model name → (field name → DB column name) */
144
- columnMaps: Map<string, Map<string, string>>;
145
- /** model name → (field name → Postgres enum type name). Only populated for Postgres. */
146
- enumTypeMaps: Map<string, Map<string, string>>;
147
- }
148
- /**
149
- * Introspect a database via information_schema to build SchemaInfo.
150
- *
151
- * Auto-maps DB names (snake_case) to model names (PascalCase) and
152
- * field names (camelCase). Override with `tableNameMap`.
153
- */
154
- declare function introspectDatabase(executor: SQLExecutor, dialect: Dialect, config: {
155
- scopeField: string;
156
- schema?: string;
157
- tableNameMap?: Record<string, string>;
158
- excludeTables?: string[];
159
- }): Promise<IntrospectionResult>;
164
+ declare function checkAllScenarios(factories: FactoryRegistry, scenarios: CheckScenario[], options?: Parameters<typeof checkScenario>[2]): Promise<CheckResult[]>;
160
165
 
161
166
  /**
162
- * Create entities via raw SQL INSERT.
167
+ * Define a factory for creating entities via user code.
163
168
  *
164
- * Entities arrive pre-sorted by FK order (handler does topo-sort via tree.ts).
165
- * Each model in `spec` is inserted sequentially; within a model, batch mode
166
- * uses a single multi-row INSERT while normal mode inserts one row at a time.
169
+ * Every factory must declare an `inputSchema` (Zod) so the SDK can:
170
+ * 1. validate the create payload before invoking `create`, and
171
+ * 2. derive the `discover` schema from the Zod shape (no DB introspection).
167
172
  *
168
- * For dialects with RETURNING (Postgres): INSERT ... RETURNING *
169
- * For dialects without (MySQL): INSERT then SELECT via LAST_INSERT_ID()
173
+ * The generics are inferred from the schemas you pass in: `create`'s
174
+ * `data` argument is typed as `z.infer<typeof inputSchema>`, and
175
+ * `teardown`'s `record` argument is typed as `z.infer<typeof refSchema>`
176
+ * when one is set. No call-site `z.infer<...>` annotations needed.
170
177
  */
171
- declare function createEntities(executor: SQLExecutor, dialect: Dialect, tableMap: Map<string, string>, columnMaps: Map<string, Map<string, string>>, spec: Record<string, ResolvedEntitySpec>, _context: CreateContext, enumTypeMaps?: Map<string, Map<string, string>>, schemaModels?: ModelInfo[]): Promise<Record<string, Record<string, unknown>[]>>;
178
+ declare function defineFactory<TInput extends ZodTypeAny, TRef extends ZodTypeAny | undefined = undefined>(definition: FactoryDefinition<TInput, TRef>): FactoryDefinition<TInput, TRef>;
172
179
 
173
- /**
174
- * Tear down all data scoped to a value, in reverse topological order.
175
- *
176
- * Strategy:
177
- * 1. Find the scope root model (e.g. Organization) from FK edges
178
- * 2. Any model with a FK pointing to the scope root is "scoped"
179
- * 3. Delete scoped models by their FK = scopeValue
180
- * 4. Delete non-scoped models by their record IDs from refs
181
- * 5. Delete the scope root entity last by id = scopeValue
182
- */
183
- /**
184
- * Compute the teardown order for models (reverse topological order).
185
- * Returns an array of model names in the order they should be deleted,
186
- * plus the scope root model name (deleted last) and cycle info for FK nullification.
187
- */
188
- declare function computeTeardownOrder(schema: SchemaInfo): {
189
- order: string[];
190
- scopeRootModel: string | null;
191
- cycles: string[][];
192
- scopeFieldByModel: Map<string, string>;
180
+ declare class AutonomaError extends Error {
181
+ readonly code: string;
182
+ readonly status: number;
183
+ constructor(message: string, code: string, status: number);
184
+ }
185
+ declare const Errors: {
186
+ readonly unknownAction: (action: string) => AutonomaError;
187
+ readonly unknownEnvironment: (name: string) => AutonomaError;
188
+ readonly invalidSignature: () => AutonomaError;
189
+ readonly invalidRefsToken: (reason: string) => AutonomaError;
190
+ readonly productionBlocked: (detail?: string) => AutonomaError;
191
+ readonly invalidBody: (reason: string) => AutonomaError;
193
192
  };
194
- declare function teardown(executor: SQLExecutor, dialect: Dialect, tableMap: Map<string, string>, columnMaps: Map<string, Map<string, string>>, schema: SchemaInfo, scopeValue: string, refs?: Record<string, Record<string, unknown>[]>, skipModels?: Set<string>): Promise<void>;
195
-
196
- /**
197
- * Define a factory for creating entities via user code instead of raw SQL.
198
- * The factory's `create` function receives pre-resolved fields (temp IDs replaced with real IDs)
199
- * and must return at least the primary key field.
200
- */
201
- declare function defineFactory(definition: FactoryDefinition): FactoryDefinition;
202
193
 
203
- export { type CheckError, type CheckResult, CreateContext, type CreateOp, type Dialect, FactoryDefinition, HandlerConfig, HandlerRequest, HandlerResponse, type IntrospectionResult, ModelInfo, PROTOCOL_VERSION, type RefNode, ResolvedEntitySpec, type ResolvedTree, SQLExecutor, ScenarioDefinition, SchemaInfo, checkAllScenarios, checkScenario, computeTeardownOrder, createEntities, defineFactory, fingerprint, getDialect, handleRequest, introspectDatabase, resolveTree, signBody, signRefs, teardown, verifyRefs, verifySignature };
194
+ export { AutonomaError, type CheckError, type CheckResult, type CheckScenario, type CreateOp, Errors, FactoryDefinition, FactoryRegistry, HandlerConfig, HandlerRequest, HandlerResponse, PROTOCOL_VERSION, type RefsPayload, type ResolvedTree, SchemaInfo, buildSchemaFromFactories, checkAllScenarios, checkScenario, computeTeardownOrder, defineFactory, fieldTypeFromZod, fingerprint, handleRequest, resolvePayloadTree, resolveTokens, schemaToWire, signBody, signRefs, verifyRefs, verifySignature };