@valtrix/sdk 0.1.1 → 0.3.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/README.md CHANGED
@@ -32,6 +32,12 @@ for await (const row of valtrix.customersClean.iterate()) {
32
32
 
33
33
  Rows come from every organization you hold an active grant for. Pass `org` to narrow to one organization. Filters, ordering, and pagination run server side.
34
34
 
35
+ Every row carries a stable `_record_id`. Store it and you can fetch the same row back later as a point lookup:
36
+
37
+ ```ts
38
+ const [invoice] = await valtrix.invoicesClean.findMany({ where: { _record_id: 'rec_9f2k7d' } })
39
+ ```
40
+
35
41
  ## Writing records
36
42
 
37
43
  Writes create records, not rows. They flow through your published transformation like any other source, so they arrive in your tables cleaned, deduped, and quality checked.
@@ -46,12 +52,14 @@ await valtrix.records.customer.upsert({
46
52
 
47
53
  The response includes the derived table rows, so you read your write already transformed. A row that fails an error-severity quality rule is reported as quarantined instead of landing in the table.
48
54
 
49
- ## Syncing changes
55
+ ## Reacting to changes
56
+
57
+ Your tables are the database, so there is nothing to copy or keep in sync. The change feed is how you react when data changes: kick off a workflow, notify someone, refresh something you derived.
50
58
 
51
59
  ```ts
52
60
  for await (const change of valtrix.customersClean.changes({ cursor })) {
53
- if (change.type === 'upsert') await warehouse.upsert(change.row)
54
- else await warehouse.remove(change.recordId)
61
+ if (change.type === 'upsert') await notifyAccountManager(change.row)
62
+ else await closeOpenTasks(change.recordId)
55
63
  cursor = change.cursor
56
64
  }
57
65
  ```
package/dist/cli.d.ts CHANGED
@@ -3,4 +3,5 @@ export type CliIo = {
3
3
  error: (message: string) => void;
4
4
  fetchImpl?: typeof fetch;
5
5
  };
6
+ export declare function loadEnvFiles(cwd: string): Promise<Record<string, string>>;
6
7
  export declare function runCli(argv: string[], env: Record<string, string | undefined>, io: CliIo): Promise<number>;
package/dist/cli.js CHANGED
@@ -1,8 +1,21 @@
1
1
  import { mkdir, readFile, writeFile } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { emitClientSource } from './codegen.js';
4
+ import { ENV_FILES, parseEnvFile } from './env.js';
4
5
  const DEFAULT_OUT = path.join('valtrix', 'client.ts');
5
6
  const DEFAULT_BASE_URL = 'https://api.valtrix.vojtadrmota.com';
7
+ export async function loadEnvFiles(cwd) {
8
+ const merged = {};
9
+ for (const file of ENV_FILES) {
10
+ try {
11
+ Object.assign(merged, parseEnvFile(await readFile(path.join(cwd, file), 'utf8')));
12
+ }
13
+ catch {
14
+ continue;
15
+ }
16
+ }
17
+ return merged;
18
+ }
6
19
  function parseArgs(argv) {
7
20
  const flags = new Map();
8
21
  let command = null;
@@ -32,18 +45,21 @@ export async function runCli(argv, env, io) {
32
45
  io.log('');
33
46
  io.log('Reads your published table schemas and writes a typed client.');
34
47
  io.log('Environment: VALTRIX_API_KEY (required), VALTRIX_API_URL (optional).');
48
+ io.log('Both are read from the shell, or from .env.local / .env in the current directory.');
35
49
  return command ? 0 : 1;
36
50
  }
37
51
  if (command !== 'generate') {
38
52
  io.error(`Unknown command "${command}". Run "valtrix help".`);
39
53
  return 1;
40
54
  }
41
- const apiKey = env.VALTRIX_API_KEY;
55
+ const fileEnv = await loadEnvFiles(process.cwd());
56
+ const apiKey = env.VALTRIX_API_KEY ?? fileEnv.VALTRIX_API_KEY;
42
57
  if (!apiKey) {
43
58
  io.error('Set VALTRIX_API_KEY to a key from your Valtrix console (Developers, API Keys).');
59
+ io.error('Export it, or put it in a gitignored .env.local or .env next to your project.');
44
60
  return 1;
45
61
  }
46
- const baseUrl = flags.get('url') ?? env.VALTRIX_API_URL ?? DEFAULT_BASE_URL;
62
+ const baseUrl = flags.get('url') ?? env.VALTRIX_API_URL ?? fileEnv.VALTRIX_API_URL ?? DEFAULT_BASE_URL;
47
63
  const outPath = flags.get('out') ?? DEFAULT_OUT;
48
64
  const checkOnly = flags.get('check') === true;
49
65
  const fetchImpl = io.fetchImpl ?? fetch;
package/dist/client.d.ts CHANGED
@@ -16,8 +16,14 @@ export type WhereOperators<V> = {
16
16
  not?: null;
17
17
  };
18
18
  export type WhereValue<V> = V | null | WhereOperators<NonNullable<V>>;
19
+ export type RecordIdFilter = string | {
20
+ eq?: string;
21
+ in?: string[];
22
+ };
19
23
  export type Where<Row> = {
20
24
  [K in keyof Row]?: WhereValue<Row[K]>;
25
+ } & {
26
+ _record_id?: RecordIdFilter;
21
27
  };
22
28
  export type OrderBy<Row> = {
23
29
  [K in keyof Row]?: 'asc' | 'desc';
@@ -127,17 +133,64 @@ export declare class ConnectApi {
127
133
  expiresAt: string;
128
134
  }>;
129
135
  }
136
+ export type OrgStatus = 'active' | 'revoked' | 'expired';
137
+ export type Org = {
138
+ id: string;
139
+ displayName: string;
140
+ status: OrgStatus;
141
+ entityTypes: string[];
142
+ connections: Array<{
143
+ connector: string;
144
+ status: string;
145
+ }>;
146
+ connectedAt: string;
147
+ expiresAt: string | null;
148
+ revokedAt: string | null;
149
+ };
150
+ export type OrgsQuery = {
151
+ status?: OrgStatus;
152
+ limit?: number;
153
+ cursor?: string;
154
+ };
155
+ export type OrgsPage = {
156
+ orgs: Org[];
157
+ nextCursor: string | null;
158
+ };
159
+ export declare class OrgsApi {
160
+ private readonly http;
161
+ constructor(http: Http);
162
+ page(query?: OrgsQuery): Promise<OrgsPage>;
163
+ list(query?: Omit<OrgsQuery, 'cursor'>): Promise<Org[]>;
164
+ iterate(query?: Omit<OrgsQuery, 'cursor'>): AsyncGenerator<Org>;
165
+ get(orgId: string): Promise<Org>;
166
+ }
130
167
  export type ClientShape = {
131
168
  tables: Record<string, object>;
132
169
  records: Record<string, object>;
133
170
  };
171
+ export type RecordByIdResult = {
172
+ record: {
173
+ id: string;
174
+ entityType: string;
175
+ externalId: string;
176
+ orgId: string;
177
+ data: Record<string, unknown>;
178
+ syncedAt: string;
179
+ };
180
+ tables: Array<{
181
+ table: string;
182
+ row: Record<string, unknown> | null;
183
+ }>;
184
+ };
134
185
  export type ValtrixClient<S extends ClientShape> = {
135
186
  [K in keyof S['tables']]: TableHandle<S['tables'][K]>;
136
187
  } & {
137
188
  records: {
138
189
  [K in keyof S['records']]: RecordHandle<S['records'][K]>;
139
190
  };
191
+ recordById: (recordId: string) => Promise<RecordByIdResult>;
140
192
  connect: ConnectApi;
193
+ orgs: OrgsApi;
141
194
  schema: () => Promise<ApiSchema>;
142
195
  };
143
196
  export type CreateClientConfig<S extends ClientShape> = {
package/dist/client.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { ENV_FILES, parseEnvFile } from './env.js';
1
2
  import { Http } from './http.js';
2
3
  function serializeScalar(value) {
3
4
  if (typeof value === 'boolean')
@@ -196,11 +197,84 @@ export class ConnectApi {
196
197
  return { connectUrl: response.connect_url, expiresAt: response.expires_at };
197
198
  }
198
199
  }
200
+ function mapOrg(org) {
201
+ return {
202
+ id: org.id,
203
+ displayName: org.display_name,
204
+ status: org.status,
205
+ entityTypes: org.scope.entity_types,
206
+ connections: org.connections.map(connection => ({ connector: connection.connector, status: connection.status })),
207
+ connectedAt: org.connected_at,
208
+ expiresAt: org.expires_at,
209
+ revokedAt: org.revoked_at,
210
+ };
211
+ }
212
+ export class OrgsApi {
213
+ http;
214
+ constructor(http) {
215
+ this.http = http;
216
+ }
217
+ async page(query = {}) {
218
+ const params = new URLSearchParams();
219
+ if (query.status)
220
+ params.set('status', query.status);
221
+ if (query.limit !== undefined)
222
+ params.set('limit', String(query.limit));
223
+ if (query.cursor)
224
+ params.set('cursor', query.cursor);
225
+ const response = await this.http.request('GET', '/v1/orgs', { query: params });
226
+ return { orgs: response.orgs.map(mapOrg), nextCursor: response.next_cursor };
227
+ }
228
+ async list(query = {}) {
229
+ const { orgs } = await this.page(query);
230
+ return orgs;
231
+ }
232
+ async *iterate(query = {}) {
233
+ let cursor;
234
+ for (;;) {
235
+ const { orgs, nextCursor } = await this.page({ ...query, cursor });
236
+ for (const org of orgs)
237
+ yield org;
238
+ if (!nextCursor)
239
+ return;
240
+ cursor = nextCursor;
241
+ }
242
+ }
243
+ async get(orgId) {
244
+ const response = await this.http.request('GET', `/v1/orgs/${encodeURIComponent(orgId)}`);
245
+ return mapOrg(response);
246
+ }
247
+ }
199
248
  const DEFAULT_BASE_URL = 'https://api.valtrix.vojtadrmota.com';
249
+ let cachedFileEnv = null;
250
+ function fileEnv(name) {
251
+ if (typeof process === 'undefined' || !process.getBuiltinModule)
252
+ return undefined;
253
+ const cwd = process.cwd();
254
+ if (!cachedFileEnv || cachedFileEnv.cwd !== cwd) {
255
+ const values = {};
256
+ try {
257
+ const fs = process.getBuiltinModule('node:fs');
258
+ for (const file of ENV_FILES) {
259
+ try {
260
+ Object.assign(values, parseEnvFile(fs.readFileSync(`${cwd}/${file}`, 'utf8')));
261
+ }
262
+ catch {
263
+ continue;
264
+ }
265
+ }
266
+ }
267
+ catch {
268
+ return undefined;
269
+ }
270
+ cachedFileEnv = { cwd, values };
271
+ }
272
+ return cachedFileEnv.values[name];
273
+ }
200
274
  function resolveEnv(name) {
201
275
  if (typeof process === 'undefined')
202
276
  return undefined;
203
- return process.env?.[name];
277
+ return process.env?.[name] ?? fileEnv(name);
204
278
  }
205
279
  export function createClient(config) {
206
280
  const apiKey = config.apiKey ?? resolveEnv('VALTRIX_API_KEY');
@@ -223,7 +297,22 @@ export function createClient(config) {
223
297
  records[entityType] = new RecordHandle(http, entityType);
224
298
  }
225
299
  client.records = records;
300
+ client.recordById = async (recordId) => {
301
+ const response = await http.request('GET', `/v1/records/by-id/${encodeURIComponent(recordId)}`);
302
+ return {
303
+ record: {
304
+ id: response.record.id,
305
+ entityType: response.record.entity_type,
306
+ externalId: response.record.external_id,
307
+ orgId: response.record.org_id,
308
+ data: response.record.data,
309
+ syncedAt: response.record.synced_at,
310
+ },
311
+ tables: response.tables,
312
+ };
313
+ };
226
314
  client.connect = new ConnectApi(http);
315
+ client.orgs = new OrgsApi(http);
227
316
  client.schema = () => http.request('GET', '/v1/schema');
228
317
  return client;
229
318
  }
package/dist/codegen.js CHANGED
@@ -53,7 +53,14 @@ export function emitClientSource(schema, options = {}) {
53
53
  parts.push('');
54
54
  tables.forEach((table, index) => {
55
55
  const { interfaceName } = tableProperties[index];
56
- const header = docComment(`Table "${table.name}" (${table.entity_type}), schema ${table.schema_version ?? 'unpublished'}.`, [], '');
56
+ const identityNote = table.row_identity === 'record'
57
+ ? ' Rows keep their source record ids; _record_id resolves via recordById().'
58
+ : table.row_identity === 'synthetic'
59
+ ? ' Rows are derived aggregates; _record_id is synthetic (syn_ prefix) and does not resolve to a record.'
60
+ : table.row_identity === 'mixed'
61
+ ? ' Rows mix source record ids and synthetic (syn_ prefixed) ids; only record ids resolve via recordById().'
62
+ : '';
63
+ const header = docComment(`Table "${table.name}" (${table.entity_type}), schema ${table.schema_version ?? 'unpublished'}.${identityNote}`, [], '');
57
64
  parts.push(`${header}export interface ${interfaceName} {`);
58
65
  for (const column of table.columns) {
59
66
  const doc = columnDoc(column, ' ');
package/dist/env.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export declare const ENV_FILES: string[];
2
+ export declare function parseEnvFile(content: string): Record<string, string>;
package/dist/env.js ADDED
@@ -0,0 +1,23 @@
1
+ export const ENV_FILES = ['.env', '.env.local'];
2
+ export function parseEnvFile(content) {
3
+ const values = {};
4
+ for (const line of content.split(/\r?\n/)) {
5
+ const trimmed = line.trim();
6
+ if (!trimmed || trimmed.startsWith('#'))
7
+ continue;
8
+ const withoutExport = trimmed.startsWith('export ') ? trimmed.slice(7).trim() : trimmed;
9
+ const separator = withoutExport.indexOf('=');
10
+ if (separator === -1)
11
+ continue;
12
+ const key = withoutExport.slice(0, separator).trim();
13
+ if (!key)
14
+ continue;
15
+ let value = withoutExport.slice(separator + 1).trim();
16
+ const quote = value[0];
17
+ if ((quote === '"' || quote === "'") && value.endsWith(quote) && value.length >= 2) {
18
+ value = value.slice(1, -1);
19
+ }
20
+ values[key] = value;
21
+ }
22
+ return values;
23
+ }
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- export { ConnectApi, createClient, RecordHandle, TableHandle, } from './client.js';
2
- export type { ClientShape, CreateClientConfig, FindManyQuery, MetaFields, OrderBy, RowsPage, TableChange, TableWriteOutcome, UpsertResult, ValtrixClient, Where, WhereOperators, WhereValue, } from './client.js';
1
+ export { ConnectApi, createClient, OrgsApi, RecordHandle, TableHandle, } from './client.js';
2
+ export type { ClientShape, CreateClientConfig, FindManyQuery, MetaFields, OrderBy, Org, OrgsPage, OrgsQuery, OrgStatus, RecordIdFilter, RowsPage, TableChange, TableWriteOutcome, UpsertResult, ValtrixClient, Where, WhereOperators, WhereValue, } from './client.js';
3
3
  export { errorFromResponse, ValtrixAuthError, ValtrixCursorExpiredError, ValtrixError, ValtrixRateLimitError, } from './errors.js';
4
4
  export type { FieldIssue } from './errors.js';
5
5
  export { camelCase, emitClientSource, pascalCase } from './codegen.js';
6
6
  export type { GeneratedClient } from './codegen.js';
7
7
  export { runCli } from './cli.js';
8
- export type { ApiChange, ApiChangesResponse, ApiColumn, ApiConnectSessionResponse, ApiRecordType, ApiRowsResponse, ApiSchema, ApiTable, ApiUpsertResponse, } from './protocol.js';
8
+ export type { ApiChange, ApiChangesResponse, ApiColumn, ApiConnectSessionResponse, ApiDeleteResponse, ApiOrg, ApiOrgConnection, ApiOrgsResponse, ApiRecord, ApiRecordResponse, ApiRecordType, ApiRowsResponse, ApiSchema, ApiTable, ApiTableOutcome, ApiUpsertResponse, } from './protocol.js';
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export { ConnectApi, createClient, RecordHandle, TableHandle, } from './client.js';
1
+ export { ConnectApi, createClient, OrgsApi, RecordHandle, TableHandle, } from './client.js';
2
2
  export { errorFromResponse, ValtrixAuthError, ValtrixCursorExpiredError, ValtrixError, ValtrixRateLimitError, } from './errors.js';
3
3
  export { camelCase, emitClientSource, pascalCase } from './codegen.js';
4
4
  export { runCli } from './cli.js';
@@ -10,6 +10,7 @@ export type ApiTable = {
10
10
  entity_type: string;
11
11
  status: string;
12
12
  row_count: number;
13
+ row_identity: 'record' | 'synthetic' | 'mixed' | null;
13
14
  last_built_at: string | null;
14
15
  schema_version: string | null;
15
16
  columns: ApiColumn[];
@@ -80,3 +81,23 @@ export type ApiConnectSessionResponse = {
80
81
  connect_url: string;
81
82
  expires_at: string;
82
83
  };
84
+ export type ApiOrgConnection = {
85
+ connector: string;
86
+ status: string;
87
+ };
88
+ export type ApiOrg = {
89
+ id: string;
90
+ display_name: string;
91
+ status: 'active' | 'revoked' | 'expired';
92
+ scope: {
93
+ entity_types: string[];
94
+ };
95
+ connections: ApiOrgConnection[];
96
+ connected_at: string;
97
+ expires_at: string | null;
98
+ revoked_at: string | null;
99
+ };
100
+ export type ApiOrgsResponse = {
101
+ orgs: ApiOrg[];
102
+ next_cursor: string | null;
103
+ };
package/package.json CHANGED
@@ -1,47 +1,53 @@
1
1
  {
2
- "name": "@valtrix/sdk",
3
- "version": "0.1.1",
4
- "description": "Typed client and codegen CLI for the Valtrix Tables API. Run valtrix generate to get a client typed against your published tables.",
5
- "license": "MIT",
6
- "type": "module",
7
- "main": "./dist/index.js",
8
- "types": "./dist/index.d.ts",
9
- "exports": {
10
- ".": {
11
- "types": "./dist/index.d.ts",
12
- "import": "./dist/index.js"
2
+ "name": "@valtrix/sdk",
3
+ "version": "0.3.0",
4
+ "description": "Typed client and codegen CLI for the Valtrix Tables API. Run valtrix generate to get a client typed against your published tables.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "src/index.ts",
8
+ "types": "src/index.ts",
9
+ "exports": {
10
+ ".": "./src/index.ts"
11
+ },
12
+ "bin": {
13
+ "valtrix": "./bin/valtrix.mjs"
14
+ },
15
+ "files": [
16
+ "bin",
17
+ "dist"
18
+ ],
19
+ "keywords": [
20
+ "valtrix",
21
+ "sdk",
22
+ "typed-client",
23
+ "codegen",
24
+ "data-api"
25
+ ],
26
+ "engines": {
27
+ "node": ">=18.17"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public",
31
+ "main": "./dist/index.js",
32
+ "types": "./dist/index.d.ts",
33
+ "exports": {
34
+ ".": {
35
+ "types": "./dist/index.d.ts",
36
+ "import": "./dist/index.js"
37
+ }
38
+ }
39
+ },
40
+ "scripts": {
41
+ "build": "tsc -p tsconfig.build.json",
42
+ "prepublishOnly": "pnpm build && pnpm test:run",
43
+ "typecheck": "tsc --noEmit",
44
+ "test": "vitest",
45
+ "test:run": "vitest run"
46
+ },
47
+ "devDependencies": {
48
+ "@types/node": "^25.0.8",
49
+ "@valtrix/tsconfig": "workspace:*",
50
+ "typescript": "^5.9.3",
51
+ "vitest": "^4.0.17"
13
52
  }
14
- },
15
- "bin": {
16
- "valtrix": "./bin/valtrix.mjs"
17
- },
18
- "files": [
19
- "bin",
20
- "dist"
21
- ],
22
- "keywords": [
23
- "valtrix",
24
- "sdk",
25
- "typed-client",
26
- "codegen",
27
- "data-api"
28
- ],
29
- "engines": {
30
- "node": ">=18.17"
31
- },
32
- "publishConfig": {
33
- "access": "public"
34
- },
35
- "devDependencies": {
36
- "@types/node": "^25.0.8",
37
- "typescript": "^5.9.3",
38
- "vitest": "^4.0.17",
39
- "@valtrix/tsconfig": "1.0.0"
40
- },
41
- "scripts": {
42
- "build": "tsc -p tsconfig.build.json",
43
- "typecheck": "tsc --noEmit",
44
- "test": "vitest",
45
- "test:run": "vitest run"
46
- }
47
- }
53
+ }
package/src/index.ts ADDED
@@ -0,0 +1,56 @@
1
+ export {
2
+ ConnectApi,
3
+ createClient,
4
+ OrgsApi,
5
+ RecordHandle,
6
+ TableHandle,
7
+ } from './client.js'
8
+ export type {
9
+ ClientShape,
10
+ CreateClientConfig,
11
+ FindManyQuery,
12
+ MetaFields,
13
+ OrderBy,
14
+ Org,
15
+ OrgsPage,
16
+ OrgsQuery,
17
+ OrgStatus,
18
+ RecordIdFilter,
19
+ RowsPage,
20
+ TableChange,
21
+ TableWriteOutcome,
22
+ UpsertResult,
23
+ ValtrixClient,
24
+ Where,
25
+ WhereOperators,
26
+ WhereValue,
27
+ } from './client.js'
28
+ export {
29
+ errorFromResponse,
30
+ ValtrixAuthError,
31
+ ValtrixCursorExpiredError,
32
+ ValtrixError,
33
+ ValtrixRateLimitError,
34
+ } from './errors.js'
35
+ export type { FieldIssue } from './errors.js'
36
+ export { camelCase, emitClientSource, pascalCase } from './codegen.js'
37
+ export type { GeneratedClient } from './codegen.js'
38
+ export { runCli } from './cli.js'
39
+ export type {
40
+ ApiChange,
41
+ ApiChangesResponse,
42
+ ApiColumn,
43
+ ApiConnectSessionResponse,
44
+ ApiDeleteResponse,
45
+ ApiOrg,
46
+ ApiOrgConnection,
47
+ ApiOrgsResponse,
48
+ ApiRecord,
49
+ ApiRecordResponse,
50
+ ApiRecordType,
51
+ ApiRowsResponse,
52
+ ApiSchema,
53
+ ApiTable,
54
+ ApiTableOutcome,
55
+ ApiUpsertResponse,
56
+ } from './protocol.js'