@runtypelabs/sdk 0.1.1

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.
Files changed (62) hide show
  1. package/README.md +398 -0
  2. package/dist/batch-builder.d.ts +106 -0
  3. package/dist/batch-builder.d.ts.map +1 -0
  4. package/dist/batch-builder.js +124 -0
  5. package/dist/batch-builder.js.map +1 -0
  6. package/dist/batches-namespace.d.ts +132 -0
  7. package/dist/batches-namespace.d.ts.map +1 -0
  8. package/dist/batches-namespace.js +128 -0
  9. package/dist/batches-namespace.js.map +1 -0
  10. package/dist/client.d.ts +121 -0
  11. package/dist/client.d.ts.map +1 -0
  12. package/dist/client.js +485 -0
  13. package/dist/client.js.map +1 -0
  14. package/dist/endpoints.d.ts +560 -0
  15. package/dist/endpoints.d.ts.map +1 -0
  16. package/dist/endpoints.js +725 -0
  17. package/dist/endpoints.js.map +1 -0
  18. package/dist/eval-builder.d.ts +216 -0
  19. package/dist/eval-builder.d.ts.map +1 -0
  20. package/dist/eval-builder.js +225 -0
  21. package/dist/eval-builder.js.map +1 -0
  22. package/dist/evals-namespace.d.ts +205 -0
  23. package/dist/evals-namespace.d.ts.map +1 -0
  24. package/dist/evals-namespace.js +208 -0
  25. package/dist/evals-namespace.js.map +1 -0
  26. package/dist/flow-builder.d.ts +620 -0
  27. package/dist/flow-builder.d.ts.map +1 -0
  28. package/dist/flow-builder.js +565 -0
  29. package/dist/flow-builder.js.map +1 -0
  30. package/dist/flow-result.d.ts +117 -0
  31. package/dist/flow-result.d.ts.map +1 -0
  32. package/dist/flow-result.js +175 -0
  33. package/dist/flow-result.js.map +1 -0
  34. package/dist/flows-namespace.d.ts +430 -0
  35. package/dist/flows-namespace.d.ts.map +1 -0
  36. package/dist/flows-namespace.js +679 -0
  37. package/dist/flows-namespace.js.map +1 -0
  38. package/dist/index.d.ts +23 -0
  39. package/dist/index.d.ts.map +1 -0
  40. package/dist/index.js +76 -0
  41. package/dist/index.js.map +1 -0
  42. package/dist/prompts-namespace.d.ts +236 -0
  43. package/dist/prompts-namespace.d.ts.map +1 -0
  44. package/dist/prompts-namespace.js +222 -0
  45. package/dist/prompts-namespace.js.map +1 -0
  46. package/dist/runtype.d.ts +232 -0
  47. package/dist/runtype.d.ts.map +1 -0
  48. package/dist/runtype.js +367 -0
  49. package/dist/runtype.js.map +1 -0
  50. package/dist/stream-utils.d.ts +58 -0
  51. package/dist/stream-utils.d.ts.map +1 -0
  52. package/dist/stream-utils.js +348 -0
  53. package/dist/stream-utils.js.map +1 -0
  54. package/dist/transform.d.ts +21 -0
  55. package/dist/transform.d.ts.map +1 -0
  56. package/dist/transform.js +170 -0
  57. package/dist/transform.js.map +1 -0
  58. package/dist/types.d.ts +626 -0
  59. package/dist/types.d.ts.map +1 -0
  60. package/dist/types.js +7 -0
  61. package/dist/types.js.map +1 -0
  62. package/package.json +61 -0
