@ontrove/sdk 0.1.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.
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Connector manifest validation for `trove connector validate`
3
+ * (see the connectors manifest reference).
4
+ *
5
+ * Two checks live here:
6
+ *
7
+ * 1. **Shape validation** — required fields (`id`, `name`, `version`), the
8
+ * `id` pattern (`^[a-z0-9-]+$`), and well-formedness of `config`.
9
+ * 2. **Credential-key lint** — the same spirit as the server-side
10
+ * `validateConfig` (`src/graphql/validate-config.ts`, invariant #6): a
11
+ * connector's `config` holds **user preferences only, never credentials**.
12
+ * The cloud rejects writes whose config contains credential-shaped keys, so
13
+ * the SDK lints the manifest locally to catch the mistake before deploy. Auth
14
+ * material belongs in the (PROPOSED) `auth` block — surfaced from the macOS
15
+ * Keychain — not in `config`.
16
+ *
17
+ * The deny-list below is kept deliberately identical in spirit to the
18
+ * authoritative cloud list so the two cannot meaningfully drift.
19
+ *
20
+ * @module
21
+ */
22
+
23
+ import type { ConnectorManifest, ManifestConfigField } from './types.js';
24
+
25
+ /**
26
+ * Credential-shaped key patterns that may NOT appear in a connector's `config`
27
+ * (invariant #6). Mirrors the authoritative cloud deny-list in
28
+ * `src/graphql/validate-config.ts`. Matched case-insensitively and
29
+ * separator-insensitively as substrings, so `apiKey`, `api_key`, `access_token`,
30
+ * and `refreshToken` all match.
31
+ */
32
+ const CREDENTIAL_KEY_PATTERNS: readonly string[] = [
33
+ 'session',
34
+ 'cookie',
35
+ 'token',
36
+ 'api_key',
37
+ 'apikey',
38
+ 'password',
39
+ 'secret',
40
+ 'auth',
41
+ 'credential',
42
+ 'bearer',
43
+ 'access_key',
44
+ 'private_key',
45
+ ];
46
+
47
+ /** The `id` pattern: lowercase letters, digits, and hyphens. */
48
+ const ID_RE = /^[a-z0-9-]+$/;
49
+
50
+ /** A permissive semver check — `MAJOR.MINOR.PATCH` with optional pre-release/build. */
51
+ const SEMVER_RE = /^\d+\.\d+\.\d+(?:[-+].+)?$/;
52
+
53
+ /**
54
+ * Normalize a config key for credential-pattern matching: lowercase and strip
55
+ * `_`/`-` separators so `api_key`, `apiKey`, and `api-key` collapse to one form.
56
+ * Identical to the cloud's `normalizeKey`.
57
+ *
58
+ * @param key - The config key to normalize.
59
+ * @returns The normalized comparable form.
60
+ */
61
+ function normalizeKey(key: string): string {
62
+ return key.toLowerCase().replaceAll('_', '').replaceAll('-', '');
63
+ }
64
+
65
+ /** Pre-normalized credential patterns, computed once. */
66
+ const NORMALIZED_CREDENTIAL_PATTERNS: readonly string[] = CREDENTIAL_KEY_PATTERNS.map(normalizeKey);
67
+
68
+ /**
69
+ * Whether a single config key looks like a credential and must be rejected.
70
+ * Mirrors the cloud's `isSensitiveConfigKey`.
71
+ *
72
+ * @param key - The config key to test.
73
+ * @returns True if the key matches a credential pattern.
74
+ */
75
+ export function isCredentialConfigKey(key: string): boolean {
76
+ const normalized = normalizeKey(key);
77
+ return NORMALIZED_CREDENTIAL_PATTERNS.some((pattern) => normalized.includes(pattern));
78
+ }
79
+
80
+ /**
81
+ * Push an error if a required string field is missing or empty.
82
+ *
83
+ * @param value - The candidate field value.
84
+ * @param field - The field name, for the message.
85
+ * @param errors - The accumulator to append to.
86
+ */
87
+ function requireString(value: unknown, field: string, errors: string[]): void {
88
+ if (typeof value !== 'string' || value.length === 0) {
89
+ errors.push(`manifest.${field} is required and must be a non-empty string`);
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Validate the `config` block: each value must be an object descriptor, and no
95
+ * key may be credential-shaped.
96
+ *
97
+ * @param config - The manifest `config` object.
98
+ * @param errors - The accumulator to append to.
99
+ */
100
+ function validateConfigBlock(config: Record<string, ManifestConfigField>, errors: string[]): void {
101
+ const offending: string[] = [];
102
+ for (const [key, descriptor] of Object.entries(config)) {
103
+ if (isCredentialConfigKey(key)) offending.push(key);
104
+ if (descriptor === null || typeof descriptor !== 'object' || Array.isArray(descriptor)) {
105
+ errors.push(`manifest.config.${key} must be a field descriptor object`);
106
+ }
107
+ }
108
+ if (offending.length > 0) {
109
+ const unique = [...new Set(offending)];
110
+ errors.push(
111
+ `manifest.config must not contain credential-shaped key(s): ${unique.join(', ')}. ` +
112
+ 'Connector credentials belong in the macOS Keychain (declared as `auth`), not in `config`.',
113
+ );
114
+ }
115
+ }
116
+
117
+ /**
118
+ * The outcome of {@link validateConnectorManifest}.
119
+ */
120
+ export interface ManifestValidationResult {
121
+ /** True when no errors were found. */
122
+ valid: boolean;
123
+ /** Human-readable error messages; empty when `valid` is true. */
124
+ errors: string[];
125
+ }
126
+
127
+ /**
128
+ * Validate a connector `manifest.json` for `trove connector validate`.
129
+ *
130
+ * Checks required fields and the `id`/`version` patterns, validates the `config`
131
+ * descriptors, and runs the credential-key lint (rejecting credential-shaped
132
+ * `config` keys — same spirit as the server-side `validateConfig`). Returns a
133
+ * structured result rather than throwing, so the CLI can print all errors at
134
+ * once.
135
+ *
136
+ * @param manifest - The parsed manifest object to validate.
137
+ * @returns `{ valid, errors }` — `valid: true` with an empty `errors` array on success.
138
+ */
139
+ export function validateConnectorManifest(manifest: unknown): ManifestValidationResult {
140
+ const errors: string[] = [];
141
+
142
+ if (manifest === null || typeof manifest !== 'object' || Array.isArray(manifest)) {
143
+ return { valid: false, errors: ['manifest must be a JSON object'] };
144
+ }
145
+
146
+ const m = manifest as Partial<ConnectorManifest>;
147
+
148
+ requireString(m.id, 'id', errors);
149
+ if (typeof m.id === 'string' && m.id.length > 0 && !ID_RE.test(m.id)) {
150
+ errors.push('manifest.id must match ^[a-z0-9-]+$ (lowercase letters, digits, hyphens)');
151
+ }
152
+
153
+ requireString(m.name, 'name', errors);
154
+
155
+ requireString(m.version, 'version', errors);
156
+ if (typeof m.version === 'string' && m.version.length > 0 && !SEMVER_RE.test(m.version)) {
157
+ errors.push('manifest.version must be a semver string (e.g. "1.0.0")');
158
+ }
159
+
160
+ if (m.config !== undefined) {
161
+ if (m.config === null || typeof m.config !== 'object' || Array.isArray(m.config)) {
162
+ errors.push('manifest.config must be an object');
163
+ } else {
164
+ validateConfigBlock(m.config, errors);
165
+ }
166
+ }
167
+
168
+ if (m.needs_browser !== undefined && typeof m.needs_browser !== 'boolean') {
169
+ errors.push('manifest.needs_browser must be a boolean');
170
+ }
171
+
172
+ return { valid: errors.length === 0, errors };
173
+ }
package/src/runtime.ts ADDED
@@ -0,0 +1,195 @@
1
+ /**
2
+ * The local-run harness — what makes `trove connector dev` / `trove connector test`
3
+ * work (connectors/sdk-reference; connectors/cursors-and-sources).
4
+ *
5
+ * {@link runConnector} builds a {@link ConnectorContext} from a `{ config, cursor }`
6
+ * spec, invokes `sync(ctx)`, then normalizes and validates the result: it accepts
7
+ * either a `ConnectorSyncResult` or a bare `ConnectorDocument[]`, deduplicates by
8
+ * `id` (first occurrence wins, matching server-side `(source, id)` dedup), and
9
+ * validates every document's required fields, surfacing problems clearly instead
10
+ * of pushing a malformed payload to the cloud.
11
+ *
12
+ * It is the symmetric sibling of `@ontrove/mcp`'s `dispatch`/`toFetchHandler`: that
13
+ * runs a tool call end-to-end without the hosted runtime; this runs a connector
14
+ * sync end-to-end without the Mac app sync engine.
15
+ *
16
+ * @module
17
+ */
18
+
19
+ import type {
20
+ ConnectorContext,
21
+ ConnectorDocument,
22
+ ConnectorSyncResult,
23
+ FetchLike,
24
+ TroveConnector,
25
+ Watermark,
26
+ } from './types.js';
27
+
28
+ /** Allowed `contentType` values (matches the GraphQL `ContentType` enum). */
29
+ const CONTENT_TYPES: readonly string[] = ['text', 'transcript', 'highlight', 'bookmark'];
30
+
31
+ /**
32
+ * The options {@link runConnector} builds a `ctx` from. The CLI passes the
33
+ * source's stored config and current cursor; tests inject `fetch`, `log`, and
34
+ * `now` for determinism.
35
+ *
36
+ * @typeParam C - The shape of the connector's typed `ctx.config` preferences.
37
+ */
38
+ export interface RunOptions<C = Record<string, unknown>> {
39
+ /** The source's preference values (no credentials). Defaults to `{}`. */
40
+ config?: C;
41
+ /** The source's current watermark. Defaults to `{ type: 'none' }`. */
42
+ cursor?: Watermark;
43
+ /** The fetch implementation to expose as `ctx.fetch`. Defaults to global `fetch`. */
44
+ fetchImpl?: FetchLike;
45
+ /** A sink for `ctx.log(...)` calls. Defaults to collecting into the returned `logs`. */
46
+ logSink?: (args: unknown[]) => void;
47
+ /** The clock backing `ctx.now()`. Defaults to `() => new Date()`. */
48
+ now?: () => Date;
49
+ }
50
+
51
+ /**
52
+ * The outcome of {@link runConnector}: the validated, deduped documents, the
53
+ * resolved cursor, and the captured log lines. Mirrors enough of what the cloud
54
+ * ingest reports for `trove connector test` to print a useful summary.
55
+ */
56
+ export interface RunResult {
57
+ /** The validated, deduped documents `sync` returned. */
58
+ documents: ConnectorDocument[];
59
+ /** The cursor `sync` returned, or `{ type: 'none' }` if it returned none. */
60
+ cursor: Watermark;
61
+ /** Captured `ctx.log(...)` lines (when no custom `logSink` was supplied). */
62
+ logs: unknown[][];
63
+ /** Count of documents dropped as duplicates of an earlier `id`. */
64
+ duplicatesSkipped: number;
65
+ }
66
+
67
+ /**
68
+ * Validate one document's required fields, throwing a clear, indexed error on the
69
+ * first problem. Mirrors the wire contract: `id` is required (→ `externalId`),
70
+ * and at least one of `text`/`audioUrl` must be present.
71
+ *
72
+ * @param doc - The document to validate.
73
+ * @param index - Its position in the returned array, for the message.
74
+ * @throws {Error} If a required field is missing or malformed.
75
+ */
76
+ function validateDocument(doc: ConnectorDocument, index: number): void {
77
+ const where = `document[${String(index)}]`;
78
+ if (doc === null || typeof doc !== 'object') {
79
+ throw new Error(`${where} must be an object`);
80
+ }
81
+ if (typeof doc.id !== 'string' || doc.id.length === 0) {
82
+ throw new Error(`${where} is missing a non-empty string \`id\` (maps to externalId)`);
83
+ }
84
+ const hasText = typeof doc.text === 'string' && doc.text.length > 0;
85
+ const hasAudio = typeof doc.audioUrl === 'string' && doc.audioUrl.length > 0;
86
+ if (!hasText && !hasAudio) {
87
+ throw new Error(
88
+ `${where} (id "${doc.id}") must provide \`text\` or \`audioUrl\` — at least one is required`,
89
+ );
90
+ }
91
+ if (doc.contentType !== undefined && !CONTENT_TYPES.includes(doc.contentType)) {
92
+ throw new Error(
93
+ `${where} (id "${doc.id}") has invalid contentType "${String(doc.contentType)}"; ` +
94
+ `expected one of ${CONTENT_TYPES.join(', ')}`,
95
+ );
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Normalize a `sync` return value to a {@link ConnectorSyncResult}, accepting a
101
+ * bare document array for convenience.
102
+ *
103
+ * @param value - The raw `sync` return value.
104
+ * @returns A normalized `{ documents, cursor? }` result.
105
+ * @throws {Error} If the value is neither an array nor a `{ documents }` object.
106
+ */
107
+ function normalizeResult(value: ConnectorSyncResult | ConnectorDocument[]): ConnectorSyncResult {
108
+ if (Array.isArray(value)) {
109
+ return { documents: value };
110
+ }
111
+ if (value !== null && typeof value === 'object' && Array.isArray(value.documents)) {
112
+ return value.cursor === undefined
113
+ ? { documents: value.documents }
114
+ : { documents: value.documents, cursor: value.cursor };
115
+ }
116
+ throw new Error('sync must return an array of documents or an object with a `documents` array');
117
+ }
118
+
119
+ /**
120
+ * Deduplicate documents by `id`, keeping the first occurrence (matching the
121
+ * server's `(source, id)` dedup, which skips re-returned ids).
122
+ *
123
+ * @param documents - The validated documents.
124
+ * @returns The deduped documents and the count dropped.
125
+ */
126
+ function dedup(documents: ConnectorDocument[]): {
127
+ unique: ConnectorDocument[];
128
+ duplicatesSkipped: number;
129
+ } {
130
+ const seen = new Set<string>();
131
+ const unique: ConnectorDocument[] = [];
132
+ let duplicatesSkipped = 0;
133
+ for (const doc of documents) {
134
+ if (seen.has(doc.id)) {
135
+ duplicatesSkipped += 1;
136
+ continue;
137
+ }
138
+ seen.add(doc.id);
139
+ unique.push(doc);
140
+ }
141
+ return { unique, duplicatesSkipped };
142
+ }
143
+
144
+ /**
145
+ * Run a connector's `sync` against a built `ctx` and collect/validate the result.
146
+ *
147
+ * This is the harness the CLI drives for `trove connector dev` / `trove connector
148
+ * test`: it builds the {@link ConnectorContext} from `{ config, cursor }`, runs
149
+ * `sync(ctx)`, normalizes a bare-array return, validates every document's
150
+ * required fields (clear, indexed errors), and dedups by `id`. Errors thrown by
151
+ * `sync` itself propagate unchanged so the CLI can report a failed run exactly as
152
+ * the Mac app would.
153
+ *
154
+ * @typeParam C - The shape of the connector's typed `ctx.config` preferences.
155
+ * @param connector - The connector whose `sync` to run.
156
+ * @param options - The `{ config, cursor }` spec plus test injection points.
157
+ * @returns The validated, deduped {@link RunResult}.
158
+ * @throws {Error} If `sync` throws, returns a malformed value, or a document fails validation.
159
+ */
160
+ export async function runConnector<C = Record<string, unknown>>(
161
+ connector: TroveConnector<C>,
162
+ options: RunOptions<C> = {},
163
+ ): Promise<RunResult> {
164
+ const logs: unknown[][] = [];
165
+ const cursor: Watermark = options.cursor ?? { type: 'none' };
166
+ const fetchImpl: FetchLike = options.fetchImpl ?? ((url, init) => globalThis.fetch(url, init));
167
+ const now = options.now ?? (() => new Date());
168
+
169
+ const ctx: ConnectorContext<C> = {
170
+ config: options.config ?? ({} as C),
171
+ cursor,
172
+ fetch: fetchImpl,
173
+ log: (...args: unknown[]) => {
174
+ if (options.logSink !== undefined) {
175
+ options.logSink(args);
176
+ } else {
177
+ logs.push(args);
178
+ }
179
+ },
180
+ now,
181
+ };
182
+
183
+ const raw = await connector.sync(ctx);
184
+ const result = normalizeResult(raw);
185
+
186
+ result.documents.forEach(validateDocument);
187
+ const { unique, duplicatesSkipped } = dedup(result.documents);
188
+
189
+ return {
190
+ documents: unique,
191
+ cursor: result.cursor ?? { type: 'none' },
192
+ logs,
193
+ duplicatesSkipped,
194
+ };
195
+ }
package/src/types.ts ADDED
@@ -0,0 +1,252 @@
1
+ /**
2
+ * Public type surface for the `@ontrove/sdk` connector authoring library.
3
+ *
4
+ * These types describe the connector contract (see the connectors SDK reference
5
+ * and the cursors-and-sources guide): a connector is
6
+ * an object with a `sync(ctx)` method that fetches from a source and returns
7
+ * documents to index. The SDK owns the document shape (which maps 1:1 onto the
8
+ * `IngestDocumentInput` wire type), the typed `ctx` capability object, the
9
+ * watermark/cursor model, and the local-run harness the CLI drives.
10
+ *
11
+ * It is the symmetric sibling of `@ontrove/mcp`: a connector returns documents to be
12
+ * _stored_ (batch `sync`); an MCP server returns tool results to be _read live_.
13
+ *
14
+ * @module
15
+ */
16
+
17
+ /**
18
+ * The default content type Trove assigns a document when it omits `contentType`.
19
+ * Mirrors the GraphQL `ContentType` enum surfaced on `IngestDocumentInput`.
20
+ */
21
+ export type ConnectorContentType = 'text' | 'transcript' | 'highlight' | 'bookmark';
22
+
23
+ /**
24
+ * A single document a connector returns from `sync`. The fields map **1:1** onto
25
+ * the GraphQL `IngestDocumentInput` the Mac app pushes via `ingestDocuments`:
26
+ *
27
+ * | SDK field | `IngestDocumentInput` field |
28
+ * |---------------|-----------------------------|
29
+ * | `id` | `externalId` (required) |
30
+ * | `title` | `title` |
31
+ * | `text` | `text` |
32
+ * | `audioUrl` | `audioUrl` |
33
+ * | `url` | `url` |
34
+ * | `author` | `author` |
35
+ * | `date` | `date` (ISO 8601 DateTime) |
36
+ * | `tags` | `tags` |
37
+ * | `metadata` | `metadata` (JSON) |
38
+ * | `contentType` | `contentType` (ContentType) |
39
+ *
40
+ * Dedup is keyed on `(source, id)`: returning the same `id` twice is safe and is
41
+ * skipped on the server, so `sync` can be idempotent and retried freely. At least
42
+ * one of `text` or `audioUrl` must be present — an audio-only document triggers
43
+ * transcription (Whisper), and the transcript becomes the document text.
44
+ */
45
+ export interface ConnectorDocument {
46
+ /**
47
+ * The stable external identifier from the source system — the dedup key within
48
+ * the source. Maps to `IngestDocumentInput.externalId`. Use the native id (HN
49
+ * `objectID`, RSS `guid`, Notion page id), never a value that changes between
50
+ * runs.
51
+ */
52
+ id: string;
53
+ /** Document title. Maps to `IngestDocumentInput.title`. */
54
+ title?: string;
55
+ /**
56
+ * Full plain-text content. Maps to `IngestDocumentInput.text`. Strip HTML/markup
57
+ * for best search quality. Required unless `audioUrl` is set.
58
+ */
59
+ text?: string;
60
+ /**
61
+ * URL to an audio file. Maps to `IngestDocumentInput.audioUrl`. Trove downloads
62
+ * and transcribes it; the transcript becomes the document text and the document
63
+ * is indexed as `contentType: transcript`. Provide instead of (or alongside)
64
+ * `text`.
65
+ */
66
+ audioUrl?: string;
67
+ /** Canonical link back to the original. Maps to `IngestDocumentInput.url`. */
68
+ url?: string;
69
+ /**
70
+ * Content author. Maps to `IngestDocumentInput.author`. For podcasts, set this
71
+ * to the show name (Trove convention).
72
+ */
73
+ author?: string;
74
+ /**
75
+ * Original creation date as an ISO 8601 string (e.g. `"2026-06-14T09:00:00Z"`).
76
+ * Maps to the `DateTime` `IngestDocumentInput.date`. Used for recency ranking
77
+ * and the "published" display.
78
+ */
79
+ date?: string;
80
+ /** Array of string tags. Maps to `IngestDocumentInput.tags`. */
81
+ tags?: string[];
82
+ /**
83
+ * Arbitrary connector-specific JSON. Maps to `IngestDocumentInput.metadata`.
84
+ * **Never** put credentials or auth headers here.
85
+ */
86
+ metadata?: Record<string, unknown>;
87
+ /**
88
+ * One of `text`, `transcript`, `highlight`, `bookmark`. Maps to
89
+ * `IngestDocumentInput.contentType`. Defaults to `text` (transcribed audio
90
+ * becomes `transcript` automatically).
91
+ */
92
+ contentType?: ConnectorContentType;
93
+ }
94
+
95
+ /**
96
+ * A typed watermark describing how a source resumes between syncs. The opaque
97
+ * `Source.cursor` string is parsed into one of these (see the cursors-and-sources
98
+ * guide, watermark types).
99
+ *
100
+ * - `date` — the source is time-ordered and supports "since &lt;date&gt;"
101
+ * filtering (RSS, most APIs); the newest `value` you push becomes the next
102
+ * cursor.
103
+ * - `idSet` — the source has monotonic ids but no reliable date filter; advance
104
+ * to the highest id seen (`max`), optionally tracking a recent id set.
105
+ * - `none` — re-fetch everything each run and rely purely on `(source, id)`
106
+ * dedup. Always correct, just less efficient.
107
+ */
108
+ export type Watermark =
109
+ | { readonly type: 'date'; readonly value: string }
110
+ | { readonly type: 'idSet'; readonly values: readonly string[]; readonly max?: string }
111
+ | { readonly type: 'none' };
112
+
113
+ /**
114
+ * The result of a connector `sync`: the documents fetched this run and, optionally,
115
+ * the watermark the source should advance to. A connector may also return a bare
116
+ * `ConnectorDocument[]` for convenience — {@link runConnector} normalizes that to
117
+ * `{ documents }` with no cursor change.
118
+ */
119
+ export interface ConnectorSyncResult {
120
+ /** The documents fetched this run, mapping 1:1 onto `IngestDocumentInput`. */
121
+ documents: ConnectorDocument[];
122
+ /**
123
+ * The watermark to advance the source cursor to. Omit (or return `{ type: 'none' }`)
124
+ * to leave the cursor unchanged. The cloud only advances if the new value is
125
+ * monotonically ahead (compare-and-swap).
126
+ */
127
+ cursor?: Watermark;
128
+ }
129
+
130
+ /**
131
+ * The standard `fetch` signature the SDK exposes on {@link ConnectorContext.fetch}.
132
+ * Matches the platform `fetch` so existing code ports unchanged.
133
+ */
134
+ export type FetchLike = (url: string | URL, init?: RequestInit) => Promise<Response>;
135
+
136
+ /**
137
+ * The single argument to `sync` — a capability object: everything a connector
138
+ * reaches the outside world through is on `ctx`. There is no ambient authority.
139
+ *
140
+ * `ctx.credentials` (Keychain-resolved auth material) and `ctx.browser` (a
141
+ * Playwright browser for `needs_browser` connectors) are **PROPOSED**, not part
142
+ * of the shipped contract, and so are intentionally absent here.
143
+ */
144
+ export interface ConnectorContext<C = Record<string, unknown>> {
145
+ /**
146
+ * The user's preference values, keyed by the field names declared in
147
+ * `manifest.json` `config`. **Preferences only — never credentials.** Feed
148
+ * URLs, usernames, section lists, and filters live here; auth material lives in
149
+ * the macOS Keychain, surfaced (PROPOSED) via `ctx.credentials`, never here.
150
+ */
151
+ readonly config: C;
152
+ /**
153
+ * The source's current watermark (the position from the previous run), or
154
+ * `{ type: 'none' }` on the first sync. Read-only — advance the cursor by
155
+ * returning a new {@link Watermark} from `sync`, not by mutating this.
156
+ */
157
+ readonly cursor: Watermark;
158
+ /**
159
+ * Behaves like the standard `fetch`. Prefer `ctx.fetch` over global `fetch` —
160
+ * in the Mac app it routes through per-connector timeouts, retry, and
161
+ * rate-limit handling, surfacing failures in the connector's error log.
162
+ */
163
+ fetch: FetchLike;
164
+ /**
165
+ * Structured log entry, surfaced in the Mac app's connector logs and the
166
+ * `createSyncRun` audit record. Useful for reporting counts and progress.
167
+ */
168
+ log(...args: unknown[]): void;
169
+ /**
170
+ * The current wall-clock time as a `Date`. Injected (rather than read from a
171
+ * global) so syncs are deterministic under test and the local-run harness.
172
+ */
173
+ now(): Date;
174
+ }
175
+
176
+ /**
177
+ * The type a connector's default export satisfies. A connector is an object with
178
+ * a `sync` method that fetches from its source and returns documents to index.
179
+ *
180
+ * @typeParam C - The shape of the connector's typed `ctx.config` preferences.
181
+ *
182
+ * @example
183
+ * ```ts
184
+ * import { defineConnector } from '@ontrove/sdk';
185
+ *
186
+ * export default defineConnector({
187
+ * async sync(ctx) {
188
+ * const res = await ctx.fetch(ctx.config.feedUrl as string);
189
+ * return parse(await res.text());
190
+ * },
191
+ * });
192
+ * ```
193
+ */
194
+ export interface TroveConnector<C = Record<string, unknown>> {
195
+ /**
196
+ * The batch entry point. Fetches from the source and returns documents to
197
+ * index, optionally with a new cursor. May return a bare `ConnectorDocument[]`
198
+ * for convenience. Throw a plain `Error` to fail the run (the Mac app records
199
+ * the error and retries next tick).
200
+ */
201
+ sync(ctx: ConnectorContext<C>): Promise<ConnectorSyncResult | ConnectorDocument[]>;
202
+ }
203
+
204
+ /**
205
+ * A single field descriptor inside a manifest `config` object — describes one
206
+ * preference input shown in the connector's setup wizard.
207
+ */
208
+ export interface ManifestConfigField {
209
+ /** Display label in the setup UI. */
210
+ label?: string;
211
+ /** Input type — `text`, `text[]`, `url`, `url[]`, `path`, `number`, `boolean`. */
212
+ type?: string;
213
+ /** Optional example text shown in the input. */
214
+ placeholder?: string;
215
+ }
216
+
217
+ /**
218
+ * A connector `manifest.json` — declares what the connector is, how often it runs,
219
+ * and which preference fields the user fills in during setup
220
+ * (connectors/manifest reference).
221
+ */
222
+ export interface ConnectorManifest {
223
+ /** Stable connector-type id; pattern `^[a-z0-9-]+$`. Required. */
224
+ id: string;
225
+ /** Human-readable display name. Required. */
226
+ name: string;
227
+ /** One-line directory description. */
228
+ description?: string;
229
+ /** A single emoji or an HTTPS URL to a square icon. */
230
+ icon?: string;
231
+ /** Semver version string. Required. */
232
+ version: string;
233
+ /** Who wrote the connector. */
234
+ author?: string;
235
+ /** Directory grouping — `reading`, `social`, `finance`, `dev`, `media`, etc. */
236
+ category?: string;
237
+ /**
238
+ * Human-readable sync cadence — `"every 6 hours"`, `"daily"`, `"on demand"`, or
239
+ * `null` for a live-only connector. Optional (default: on demand).
240
+ */
241
+ schedule?: string | null;
242
+ /** The preference fields shown in the setup wizard. Preferences only — no credentials. */
243
+ config?: Record<string, ManifestConfigField>;
244
+ /** Whether the connector requires a Playwright browser. Default `false`. */
245
+ needs_browser?: boolean;
246
+ /** What kind of source this is — `feed`, `account`, `files`, `api`. */
247
+ kind?: string;
248
+ /** How the connector reaches the source — `http`, `browser`, `fs`. */
249
+ transport?: string;
250
+ /** Default content type for documents this connector produces. */
251
+ document_semantics?: ConnectorContentType;
252
+ }