@simple-ai-lab/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.
package/LICENSE ADDED
@@ -0,0 +1,93 @@
1
+ Elastic License 2.0
2
+
3
+ URL: https://www.elastic.co/licensing/elastic-license
4
+
5
+ ## Acceptance
6
+
7
+ By using the software, you agree to all of the terms and conditions below.
8
+
9
+ ## Copyright License
10
+
11
+ The licensor grants you a non-exclusive, royalty-free, worldwide,
12
+ non-sublicensable, non-transferable license to use, copy, distribute, make
13
+ available, and prepare derivative works of the software, in each case subject to
14
+ the limitations and conditions below.
15
+
16
+ ## Limitations
17
+
18
+ You may not provide the software to third parties as a hosted or managed
19
+ service, where the service provides users with access to any substantial set of
20
+ the features or functionality of the software.
21
+
22
+ You may not move, change, disable, or circumvent the license key functionality
23
+ in the software, and you may not remove or obscure any functionality in the
24
+ software that is protected by the license key.
25
+
26
+ You may not alter, remove, or obscure any licensing, copyright, or other notices
27
+ of the licensor in the software. Any use of the licensor’s trademarks is subject
28
+ to applicable law.
29
+
30
+ ## Patents
31
+
32
+ The licensor grants you a license, under any patent claims the licensor can
33
+ license, or becomes able to license, to make, have made, use, sell, offer for
34
+ sale, import and have imported the software, in each case subject to the
35
+ limitations and conditions in this license. This license does not cover any
36
+ patent claims that you cause to be infringed by modifications or additions to
37
+ the software. If you or your company make any written claim that the software
38
+ infringes or contributes to infringement of any patent, your patent license for
39
+ the software granted under these terms ends immediately. If your company makes
40
+ such a claim, your patent license ends immediately for work on behalf of your
41
+ company.
42
+
43
+ ## Notices
44
+
45
+ You must ensure that anyone who gets a copy of any part of the software from you
46
+ also gets a copy of these terms.
47
+
48
+ If you modify the software, you must include in any modified copies of the
49
+ software prominent notices stating that you have modified the software.
50
+
51
+ ## No Other Rights
52
+
53
+ These terms do not imply any licenses other than those expressly granted in
54
+ these terms.
55
+
56
+ ## Termination
57
+
58
+ If you use the software in violation of these terms, such use is not licensed,
59
+ and your licenses will automatically terminate. If the licensor provides you
60
+ with a notice of your violation, and you cease all violation of this license no
61
+ later than 30 days after you receive that notice, your licenses will be
62
+ reinstated retroactively. However, if you violate these terms after such
63
+ reinstatement, any additional violation of these terms will cause your licenses
64
+ to terminate automatically and permanently.
65
+
66
+ ## No Liability
67
+
68
+ *As far as the law allows, the software comes as is, without any warranty or
69
+ condition, and the licensor will not be liable to you for any damages arising
70
+ out of these terms or the use or nature of the software, under any kind of
71
+ legal claim.*
72
+
73
+ ## Definitions
74
+
75
+ The **licensor** is the entity offering these terms, and the **software** is the
76
+ software the licensor makes available under these terms, including any portion
77
+ of it.
78
+
79
+ **you** refers to the individual or entity agreeing to these terms.
80
+
81
+ **your company** is any legal entity, sole proprietorship, or other kind of
82
+ organization that you work for, plus all organizations that have control over,
83
+ are under the control of, or are under common control with that
84
+ organization. **control** means ownership of substantially all the assets of an
85
+ entity, or the power to direct its management and policies by vote, contract, or
86
+ otherwise. Control can be direct or indirect.
87
+
88
+ **your licenses** are all the licenses granted to you for the software under
89
+ these terms.
90
+
91
+ **use** means anything you do with the software requiring one of your licenses.
92
+
93
+ **trademark** means trademarks, service marks, and similar rights.
package/README.md ADDED
@@ -0,0 +1,47 @@
1
+ # Simple AI SDK
2
+
3
+ Typed TypeScript client for the [Simple AI](https://usesimple.ai) API. Use it inside Simple AI code actions (preinstalled and authenticated automatically) or in your own applications with an API key.
4
+
5
+ ```bash
6
+ npm install @simple-ai-lab/sdk
7
+ ```
8
+
9
+ ## Inside a code action
10
+
11
+ ```typescript
12
+ import { defineAction } from '@simple-ai-lab/sdk';
13
+
14
+ export default defineAction(async ({ inputs, config, client }) => {
15
+ const { records } = await client.data.query({
16
+ tableName: 'customers',
17
+ filters: [{ column: 'email', values: [inputs.email] }],
18
+ });
19
+ return { found: records.length > 0 };
20
+ });
21
+ ```
22
+
23
+ No API key handling needed — the sandbox injects short-lived, organization-scoped credentials automatically.
24
+
25
+ ## In your own application
26
+
27
+ ```typescript
28
+ import { SimpleAI } from '@simple-ai-lab/sdk';
29
+
30
+ // Reads SIMPLE_API_KEY from the environment (dashboard: Settings → API Keys)
31
+ const client = new SimpleAI();
32
+
33
+ const { records, total } = await client.data.query({
34
+ tableName: 'orders',
35
+ text: 'ORD-1042',
36
+ });
37
+ ```
38
+
39
+ `client.data` covers custom data end to end: `query`, `facets`, `list`, `get`, `create`, `update`, `delete`, `deleteAll`, `batchUpsert`, and `getBatch`. Errors throw `SimpleAIError` with the HTTP `status`, machine-readable `code`, and parsed `body`.
40
+
41
+ ## Documentation
42
+
43
+ Full docs: https://docs.usesimple.ai — see the SDK Quickstart and Code Actions guides.
44
+
45
+ ## License
46
+
47
+ [Elastic License 2.0](./LICENSE) — free to use; the SDK may not be provided to third parties as a hosted or managed service.
package/dist/index.cjs ADDED
@@ -0,0 +1,302 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ DataClient: () => DataClient,
24
+ MAX_BATCH_ROWS: () => MAX_BATCH_ROWS,
25
+ MAX_QUERY_SIZE: () => MAX_QUERY_SIZE,
26
+ SIMPLE_ACTION_BRAND: () => SIMPLE_ACTION_BRAND,
27
+ SimpleAI: () => SimpleAI,
28
+ SimpleAIError: () => SimpleAIError,
29
+ batchUpsertRowsSchema: () => batchUpsertRowsSchema,
30
+ dataColumnPathSchema: () => dataColumnPathSchema,
31
+ dataFilterSchema: () => dataFilterSchema,
32
+ defineAction: () => defineAction,
33
+ listOptionsSchema: () => listOptionsSchema,
34
+ queryInputSchema: () => queryInputSchema,
35
+ recordPayloadSchema: () => recordPayloadSchema,
36
+ tableNameSchema: () => tableNameSchema
37
+ });
38
+ module.exports = __toCommonJS(index_exports);
39
+
40
+ // src/schemas.ts
41
+ var import_zod = require("zod");
42
+ var MAX_QUERY_SIZE = 50;
43
+ var MAX_BATCH_ROWS = 1e3;
44
+ var tableNameSchema = import_zod.z.string().regex(/^[a-z0-9_]+$/, "Table names are lowercase snake_case identifiers");
45
+ var filterValueSchema = import_zod.z.union([import_zod.z.string(), import_zod.z.number(), import_zod.z.boolean()]);
46
+ var dataColumnPathSchema = import_zod.z.string().trim().min(1).max(1024).refine((path) => path.split(".").every((segment) => segment.length > 0), {
47
+ message: "Must be a dot-separated column path with no empty segments"
48
+ });
49
+ var dataFilterSchema = import_zod.z.object({
50
+ column: dataColumnPathSchema,
51
+ values: import_zod.z.array(filterValueSchema)
52
+ });
53
+ var queryInputSchema = import_zod.z.object({
54
+ tableName: tableNameSchema,
55
+ filters: import_zod.z.array(dataFilterSchema).optional(),
56
+ text: import_zod.z.string().max(5e3).optional(),
57
+ size: import_zod.z.number().int().min(0).max(MAX_QUERY_SIZE).optional(),
58
+ from: import_zod.z.number().int().min(0).optional()
59
+ });
60
+ var listOptionsSchema = import_zod.z.object({
61
+ page: import_zod.z.number().int().min(1).optional(),
62
+ perPage: import_zod.z.number().int().min(1).max(200).optional(),
63
+ orderBy: import_zod.z.string().optional(),
64
+ orderDirection: import_zod.z.enum(["asc", "desc"]).optional(),
65
+ /** Column-name → value equality filters applied server-side. */
66
+ filters: import_zod.z.record(import_zod.z.string(), import_zod.z.string()).optional()
67
+ });
68
+ var recordPayloadSchema = import_zod.z.record(import_zod.z.string(), import_zod.z.unknown());
69
+ var batchUpsertRowsSchema = import_zod.z.array(recordPayloadSchema).min(1).max(MAX_BATCH_ROWS);
70
+
71
+ // src/data.ts
72
+ function encodeTable(tableName) {
73
+ return encodeURIComponent(tableNameSchema.parse(tableName));
74
+ }
75
+ var DataClient = class {
76
+ #http;
77
+ constructor(http) {
78
+ this.#http = http;
79
+ }
80
+ /** Facet-filtered search over an indexed table (Elasticsearch-backed, max 50 hits). */
81
+ async query(input) {
82
+ const parsed = queryInputSchema.parse(input);
83
+ const result = await this.#http.request({ method: "POST", path: "/data/query", body: parsed });
84
+ return result;
85
+ }
86
+ /** Facet values for an indexed table. */
87
+ async facets(tableName) {
88
+ const result = await this.#http.request({ method: "GET", path: `/data/facets/${encodeTable(tableName)}` });
89
+ return result;
90
+ }
91
+ /** Paginated listing straight from the relational store. */
92
+ async list(tableName, options = {}) {
93
+ const parsed = listOptionsSchema.parse(options);
94
+ const query = { ...parsed.filters ?? {} };
95
+ if (parsed.page !== void 0) {
96
+ query.page = String(parsed.page);
97
+ }
98
+ if (parsed.perPage !== void 0) {
99
+ query.per_page = String(parsed.perPage);
100
+ }
101
+ if (parsed.orderBy !== void 0) {
102
+ query.order_by = parsed.orderBy;
103
+ }
104
+ if (parsed.orderDirection !== void 0) {
105
+ query.order_direction = parsed.orderDirection;
106
+ }
107
+ const result = await this.#http.request({ method: "GET", path: `/data/${encodeTable(tableName)}`, query });
108
+ return result;
109
+ }
110
+ async get(tableName, id) {
111
+ const result = await this.#http.request({ method: "GET", path: `/data/${encodeTable(tableName)}/${id}` });
112
+ return result;
113
+ }
114
+ async create(tableName, payload) {
115
+ const result = await this.#http.request({
116
+ method: "PUT",
117
+ path: `/data/${encodeTable(tableName)}`,
118
+ body: recordPayloadSchema.parse(payload)
119
+ });
120
+ return result;
121
+ }
122
+ async update(tableName, id, payload) {
123
+ const result = await this.#http.request({
124
+ method: "PATCH",
125
+ path: `/data/${encodeTable(tableName)}/${id}`,
126
+ body: recordPayloadSchema.parse(payload)
127
+ });
128
+ return result;
129
+ }
130
+ async delete(tableName, id) {
131
+ const result = await this.#http.request({ method: "DELETE", path: `/data/${encodeTable(tableName)}/${id}` });
132
+ return result;
133
+ }
134
+ /** Deletes every record in the table. Irreversible. */
135
+ async deleteAll(tableName) {
136
+ const result = await this.#http.request({ method: "DELETE", path: `/data/${encodeTable(tableName)}` });
137
+ return result;
138
+ }
139
+ /**
140
+ * Asynchronous bulk upsert (max 1000 rows per call). Rows are FULL-ROW
141
+ * REPLACE on key conflict — omitted columns are cleared, not preserved.
142
+ * Returns a batch handle; poll `getBatch` for completion.
143
+ */
144
+ async batchUpsert(tableName, rows) {
145
+ const result = await this.#http.request({
146
+ method: "PUT",
147
+ path: `/data/${encodeTable(tableName)}/batch`,
148
+ body: { rows: batchUpsertRowsSchema.parse(rows) }
149
+ });
150
+ return result;
151
+ }
152
+ /** Status of an async upsert batch created by `batchUpsert`. */
153
+ async getBatch(ingestBatchId) {
154
+ const result = await this.#http.request({
155
+ method: "GET",
156
+ path: `/data/_batches/${encodeURIComponent(ingestBatchId)}`
157
+ });
158
+ return result;
159
+ }
160
+ };
161
+
162
+ // src/errors.ts
163
+ var SimpleAIError = class extends Error {
164
+ /** HTTP status code, or 0 when the request never reached the API. */
165
+ status;
166
+ /** Machine-readable error code from the API body, when present. */
167
+ code;
168
+ /** The parsed response body (JSON when possible, otherwise raw text). */
169
+ body;
170
+ constructor({
171
+ message,
172
+ status,
173
+ code,
174
+ body,
175
+ cause
176
+ }) {
177
+ super(message, cause === void 0 ? void 0 : { cause });
178
+ this.name = "SimpleAIError";
179
+ this.status = status;
180
+ this.code = code;
181
+ this.body = body;
182
+ }
183
+ };
184
+
185
+ // src/http.ts
186
+ function parseBody(text) {
187
+ if (text.length === 0) {
188
+ return null;
189
+ }
190
+ try {
191
+ return JSON.parse(text);
192
+ } catch {
193
+ return text;
194
+ }
195
+ }
196
+ function errorDetails(body) {
197
+ if (body !== null && typeof body === "object") {
198
+ const record = body;
199
+ const code = typeof record.code === "string" ? record.code : null;
200
+ const message = typeof record.message === "string" ? record.message : typeof record.error === "string" ? record.error : null;
201
+ return { code, message };
202
+ }
203
+ return { code: null, message: typeof body === "string" && body.length > 0 ? body : null };
204
+ }
205
+ function createHttpClient({
206
+ baseUrl,
207
+ apiKey,
208
+ fetchImplementation
209
+ }) {
210
+ const normalizedBase = baseUrl.replace(/\/+$/, "");
211
+ return {
212
+ request: async ({ method, path, query, body }) => {
213
+ const queryString = query === void 0 || Object.keys(query).length === 0 ? "" : `?${new URLSearchParams(query).toString()}`;
214
+ const url = `${normalizedBase}${path}${queryString}`;
215
+ let response;
216
+ try {
217
+ response = await fetchImplementation(url, {
218
+ method,
219
+ headers: {
220
+ authorization: `Bearer ${apiKey}`,
221
+ "content-type": "application/json",
222
+ accept: "application/json"
223
+ },
224
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
225
+ });
226
+ } catch (e) {
227
+ throw new SimpleAIError({
228
+ message: `Request to ${method} ${path} failed: ${e instanceof Error ? e.message : String(e)}`,
229
+ status: 0,
230
+ code: "network_error",
231
+ body: null,
232
+ cause: e
233
+ });
234
+ }
235
+ const parsed = parseBody(await response.text());
236
+ if (!response.ok) {
237
+ const { code, message } = errorDetails(parsed);
238
+ throw new SimpleAIError({
239
+ message: message ?? `Request to ${method} ${path} failed with status ${response.status}`,
240
+ status: response.status,
241
+ code,
242
+ body: parsed
243
+ });
244
+ }
245
+ return parsed;
246
+ }
247
+ };
248
+ }
249
+
250
+ // src/client.ts
251
+ var DEFAULT_BASE_URL = "https://api.prod.usesimple.ai/api/v1";
252
+ function envVar(name) {
253
+ if (typeof process === "undefined" || process.env === void 0) {
254
+ return void 0;
255
+ }
256
+ const value = process.env[name];
257
+ return value === void 0 || value === "" ? void 0 : value;
258
+ }
259
+ var SimpleAI = class {
260
+ /** Custom data tables — query, read, and write records. */
261
+ data;
262
+ constructor(options = {}) {
263
+ const apiKey = options.apiKey ?? envVar("SIMPLE_API_KEY");
264
+ if (apiKey === void 0) {
265
+ throw new Error(
266
+ "Missing API key. Pass `apiKey` to new SimpleAI(...) or set the SIMPLE_API_KEY environment variable. Inside Simple AI code actions the key is injected automatically."
267
+ );
268
+ }
269
+ const baseUrl = options.baseUrl ?? envVar("SIMPLE_BASE_URL") ?? DEFAULT_BASE_URL;
270
+ const fetchImplementation = options.fetch ?? ((url, init) => fetch(url, init));
271
+ const http = createHttpClient({ baseUrl, apiKey, fetchImplementation });
272
+ this.data = new DataClient(http);
273
+ }
274
+ };
275
+
276
+ // src/define-action.ts
277
+ var SIMPLE_ACTION_BRAND = /* @__PURE__ */ Symbol.for("simple-ai.action");
278
+ function defineAction(handler) {
279
+ const wrapped = async ({ inputs, config }) => {
280
+ const client = new SimpleAI();
281
+ return handler({ inputs, config, client });
282
+ };
283
+ return Object.assign(wrapped, { [SIMPLE_ACTION_BRAND]: true });
284
+ }
285
+ // Annotate the CommonJS export names for ESM import in node:
286
+ 0 && (module.exports = {
287
+ DataClient,
288
+ MAX_BATCH_ROWS,
289
+ MAX_QUERY_SIZE,
290
+ SIMPLE_ACTION_BRAND,
291
+ SimpleAI,
292
+ SimpleAIError,
293
+ batchUpsertRowsSchema,
294
+ dataColumnPathSchema,
295
+ dataFilterSchema,
296
+ defineAction,
297
+ listOptionsSchema,
298
+ queryInputSchema,
299
+ recordPayloadSchema,
300
+ tableNameSchema
301
+ });
302
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/schemas.ts","../src/data.ts","../src/errors.ts","../src/http.ts","../src/client.ts","../src/define-action.ts"],"sourcesContent":["export { SimpleAI, type SimpleAIOptions } from './client';\nexport { DataClient } from './data';\nexport {\n type ActionContext,\n type ActionHandler,\n defineAction,\n SIMPLE_ACTION_BRAND,\n} from './define-action';\nexport { SimpleAIError } from './errors';\nexport type {\n BatchUpsertResult,\n DataFilter,\n DataRecord,\n DeleteResult,\n FacetsResult,\n IngestBatchStatus,\n ListOptions,\n ListResult,\n QueryInput,\n QueryResult,\n RecordPayload,\n RecordResult,\n} from './schemas';\nexport {\n batchUpsertRowsSchema,\n dataColumnPathSchema,\n dataFilterSchema,\n listOptionsSchema,\n MAX_BATCH_ROWS,\n MAX_QUERY_SIZE,\n queryInputSchema,\n recordPayloadSchema,\n tableNameSchema,\n} from './schemas';\n","import { z } from 'zod';\n\n/**\n * Request wire schemas for the Simple AI public REST API (`/api/v1`).\n *\n * These deliberately mirror the server's own schemas (see\n * `projects/server-v2/src/domains/data/query-schemas.ts` and\n * `domains/data/public/types.ts`); a contract test in server-v2 keeps the two\n * in sync. Responses are typed but not strictly validated, so additive server\n * changes never break deployed SDK consumers.\n */\n\n/** Hard cap on hits a single query may return. */\nexport const MAX_QUERY_SIZE = 50;\n/** Maximum rows accepted by a single batch-upsert chunk. */\nexport const MAX_BATCH_ROWS = 1000;\n\nexport const tableNameSchema = z.string().regex(/^[a-z0-9_]+$/, 'Table names are lowercase snake_case identifiers');\n\nexport const filterValueSchema = z.union([z.string(), z.number(), z.boolean()]);\n\n// Mirrors the server's customDataFacetAttributePathSchema: dot-separated\n// column paths with no empty segments (OBJECT leaves are parent.child).\nexport const dataColumnPathSchema = z\n .string()\n .trim()\n .min(1)\n .max(1024)\n .refine((path) => path.split('.').every((segment) => segment.length > 0), {\n message: 'Must be a dot-separated column path with no empty segments',\n });\n\nexport const dataFilterSchema = z.object({\n column: dataColumnPathSchema,\n values: z.array(filterValueSchema),\n});\nexport type DataFilter = z.infer<typeof dataFilterSchema>;\n\nexport const queryInputSchema = z.object({\n tableName: tableNameSchema,\n filters: z.array(dataFilterSchema).optional(),\n text: z.string().max(5000).optional(),\n size: z.number().int().min(0).max(MAX_QUERY_SIZE).optional(),\n from: z.number().int().min(0).optional(),\n});\nexport type QueryInput = z.input<typeof queryInputSchema>;\n\nexport const listOptionsSchema = z.object({\n page: z.number().int().min(1).optional(),\n perPage: z.number().int().min(1).max(200).optional(),\n orderBy: z.string().optional(),\n orderDirection: z.enum(['asc', 'desc']).optional(),\n /** Column-name → value equality filters applied server-side. */\n filters: z.record(z.string(), z.string()).optional(),\n});\nexport type ListOptions = z.input<typeof listOptionsSchema>;\n\nexport const recordPayloadSchema = z.record(z.string(), z.unknown());\nexport type RecordPayload = z.infer<typeof recordPayloadSchema>;\n\nexport const batchUpsertRowsSchema = z.array(recordPayloadSchema).min(1).max(MAX_BATCH_ROWS);\n\n// ---------------------------------------------------------------------------\n// Response types (typed, tolerantly parsed)\n// ---------------------------------------------------------------------------\n\nexport type DataRecord = Record<string, unknown>;\n\nexport type QueryResult = {\n records: DataRecord[];\n total: number;\n};\n\nexport type ListResult = {\n records: DataRecord[];\n total_count: number;\n page: number;\n per_page: number;\n};\n\nexport type RecordResult = {\n record: DataRecord;\n};\n\nexport type DeleteResult = {\n success: boolean;\n message: string;\n};\n\nexport type BatchUpsertResult = {\n ingestBatchId: string;\n status: string;\n};\n\nexport type IngestBatchStatus = {\n id: string;\n tableName: string;\n status: string;\n rowCount: number;\n upsertedCount: number | null;\n errorMessage: string | null;\n createdAt: string;\n startedAt: string | null;\n finishedAt: string | null;\n};\n\nexport type FacetsResult = Record<string, unknown>;\n","import type { HttpClient } from './http';\nimport {\n type BatchUpsertResult,\n batchUpsertRowsSchema,\n type DataRecord,\n type DeleteResult,\n type FacetsResult,\n type IngestBatchStatus,\n type ListOptions,\n type ListResult,\n listOptionsSchema,\n type QueryInput,\n type QueryResult,\n queryInputSchema,\n type RecordPayload,\n type RecordResult,\n recordPayloadSchema,\n tableNameSchema,\n} from './schemas';\n\nfunction encodeTable(tableName: string): string {\n return encodeURIComponent(tableNameSchema.parse(tableName));\n}\n\n/**\n * Custom data tables — query, read, and write your organization's records.\n * Wraps the `/api/v1/data` REST endpoints.\n */\nexport class DataClient {\n readonly #http: HttpClient;\n\n constructor(http: HttpClient) {\n this.#http = http;\n }\n\n /** Facet-filtered search over an indexed table (Elasticsearch-backed, max 50 hits). */\n async query<TRecord extends DataRecord = DataRecord>(\n input: QueryInput\n ): Promise<{ records: TRecord[]; total: number }> {\n const parsed = queryInputSchema.parse(input);\n const result = await this.#http.request({ method: 'POST', path: '/data/query', body: parsed });\n return result as { records: TRecord[]; total: number };\n }\n\n /** Facet values for an indexed table. */\n async facets(tableName: string): Promise<FacetsResult> {\n const result = await this.#http.request({ method: 'GET', path: `/data/facets/${encodeTable(tableName)}` });\n return result as FacetsResult;\n }\n\n /** Paginated listing straight from the relational store. */\n async list<TRecord extends DataRecord = DataRecord>(\n tableName: string,\n options: ListOptions = {}\n ): Promise<{ records: TRecord[]; total_count: number; page: number; per_page: number }> {\n const parsed = listOptionsSchema.parse(options);\n const query: Record<string, string> = { ...(parsed.filters ?? {}) };\n if (parsed.page !== undefined) {\n query.page = String(parsed.page);\n }\n if (parsed.perPage !== undefined) {\n query.per_page = String(parsed.perPage);\n }\n if (parsed.orderBy !== undefined) {\n query.order_by = parsed.orderBy;\n }\n if (parsed.orderDirection !== undefined) {\n query.order_direction = parsed.orderDirection;\n }\n const result = await this.#http.request({ method: 'GET', path: `/data/${encodeTable(tableName)}`, query });\n return result as ListResult & { records: TRecord[] };\n }\n\n async get<TRecord extends DataRecord = DataRecord>(tableName: string, id: number): Promise<{ record: TRecord }> {\n const result = await this.#http.request({ method: 'GET', path: `/data/${encodeTable(tableName)}/${id}` });\n return result as RecordResult & { record: TRecord };\n }\n\n async create<TRecord extends DataRecord = DataRecord>(\n tableName: string,\n payload: RecordPayload\n ): Promise<{ record: TRecord }> {\n const result = await this.#http.request({\n method: 'PUT',\n path: `/data/${encodeTable(tableName)}`,\n body: recordPayloadSchema.parse(payload),\n });\n return result as RecordResult & { record: TRecord };\n }\n\n async update<TRecord extends DataRecord = DataRecord>(\n tableName: string,\n id: number,\n payload: RecordPayload\n ): Promise<{ record: TRecord }> {\n const result = await this.#http.request({\n method: 'PATCH',\n path: `/data/${encodeTable(tableName)}/${id}`,\n body: recordPayloadSchema.parse(payload),\n });\n return result as RecordResult & { record: TRecord };\n }\n\n async delete(tableName: string, id: number): Promise<DeleteResult> {\n const result = await this.#http.request({ method: 'DELETE', path: `/data/${encodeTable(tableName)}/${id}` });\n return result as DeleteResult;\n }\n\n /** Deletes every record in the table. Irreversible. */\n async deleteAll(tableName: string): Promise<DeleteResult> {\n const result = await this.#http.request({ method: 'DELETE', path: `/data/${encodeTable(tableName)}` });\n return result as DeleteResult;\n }\n\n /**\n * Asynchronous bulk upsert (max 1000 rows per call). Rows are FULL-ROW\n * REPLACE on key conflict — omitted columns are cleared, not preserved.\n * Returns a batch handle; poll `getBatch` for completion.\n */\n async batchUpsert(tableName: string, rows: RecordPayload[]): Promise<BatchUpsertResult> {\n const result = await this.#http.request({\n method: 'PUT',\n path: `/data/${encodeTable(tableName)}/batch`,\n body: { rows: batchUpsertRowsSchema.parse(rows) },\n });\n return result as BatchUpsertResult;\n }\n\n /** Status of an async upsert batch created by `batchUpsert`. */\n async getBatch(ingestBatchId: string): Promise<IngestBatchStatus> {\n const result = await this.#http.request({\n method: 'GET',\n path: `/data/_batches/${encodeURIComponent(ingestBatchId)}`,\n });\n return result as IngestBatchStatus;\n }\n}\n","/** Error thrown for any non-2xx response from the Simple AI API. */\nexport class SimpleAIError extends Error {\n /** HTTP status code, or 0 when the request never reached the API. */\n readonly status: number;\n /** Machine-readable error code from the API body, when present. */\n readonly code: string | null;\n /** The parsed response body (JSON when possible, otherwise raw text). */\n readonly body: unknown;\n\n constructor({\n message,\n status,\n code,\n body,\n cause,\n }: {\n message: string;\n status: number;\n code: string | null;\n body: unknown;\n cause?: unknown;\n }) {\n super(message, cause === undefined ? undefined : { cause });\n this.name = 'SimpleAIError';\n this.status = status;\n this.code = code;\n this.body = body;\n }\n}\n","import { SimpleAIError } from './errors';\n\nexport type FetchLike = (url: string, init: RequestInit) => Promise<Response>;\n\nexport type HttpClient = {\n request: (args: {\n method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n path: string;\n query?: Record<string, string>;\n body?: unknown;\n }) => Promise<unknown>;\n};\n\nfunction parseBody(text: string): unknown {\n if (text.length === 0) {\n return null;\n }\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nfunction errorDetails(body: unknown): { code: string | null; message: string | null } {\n if (body !== null && typeof body === 'object') {\n const record = body as { code?: unknown; error?: unknown; message?: unknown };\n const code = typeof record.code === 'string' ? record.code : null;\n const message =\n typeof record.message === 'string' ? record.message : typeof record.error === 'string' ? record.error : null;\n return { code, message };\n }\n return { code: null, message: typeof body === 'string' && body.length > 0 ? body : null };\n}\n\nexport function createHttpClient({\n baseUrl,\n apiKey,\n fetchImplementation,\n}: {\n baseUrl: string;\n apiKey: string;\n fetchImplementation: FetchLike;\n}): HttpClient {\n const normalizedBase = baseUrl.replace(/\\/+$/, '');\n\n return {\n request: async ({ method, path, query, body }) => {\n const queryString =\n query === undefined || Object.keys(query).length === 0 ? '' : `?${new URLSearchParams(query).toString()}`;\n const url = `${normalizedBase}${path}${queryString}`;\n\n let response: Response;\n try {\n response = await fetchImplementation(url, {\n method,\n headers: {\n authorization: `Bearer ${apiKey}`,\n 'content-type': 'application/json',\n accept: 'application/json',\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n } catch (e) {\n throw new SimpleAIError({\n message: `Request to ${method} ${path} failed: ${e instanceof Error ? e.message : String(e)}`,\n status: 0,\n code: 'network_error',\n body: null,\n cause: e,\n });\n }\n\n const parsed = parseBody(await response.text());\n if (!response.ok) {\n const { code, message } = errorDetails(parsed);\n throw new SimpleAIError({\n message: message ?? `Request to ${method} ${path} failed with status ${response.status}`,\n status: response.status,\n code,\n body: parsed,\n });\n }\n return parsed;\n },\n };\n}\n","import { DataClient } from './data';\nimport type { FetchLike } from './http';\nimport { createHttpClient } from './http';\n\nconst DEFAULT_BASE_URL = 'https://api.prod.usesimple.ai/api/v1';\n\nexport type SimpleAIOptions = {\n /** API key (dashboard: Settings → API Keys). Defaults to SIMPLE_API_KEY — inside code actions this is injected automatically. */\n apiKey?: string;\n /** API base URL. Defaults to SIMPLE_BASE_URL, then the production API. */\n baseUrl?: string;\n /** Custom fetch implementation (for testing or instrumentation). */\n fetch?: FetchLike;\n};\n\nfunction envVar(name: string): string | undefined {\n if (typeof process === 'undefined' || process.env === undefined) {\n return undefined;\n }\n const value = process.env[name];\n return value === undefined || value === '' ? undefined : value;\n}\n\nexport class SimpleAI {\n /** Custom data tables — query, read, and write records. */\n readonly data: DataClient;\n\n constructor(options: SimpleAIOptions = {}) {\n const apiKey = options.apiKey ?? envVar('SIMPLE_API_KEY');\n if (apiKey === undefined) {\n throw new Error(\n 'Missing API key. Pass `apiKey` to new SimpleAI(...) or set the SIMPLE_API_KEY environment variable. ' +\n 'Inside Simple AI code actions the key is injected automatically.'\n );\n }\n const baseUrl = options.baseUrl ?? envVar('SIMPLE_BASE_URL') ?? DEFAULT_BASE_URL;\n const fetchImplementation: FetchLike = options.fetch ?? ((url, init) => fetch(url, init));\n\n const http = createHttpClient({ baseUrl, apiKey, fetchImplementation });\n this.data = new DataClient(http);\n }\n}\n","import { SimpleAI } from './client';\n\n/**\n * Brand the code-action runner uses to recognize `defineAction` handlers. The\n * runner calls the default export with `{ inputs, config }` either way; the\n * wrapper adds the authenticated `client` to the handler's context.\n */\nexport const SIMPLE_ACTION_BRAND = Symbol.for('simple-ai.action');\n\nexport type ActionContext<TInputs = Record<string, unknown>> = {\n /** The Action's declared inputs, already validated against its input schema. */\n inputs: TInputs;\n /** Your organization's configuration variables. */\n config: Record<string, string>;\n /** The Simple AI SDK, authenticated for your organization. */\n client: SimpleAI;\n};\n\nexport type ActionHandler<TInputs = Record<string, unknown>, TResult = unknown> = ((args: {\n inputs: TInputs;\n config: Record<string, string>;\n}) => Promise<TResult>) & { [SIMPLE_ACTION_BRAND]: true };\n\n/**\n * Define a code action with a typed context and an org-authenticated SDK\n * client. The returned value must be your module's default export.\n *\n * ```ts\n * import { defineAction } from '@simple-ai-lab/sdk';\n *\n * export default defineAction(async ({ inputs, config, client }) => {\n * const { records } = await client.data.query({ tableName: 'customers', text: inputs.email });\n * return { found: records.length > 0 };\n * });\n * ```\n */\nexport function defineAction<TInputs = Record<string, unknown>, TResult = unknown>(\n handler: (context: ActionContext<TInputs>) => Promise<TResult> | TResult\n): ActionHandler<TInputs, TResult> {\n const wrapped = async ({ inputs, config }: { inputs: TInputs; config: Record<string, string> }): Promise<TResult> => {\n // Constructed lazily per invocation so the injected SIMPLE_API_KEY env is\n // read at run time, not module-load time.\n const client = new SimpleAI();\n return handler({ inputs, config, client });\n };\n return Object.assign(wrapped, { [SIMPLE_ACTION_BRAND]: true as const });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,iBAAkB;AAaX,IAAM,iBAAiB;AAEvB,IAAM,iBAAiB;AAEvB,IAAM,kBAAkB,aAAE,OAAO,EAAE,MAAM,gBAAgB,kDAAkD;AAE3G,IAAM,oBAAoB,aAAE,MAAM,CAAC,aAAE,OAAO,GAAG,aAAE,OAAO,GAAG,aAAE,QAAQ,CAAC,CAAC;AAIvE,IAAM,uBAAuB,aACjC,OAAO,EACP,KAAK,EACL,IAAI,CAAC,EACL,IAAI,IAAI,EACR,OAAO,CAAC,SAAS,KAAK,MAAM,GAAG,EAAE,MAAM,CAAC,YAAY,QAAQ,SAAS,CAAC,GAAG;AAAA,EACxE,SAAS;AACX,CAAC;AAEI,IAAM,mBAAmB,aAAE,OAAO;AAAA,EACvC,QAAQ;AAAA,EACR,QAAQ,aAAE,MAAM,iBAAiB;AACnC,CAAC;AAGM,IAAM,mBAAmB,aAAE,OAAO;AAAA,EACvC,WAAW;AAAA,EACX,SAAS,aAAE,MAAM,gBAAgB,EAAE,SAAS;AAAA,EAC5C,MAAM,aAAE,OAAO,EAAE,IAAI,GAAI,EAAE,SAAS;AAAA,EACpC,MAAM,aAAE,OAAO,EAAE,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AACA,SAAO,OAAO,OAAO,SAAS,EAAE,CAAC,mBAAmB,GAAG,KAAc,CAAC;AACxE;","names":[]}
@@ -0,0 +1,202 @@
1
+ import { z } from 'zod';
2
+
3
+ type FetchLike = (url: string, init: RequestInit) => Promise<Response>;
4
+ type HttpClient = {
5
+ request: (args: {
6
+ method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
7
+ path: string;
8
+ query?: Record<string, string>;
9
+ body?: unknown;
10
+ }) => Promise<unknown>;
11
+ };
12
+
13
+ /**
14
+ * Request wire schemas for the Simple AI public REST API (`/api/v1`).
15
+ *
16
+ * These deliberately mirror the server's own schemas (see
17
+ * `projects/server-v2/src/domains/data/query-schemas.ts` and
18
+ * `domains/data/public/types.ts`); a contract test in server-v2 keeps the two
19
+ * in sync. Responses are typed but not strictly validated, so additive server
20
+ * changes never break deployed SDK consumers.
21
+ */
22
+ /** Hard cap on hits a single query may return. */
23
+ declare const MAX_QUERY_SIZE = 50;
24
+ /** Maximum rows accepted by a single batch-upsert chunk. */
25
+ declare const MAX_BATCH_ROWS = 1000;
26
+ declare const tableNameSchema: z.ZodString;
27
+ declare const dataColumnPathSchema: z.ZodString;
28
+ declare const dataFilterSchema: z.ZodObject<{
29
+ column: z.ZodString;
30
+ values: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
31
+ }, z.core.$strip>;
32
+ type DataFilter = z.infer<typeof dataFilterSchema>;
33
+ declare const queryInputSchema: z.ZodObject<{
34
+ tableName: z.ZodString;
35
+ filters: z.ZodOptional<z.ZodArray<z.ZodObject<{
36
+ column: z.ZodString;
37
+ values: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
38
+ }, z.core.$strip>>>;
39
+ text: z.ZodOptional<z.ZodString>;
40
+ size: z.ZodOptional<z.ZodNumber>;
41
+ from: z.ZodOptional<z.ZodNumber>;
42
+ }, z.core.$strip>;
43
+ type QueryInput = z.input<typeof queryInputSchema>;
44
+ declare const listOptionsSchema: z.ZodObject<{
45
+ page: z.ZodOptional<z.ZodNumber>;
46
+ perPage: z.ZodOptional<z.ZodNumber>;
47
+ orderBy: z.ZodOptional<z.ZodString>;
48
+ orderDirection: z.ZodOptional<z.ZodEnum<{
49
+ asc: "asc";
50
+ desc: "desc";
51
+ }>>;
52
+ filters: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
53
+ }, z.core.$strip>;
54
+ type ListOptions = z.input<typeof listOptionsSchema>;
55
+ declare const recordPayloadSchema: z.ZodRecord<z.ZodString, z.ZodUnknown>;
56
+ type RecordPayload = z.infer<typeof recordPayloadSchema>;
57
+ declare const batchUpsertRowsSchema: z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
58
+ type DataRecord = Record<string, unknown>;
59
+ type QueryResult = {
60
+ records: DataRecord[];
61
+ total: number;
62
+ };
63
+ type ListResult = {
64
+ records: DataRecord[];
65
+ total_count: number;
66
+ page: number;
67
+ per_page: number;
68
+ };
69
+ type RecordResult = {
70
+ record: DataRecord;
71
+ };
72
+ type DeleteResult = {
73
+ success: boolean;
74
+ message: string;
75
+ };
76
+ type BatchUpsertResult = {
77
+ ingestBatchId: string;
78
+ status: string;
79
+ };
80
+ type IngestBatchStatus = {
81
+ id: string;
82
+ tableName: string;
83
+ status: string;
84
+ rowCount: number;
85
+ upsertedCount: number | null;
86
+ errorMessage: string | null;
87
+ createdAt: string;
88
+ startedAt: string | null;
89
+ finishedAt: string | null;
90
+ };
91
+ type FacetsResult = Record<string, unknown>;
92
+
93
+ /**
94
+ * Custom data tables — query, read, and write your organization's records.
95
+ * Wraps the `/api/v1/data` REST endpoints.
96
+ */
97
+ declare class DataClient {
98
+ #private;
99
+ constructor(http: HttpClient);
100
+ /** Facet-filtered search over an indexed table (Elasticsearch-backed, max 50 hits). */
101
+ query<TRecord extends DataRecord = DataRecord>(input: QueryInput): Promise<{
102
+ records: TRecord[];
103
+ total: number;
104
+ }>;
105
+ /** Facet values for an indexed table. */
106
+ facets(tableName: string): Promise<FacetsResult>;
107
+ /** Paginated listing straight from the relational store. */
108
+ list<TRecord extends DataRecord = DataRecord>(tableName: string, options?: ListOptions): Promise<{
109
+ records: TRecord[];
110
+ total_count: number;
111
+ page: number;
112
+ per_page: number;
113
+ }>;
114
+ get<TRecord extends DataRecord = DataRecord>(tableName: string, id: number): Promise<{
115
+ record: TRecord;
116
+ }>;
117
+ create<TRecord extends DataRecord = DataRecord>(tableName: string, payload: RecordPayload): Promise<{
118
+ record: TRecord;
119
+ }>;
120
+ update<TRecord extends DataRecord = DataRecord>(tableName: string, id: number, payload: RecordPayload): Promise<{
121
+ record: TRecord;
122
+ }>;
123
+ delete(tableName: string, id: number): Promise<DeleteResult>;
124
+ /** Deletes every record in the table. Irreversible. */
125
+ deleteAll(tableName: string): Promise<DeleteResult>;
126
+ /**
127
+ * Asynchronous bulk upsert (max 1000 rows per call). Rows are FULL-ROW
128
+ * REPLACE on key conflict — omitted columns are cleared, not preserved.
129
+ * Returns a batch handle; poll `getBatch` for completion.
130
+ */
131
+ batchUpsert(tableName: string, rows: RecordPayload[]): Promise<BatchUpsertResult>;
132
+ /** Status of an async upsert batch created by `batchUpsert`. */
133
+ getBatch(ingestBatchId: string): Promise<IngestBatchStatus>;
134
+ }
135
+
136
+ type SimpleAIOptions = {
137
+ /** API key (dashboard: Settings → API Keys). Defaults to SIMPLE_API_KEY — inside code actions this is injected automatically. */
138
+ apiKey?: string;
139
+ /** API base URL. Defaults to SIMPLE_BASE_URL, then the production API. */
140
+ baseUrl?: string;
141
+ /** Custom fetch implementation (for testing or instrumentation). */
142
+ fetch?: FetchLike;
143
+ };
144
+ declare class SimpleAI {
145
+ /** Custom data tables — query, read, and write records. */
146
+ readonly data: DataClient;
147
+ constructor(options?: SimpleAIOptions);
148
+ }
149
+
150
+ /**
151
+ * Brand the code-action runner uses to recognize `defineAction` handlers. The
152
+ * runner calls the default export with `{ inputs, config }` either way; the
153
+ * wrapper adds the authenticated `client` to the handler's context.
154
+ */
155
+ declare const SIMPLE_ACTION_BRAND: unique symbol;
156
+ type ActionContext<TInputs = Record<string, unknown>> = {
157
+ /** The Action's declared inputs, already validated against its input schema. */
158
+ inputs: TInputs;
159
+ /** Your organization's configuration variables. */
160
+ config: Record<string, string>;
161
+ /** The Simple AI SDK, authenticated for your organization. */
162
+ client: SimpleAI;
163
+ };
164
+ type ActionHandler<TInputs = Record<string, unknown>, TResult = unknown> = ((args: {
165
+ inputs: TInputs;
166
+ config: Record<string, string>;
167
+ }) => Promise<TResult>) & {
168
+ [SIMPLE_ACTION_BRAND]: true;
169
+ };
170
+ /**
171
+ * Define a code action with a typed context and an org-authenticated SDK
172
+ * client. The returned value must be your module's default export.
173
+ *
174
+ * ```ts
175
+ * import { defineAction } from '@simple-ai-lab/sdk';
176
+ *
177
+ * export default defineAction(async ({ inputs, config, client }) => {
178
+ * const { records } = await client.data.query({ tableName: 'customers', text: inputs.email });
179
+ * return { found: records.length > 0 };
180
+ * });
181
+ * ```
182
+ */
183
+ declare function defineAction<TInputs = Record<string, unknown>, TResult = unknown>(handler: (context: ActionContext<TInputs>) => Promise<TResult> | TResult): ActionHandler<TInputs, TResult>;
184
+
185
+ /** Error thrown for any non-2xx response from the Simple AI API. */
186
+ declare class SimpleAIError extends Error {
187
+ /** HTTP status code, or 0 when the request never reached the API. */
188
+ readonly status: number;
189
+ /** Machine-readable error code from the API body, when present. */
190
+ readonly code: string | null;
191
+ /** The parsed response body (JSON when possible, otherwise raw text). */
192
+ readonly body: unknown;
193
+ constructor({ message, status, code, body, cause, }: {
194
+ message: string;
195
+ status: number;
196
+ code: string | null;
197
+ body: unknown;
198
+ cause?: unknown;
199
+ });
200
+ }
201
+
202
+ export { type ActionContext, type ActionHandler, type BatchUpsertResult, DataClient, type DataFilter, type DataRecord, type DeleteResult, type FacetsResult, type IngestBatchStatus, type ListOptions, type ListResult, MAX_BATCH_ROWS, MAX_QUERY_SIZE, type QueryInput, type QueryResult, type RecordPayload, type RecordResult, SIMPLE_ACTION_BRAND, SimpleAI, SimpleAIError, type SimpleAIOptions, batchUpsertRowsSchema, dataColumnPathSchema, dataFilterSchema, defineAction, listOptionsSchema, queryInputSchema, recordPayloadSchema, tableNameSchema };
@@ -0,0 +1,202 @@
1
+ import { z } from 'zod';
2
+
3
+ type FetchLike = (url: string, init: RequestInit) => Promise<Response>;
4
+ type HttpClient = {
5
+ request: (args: {
6
+ method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
7
+ path: string;
8
+ query?: Record<string, string>;
9
+ body?: unknown;
10
+ }) => Promise<unknown>;
11
+ };
12
+
13
+ /**
14
+ * Request wire schemas for the Simple AI public REST API (`/api/v1`).
15
+ *
16
+ * These deliberately mirror the server's own schemas (see
17
+ * `projects/server-v2/src/domains/data/query-schemas.ts` and
18
+ * `domains/data/public/types.ts`); a contract test in server-v2 keeps the two
19
+ * in sync. Responses are typed but not strictly validated, so additive server
20
+ * changes never break deployed SDK consumers.
21
+ */
22
+ /** Hard cap on hits a single query may return. */
23
+ declare const MAX_QUERY_SIZE = 50;
24
+ /** Maximum rows accepted by a single batch-upsert chunk. */
25
+ declare const MAX_BATCH_ROWS = 1000;
26
+ declare const tableNameSchema: z.ZodString;
27
+ declare const dataColumnPathSchema: z.ZodString;
28
+ declare const dataFilterSchema: z.ZodObject<{
29
+ column: z.ZodString;
30
+ values: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
31
+ }, z.core.$strip>;
32
+ type DataFilter = z.infer<typeof dataFilterSchema>;
33
+ declare const queryInputSchema: z.ZodObject<{
34
+ tableName: z.ZodString;
35
+ filters: z.ZodOptional<z.ZodArray<z.ZodObject<{
36
+ column: z.ZodString;
37
+ values: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
38
+ }, z.core.$strip>>>;
39
+ text: z.ZodOptional<z.ZodString>;
40
+ size: z.ZodOptional<z.ZodNumber>;
41
+ from: z.ZodOptional<z.ZodNumber>;
42
+ }, z.core.$strip>;
43
+ type QueryInput = z.input<typeof queryInputSchema>;
44
+ declare const listOptionsSchema: z.ZodObject<{
45
+ page: z.ZodOptional<z.ZodNumber>;
46
+ perPage: z.ZodOptional<z.ZodNumber>;
47
+ orderBy: z.ZodOptional<z.ZodString>;
48
+ orderDirection: z.ZodOptional<z.ZodEnum<{
49
+ asc: "asc";
50
+ desc: "desc";
51
+ }>>;
52
+ filters: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
53
+ }, z.core.$strip>;
54
+ type ListOptions = z.input<typeof listOptionsSchema>;
55
+ declare const recordPayloadSchema: z.ZodRecord<z.ZodString, z.ZodUnknown>;
56
+ type RecordPayload = z.infer<typeof recordPayloadSchema>;
57
+ declare const batchUpsertRowsSchema: z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
58
+ type DataRecord = Record<string, unknown>;
59
+ type QueryResult = {
60
+ records: DataRecord[];
61
+ total: number;
62
+ };
63
+ type ListResult = {
64
+ records: DataRecord[];
65
+ total_count: number;
66
+ page: number;
67
+ per_page: number;
68
+ };
69
+ type RecordResult = {
70
+ record: DataRecord;
71
+ };
72
+ type DeleteResult = {
73
+ success: boolean;
74
+ message: string;
75
+ };
76
+ type BatchUpsertResult = {
77
+ ingestBatchId: string;
78
+ status: string;
79
+ };
80
+ type IngestBatchStatus = {
81
+ id: string;
82
+ tableName: string;
83
+ status: string;
84
+ rowCount: number;
85
+ upsertedCount: number | null;
86
+ errorMessage: string | null;
87
+ createdAt: string;
88
+ startedAt: string | null;
89
+ finishedAt: string | null;
90
+ };
91
+ type FacetsResult = Record<string, unknown>;
92
+
93
+ /**
94
+ * Custom data tables — query, read, and write your organization's records.
95
+ * Wraps the `/api/v1/data` REST endpoints.
96
+ */
97
+ declare class DataClient {
98
+ #private;
99
+ constructor(http: HttpClient);
100
+ /** Facet-filtered search over an indexed table (Elasticsearch-backed, max 50 hits). */
101
+ query<TRecord extends DataRecord = DataRecord>(input: QueryInput): Promise<{
102
+ records: TRecord[];
103
+ total: number;
104
+ }>;
105
+ /** Facet values for an indexed table. */
106
+ facets(tableName: string): Promise<FacetsResult>;
107
+ /** Paginated listing straight from the relational store. */
108
+ list<TRecord extends DataRecord = DataRecord>(tableName: string, options?: ListOptions): Promise<{
109
+ records: TRecord[];
110
+ total_count: number;
111
+ page: number;
112
+ per_page: number;
113
+ }>;
114
+ get<TRecord extends DataRecord = DataRecord>(tableName: string, id: number): Promise<{
115
+ record: TRecord;
116
+ }>;
117
+ create<TRecord extends DataRecord = DataRecord>(tableName: string, payload: RecordPayload): Promise<{
118
+ record: TRecord;
119
+ }>;
120
+ update<TRecord extends DataRecord = DataRecord>(tableName: string, id: number, payload: RecordPayload): Promise<{
121
+ record: TRecord;
122
+ }>;
123
+ delete(tableName: string, id: number): Promise<DeleteResult>;
124
+ /** Deletes every record in the table. Irreversible. */
125
+ deleteAll(tableName: string): Promise<DeleteResult>;
126
+ /**
127
+ * Asynchronous bulk upsert (max 1000 rows per call). Rows are FULL-ROW
128
+ * REPLACE on key conflict — omitted columns are cleared, not preserved.
129
+ * Returns a batch handle; poll `getBatch` for completion.
130
+ */
131
+ batchUpsert(tableName: string, rows: RecordPayload[]): Promise<BatchUpsertResult>;
132
+ /** Status of an async upsert batch created by `batchUpsert`. */
133
+ getBatch(ingestBatchId: string): Promise<IngestBatchStatus>;
134
+ }
135
+
136
+ type SimpleAIOptions = {
137
+ /** API key (dashboard: Settings → API Keys). Defaults to SIMPLE_API_KEY — inside code actions this is injected automatically. */
138
+ apiKey?: string;
139
+ /** API base URL. Defaults to SIMPLE_BASE_URL, then the production API. */
140
+ baseUrl?: string;
141
+ /** Custom fetch implementation (for testing or instrumentation). */
142
+ fetch?: FetchLike;
143
+ };
144
+ declare class SimpleAI {
145
+ /** Custom data tables — query, read, and write records. */
146
+ readonly data: DataClient;
147
+ constructor(options?: SimpleAIOptions);
148
+ }
149
+
150
+ /**
151
+ * Brand the code-action runner uses to recognize `defineAction` handlers. The
152
+ * runner calls the default export with `{ inputs, config }` either way; the
153
+ * wrapper adds the authenticated `client` to the handler's context.
154
+ */
155
+ declare const SIMPLE_ACTION_BRAND: unique symbol;
156
+ type ActionContext<TInputs = Record<string, unknown>> = {
157
+ /** The Action's declared inputs, already validated against its input schema. */
158
+ inputs: TInputs;
159
+ /** Your organization's configuration variables. */
160
+ config: Record<string, string>;
161
+ /** The Simple AI SDK, authenticated for your organization. */
162
+ client: SimpleAI;
163
+ };
164
+ type ActionHandler<TInputs = Record<string, unknown>, TResult = unknown> = ((args: {
165
+ inputs: TInputs;
166
+ config: Record<string, string>;
167
+ }) => Promise<TResult>) & {
168
+ [SIMPLE_ACTION_BRAND]: true;
169
+ };
170
+ /**
171
+ * Define a code action with a typed context and an org-authenticated SDK
172
+ * client. The returned value must be your module's default export.
173
+ *
174
+ * ```ts
175
+ * import { defineAction } from '@simple-ai-lab/sdk';
176
+ *
177
+ * export default defineAction(async ({ inputs, config, client }) => {
178
+ * const { records } = await client.data.query({ tableName: 'customers', text: inputs.email });
179
+ * return { found: records.length > 0 };
180
+ * });
181
+ * ```
182
+ */
183
+ declare function defineAction<TInputs = Record<string, unknown>, TResult = unknown>(handler: (context: ActionContext<TInputs>) => Promise<TResult> | TResult): ActionHandler<TInputs, TResult>;
184
+
185
+ /** Error thrown for any non-2xx response from the Simple AI API. */
186
+ declare class SimpleAIError extends Error {
187
+ /** HTTP status code, or 0 when the request never reached the API. */
188
+ readonly status: number;
189
+ /** Machine-readable error code from the API body, when present. */
190
+ readonly code: string | null;
191
+ /** The parsed response body (JSON when possible, otherwise raw text). */
192
+ readonly body: unknown;
193
+ constructor({ message, status, code, body, cause, }: {
194
+ message: string;
195
+ status: number;
196
+ code: string | null;
197
+ body: unknown;
198
+ cause?: unknown;
199
+ });
200
+ }
201
+
202
+ export { type ActionContext, type ActionHandler, type BatchUpsertResult, DataClient, type DataFilter, type DataRecord, type DeleteResult, type FacetsResult, type IngestBatchStatus, type ListOptions, type ListResult, MAX_BATCH_ROWS, MAX_QUERY_SIZE, type QueryInput, type QueryResult, type RecordPayload, type RecordResult, SIMPLE_ACTION_BRAND, SimpleAI, SimpleAIError, type SimpleAIOptions, batchUpsertRowsSchema, dataColumnPathSchema, dataFilterSchema, defineAction, listOptionsSchema, queryInputSchema, recordPayloadSchema, tableNameSchema };
package/dist/index.js ADDED
@@ -0,0 +1,262 @@
1
+ // src/schemas.ts
2
+ import { z } from "zod";
3
+ var MAX_QUERY_SIZE = 50;
4
+ var MAX_BATCH_ROWS = 1e3;
5
+ var tableNameSchema = z.string().regex(/^[a-z0-9_]+$/, "Table names are lowercase snake_case identifiers");
6
+ var filterValueSchema = z.union([z.string(), z.number(), z.boolean()]);
7
+ var dataColumnPathSchema = z.string().trim().min(1).max(1024).refine((path) => path.split(".").every((segment) => segment.length > 0), {
8
+ message: "Must be a dot-separated column path with no empty segments"
9
+ });
10
+ var dataFilterSchema = z.object({
11
+ column: dataColumnPathSchema,
12
+ values: z.array(filterValueSchema)
13
+ });
14
+ var queryInputSchema = z.object({
15
+ tableName: tableNameSchema,
16
+ filters: z.array(dataFilterSchema).optional(),
17
+ text: z.string().max(5e3).optional(),
18
+ size: z.number().int().min(0).max(MAX_QUERY_SIZE).optional(),
19
+ from: z.number().int().min(0).optional()
20
+ });
21
+ var listOptionsSchema = z.object({
22
+ page: z.number().int().min(1).optional(),
23
+ perPage: z.number().int().min(1).max(200).optional(),
24
+ orderBy: z.string().optional(),
25
+ orderDirection: z.enum(["asc", "desc"]).optional(),
26
+ /** Column-name → value equality filters applied server-side. */
27
+ filters: z.record(z.string(), z.string()).optional()
28
+ });
29
+ var recordPayloadSchema = z.record(z.string(), z.unknown());
30
+ var batchUpsertRowsSchema = z.array(recordPayloadSchema).min(1).max(MAX_BATCH_ROWS);
31
+
32
+ // src/data.ts
33
+ function encodeTable(tableName) {
34
+ return encodeURIComponent(tableNameSchema.parse(tableName));
35
+ }
36
+ var DataClient = class {
37
+ #http;
38
+ constructor(http) {
39
+ this.#http = http;
40
+ }
41
+ /** Facet-filtered search over an indexed table (Elasticsearch-backed, max 50 hits). */
42
+ async query(input) {
43
+ const parsed = queryInputSchema.parse(input);
44
+ const result = await this.#http.request({ method: "POST", path: "/data/query", body: parsed });
45
+ return result;
46
+ }
47
+ /** Facet values for an indexed table. */
48
+ async facets(tableName) {
49
+ const result = await this.#http.request({ method: "GET", path: `/data/facets/${encodeTable(tableName)}` });
50
+ return result;
51
+ }
52
+ /** Paginated listing straight from the relational store. */
53
+ async list(tableName, options = {}) {
54
+ const parsed = listOptionsSchema.parse(options);
55
+ const query = { ...parsed.filters ?? {} };
56
+ if (parsed.page !== void 0) {
57
+ query.page = String(parsed.page);
58
+ }
59
+ if (parsed.perPage !== void 0) {
60
+ query.per_page = String(parsed.perPage);
61
+ }
62
+ if (parsed.orderBy !== void 0) {
63
+ query.order_by = parsed.orderBy;
64
+ }
65
+ if (parsed.orderDirection !== void 0) {
66
+ query.order_direction = parsed.orderDirection;
67
+ }
68
+ const result = await this.#http.request({ method: "GET", path: `/data/${encodeTable(tableName)}`, query });
69
+ return result;
70
+ }
71
+ async get(tableName, id) {
72
+ const result = await this.#http.request({ method: "GET", path: `/data/${encodeTable(tableName)}/${id}` });
73
+ return result;
74
+ }
75
+ async create(tableName, payload) {
76
+ const result = await this.#http.request({
77
+ method: "PUT",
78
+ path: `/data/${encodeTable(tableName)}`,
79
+ body: recordPayloadSchema.parse(payload)
80
+ });
81
+ return result;
82
+ }
83
+ async update(tableName, id, payload) {
84
+ const result = await this.#http.request({
85
+ method: "PATCH",
86
+ path: `/data/${encodeTable(tableName)}/${id}`,
87
+ body: recordPayloadSchema.parse(payload)
88
+ });
89
+ return result;
90
+ }
91
+ async delete(tableName, id) {
92
+ const result = await this.#http.request({ method: "DELETE", path: `/data/${encodeTable(tableName)}/${id}` });
93
+ return result;
94
+ }
95
+ /** Deletes every record in the table. Irreversible. */
96
+ async deleteAll(tableName) {
97
+ const result = await this.#http.request({ method: "DELETE", path: `/data/${encodeTable(tableName)}` });
98
+ return result;
99
+ }
100
+ /**
101
+ * Asynchronous bulk upsert (max 1000 rows per call). Rows are FULL-ROW
102
+ * REPLACE on key conflict — omitted columns are cleared, not preserved.
103
+ * Returns a batch handle; poll `getBatch` for completion.
104
+ */
105
+ async batchUpsert(tableName, rows) {
106
+ const result = await this.#http.request({
107
+ method: "PUT",
108
+ path: `/data/${encodeTable(tableName)}/batch`,
109
+ body: { rows: batchUpsertRowsSchema.parse(rows) }
110
+ });
111
+ return result;
112
+ }
113
+ /** Status of an async upsert batch created by `batchUpsert`. */
114
+ async getBatch(ingestBatchId) {
115
+ const result = await this.#http.request({
116
+ method: "GET",
117
+ path: `/data/_batches/${encodeURIComponent(ingestBatchId)}`
118
+ });
119
+ return result;
120
+ }
121
+ };
122
+
123
+ // src/errors.ts
124
+ var SimpleAIError = class extends Error {
125
+ /** HTTP status code, or 0 when the request never reached the API. */
126
+ status;
127
+ /** Machine-readable error code from the API body, when present. */
128
+ code;
129
+ /** The parsed response body (JSON when possible, otherwise raw text). */
130
+ body;
131
+ constructor({
132
+ message,
133
+ status,
134
+ code,
135
+ body,
136
+ cause
137
+ }) {
138
+ super(message, cause === void 0 ? void 0 : { cause });
139
+ this.name = "SimpleAIError";
140
+ this.status = status;
141
+ this.code = code;
142
+ this.body = body;
143
+ }
144
+ };
145
+
146
+ // src/http.ts
147
+ function parseBody(text) {
148
+ if (text.length === 0) {
149
+ return null;
150
+ }
151
+ try {
152
+ return JSON.parse(text);
153
+ } catch {
154
+ return text;
155
+ }
156
+ }
157
+ function errorDetails(body) {
158
+ if (body !== null && typeof body === "object") {
159
+ const record = body;
160
+ const code = typeof record.code === "string" ? record.code : null;
161
+ const message = typeof record.message === "string" ? record.message : typeof record.error === "string" ? record.error : null;
162
+ return { code, message };
163
+ }
164
+ return { code: null, message: typeof body === "string" && body.length > 0 ? body : null };
165
+ }
166
+ function createHttpClient({
167
+ baseUrl,
168
+ apiKey,
169
+ fetchImplementation
170
+ }) {
171
+ const normalizedBase = baseUrl.replace(/\/+$/, "");
172
+ return {
173
+ request: async ({ method, path, query, body }) => {
174
+ const queryString = query === void 0 || Object.keys(query).length === 0 ? "" : `?${new URLSearchParams(query).toString()}`;
175
+ const url = `${normalizedBase}${path}${queryString}`;
176
+ let response;
177
+ try {
178
+ response = await fetchImplementation(url, {
179
+ method,
180
+ headers: {
181
+ authorization: `Bearer ${apiKey}`,
182
+ "content-type": "application/json",
183
+ accept: "application/json"
184
+ },
185
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
186
+ });
187
+ } catch (e) {
188
+ throw new SimpleAIError({
189
+ message: `Request to ${method} ${path} failed: ${e instanceof Error ? e.message : String(e)}`,
190
+ status: 0,
191
+ code: "network_error",
192
+ body: null,
193
+ cause: e
194
+ });
195
+ }
196
+ const parsed = parseBody(await response.text());
197
+ if (!response.ok) {
198
+ const { code, message } = errorDetails(parsed);
199
+ throw new SimpleAIError({
200
+ message: message ?? `Request to ${method} ${path} failed with status ${response.status}`,
201
+ status: response.status,
202
+ code,
203
+ body: parsed
204
+ });
205
+ }
206
+ return parsed;
207
+ }
208
+ };
209
+ }
210
+
211
+ // src/client.ts
212
+ var DEFAULT_BASE_URL = "https://api.prod.usesimple.ai/api/v1";
213
+ function envVar(name) {
214
+ if (typeof process === "undefined" || process.env === void 0) {
215
+ return void 0;
216
+ }
217
+ const value = process.env[name];
218
+ return value === void 0 || value === "" ? void 0 : value;
219
+ }
220
+ var SimpleAI = class {
221
+ /** Custom data tables — query, read, and write records. */
222
+ data;
223
+ constructor(options = {}) {
224
+ const apiKey = options.apiKey ?? envVar("SIMPLE_API_KEY");
225
+ if (apiKey === void 0) {
226
+ throw new Error(
227
+ "Missing API key. Pass `apiKey` to new SimpleAI(...) or set the SIMPLE_API_KEY environment variable. Inside Simple AI code actions the key is injected automatically."
228
+ );
229
+ }
230
+ const baseUrl = options.baseUrl ?? envVar("SIMPLE_BASE_URL") ?? DEFAULT_BASE_URL;
231
+ const fetchImplementation = options.fetch ?? ((url, init) => fetch(url, init));
232
+ const http = createHttpClient({ baseUrl, apiKey, fetchImplementation });
233
+ this.data = new DataClient(http);
234
+ }
235
+ };
236
+
237
+ // src/define-action.ts
238
+ var SIMPLE_ACTION_BRAND = /* @__PURE__ */ Symbol.for("simple-ai.action");
239
+ function defineAction(handler) {
240
+ const wrapped = async ({ inputs, config }) => {
241
+ const client = new SimpleAI();
242
+ return handler({ inputs, config, client });
243
+ };
244
+ return Object.assign(wrapped, { [SIMPLE_ACTION_BRAND]: true });
245
+ }
246
+ export {
247
+ DataClient,
248
+ MAX_BATCH_ROWS,
249
+ MAX_QUERY_SIZE,
250
+ SIMPLE_ACTION_BRAND,
251
+ SimpleAI,
252
+ SimpleAIError,
253
+ batchUpsertRowsSchema,
254
+ dataColumnPathSchema,
255
+ dataFilterSchema,
256
+ defineAction,
257
+ listOptionsSchema,
258
+ queryInputSchema,
259
+ recordPayloadSchema,
260
+ tableNameSchema
261
+ };
262
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/schemas.ts","../src/data.ts","../src/errors.ts","../src/http.ts","../src/client.ts","../src/define-action.ts"],"sourcesContent":["import { z } from 'zod';\n\n/**\n * Request wire schemas for the Simple AI public REST API (`/api/v1`).\n *\n * These deliberately mirror the server's own schemas (see\n * `projects/server-v2/src/domains/data/query-schemas.ts` and\n * `domains/data/public/types.ts`); a contract test in server-v2 keeps the two\n * in sync. Responses are typed but not strictly validated, so additive server\n * changes never break deployed SDK consumers.\n */\n\n/** Hard cap on hits a single query may return. */\nexport const MAX_QUERY_SIZE = 50;\n/** Maximum rows accepted by a single batch-upsert chunk. */\nexport const MAX_BATCH_ROWS = 1000;\n\nexport const tableNameSchema = z.string().regex(/^[a-z0-9_]+$/, 'Table names are lowercase snake_case identifiers');\n\nexport const filterValueSchema = z.union([z.string(), z.number(), z.boolean()]);\n\n// Mirrors the server's customDataFacetAttributePathSchema: dot-separated\n// column paths with no empty segments (OBJECT leaves are parent.child).\nexport const dataColumnPathSchema = z\n .string()\n .trim()\n .min(1)\n .max(1024)\n .refine((path) => path.split('.').every((segment) => segment.length > 0), {\n message: 'Must be a dot-separated column path with no empty segments',\n });\n\nexport const dataFilterSchema = z.object({\n column: dataColumnPathSchema,\n values: z.array(filterValueSchema),\n});\nexport type DataFilter = z.infer<typeof dataFilterSchema>;\n\nexport const queryInputSchema = z.object({\n tableName: tableNameSchema,\n filters: z.array(dataFilterSchema).optional(),\n text: z.string().max(5000).optional(),\n size: z.number().int().min(0).max(MAX_QUERY_SIZE).optional(),\n from: z.number().int().min(0).optional(),\n});\nexport type QueryInput = z.input<typeof queryInputSchema>;\n\nexport const listOptionsSchema = z.object({\n page: z.number().int().min(1).optional(),\n perPage: z.number().int().min(1).max(200).optional(),\n orderBy: z.string().optional(),\n orderDirection: z.enum(['asc', 'desc']).optional(),\n /** Column-name → value equality filters applied server-side. */\n filters: z.record(z.string(), z.string()).optional(),\n});\nexport type ListOptions = z.input<typeof listOptionsSchema>;\n\nexport const recordPayloadSchema = z.record(z.string(), z.unknown());\nexport type RecordPayload = z.infer<typeof recordPayloadSchema>;\n\nexport const batchUpsertRowsSchema = z.array(recordPayloadSchema).min(1).max(MAX_BATCH_ROWS);\n\n// ---------------------------------------------------------------------------\n// Response types (typed, tolerantly parsed)\n// ---------------------------------------------------------------------------\n\nexport type DataRecord = Record<string, unknown>;\n\nexport type QueryResult = {\n records: DataRecord[];\n total: number;\n};\n\nexport type ListResult = {\n records: DataRecord[];\n total_count: number;\n page: number;\n per_page: number;\n};\n\nexport type RecordResult = {\n record: DataRecord;\n};\n\nexport type DeleteResult = {\n success: boolean;\n message: string;\n};\n\nexport type BatchUpsertResult = {\n ingestBatchId: string;\n status: string;\n};\n\nexport type IngestBatchStatus = {\n id: string;\n tableName: string;\n status: string;\n rowCount: number;\n upsertedCount: number | null;\n errorMessage: string | null;\n createdAt: string;\n startedAt: string | null;\n finishedAt: string | null;\n};\n\nexport type FacetsResult = Record<string, unknown>;\n","import type { HttpClient } from './http';\nimport {\n type BatchUpsertResult,\n batchUpsertRowsSchema,\n type DataRecord,\n type DeleteResult,\n type FacetsResult,\n type IngestBatchStatus,\n type ListOptions,\n type ListResult,\n listOptionsSchema,\n type QueryInput,\n type QueryResult,\n queryInputSchema,\n type RecordPayload,\n type RecordResult,\n recordPayloadSchema,\n tableNameSchema,\n} from './schemas';\n\nfunction encodeTable(tableName: string): string {\n return encodeURIComponent(tableNameSchema.parse(tableName));\n}\n\n/**\n * Custom data tables — query, read, and write your organization's records.\n * Wraps the `/api/v1/data` REST endpoints.\n */\nexport class DataClient {\n readonly #http: HttpClient;\n\n constructor(http: HttpClient) {\n this.#http = http;\n }\n\n /** Facet-filtered search over an indexed table (Elasticsearch-backed, max 50 hits). */\n async query<TRecord extends DataRecord = DataRecord>(\n input: QueryInput\n ): Promise<{ records: TRecord[]; total: number }> {\n const parsed = queryInputSchema.parse(input);\n const result = await this.#http.request({ method: 'POST', path: '/data/query', body: parsed });\n return result as { records: TRecord[]; total: number };\n }\n\n /** Facet values for an indexed table. */\n async facets(tableName: string): Promise<FacetsResult> {\n const result = await this.#http.request({ method: 'GET', path: `/data/facets/${encodeTable(tableName)}` });\n return result as FacetsResult;\n }\n\n /** Paginated listing straight from the relational store. */\n async list<TRecord extends DataRecord = DataRecord>(\n tableName: string,\n options: ListOptions = {}\n ): Promise<{ records: TRecord[]; total_count: number; page: number; per_page: number }> {\n const parsed = listOptionsSchema.parse(options);\n const query: Record<string, string> = { ...(parsed.filters ?? {}) };\n if (parsed.page !== undefined) {\n query.page = String(parsed.page);\n }\n if (parsed.perPage !== undefined) {\n query.per_page = String(parsed.perPage);\n }\n if (parsed.orderBy !== undefined) {\n query.order_by = parsed.orderBy;\n }\n if (parsed.orderDirection !== undefined) {\n query.order_direction = parsed.orderDirection;\n }\n const result = await this.#http.request({ method: 'GET', path: `/data/${encodeTable(tableName)}`, query });\n return result as ListResult & { records: TRecord[] };\n }\n\n async get<TRecord extends DataRecord = DataRecord>(tableName: string, id: number): Promise<{ record: TRecord }> {\n const result = await this.#http.request({ method: 'GET', path: `/data/${encodeTable(tableName)}/${id}` });\n return result as RecordResult & { record: TRecord };\n }\n\n async create<TRecord extends DataRecord = DataRecord>(\n tableName: string,\n payload: RecordPayload\n ): Promise<{ record: TRecord }> {\n const result = await this.#http.request({\n method: 'PUT',\n path: `/data/${encodeTable(tableName)}`,\n body: recordPayloadSchema.parse(payload),\n });\n return result as RecordResult & { record: TRecord };\n }\n\n async update<TRecord extends DataRecord = DataRecord>(\n tableName: string,\n id: number,\n payload: RecordPayload\n ): Promise<{ record: TRecord }> {\n const result = await this.#http.request({\n method: 'PATCH',\n path: `/data/${encodeTable(tableName)}/${id}`,\n body: recordPayloadSchema.parse(payload),\n });\n return result as RecordResult & { record: TRecord };\n }\n\n async delete(tableName: string, id: number): Promise<DeleteResult> {\n const result = await this.#http.request({ method: 'DELETE', path: `/data/${encodeTable(tableName)}/${id}` });\n return result as DeleteResult;\n }\n\n /** Deletes every record in the table. Irreversible. */\n async deleteAll(tableName: string): Promise<DeleteResult> {\n const result = await this.#http.request({ method: 'DELETE', path: `/data/${encodeTable(tableName)}` });\n return result as DeleteResult;\n }\n\n /**\n * Asynchronous bulk upsert (max 1000 rows per call). Rows are FULL-ROW\n * REPLACE on key conflict — omitted columns are cleared, not preserved.\n * Returns a batch handle; poll `getBatch` for completion.\n */\n async batchUpsert(tableName: string, rows: RecordPayload[]): Promise<BatchUpsertResult> {\n const result = await this.#http.request({\n method: 'PUT',\n path: `/data/${encodeTable(tableName)}/batch`,\n body: { rows: batchUpsertRowsSchema.parse(rows) },\n });\n return result as BatchUpsertResult;\n }\n\n /** Status of an async upsert batch created by `batchUpsert`. */\n async getBatch(ingestBatchId: string): Promise<IngestBatchStatus> {\n const result = await this.#http.request({\n method: 'GET',\n path: `/data/_batches/${encodeURIComponent(ingestBatchId)}`,\n });\n return result as IngestBatchStatus;\n }\n}\n","/** Error thrown for any non-2xx response from the Simple AI API. */\nexport class SimpleAIError extends Error {\n /** HTTP status code, or 0 when the request never reached the API. */\n readonly status: number;\n /** Machine-readable error code from the API body, when present. */\n readonly code: string | null;\n /** The parsed response body (JSON when possible, otherwise raw text). */\n readonly body: unknown;\n\n constructor({\n message,\n status,\n code,\n body,\n cause,\n }: {\n message: string;\n status: number;\n code: string | null;\n body: unknown;\n cause?: unknown;\n }) {\n super(message, cause === undefined ? undefined : { cause });\n this.name = 'SimpleAIError';\n this.status = status;\n this.code = code;\n this.body = body;\n }\n}\n","import { SimpleAIError } from './errors';\n\nexport type FetchLike = (url: string, init: RequestInit) => Promise<Response>;\n\nexport type HttpClient = {\n request: (args: {\n method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n path: string;\n query?: Record<string, string>;\n body?: unknown;\n }) => Promise<unknown>;\n};\n\nfunction parseBody(text: string): unknown {\n if (text.length === 0) {\n return null;\n }\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nfunction errorDetails(body: unknown): { code: string | null; message: string | null } {\n if (body !== null && typeof body === 'object') {\n const record = body as { code?: unknown; error?: unknown; message?: unknown };\n const code = typeof record.code === 'string' ? record.code : null;\n const message =\n typeof record.message === 'string' ? record.message : typeof record.error === 'string' ? record.error : null;\n return { code, message };\n }\n return { code: null, message: typeof body === 'string' && body.length > 0 ? body : null };\n}\n\nexport function createHttpClient({\n baseUrl,\n apiKey,\n fetchImplementation,\n}: {\n baseUrl: string;\n apiKey: string;\n fetchImplementation: FetchLike;\n}): HttpClient {\n const normalizedBase = baseUrl.replace(/\\/+$/, '');\n\n return {\n request: async ({ method, path, query, body }) => {\n const queryString =\n query === undefined || Object.keys(query).length === 0 ? '' : `?${new URLSearchParams(query).toString()}`;\n const url = `${normalizedBase}${path}${queryString}`;\n\n let response: Response;\n try {\n response = await fetchImplementation(url, {\n method,\n headers: {\n authorization: `Bearer ${apiKey}`,\n 'content-type': 'application/json',\n accept: 'application/json',\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n } catch (e) {\n throw new SimpleAIError({\n message: `Request to ${method} ${path} failed: ${e instanceof Error ? e.message : String(e)}`,\n status: 0,\n code: 'network_error',\n body: null,\n cause: e,\n });\n }\n\n const parsed = parseBody(await response.text());\n if (!response.ok) {\n const { code, message } = errorDetails(parsed);\n throw new SimpleAIError({\n message: message ?? `Request to ${method} ${path} failed with status ${response.status}`,\n status: response.status,\n code,\n body: parsed,\n });\n }\n return parsed;\n },\n };\n}\n","import { DataClient } from './data';\nimport type { FetchLike } from './http';\nimport { createHttpClient } from './http';\n\nconst DEFAULT_BASE_URL = 'https://api.prod.usesimple.ai/api/v1';\n\nexport type SimpleAIOptions = {\n /** API key (dashboard: Settings → API Keys). Defaults to SIMPLE_API_KEY — inside code actions this is injected automatically. */\n apiKey?: string;\n /** API base URL. Defaults to SIMPLE_BASE_URL, then the production API. */\n baseUrl?: string;\n /** Custom fetch implementation (for testing or instrumentation). */\n fetch?: FetchLike;\n};\n\nfunction envVar(name: string): string | undefined {\n if (typeof process === 'undefined' || process.env === undefined) {\n return undefined;\n }\n const value = process.env[name];\n return value === undefined || value === '' ? undefined : value;\n}\n\nexport class SimpleAI {\n /** Custom data tables — query, read, and write records. */\n readonly data: DataClient;\n\n constructor(options: SimpleAIOptions = {}) {\n const apiKey = options.apiKey ?? envVar('SIMPLE_API_KEY');\n if (apiKey === undefined) {\n throw new Error(\n 'Missing API key. Pass `apiKey` to new SimpleAI(...) or set the SIMPLE_API_KEY environment variable. ' +\n 'Inside Simple AI code actions the key is injected automatically.'\n );\n }\n const baseUrl = options.baseUrl ?? envVar('SIMPLE_BASE_URL') ?? DEFAULT_BASE_URL;\n const fetchImplementation: FetchLike = options.fetch ?? ((url, init) => fetch(url, init));\n\n const http = createHttpClient({ baseUrl, apiKey, fetchImplementation });\n this.data = new DataClient(http);\n }\n}\n","import { SimpleAI } from './client';\n\n/**\n * Brand the code-action runner uses to recognize `defineAction` handlers. The\n * runner calls the default export with `{ inputs, config }` either way; the\n * wrapper adds the authenticated `client` to the handler's context.\n */\nexport const SIMPLE_ACTION_BRAND = Symbol.for('simple-ai.action');\n\nexport type ActionContext<TInputs = Record<string, unknown>> = {\n /** The Action's declared inputs, already validated against its input schema. */\n inputs: TInputs;\n /** Your organization's configuration variables. */\n config: Record<string, string>;\n /** The Simple AI SDK, authenticated for your organization. */\n client: SimpleAI;\n};\n\nexport type ActionHandler<TInputs = Record<string, unknown>, TResult = unknown> = ((args: {\n inputs: TInputs;\n config: Record<string, string>;\n}) => Promise<TResult>) & { [SIMPLE_ACTION_BRAND]: true };\n\n/**\n * Define a code action with a typed context and an org-authenticated SDK\n * client. The returned value must be your module's default export.\n *\n * ```ts\n * import { defineAction } from '@simple-ai-lab/sdk';\n *\n * export default defineAction(async ({ inputs, config, client }) => {\n * const { records } = await client.data.query({ tableName: 'customers', text: inputs.email });\n * return { found: records.length > 0 };\n * });\n * ```\n */\nexport function defineAction<TInputs = Record<string, unknown>, TResult = unknown>(\n handler: (context: ActionContext<TInputs>) => Promise<TResult> | TResult\n): ActionHandler<TInputs, TResult> {\n const wrapped = async ({ inputs, config }: { inputs: TInputs; config: Record<string, string> }): Promise<TResult> => {\n // Constructed lazily per invocation so the injected SIMPLE_API_KEY env is\n // read at run time, not module-load time.\n const client = new SimpleAI();\n return handler({ inputs, config, client });\n };\n return Object.assign(wrapped, { [SIMPLE_ACTION_BRAND]: true as const });\n}\n"],"mappings":";AAAA,SAAS,SAAS;AAaX,IAAM,iBAAiB;AAEvB,IAAM,iBAAiB;AAEvB,IAAM,kBAAkB,EAAE,OAAO,EAAE,MAAM,gBAAgB,kDAAkD;AAE3G,IAAM,oBAAoB,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,CAAC;AAIvE,IAAM,uBAAuB,EACjC,OAAO,EACP,KAAK,EACL,IAAI,CAAC,EACL,IAAI,IAAI,E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,iBAAiB,KAAK;AAChE,UAAM,sBAAiC,QAAQ,UAAU,CAAC,KAAK,SAAS,MAAM,KAAK,IAAI;AAEvF,UAAM,OAAO,iBAAiB,EAAE,SAAS,QAAQ,oBAAoB,CAAC;AACtE,SAAK,OAAO,IAAI,WAAW,IAAI;AAAA,EACjC;AACF;;;AClCO,IAAM,sBAAsB,uBAAO,IAAI,kBAAkB;AA6BzD,SAAS,aACd,SACiC;AACjC,QAAM,UAAU,OAAO,EAAE,QAAQ,OAAO,MAA6E;AAGnH,UAAM,SAAS,IAAI,SAAS;AAC5B,WAAO,QAAQ,EAAE,QAAQ,QAAQ,OAAO,CAAC;AAAA,EAC3C;AACA,SAAO,OAAO,OAAO,SAAS,EAAE,CAAC,mBAAmB,GAAG,KAAc,CAAC;AACxE;","names":[]}
package/package.json ADDED
@@ -0,0 +1,65 @@
1
+ {
2
+ "name": "@simple-ai-lab/sdk",
3
+ "version": "0.1.0",
4
+ "description": "Simple AI SDK — access your Simple AI organization's data from code actions and your own applications.",
5
+ "type": "module",
6
+ "license": "Elastic-2.0",
7
+ "author": "Simple AI Lab",
8
+ "homepage": "https://docs.usesimple.ai",
9
+ "sideEffects": false,
10
+ "engines": {
11
+ "node": ">=20"
12
+ },
13
+ "files": [
14
+ "dist",
15
+ "LICENSE",
16
+ "README.md"
17
+ ],
18
+ "main": "./dist/index.cjs",
19
+ "module": "./dist/index.js",
20
+ "types": "./dist/index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "import": {
24
+ "types": "./dist/index.d.ts",
25
+ "default": "./dist/index.js"
26
+ },
27
+ "require": {
28
+ "types": "./dist/index.d.cts",
29
+ "default": "./dist/index.cjs"
30
+ }
31
+ }
32
+ },
33
+ "dependencies": {
34
+ "zod": "^4.1.12"
35
+ },
36
+ "devDependencies": {
37
+ "@biomejs/biome": "^2.4.4",
38
+ "@types/node": "^25.9.3",
39
+ "tsup": "^8.5.1",
40
+ "typescript": "^5.9.3",
41
+ "vitest": "^4.1.3"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public"
45
+ },
46
+ "repository": {
47
+ "type": "git",
48
+ "url": "https://github.com/simple-ai-lab/simple.git",
49
+ "directory": "projects/simple-ai-sdk"
50
+ },
51
+ "keywords": [
52
+ "simple-ai",
53
+ "voice-ai",
54
+ "sdk",
55
+ "code-actions"
56
+ ],
57
+ "scripts": {
58
+ "build": "tsup",
59
+ "lint": "tsc --noEmit",
60
+ "lint-fix": "biome check --fix",
61
+ "typecheck": "tsc --noEmit",
62
+ "test": "vitest --run",
63
+ "format": "biome check --fix"
64
+ }
65
+ }