package/README.md ADDED
@@ -0,0 +1,398 @@
1
+ # @runtypelabs/sdk
2
+
3
+ TypeScript client SDK for the Runtype API with FlowBuilder for constructing and executing AI workflows.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @runtypelabs/sdk
9
+ # or
10
+ yarn add @runtypelabs/sdk
11
+ # or
12
+ pnpm add @runtypelabs/sdk
13
+ ```
14
+
15
+ ## Quick Start
16
+
17
+ ```typescript
18
+ import { RuntypeClient } from '@runtypelabs/sdk'
19
+
20
+ // Initialize the client
21
+ const runtype = new RuntypeClient({
22
+ apiKey: 'your-api-key',
23
+ baseUrl: 'https://api.runtype.com' // optional, defaults to production
24
+ })
25
+
26
+ // Use the FlowBuilder for intuitive flow construction
27
+ const result = await runtype
28
+ .flow('My AI Workflow')
29
+ .withRecord({ name: 'Test', type: 'data', metadata: { url: 'https://example.com' } })
30
+ .fetchUrl({
31
+ name: 'Fetch Content',
32
+ url: '{{_record.metadata.url}}',
33
+ outputVariable: 'content'
34
+ })
35
+ .prompt({
36
+ name: 'Analyze',
37
+ model: 'gpt-4',
38
+ userPrompt: 'Analyze this content: {{content}}',
39
+ responseFormat: 'json'
40
+ })
41
+ .run({ streamResponse: true, flowMode: 'virtual' })
42
+
43
+ // Get the analysis result
44
+ const analysis = await result.getResult('Analyze')
45
+ console.log(analysis)
46
+ ```
47
+
48
+ ## Features
49
+
50
+ - **FlowBuilder API**: Fluent, chainable API for building AI workflows
51
+ - **Streaming Support**: Process streaming responses with callbacks or async iteration
52
+ - **Automatic Field Transformation**: All request/response data is automatically transformed between camelCase (client) and snake_case (API)
53
+ - **Type Safety**: Full TypeScript support with comprehensive type definitions
54
+ - **Error Handling**: Proper error handling with custom error types
55
+ - **Zero Dependencies**: No external runtime dependencies
56
+
57
+ ## FlowBuilder API
58
+
59
+ The FlowBuilder provides a fluent interface for constructing and executing flows.
60
+
61
+ ### Basic Usage
62
+
63
+ ```typescript
64
+ import { RuntypeClient } from '@runtypelabs/sdk'
65
+
66
+ const runtype = new RuntypeClient({ apiKey: 'sk-...' })
67
+
68
+ // Build and execute a flow
69
+ const result = await runtype
70
+ .flow('Theme Generator')
71
+ .withRecord({ name: 'Test', type: 'theme', metadata: { url: 'https://example.com' } })
72
+ .fetchUrl({
73
+ name: 'Capture Screenshot',
74
+ url: '{{_record.metadata.url}}',
75
+ fetchMethod: 'firecrawl',
76
+ outputVariable: 'screenshot'
77
+ })
78
+ .prompt({
79
+ name: 'Analyze',
80
+ model: 'gemini-2.5-flash',
81
+ userPrompt: 'Analyze the screenshot and extract color themes...',
82
+ responseFormat: 'json'
83
+ })
84
+ .run({ streamResponse: true, flowMode: 'virtual' })
85
+
86
+ // Get specific step result
87
+ const analysis = await result.getResult('Analyze')
88
+ ```
89
+
90
+ ### With Streaming Callbacks
91
+
92
+ ```typescript
93
+ const summary = await runtype
94
+ .flow('My Flow')
95
+ .prompt({ name: 'Process', model: 'gpt-4', userPrompt: '...' })
96
+ .run({ streamResponse: true }, {
97
+ onStepStart: (event) => console.log('Starting:', event.name),
98
+ onStepChunk: (chunk) => process.stdout.write(chunk),
99
+ onStepComplete: (result, event) => console.log('Done:', event.name),
100
+ onFlowComplete: (event) => console.log('Complete!'),
101
+ })
102
+ ```
103
+
104
+ ### Using Existing Flows
105
+
106
+ ```typescript
107
+ // Reference an existing flow by ID
108
+ const result = await runtype
109
+ .flow('Existing Flow')
110
+ .useExistingFlow('flow_abc123')
111
+ .withRecord({ name: 'Test', type: 'data' })
112
+ .run({ streamResponse: true })
113
+ ```
114
+
115
+ ### Standalone FlowBuilder
116
+
117
+ ```typescript
118
+ import { FlowBuilder } from '@runtypelabs/sdk'
119
+
120
+ // Build flow definition without a client
121
+ const flowBuilder = new FlowBuilder()
122
+ .createFlow({ name: 'My Flow' })
123
+ .withRecord({ name: 'Test', type: 'data' })
124
+ .prompt({ name: 'Step 1', model: 'gpt-4', userPrompt: '...' })
125
+
126
+ // Execute with any client that implements DispatchClient interface
127
+ const flowResult = await flowBuilder.run(apiClient, {
128
+ streamResponse: true,
129
+ flowMode: 'virtual',
130
+ storeResults: true
131
+ })
132
+
133
+ // Get specific step result
134
+ const stepResult = await flowResult.getResult('Step 1')
135
+
136
+ // Or get all results
137
+ const allResults = await flowResult.getAllResults()
138
+ ```
139
+
140
+ ### Available Step Methods
141
+
142
+ | Method | Step Type | Description |
143
+ |--------|-----------|-------------|
144
+ | `.prompt()` | `prompt` | AI prompt execution |
145
+ | `.fetchUrl()` | `fetch-url` | HTTP/Firecrawl fetch |
146
+ | `.transformData()` | `transform-data` | JavaScript transformation |
147
+ | `.setVariable()` | `set-variable` | Set a variable |
148
+ | `.conditional()` | `conditional` | If/else branching |
149
+ | `.search()` | `search` | Web search (Exa, etc.) |
150
+ | `.sendEmail()` | `send-email` | Send email |
151
+ | `.sendStream()` | `send-stream` | Stream message to client |
152
+ | `.retrieveRecord()` | `retrieve-record` | Load record data |
153
+ | `.upsertRecord()` | `upsert-record` | Create/update record |
154
+ | `.vectorSearch()` | `vector-search` | Semantic search |
155
+ | `.generateEmbedding()` | `generate-embedding` | Create embedding |
156
+ | `.waitUntil()` | `wait-until` | Delay or poll |
157
+ | `.sendEvent()` | `send-event` | Analytics event |
158
+ | `.sendText()` | `send-text` | SMS message |
159
+ | `.fetchGitHub()` | `fetch-github` | GitHub API |
160
+
161
+ ### Configuration Methods
162
+
163
+ - `.createFlow({ name, description })` - Initialize flow
164
+ - `.useExistingFlow(flowId)` - Use an existing flow by ID
165
+ - `.withRecord({ id?, name?, type?, metadata? })` - Set record config
166
+ - `.withMessages([...])` - Set conversation messages
167
+ - `.withOptions({ ... })` - Set default options
168
+
169
+ ### FlowResult Methods
170
+
171
+ - `.getResult(stepName)` - Get a specific step's result
172
+ - `.getAllResults()` - Get all step results as `Map<string, any>`
173
+ - `.getSummary()` - Get `FlowSummary` with execution details
174
+ - `.stream(callbacks?)` - Process stream with optional callbacks
175
+ - `.raw` - Access raw `Response` for manual handling
176
+
177
+ ### Streaming Callbacks
178
+
179
+ ```typescript
180
+ interface StreamCallbacks {
181
+ onFlowStart?: (event: FlowStartEvent) => void
182
+ onStepStart?: (event: StepStartEvent) => void
183
+ onStepChunk?: (chunk: string, event: StepChunkEvent) => void
184
+ onStepComplete?: (result: any, event: StepCompleteEvent) => void
185
+ onFlowComplete?: (event: FlowCompleteEvent) => void
186
+ onError?: (error: Error) => void
187
+ }
188
+ ```
189
+
190
+ ## Traditional API Usage
191
+
192
+ The client also provides traditional endpoint-based API access:
193
+
194
+ ### Flows
195
+
196
+ ```typescript
197
+ // List flows with pagination
198
+ const flows = await runtype.flows.list({ limit: 20, cursor: 'next-page-cursor' })
199
+
200
+ // Get a specific flow
201
+ const flow = await runtype.flows.get('flow_123')
202
+
203
+ // Create a new flow
204
+ const newFlow = await runtype.flows.create({
205
+ name: 'Analysis Flow',
206
+ description: 'Analyzes customer data',
207
+ prompts: [...]
208
+ })
209
+
210
+ // Update a flow
211
+ const updatedFlow = await runtype.flows.update('flow_123', { name: 'Updated Name' })
212
+
213
+ // Delete a flow
214
+ await runtype.flows.delete('flow_123')
215
+ ```
216
+
217
+ ### Records
218
+
219
+ ```typescript
220
+ // List records with filtering
221
+ const records = await runtype.records.list({
222
+ metadataKeys: 'company,industry',
223
+ minFields: 5
224
+ })
225
+
226
+ // Create a record
227
+ const record = await runtype.records.create({
228
+ type: 'customer',
229
+ name: 'Acme Corp',
230
+ metadata: {
231
+ industry: 'Technology',
232
+ revenue: 1000000
233
+ }
234
+ })
235
+
236
+ // Bulk edit records
237
+ const result = await runtype.records.bulkEdit({
238
+ recordIds: ['rec_1', 'rec_2'],
239
+ updates: { status: 'processed' }
240
+ })
241
+ ```
242
+
243
+ ### Model Configurations
244
+
245
+ ```typescript
246
+ // Get available models
247
+ const models = await runtype.modelConfigs.getAvailable()
248
+
249
+ // Create a model configuration
250
+ const config = await runtype.modelConfigs.create({
251
+ provider: 'openai',
252
+ modelId: 'gpt-4',
253
+ apiKey: 'your-openai-key'
254
+ })
255
+
256
+ // Set as default
257
+ await runtype.modelConfigs.setDefault(config.id)
258
+ ```
259
+
260
+ ### Dispatch (Atomic Operations)
261
+
262
+ ```typescript
263
+ // Create record and flow, then execute atomically
264
+ const result = await runtype.dispatch.execute({
265
+ record: {
266
+ name: 'New Customer',
267
+ type: 'customer',
268
+ metadata: { industry: 'Tech' }
269
+ },
270
+ flow: {
271
+ name: 'Customer Analysis',
272
+ prompts: [
273
+ {
274
+ name: 'Analyze Industry',
275
+ text: 'Analyze this {{metadata.industry}} company',
276
+ model: 'gpt-4',
277
+ responseFormat: 'json'
278
+ }
279
+ ]
280
+ },
281
+ options: {
282
+ streamResponse: true
283
+ }
284
+ })
285
+ ```
286
+
287
+ ## Field Name Transformation
288
+
289
+ The SDK automatically handles field name transformation between camelCase (client) and snake_case (API):
290
+
291
+ ```typescript
292
+ // You write (camelCase):
293
+ const record = await runtype.records.create({
294
+ recordType: 'customer',
295
+ metadataSchema: { ... }
296
+ })
297
+
298
+ // API receives (snake_case):
299
+ // { "record_type": "customer", "metadata_schema": { ... } }
300
+
301
+ // API responds (snake_case):
302
+ // { "created_at": "2024-01-01T00:00:00Z" }
303
+
304
+ // You receive (camelCase):
305
+ console.log(record.createdAt) // "2024-01-01T00:00:00Z"
306
+ ```
307
+
308
+ ## Error Handling
309
+
310
+ ```typescript
311
+ import { RuntypeApiError } from '@runtypelabs/sdk'
312
+
313
+ try {
314
+ const flow = await runtype.flows.get('invalid_id')
315
+ } catch (error) {
316
+ if (error instanceof RuntypeApiError) {
317
+ console.log('API Error:', error.message)
318
+ console.log('Status Code:', error.statusCode)
319
+ console.log('Error Data:', error.data)
320
+ } else {
321
+ console.log('Network or other error:', error)
322
+ }
323
+ }
324
+ ```
325
+
326
+ ## TypeScript Support
327
+
328
+ The SDK is built with TypeScript and provides full type safety:
329
+
330
+ ```typescript
331
+ import type {
332
+ Flow,
333
+ RuntypeRecord,
334
+ Prompt,
335
+ FlowBuilder,
336
+ FlowResult,
337
+ StreamCallbacks
338
+ } from '@runtypelabs/sdk'
339
+
340
+ // All types use camelCase field names
341
+ const flow: Flow = await runtype.flows.get('flow_123')
342
+ console.log(flow.createdAt) // TypeScript knows this is a string
343
+ ```
344
+
345
+ ## Configuration Options
346
+
347
+ ```typescript
348
+ const runtype = new RuntypeClient({
349
+ apiKey: 'your-api-key', // Required for authenticated endpoints
350
+ baseUrl: 'https://api.runtype.com', // Optional, defaults to production
351
+ apiVersion: 'v1', // Optional, API version (default: 'v1')
352
+ timeout: 30000, // Optional, request timeout in ms (default: 30000)
353
+ headers: { // Optional, additional headers
354
+ 'X-Custom-Header': 'value'
355
+ }
356
+ })
357
+ ```
358
+
359
+ ## Publishing
360
+
361
+ ### Prerequisites
362
+
363
+ - npm account with publish access to `@runtypelabs/sdk`
364
+ - Logged in via `npm login`
365
+
366
+ ### Steps
367
+
368
+ ```bash
369
+ # 1. Ensure you're on main/staging with clean working tree
370
+ git status
371
+
372
+ # 2. Build the package
373
+ cd packages/client
374
+ pnpm build
375
+
376
+ # 3. Bump version (edit package.json manually or use npm with --ignore-scripts)
377
+ npm version patch --ignore-scripts # 0.1.0 → 0.1.1
378
+ # npm version minor --ignore-scripts # 0.1.0 → 0.2.0
379
+ # npm version major --ignore-scripts # 0.1.0 → 1.0.0
380
+
381
+ # 4. Publish to npm (pnpm handles workspace protocol correctly)
382
+ pnpm publish --access public --no-git-checks
383
+
384
+ # 5. Push version commit and tag to git
385
+ git push && git push --tags
386
+ ```
387
+
388
+ ### Dry Run
389
+
390
+ To preview what will be published without actually publishing:
391
+
392
+ ```bash
393
+ pnpm publish --dry-run
394
+ ```
395
+
396
+ ## License
397
+
398
+ MIT
@@ -0,0 +1,106 @@
1
+ /**
2
+ * BatchBuilder - Fluent builder for batch operations
3
+ *
4
+ * Provides a chainable API for building batch dispatch configurations
5
+ * that execute a flow across multiple records of the same type.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * import { BatchBuilder } from '@runtypelabs/sdk'
10
+ *
11
+ * const batch = await new BatchBuilder()
12
+ * .useFlow('flow_abc123')
13
+ * .forRecordType('customer')
14
+ * .withOptions({ async: true })
15
+ * .run(apiClient)
16
+ * ```
17
+ */
18
+ export interface BatchOptions {
19
+ /** Run batch asynchronously (default: true) */
20
+ async?: boolean;
21
+ /** Maximum concurrent executions */
22
+ concurrency?: number;
23
+ /** Continue on individual record failures */
24
+ continueOnError?: boolean;
25
+ /** Store results for each record */
26
+ storeResults?: boolean;
27
+ /** Model override for batch execution */
28
+ modelOverride?: string;
29
+ }
30
+ export interface BatchRequest {
31
+ flowId: string;
32
+ recordType: string;
33
+ options?: BatchOptions;
34
+ /** Optional filter for records */
35
+ filter?: Record<string, any>;
36
+ /** Optional limit on number of records */
37
+ limit?: number;
38
+ }
39
+ export interface BatchResult {
40
+ batchId: string;
41
+ status: 'queued' | 'running' | 'completed' | 'failed';
42
+ totalRecords: number;
43
+ processedRecords: number;
44
+ failedRecords: number;
45
+ }
46
+ export declare class BatchBuilder {
47
+ private flowId;
48
+ private recordType;
49
+ private batchOptions;
50
+ private filterConfig;
51
+ private limitConfig;
52
+ /**
53
+ * Specify the flow to execute for each record
54
+ */
55
+ useFlow(flowId: string): this;
56
+ /**
57
+ * Specify the record type to batch process
58
+ */
59
+ forRecordType(recordType: string): this;
60
+ /**
61
+ * Set batch execution options
62
+ */
63
+ withOptions(options: BatchOptions): this;
64
+ /**
65
+ * Filter records to process
66
+ *
67
+ * @example
68
+ * ```typescript
69
+ * .withFilter({ status: 'pending', createdAt: { $gt: '2024-01-01' } })
70
+ * ```
71
+ */
72
+ withFilter(filter: Record<string, any>): this;
73
+ /**
74
+ * Limit the number of records to process
75
+ */
76
+ withLimit(limit: number): this;
77
+ /**
78
+ * Build the batch request configuration
79
+ */
80
+ build(): BatchRequest;
81
+ /**
82
+ * Execute the batch operation
83
+ *
84
+ * @param client - Client with batch dispatch capability
85
+ * @returns BatchResult with batch status
86
+ */
87
+ run(client: BatchClient): Promise<BatchResult>;
88
+ }
89
+ /**
90
+ * Interface for clients that can execute batch operations
91
+ */
92
+ export interface BatchClient {
93
+ batch(config: BatchRequest): Promise<BatchResult>;
94
+ }
95
+ /**
96
+ * BatchBuilder that is bound to a client for direct execution
97
+ */
98
+ export declare class ClientBatchBuilder extends BatchBuilder {
99
+ private boundClient;
100
+ constructor(client: BatchClient);
101
+ /**
102
+ * Execute the batch using the bound client
103
+ */
104
+ run(): Promise<BatchResult>;
105
+ }
106
+ //# sourceMappingURL=batch-builder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"batch-builder.d.ts","sourceRoot":"","sources":["../src/batch-builder.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAQH,MAAM,WAAW,YAAY;IAC3B,+CAA+C;IAC/C,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,oCAAoC;IACpC,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,6CAA6C;IAC7C,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,oCAAoC;IACpC,YAAY,CAAC,EAAE,OAAO,CAAA;IACtB,yCAAyC;IACzC,aAAa,CAAC,EAAE,MAAM,CA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CAAC,CAAA;CAClD;AAED;;GAEG;AACH,qBAAa,kBAAmB,SAAQ,YAAY;IAClD,OAAO,CAAC,WAAW,CAAa;gBAEpB,MAAM,EAAE,WAAW;IAK/B;;OAEG;IACG,GAAG,IAAI,OAAO,CAAC,WAAW,CAAC;CAIlC"}
@@ -0,0 +1,124 @@
1
+ "use strict";
2
+ /**
3
+ * BatchBuilder - Fluent builder for batch operations
4
+ *
5
+ * Provides a chainable API for building batch dispatch configurations
6
+ * that execute a flow across multiple records of the same type.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { BatchBuilder } from '@runtypelabs/sdk'
11
+ *
12
+ * const batch = await new BatchBuilder()
13
+ * .useFlow('flow_abc123')
14
+ * .forRecordType('customer')
15
+ * .withOptions({ async: true })
16
+ * .run(apiClient)
17
+ * ```
18
+ */
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.ClientBatchBuilder = exports.BatchBuilder = void 0;
21
+ // ============================================================================
22
+ // BatchBuilder Class
23
+ // ============================================================================
24
+ class BatchBuilder {
25
+ constructor() {
26
+ this.flowId = '';
27
+ this.recordType = '';
28
+ this.batchOptions = {};
29
+ }
30
+ /**
31
+ * Specify the flow to execute for each record
32
+ */
33
+ useFlow(flowId) {
34
+ this.flowId = flowId;
35
+ return this;
36
+ }
37
+ /**
38
+ * Specify the record type to batch process
39
+ */
40
+ forRecordType(recordType) {
41
+ this.recordType = recordType;
42
+ return this;
43
+ }
44
+ /**
45
+ * Set batch execution options
46
+ */
47
+ withOptions(options) {
48
+ this.batchOptions = { ...this.batchOptions, ...options };
49
+ return this;
50
+ }
51
+ /**
52
+ * Filter records to process
53
+ *
54
+ * @example
55
+ * ```typescript
56
+ * .withFilter({ status: 'pending', createdAt: { $gt: '2024-01-01' } })
57
+ * ```
58
+ */
59
+ withFilter(filter) {
60
+ this.filterConfig = filter;
61
+ return this;
62
+ }
63
+ /**
64
+ * Limit the number of records to process
65
+ */
66
+ withLimit(limit) {
67
+ this.limitConfig = limit;
68
+ return this;
69
+ }
70
+ /**
71
+ * Build the batch request configuration
72
+ */
73
+ build() {
74
+ if (!this.flowId) {
75
+ throw new Error('BatchBuilder: flowId is required. Call .useFlow(flowId) first.');
76
+ }
77
+ if (!this.recordType) {
78
+ throw new Error('BatchBuilder: recordType is required. Call .forRecordType(type) first.');
79
+ }
80
+ const request = {
81
+ flowId: this.flowId,
82
+ recordType: this.recordType,
83
+ };
84
+ if (Object.keys(this.batchOptions).length > 0) {
85
+ request.options = this.batchOptions;
86
+ }
87
+ if (this.filterConfig) {
88
+ request.filter = this.filterConfig;
89
+ }
90
+ if (this.limitConfig !== undefined) {
91
+ request.limit = this.limitConfig;
92
+ }
93
+ return request;
94
+ }
95
+ /**
96
+ * Execute the batch operation
97
+ *
98
+ * @param client - Client with batch dispatch capability
99
+ * @returns BatchResult with batch status
100
+ */
101
+ async run(client) {
102
+ const config = this.build();
103
+ return client.batch(config);
104
+ }
105
+ }
106
+ exports.BatchBuilder = BatchBuilder;
107
+ /**
108
+ * BatchBuilder that is bound to a client for direct execution
109
+ */
110
+ class ClientBatchBuilder extends BatchBuilder {
111
+ constructor(client) {
112
+ super();
113
+ this.boundClient = client;
114
+ }
115
+ /**
116
+ * Execute the batch using the bound client
117
+ */
118
+ async run() {
119
+ const config = this.build();
120
+ return this.boundClient.batch(config);
121
+ }
122
+ }
123
+ exports.ClientBatchBuilder = ClientBatchBuilder;
124
+ //# sourceMappingURL=batch-builder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"batch-builder.js","sourceRoot":"","sources":["../src/batch-builder.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;GAgBG;;;AAuCH,+EAA+E;AAC/E,qBAAqB;AACrB,+EAA+E;AAE/E,MAAa,YAAY;IAAzB;QACU,WAAM,GAAW,EAAE,CAAA;QACnB,eAAU,GAAW,EAAE,CAAA;QACvB,iBAAY,GAAiB,EAAE,CAAA;IA0FzC,CAAC;IAtFC;;OAEG;IACH,OAAO,CA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