@ontrails/core 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +849 -0
- package/README.md +190 -0
- package/package.json +36 -0
- package/src/activation-provenance.ts +116 -0
- package/src/activation-source-compatibility.ts +430 -0
- package/src/activation-source-derivation.ts +227 -0
- package/src/activation-source.ts +93 -0
- package/src/blob-ref.ts +90 -0
- package/src/branded.ts +135 -0
- package/src/collections.ts +99 -0
- package/src/compose-batch.ts +69 -0
- package/src/compose-schema.ts +36 -0
- package/src/context.ts +66 -0
- package/src/derive.ts +485 -0
- package/src/detours.ts +8 -0
- package/src/diagnostics.ts +21 -0
- package/src/draft.ts +350 -0
- package/src/entity.ts +346 -0
- package/src/error-rendering.ts +87 -0
- package/src/errors.ts +483 -0
- package/src/execute.ts +1577 -0
- package/src/fetch.ts +138 -0
- package/src/fire.ts +1172 -0
- package/src/glob.ts +81 -0
- package/src/guards.ts +37 -0
- package/src/index.ts +704 -0
- package/src/internal/fork-ctx.ts +69 -0
- package/src/layer-field-rendering.ts +193 -0
- package/src/layer.ts +81 -0
- package/src/observe.ts +361 -0
- package/src/path-scope.ts +66 -0
- package/src/path-security.ts +98 -0
- package/src/patterns/bulk.ts +16 -0
- package/src/patterns/change.ts +12 -0
- package/src/patterns/date-range.ts +12 -0
- package/src/patterns/index.ts +8 -0
- package/src/patterns/pagination.ts +22 -0
- package/src/patterns/progress.ts +13 -0
- package/src/patterns/sorting.ts +14 -0
- package/src/patterns/status.ts +11 -0
- package/src/patterns/timestamps.ts +12 -0
- package/src/permits.ts +12 -0
- package/src/queue.ts +163 -0
- package/src/redaction/index.ts +3 -0
- package/src/redaction/patterns.ts +50 -0
- package/src/redaction/redactor.ts +178 -0
- package/src/resilience.ts +234 -0
- package/src/resource-config.ts +804 -0
- package/src/resource.ts +194 -0
- package/src/result.ts +212 -0
- package/src/run.ts +76 -0
- package/src/runtime-builtins.ts +69 -0
- package/src/schedule-runtime.ts +689 -0
- package/src/schedule.ts +326 -0
- package/src/serialization.ts +265 -0
- package/src/sha256.ts +136 -0
- package/src/signal-diagnostics.ts +633 -0
- package/src/signal-ref.ts +111 -0
- package/src/signal.ts +104 -0
- package/src/store/accessor-protocol.ts +56 -0
- package/src/store/index.ts +4 -0
- package/src/structured-examples.ts +248 -0
- package/src/surface-derivation.ts +91 -0
- package/src/surface-filter.ts +101 -0
- package/src/surface-overlay.ts +694 -0
- package/src/surface-versioning.ts +42 -0
- package/src/topo.ts +835 -0
- package/src/tracing.ts +346 -0
- package/src/trail-id-glob.ts +15 -0
- package/src/trail.ts +1351 -0
- package/src/trails/derive-trail.ts +835 -0
- package/src/trails/index.ts +9 -0
- package/src/trails/ingest.ts +152 -0
- package/src/trails-db.ts +212 -0
- package/src/transport-error-map.ts +163 -0
- package/src/type-utils.ts +87 -0
- package/src/types.ts +300 -0
- package/src/validate-established-topo.ts +73 -0
- package/src/validate-topo.ts +725 -0
- package/src/validation.ts +330 -0
- package/src/version-marker.ts +716 -0
- package/src/version-resolution.ts +308 -0
- package/src/version-runtime.ts +120 -0
- package/src/webhook.ts +461 -0
- package/src/workspace.ts +244 -0
- package/src/zod-wrappers.ts +72 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { deriveTrail } from './derive-trail.js';
|
|
2
|
+
export type {
|
|
3
|
+
DeriveTrailInput,
|
|
4
|
+
DeriveTrailOperation,
|
|
5
|
+
DeriveTrailOutput,
|
|
6
|
+
DeriveTrailSpec,
|
|
7
|
+
} from './derive-trail.js';
|
|
8
|
+
export { ingest } from './ingest.js';
|
|
9
|
+
export type { IngestOptions, IngestTransform } from './ingest.js';
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
import { InternalError } from '../errors.js';
|
|
4
|
+
import { composeLayers } from '../layer.js';
|
|
5
|
+
import type { Layer } from '../layer.js';
|
|
6
|
+
import { Result } from '../result.js';
|
|
7
|
+
import type { Signal } from '../signal.js';
|
|
8
|
+
import { trail } from '../trail.js';
|
|
9
|
+
import type { Trail, TrailExample, TrailSpec } from '../trail.js';
|
|
10
|
+
import type { TrailContext } from '../types.js';
|
|
11
|
+
|
|
12
|
+
type SchemaValue<TSchema extends z.ZodType> = z.output<TSchema>;
|
|
13
|
+
|
|
14
|
+
type ExampleBearingSchema<TSchema extends z.ZodType> = TSchema & {
|
|
15
|
+
readonly examples?: readonly Partial<SchemaValue<TSchema>>[] | undefined;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
interface IngestBaseOptions<TSchema extends z.ZodType, TSignal> extends Omit<
|
|
19
|
+
TrailSpec<SchemaValue<TSchema>, void>,
|
|
20
|
+
| 'implementation'
|
|
21
|
+
| 'examples'
|
|
22
|
+
| 'fires'
|
|
23
|
+
| 'input'
|
|
24
|
+
| 'intent'
|
|
25
|
+
| 'output'
|
|
26
|
+
| 'pattern'
|
|
27
|
+
> {
|
|
28
|
+
/** Override the derived trail id. Defaults to `${signal}.ingest`. */
|
|
29
|
+
readonly id?: string | undefined;
|
|
30
|
+
/** Validated external payload shape. */
|
|
31
|
+
readonly schema: TSchema;
|
|
32
|
+
/** Signal to fire after verification and optional transformation. */
|
|
33
|
+
readonly signal: Signal<TSignal>;
|
|
34
|
+
/** Optional per-trail verification layer, e.g. HMAC signature checks. */
|
|
35
|
+
readonly verify?: Layer | undefined;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export type IngestTransform<TInput, TSignal> = (
|
|
39
|
+
payload: TInput,
|
|
40
|
+
ctx: TrailContext
|
|
41
|
+
) => TSignal | Promise<TSignal>;
|
|
42
|
+
|
|
43
|
+
export interface IngestOptions<
|
|
44
|
+
TSchema extends z.ZodType,
|
|
45
|
+
TSignal,
|
|
46
|
+
> extends IngestBaseOptions<TSchema, TSignal> {
|
|
47
|
+
readonly transform?:
|
|
48
|
+
| IngestTransform<SchemaValue<TSchema>, TSignal>
|
|
49
|
+
| undefined;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const deriveExampleName = (signalId: string, index: number): string =>
|
|
53
|
+
`Ingest ${signalId} ${index + 1}`;
|
|
54
|
+
|
|
55
|
+
const deriveExamples = <TSchema extends z.ZodType>(
|
|
56
|
+
schema: ExampleBearingSchema<TSchema>,
|
|
57
|
+
signalId: string
|
|
58
|
+
): readonly TrailExample<SchemaValue<TSchema>, void>[] | undefined => {
|
|
59
|
+
const { examples } = schema;
|
|
60
|
+
if (examples === undefined || examples.length === 0) {
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return Object.freeze(
|
|
65
|
+
examples.map((example, index) => ({
|
|
66
|
+
input: example,
|
|
67
|
+
name: deriveExampleName(signalId, index),
|
|
68
|
+
}))
|
|
69
|
+
);
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const createIngestImplementation =
|
|
73
|
+
<TSchema extends z.ZodType, TSignal>(
|
|
74
|
+
signalRef: Signal<TSignal>,
|
|
75
|
+
signalId: string,
|
|
76
|
+
trailId: string,
|
|
77
|
+
transform: IngestTransform<SchemaValue<TSchema>, TSignal> | undefined
|
|
78
|
+
) =>
|
|
79
|
+
async (
|
|
80
|
+
input: SchemaValue<TSchema>,
|
|
81
|
+
ctx: TrailContext
|
|
82
|
+
): Promise<Result<void, Error>> => {
|
|
83
|
+
if (ctx.fire === undefined) {
|
|
84
|
+
return Result.err(
|
|
85
|
+
new InternalError(
|
|
86
|
+
`ingest("${trailId}") requires topo-backed execution to fire "${signalId}"`
|
|
87
|
+
)
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
try {
|
|
92
|
+
const payload =
|
|
93
|
+
transform === undefined
|
|
94
|
+
? (input as TSignal)
|
|
95
|
+
: await transform(input, ctx);
|
|
96
|
+
await ctx.fire(signalRef, payload);
|
|
97
|
+
return Result.ok();
|
|
98
|
+
} catch (error) {
|
|
99
|
+
const message = `ingest("${trailId}"): ${error instanceof Error ? error.message : String(error)}`;
|
|
100
|
+
return Result.err(
|
|
101
|
+
error instanceof Error
|
|
102
|
+
? new InternalError(message, { cause: error })
|
|
103
|
+
: new InternalError(message)
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
export const ingest = <
|
|
109
|
+
TSchema extends z.ZodType,
|
|
110
|
+
TSignal = SchemaValue<TSchema>,
|
|
111
|
+
>(
|
|
112
|
+
options: IngestOptions<TSchema, TSignal>
|
|
113
|
+
): Trail<SchemaValue<TSchema>, void> => {
|
|
114
|
+
const signalId = options.signal.id;
|
|
115
|
+
const id = options.id ?? `${signalId}.ingest`;
|
|
116
|
+
const { id: _id, schema, signal, transform, verify, ...trailSpec } = options;
|
|
117
|
+
const baseImplementation = createIngestImplementation<TSchema, TSignal>(
|
|
118
|
+
signal,
|
|
119
|
+
signalId,
|
|
120
|
+
id,
|
|
121
|
+
transform
|
|
122
|
+
);
|
|
123
|
+
const baseSpec = {
|
|
124
|
+
...trailSpec,
|
|
125
|
+
examples: deriveExamples(schema as ExampleBearingSchema<TSchema>, signalId),
|
|
126
|
+
fires: [signal],
|
|
127
|
+
implementation: baseImplementation as TrailSpec<
|
|
128
|
+
unknown,
|
|
129
|
+
unknown
|
|
130
|
+
>['implementation'],
|
|
131
|
+
input: schema as z.ZodType<unknown>,
|
|
132
|
+
intent: 'write',
|
|
133
|
+
output: z.void(),
|
|
134
|
+
pattern: 'ingest',
|
|
135
|
+
} as TrailSpec<unknown, unknown>;
|
|
136
|
+
const baseTrail = trail(id, baseSpec) as Trail<SchemaValue<TSchema>, void>;
|
|
137
|
+
|
|
138
|
+
if (verify === undefined) {
|
|
139
|
+
return baseTrail;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Verification is a per-factory concern, so compose it locally instead of
|
|
143
|
+
// mutating runner-wide layer configuration.
|
|
144
|
+
return Object.freeze({
|
|
145
|
+
...baseTrail,
|
|
146
|
+
implementation: composeLayers(
|
|
147
|
+
[verify],
|
|
148
|
+
baseTrail,
|
|
149
|
+
baseTrail.implementation
|
|
150
|
+
),
|
|
151
|
+
}) as Trail<SchemaValue<TSchema>, void>;
|
|
152
|
+
};
|
package/src/trails-db.ts
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import type { Database } from 'bun:sqlite';
|
|
2
|
+
|
|
3
|
+
import { NotFoundError } from './errors.js';
|
|
4
|
+
import { loadRuntimeBuiltin } from './runtime-builtins.js';
|
|
5
|
+
import { sha256Hex } from './sha256.js';
|
|
6
|
+
|
|
7
|
+
// Altitude ruling (TRL-1198, ADR-0051 lens): trails-db stays core-owned
|
|
8
|
+
// shared framework infrastructure (ADR-0014) and stays on the barrel —
|
|
9
|
+
// topography, tracing, warden, wayfinder, and the operator app all
|
|
10
|
+
// consume it from `@ontrails/core`. What it may NOT do is assume runtime
|
|
11
|
+
// capabilities eagerly: `bun:sqlite` and the node builtins load lazily at
|
|
12
|
+
// first use so the barrel's module graph stays execution-portable.
|
|
13
|
+
const sqlite = () => loadRuntimeBuiltin('bun:sqlite');
|
|
14
|
+
const fs = () => loadRuntimeBuiltin('node:fs');
|
|
15
|
+
const os = () => loadRuntimeBuiltin('node:os');
|
|
16
|
+
const nodePath = () => loadRuntimeBuiltin('node:path');
|
|
17
|
+
|
|
18
|
+
const TRAILS_DIR = '.trails';
|
|
19
|
+
const TRAILS_DB_FILE = 'trails.db';
|
|
20
|
+
const TRAILS_STORE_DIR = 'trails';
|
|
21
|
+
const TRAILS_PROJECTS_DIR = 'projects';
|
|
22
|
+
const SCHEMA_VERSION_TABLE = 'meta_schema_versions';
|
|
23
|
+
const SQLITE_BUSY_TIMEOUT_MS = 5000;
|
|
24
|
+
const PROJECT_KEY_HASH_LENGTH = 16;
|
|
25
|
+
const PROJECT_KEY_NAME_FALLBACK = 'project';
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Legacy no-op compatibility export.
|
|
29
|
+
*
|
|
30
|
+
* `.trails/` is committed project control, not disposable cache/state. New
|
|
31
|
+
* code should not write a `.trails/.gitignore`; keep this export available for
|
|
32
|
+
* older callers during the pre-1.0 cutover.
|
|
33
|
+
*/
|
|
34
|
+
export const WORKSPACE_GITIGNORE_LINES = [] as const;
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Legacy no-op compatibility export. See {@link WORKSPACE_GITIGNORE_LINES}.
|
|
38
|
+
*/
|
|
39
|
+
export const WORKSPACE_GITIGNORE_CONTENT = '';
|
|
40
|
+
|
|
41
|
+
export interface TrailsDbLocationOptions {
|
|
42
|
+
readonly env?: Record<string, string | undefined>;
|
|
43
|
+
readonly path?: string;
|
|
44
|
+
readonly rootDir?: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface EnsureSubsystemSchemaOptions {
|
|
48
|
+
readonly migrate: (currentVersion: number) => void;
|
|
49
|
+
readonly subsystem: string;
|
|
50
|
+
readonly version: number;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
interface SchemaVersionRow {
|
|
54
|
+
readonly version: number;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const deriveRootDir = (rootDir?: string): string =>
|
|
58
|
+
nodePath().resolve(rootDir ?? process.cwd());
|
|
59
|
+
|
|
60
|
+
const sanitizeProjectKeyName = (name: string): string => {
|
|
61
|
+
const normalized = name.replaceAll(/[^a-zA-Z0-9._-]+/g, '-');
|
|
62
|
+
return normalized.length > 0 ? normalized : PROJECT_KEY_NAME_FALLBACK;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
const projectHash = (rootDir: string): string =>
|
|
66
|
+
sha256Hex(rootDir).slice(0, PROJECT_KEY_HASH_LENGTH);
|
|
67
|
+
|
|
68
|
+
export const deriveTrailsProjectKey = (
|
|
69
|
+
options?: TrailsDbLocationOptions
|
|
70
|
+
): string => {
|
|
71
|
+
const rootDir = deriveRootDir(options?.rootDir);
|
|
72
|
+
return `${sanitizeProjectKeyName(nodePath().basename(rootDir))}-${projectHash(rootDir)}`;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
export const deriveTrailsStateHome = (
|
|
76
|
+
options?: TrailsDbLocationOptions
|
|
77
|
+
): string => {
|
|
78
|
+
const env = options?.env ?? process.env;
|
|
79
|
+
return nodePath().resolve(
|
|
80
|
+
env['TRAILS_STATE_HOME'] ??
|
|
81
|
+
env['XDG_STATE_HOME'] ??
|
|
82
|
+
nodePath().join(os().homedir(), '.local', 'state')
|
|
83
|
+
);
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
export const deriveTrailsStateDir = (
|
|
87
|
+
options?: TrailsDbLocationOptions
|
|
88
|
+
): string =>
|
|
89
|
+
nodePath().join(
|
|
90
|
+
deriveTrailsStateHome(options),
|
|
91
|
+
TRAILS_STORE_DIR,
|
|
92
|
+
TRAILS_PROJECTS_DIR,
|
|
93
|
+
deriveTrailsProjectKey(options)
|
|
94
|
+
);
|
|
95
|
+
|
|
96
|
+
export const deriveTrailsDir = (options?: TrailsDbLocationOptions): string =>
|
|
97
|
+
nodePath().join(deriveRootDir(options?.rootDir), TRAILS_DIR);
|
|
98
|
+
|
|
99
|
+
export const deriveTrailsDbPath = (options?: TrailsDbLocationOptions): string =>
|
|
100
|
+
options?.path
|
|
101
|
+
? nodePath().resolve(options.path)
|
|
102
|
+
: nodePath().join(deriveTrailsStateDir(options), TRAILS_DB_FILE);
|
|
103
|
+
|
|
104
|
+
const ensureDbParentDir = (dbPath: string): void => {
|
|
105
|
+
fs().mkdirSync(nodePath().dirname(dbPath), { recursive: true });
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Bootstrap the `.trails/` workspace at `rootDir`.
|
|
110
|
+
*
|
|
111
|
+
* Creates only the committed-control directory. Derived cache and observed
|
|
112
|
+
* state live in the per-user Trails store, so this helper intentionally does
|
|
113
|
+
* not create `.trails/cache`, `.trails/state`, or `.trails/.gitignore`.
|
|
114
|
+
*/
|
|
115
|
+
export const ensureTrailsWorkspace = (rootDir: string): void => {
|
|
116
|
+
const trailsDir = deriveTrailsDir({ rootDir });
|
|
117
|
+
fs().mkdirSync(trailsDir, { recursive: true });
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
const initializeWritePragmas = (db: Database): void => {
|
|
121
|
+
db.run(`PRAGMA busy_timeout = ${SQLITE_BUSY_TIMEOUT_MS.toString()}`);
|
|
122
|
+
db.run('PRAGMA journal_mode = WAL');
|
|
123
|
+
db.run('PRAGMA synchronous = NORMAL');
|
|
124
|
+
db.run('PRAGMA foreign_keys = ON');
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
const initializeReadPragmas = (db: Database): void => {
|
|
128
|
+
db.run(`PRAGMA busy_timeout = ${SQLITE_BUSY_TIMEOUT_MS.toString()}`);
|
|
129
|
+
db.run('PRAGMA foreign_keys = ON');
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
const ensureSchemaVersionTable = (db: Database): void => {
|
|
133
|
+
db.run(`CREATE TABLE IF NOT EXISTS ${SCHEMA_VERSION_TABLE} (
|
|
134
|
+
subsystem TEXT PRIMARY KEY,
|
|
135
|
+
version INTEGER NOT NULL,
|
|
136
|
+
updated_at TEXT NOT NULL
|
|
137
|
+
)`);
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
const readSubsystemVersion = (db: Database, subsystem: string): number => {
|
|
141
|
+
const row = db
|
|
142
|
+
.query<SchemaVersionRow, [string]>(
|
|
143
|
+
`SELECT version FROM ${SCHEMA_VERSION_TABLE} WHERE subsystem = ?`
|
|
144
|
+
)
|
|
145
|
+
.get(subsystem);
|
|
146
|
+
return row?.version ?? 0;
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
const writeSubsystemVersion = (
|
|
150
|
+
db: Database,
|
|
151
|
+
subsystem: string,
|
|
152
|
+
version: number
|
|
153
|
+
): void => {
|
|
154
|
+
db.run(
|
|
155
|
+
`INSERT INTO ${SCHEMA_VERSION_TABLE} (subsystem, version, updated_at)
|
|
156
|
+
VALUES (?, ?, ?)
|
|
157
|
+
ON CONFLICT(subsystem) DO UPDATE SET
|
|
158
|
+
version = excluded.version,
|
|
159
|
+
updated_at = excluded.updated_at`,
|
|
160
|
+
[subsystem, version, new Date().toISOString()]
|
|
161
|
+
);
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
export const openWriteTrailsDb = (
|
|
165
|
+
options?: TrailsDbLocationOptions
|
|
166
|
+
): Database => {
|
|
167
|
+
const rootDir = deriveRootDir(options?.rootDir);
|
|
168
|
+
const locationOptions: TrailsDbLocationOptions = {
|
|
169
|
+
...(options?.env === undefined ? {} : { env: options.env }),
|
|
170
|
+
...(options?.path === undefined ? {} : { path: options.path }),
|
|
171
|
+
rootDir,
|
|
172
|
+
};
|
|
173
|
+
const dbPath = deriveTrailsDbPath(locationOptions);
|
|
174
|
+
|
|
175
|
+
ensureDbParentDir(dbPath);
|
|
176
|
+
|
|
177
|
+
const db = new (sqlite().Database)(dbPath, { create: true });
|
|
178
|
+
initializeWritePragmas(db);
|
|
179
|
+
ensureSchemaVersionTable(db);
|
|
180
|
+
return db;
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
export const openReadTrailsDb = (
|
|
184
|
+
options?: TrailsDbLocationOptions
|
|
185
|
+
): Database => {
|
|
186
|
+
const dbPath = deriveTrailsDbPath(options);
|
|
187
|
+
if (!fs().existsSync(dbPath)) {
|
|
188
|
+
throw new NotFoundError(
|
|
189
|
+
`Trails database not found at "${dbPath}". Run a write operation first to initialize it.`
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
const db = new (sqlite().Database)(dbPath, { readonly: true });
|
|
193
|
+
initializeReadPragmas(db);
|
|
194
|
+
return db;
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
export const ensureSubsystemSchema = (
|
|
198
|
+
db: Database,
|
|
199
|
+
options: EnsureSubsystemSchemaOptions
|
|
200
|
+
): void => {
|
|
201
|
+
ensureSchemaVersionTable(db);
|
|
202
|
+
|
|
203
|
+
db.transaction(() => {
|
|
204
|
+
const currentVersion = readSubsystemVersion(db, options.subsystem);
|
|
205
|
+
if (currentVersion >= options.version) {
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
options.migrate(currentVersion);
|
|
210
|
+
writeSubsystemVersion(db, options.subsystem, options.version);
|
|
211
|
+
})();
|
|
212
|
+
};
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ErrorCategory,
|
|
3
|
+
ErrorCategoryCodes,
|
|
4
|
+
ErrorClassRegistryEntry,
|
|
5
|
+
FixedErrorClassRegistryEntry,
|
|
6
|
+
TrailsError,
|
|
7
|
+
} from './errors.js';
|
|
8
|
+
import {
|
|
9
|
+
codesByCategory,
|
|
10
|
+
errorClasses,
|
|
11
|
+
exitCodeMap,
|
|
12
|
+
jsonRpcCodeMap,
|
|
13
|
+
statusCodeMap,
|
|
14
|
+
} from './errors.js';
|
|
15
|
+
import { renderPublicError } from './error-rendering.js';
|
|
16
|
+
|
|
17
|
+
const CLI_INTERNAL_ERROR_PUBLIC_MESSAGE = 'Internal error';
|
|
18
|
+
|
|
19
|
+
export const surfaceNames = ['cli', 'http', 'jsonRpc', 'mcp'] as const;
|
|
20
|
+
|
|
21
|
+
export type SurfaceName = (typeof surfaceNames)[number];
|
|
22
|
+
|
|
23
|
+
const surfaceCodeKeys = {
|
|
24
|
+
cli: 'exit',
|
|
25
|
+
http: 'http',
|
|
26
|
+
jsonRpc: 'jsonRpc',
|
|
27
|
+
mcp: 'jsonRpc',
|
|
28
|
+
} as const satisfies Record<SurfaceName, keyof ErrorCategoryCodes>;
|
|
29
|
+
|
|
30
|
+
export type SurfaceErrorMapper<T> = (error: TrailsError) => T;
|
|
31
|
+
|
|
32
|
+
export type SurfaceErrorMappings<T> = Record<ErrorCategory, T>;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Union of every surface-specific error code emitted by {@link surfaceErrorMap}.
|
|
36
|
+
*
|
|
37
|
+
* @remarks
|
|
38
|
+
* Previously parameterized by surface (`SurfaceErrorCode<'cli'>` etc.), but
|
|
39
|
+
* the generic collapsed to `number` because the underlying maps were typed as
|
|
40
|
+
* `Record<ErrorCategory, number>`. With `as const satisfies` on the maps the
|
|
41
|
+
* per-surface literals are now observable, but TypeScript cannot narrow
|
|
42
|
+
* `surfaceErrorMap[surface][error.category]` through a generic `TSurface`
|
|
43
|
+
* without an unsound cast. The non-generic union honestly reflects what
|
|
44
|
+
* `mapSurfaceError` returns at the call site.
|
|
45
|
+
*/
|
|
46
|
+
export type SurfaceErrorCode =
|
|
47
|
+
(typeof codesByCategory)[ErrorCategory][(typeof surfaceCodeKeys)[SurfaceName]];
|
|
48
|
+
|
|
49
|
+
export interface SurfaceErrorRendering {
|
|
50
|
+
readonly category: ErrorCategory;
|
|
51
|
+
readonly code: SurfaceErrorCode;
|
|
52
|
+
readonly message: string;
|
|
53
|
+
readonly name: string;
|
|
54
|
+
readonly retryable: boolean;
|
|
55
|
+
readonly surface: SurfaceName;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface ErrorClassSurfaceRendering {
|
|
59
|
+
readonly category: ErrorCategory;
|
|
60
|
+
readonly code: SurfaceErrorCode;
|
|
61
|
+
readonly name: string;
|
|
62
|
+
readonly retryable: boolean;
|
|
63
|
+
readonly surface: SurfaceName;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export const createSurfaceErrorMapper =
|
|
67
|
+
<T>(mappings: SurfaceErrorMappings<T>): SurfaceErrorMapper<T> =>
|
|
68
|
+
(error) =>
|
|
69
|
+
mappings[error.category];
|
|
70
|
+
|
|
71
|
+
export const surfaceErrorMap = {
|
|
72
|
+
cli: exitCodeMap,
|
|
73
|
+
http: statusCodeMap,
|
|
74
|
+
jsonRpc: jsonRpcCodeMap,
|
|
75
|
+
mcp: jsonRpcCodeMap,
|
|
76
|
+
} as const satisfies Record<SurfaceName, SurfaceErrorMappings<number>>;
|
|
77
|
+
|
|
78
|
+
export const surfaceErrorRegistry = {
|
|
79
|
+
cli: {
|
|
80
|
+
map: createSurfaceErrorMapper(surfaceErrorMap.cli),
|
|
81
|
+
values: surfaceErrorMap.cli,
|
|
82
|
+
},
|
|
83
|
+
http: {
|
|
84
|
+
map: createSurfaceErrorMapper(surfaceErrorMap.http),
|
|
85
|
+
values: surfaceErrorMap.http,
|
|
86
|
+
},
|
|
87
|
+
jsonRpc: {
|
|
88
|
+
map: createSurfaceErrorMapper(surfaceErrorMap.jsonRpc),
|
|
89
|
+
values: surfaceErrorMap.jsonRpc,
|
|
90
|
+
},
|
|
91
|
+
mcp: {
|
|
92
|
+
map: createSurfaceErrorMapper(surfaceErrorMap.mcp),
|
|
93
|
+
values: surfaceErrorMap.mcp,
|
|
94
|
+
},
|
|
95
|
+
} as const;
|
|
96
|
+
|
|
97
|
+
export const mapSurfaceError = (
|
|
98
|
+
surface: SurfaceName,
|
|
99
|
+
error: TrailsError
|
|
100
|
+
): SurfaceErrorCode =>
|
|
101
|
+
codesByCategory[error.category][surfaceCodeKeys[surface]];
|
|
102
|
+
|
|
103
|
+
export const renderSurfaceError = (
|
|
104
|
+
surface: SurfaceName,
|
|
105
|
+
error: TrailsError
|
|
106
|
+
): SurfaceErrorRendering => ({
|
|
107
|
+
category: error.category,
|
|
108
|
+
code: mapSurfaceError(surface, error),
|
|
109
|
+
message: error.message,
|
|
110
|
+
name: error.name,
|
|
111
|
+
retryable: error.retryable,
|
|
112
|
+
surface,
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
export const renderPublicSurfaceError = (
|
|
116
|
+
surface: SurfaceName,
|
|
117
|
+
error: Error
|
|
118
|
+
): SurfaceErrorRendering => {
|
|
119
|
+
const rendering = renderPublicError(error);
|
|
120
|
+
return {
|
|
121
|
+
...rendering,
|
|
122
|
+
code: codesByCategory[rendering.category][surfaceCodeKeys[surface]],
|
|
123
|
+
message:
|
|
124
|
+
surface === 'cli' && rendering.category === 'internal'
|
|
125
|
+
? CLI_INTERNAL_ERROR_PUBLIC_MESSAGE
|
|
126
|
+
: rendering.message,
|
|
127
|
+
surface,
|
|
128
|
+
};
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
const isFixedErrorClassEntry = (
|
|
132
|
+
entry: ErrorClassRegistryEntry
|
|
133
|
+
): entry is FixedErrorClassRegistryEntry => entry.category !== 'dynamic';
|
|
134
|
+
|
|
135
|
+
const fixedErrorClassByName: ReadonlyMap<string, FixedErrorClassRegistryEntry> =
|
|
136
|
+
new Map(
|
|
137
|
+
errorClasses.flatMap((entry): [string, FixedErrorClassRegistryEntry][] =>
|
|
138
|
+
isFixedErrorClassEntry(entry) ? [[entry.name, entry]] : []
|
|
139
|
+
)
|
|
140
|
+
);
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Render a known error class name onto a surface without constructing it.
|
|
144
|
+
*
|
|
145
|
+
* Dynamic-category errors such as `RetryExhaustedError` return `undefined`
|
|
146
|
+
* because their surface code depends on the wrapped runtime error.
|
|
147
|
+
*/
|
|
148
|
+
export const renderErrorClassSurface = (
|
|
149
|
+
surface: SurfaceName,
|
|
150
|
+
errorName: string
|
|
151
|
+
): ErrorClassSurfaceRendering | undefined => {
|
|
152
|
+
const entry = fixedErrorClassByName.get(errorName);
|
|
153
|
+
if (entry === undefined) {
|
|
154
|
+
return undefined;
|
|
155
|
+
}
|
|
156
|
+
return {
|
|
157
|
+
category: entry.category,
|
|
158
|
+
code: codesByCategory[entry.category][surfaceCodeKeys[surface]],
|
|
159
|
+
name: entry.name,
|
|
160
|
+
retryable: entry.retryable,
|
|
161
|
+
surface,
|
|
162
|
+
};
|
|
163
|
+
};
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Type utilities for extracting input/output types from trails.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import type { Result } from './result.js';
|
|
6
|
+
import type { AnyTrail, Trail } from './trail.js';
|
|
7
|
+
import type { Implementation } from './types.js';
|
|
8
|
+
import type { z } from 'zod';
|
|
9
|
+
|
|
10
|
+
// ---------------------------------------------------------------------------
|
|
11
|
+
// Utility types
|
|
12
|
+
// ---------------------------------------------------------------------------
|
|
13
|
+
|
|
14
|
+
/* oxlint-disable no-explicit-any -- `any` required for conditional type inference; `unknown` breaks inference */
|
|
15
|
+
|
|
16
|
+
type SchemaInputOrFallback<TSchema extends z.ZodType, TFallback> =
|
|
17
|
+
unknown extends z.input<TSchema> ? TFallback : z.input<TSchema>;
|
|
18
|
+
|
|
19
|
+
type ComposeSchemaOf<T extends AnyTrail> = T extends {
|
|
20
|
+
readonly composeInput?: (infer TComposeSchema) | undefined;
|
|
21
|
+
}
|
|
22
|
+
? NonNullable<TComposeSchema>
|
|
23
|
+
: never;
|
|
24
|
+
|
|
25
|
+
type ComposeInputPart<T extends AnyTrail> =
|
|
26
|
+
ComposeSchemaOf<T> extends z.ZodType
|
|
27
|
+
? T extends Trail<any, any, infer CI>
|
|
28
|
+
? SchemaInputOrFallback<ComposeSchemaOf<T>, CI>
|
|
29
|
+
: z.input<ComposeSchemaOf<T>>
|
|
30
|
+
: T extends Trail<any, any, infer CI>
|
|
31
|
+
? CI
|
|
32
|
+
: never;
|
|
33
|
+
|
|
34
|
+
/** Extract the input type from a Trail. */
|
|
35
|
+
export type TrailInput<T extends AnyTrail> = T extends {
|
|
36
|
+
readonly input: infer TInputSchema extends z.ZodType;
|
|
37
|
+
}
|
|
38
|
+
? T extends Trail<infer I, any, any>
|
|
39
|
+
? SchemaInputOrFallback<TInputSchema, I>
|
|
40
|
+
: z.input<TInputSchema>
|
|
41
|
+
: never;
|
|
42
|
+
|
|
43
|
+
/** Extract the output type from a Trail. */
|
|
44
|
+
export type TrailOutput<T extends AnyTrail> = T extends {
|
|
45
|
+
readonly implementation: Implementation<any, infer O>;
|
|
46
|
+
}
|
|
47
|
+
? O
|
|
48
|
+
: never;
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Extract the compose-callable input type from a trail.
|
|
52
|
+
*
|
|
53
|
+
* When a trail declares `composeInput`, callers via `ctx.compose()` must pass
|
|
54
|
+
* both the public input fields and the composition-only fields. This type
|
|
55
|
+
* merges both schemas so the compiler enforces the full shape at the call
|
|
56
|
+
* site. Falls back to plain `TrailInput<T>` when no `composeInput` exists.
|
|
57
|
+
*/
|
|
58
|
+
export type ComposeInput<T extends AnyTrail> = [ComposeInputPart<T>] extends [
|
|
59
|
+
never,
|
|
60
|
+
]
|
|
61
|
+
? TrailInput<T>
|
|
62
|
+
: TrailInput<T> & ComposeInputPart<T>;
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Extracts the full `Result<Output, Error>` type from a trail definition.
|
|
66
|
+
*
|
|
67
|
+
* @example
|
|
68
|
+
* ```typescript
|
|
69
|
+
* type SearchResult = TrailResult<typeof searchTrail>;
|
|
70
|
+
* // Result<{ results: Item[]; count: number }, Error>
|
|
71
|
+
* ```
|
|
72
|
+
*/
|
|
73
|
+
export type TrailResult<T extends AnyTrail> = Result<TrailOutput<T>, Error>;
|
|
74
|
+
|
|
75
|
+
/* oxlint-enable no-explicit-any */
|
|
76
|
+
|
|
77
|
+
// ---------------------------------------------------------------------------
|
|
78
|
+
// Runtime schema accessors
|
|
79
|
+
// ---------------------------------------------------------------------------
|
|
80
|
+
|
|
81
|
+
/** Get the input Zod schema from a trail, preserving the specific schema type. */
|
|
82
|
+
export const inputOf = <T extends AnyTrail>(trail: T): T['input'] =>
|
|
83
|
+
trail.input;
|
|
84
|
+
|
|
85
|
+
/** Get the output Zod schema from a trail, if defined, preserving the specific schema type. */
|
|
86
|
+
export const outputOf = <T extends AnyTrail>(trail: T): T['output'] =>
|
|
87
|
+
trail.output;
|