@pgflow/dsl 0.0.0-0-10-0-ac3e1101-20251210151347

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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2025 Wojciech Majewski <owner@pgflow.dev>
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,346 @@
1
+ # @pgflow/dsl
2
+
3
+ The TypeScript Domain Specific Language (DSL) for defining type-safe workflow definitions in pgflow.
4
+
5
+ > [!NOTE]
6
+ > This project and all its components are licensed under [Apache 2.0](./LICENSE) license.
7
+
8
+ ## Overview
9
+
10
+ `@pgflow/dsl` provides a type-safe, fluent interface for defining data-driven workflows with explicit dependencies. The DSL ensures that data flows correctly between steps and maintains type safety throughout the entire workflow definition.
11
+
12
+ Key features:
13
+
14
+ - **Type Safety** - Complete TypeScript type checking from flow inputs to outputs
15
+ - **Fluent Interface** - Chainable method calls for defining steps and dependencies
16
+ - **Functional Approach** - Clean separation between task implementation and flow orchestration
17
+ - **JSON-Compatible** - All inputs and outputs are JSON-serializable for database storage
18
+ - **Immutable Flow Definitions** - Each step operation returns a new Flow instance
19
+
20
+ ## Usage
21
+
22
+ ### Basic Example
23
+
24
+ ```typescript
25
+ import { Flow } from '@pgflow/dsl';
26
+
27
+ // Define input type for the flow
28
+ type Input = {
29
+ url: string;
30
+ };
31
+
32
+ // Define a flow with steps and dependencies
33
+ export const AnalyzeWebsite = new Flow<Input>({
34
+ slug: 'analyzeWebsite',
35
+ maxAttempts: 3,
36
+ baseDelay: 5,
37
+ timeout: 10,
38
+ })
39
+ .step(
40
+ { slug: 'website' },
41
+ async (input) => await scrapeWebsite(input.run.url)
42
+ )
43
+ .step(
44
+ { slug: 'sentiment', dependsOn: ['website'] },
45
+ async (input) => await analyzeSentiment(input.website.content)
46
+ )
47
+ .step(
48
+ { slug: 'summary', dependsOn: ['website'] },
49
+ async (input) => await summarizeWithAI(input.website.content)
50
+ )
51
+ .step(
52
+ { slug: 'saveToDb', dependsOn: ['sentiment', 'summary'] },
53
+ async (input) => {
54
+ return await saveToDb({
55
+ websiteUrl: input.run.url,
56
+ sentiment: input.sentiment.score,
57
+ summary: input.summary.aiSummary,
58
+ });
59
+ }
60
+ );
61
+ ```
62
+
63
+ ### Understanding Data Flow
64
+
65
+ In pgflow, each step receives an `input` object that contains:
66
+
67
+ 1. **`input.run`** - The original flow input (available to all steps)
68
+ 2. **`input.{stepName}`** - Outputs from dependency steps
69
+
70
+ This design ensures:
71
+
72
+ - Original flow parameters are accessible throughout the entire flow
73
+ - Data doesn't need to be manually forwarded through intermediate steps
74
+ - Steps can combine original input with processed data from previous steps
75
+
76
+ ### Step Methods
77
+
78
+ The Flow DSL provides three methods for defining steps in your workflow:
79
+
80
+ #### `.step()` - Regular Steps
81
+
82
+ The standard method for adding steps to a flow. Each step processes input and returns output.
83
+
84
+ ```typescript
85
+ .step(
86
+ { slug: 'process', dependsOn: ['previous'] },
87
+ async (input) => {
88
+ // Access input.run and input.previous
89
+ return { result: 'processed' };
90
+ }
91
+ )
92
+ ```
93
+
94
+ #### `.array()` - Array-Returning Steps
95
+
96
+ A semantic wrapper around `.step()` that provides type enforcement for steps that return arrays. Useful for data fetching or collection steps that will be processed by map steps.
97
+
98
+ ```typescript
99
+ // Fetch an array of items to be processed
100
+ .array(
101
+ { slug: 'fetchItems' },
102
+ async () => [1, 2, 3, 4, 5]
103
+ )
104
+
105
+ // With dependencies - combining data from multiple sources
106
+ .array(
107
+ { slug: 'combineResults', dependsOn: ['source1', 'source2'] },
108
+ async (input) => [...input.source1, ...input.source2]
109
+ )
110
+ ```
111
+
112
+ **Key Points:**
113
+ - Return type is enforced to be an array at compile time
114
+ - Commonly used as input for subsequent map steps
115
+ - Can depend on other steps just like regular steps
116
+
117
+ #### `.map()` - Array Processing Steps
118
+
119
+ Processes arrays element-by-element, similar to JavaScript's `Array.map()`. The handler receives individual items instead of the full input object.
120
+
121
+ **Two Modes of Operation:**
122
+
123
+ 1. **Root Map** (no `array:` property): Processes the flow's input array directly
124
+ - The flow input MUST be an array when using root maps
125
+ - Omitting the `array:` property tells pgflow to use the flow input
126
+
127
+ 2. **Dependent Map** (with `array:` property): Processes another step's array output
128
+ - The `array:` property specifies which step's output to process
129
+ - That step must return an array
130
+
131
+ ```typescript
132
+ // ROOT MAP - No array: property means use flow input
133
+ // Flow input MUST be an array (e.g., ["hello", "world"])
134
+ new Flow<string[]>({ slug: 'processStrings' })
135
+ .map(
136
+ { slug: 'uppercase' }, // No array: property!
137
+ (item) => item.toUpperCase()
138
+ );
139
+ // Each string in the input array gets uppercased in parallel
140
+
141
+ // DEPENDENT MAP - array: property specifies the source step
142
+ new Flow<{}>({ slug: 'dataPipeline' })
143
+ .array({ slug: 'numbers' }, () => [1, 2, 3])
144
+ .map(
145
+ { slug: 'double', array: 'numbers' }, // Processes 'numbers' output
146
+ (n) => n * 2
147
+ )
148
+ .map(
149
+ { slug: 'square', array: 'double' }, // Chains from 'double'
150
+ (n) => n * n
151
+ );
152
+ // Results: numbers: [1,2,3] → double: [2,4,6] → square: [4,16,36]
153
+ ```
154
+
155
+ **Key differences from regular steps:**
156
+ - Uses `array:` to specify dependency (not `dependsOn:`)
157
+ - When `array:` is omitted, uses flow input array (root map)
158
+ - Handler signature is `(item, context) => result` instead of `(input, context) => result`
159
+ - Return type is always an array
160
+ - Map steps can have at most one dependency (the array source)
161
+ - Generates SQL with `step_type => 'map'` parameter for pgflow's map processing
162
+
163
+ **Type Safety:**
164
+ The `.map()` method provides full TypeScript type inference for array elements:
165
+
166
+ ```typescript
167
+ type User = { id: number; name: string };
168
+
169
+ new Flow<{}>({ slug: 'userFlow' })
170
+ .array({ slug: 'users' }, (): User[] => [
171
+ { id: 1, name: 'Alice' },
172
+ { id: 2, name: 'Bob' }
173
+ ])
174
+ .map({ slug: 'greet', array: 'users' }, (user) => {
175
+ // TypeScript knows user is of type User
176
+ return `Hello, ${user.name} (ID: ${user.id})`;
177
+ });
178
+ ```
179
+
180
+ **Common Patterns:**
181
+
182
+ ```typescript
183
+ // Batch processing - process multiple items in parallel
184
+ new Flow<number[]>({ slug: 'batchProcessor' })
185
+ .map({ slug: 'validate' }, (item) => {
186
+ if (item < 0) throw new Error('Invalid item');
187
+ return item;
188
+ })
189
+ .map({ slug: 'process', array: 'validate' }, async (item) => {
190
+ // Each item processed in its own task
191
+ return await expensiveOperation(item);
192
+ });
193
+
194
+ // Data transformation pipeline
195
+ new Flow<{}>({ slug: 'etlPipeline' })
196
+ .step({ slug: 'fetchUrls' }, () => ['url1', 'url2', 'url3'])
197
+ .map({ slug: 'scrape', array: 'fetchUrls' }, async (url) => {
198
+ return await fetchContent(url);
199
+ })
200
+ .map({ slug: 'extract', array: 'scrape' }, (html) => {
201
+ return extractData(html);
202
+ })
203
+ .step({ slug: 'aggregate', dependsOn: ['extract'] }, (input) => {
204
+ // input.extract is the aggregated array from all map tasks
205
+ return consolidateResults(input.extract);
206
+ });
207
+ ```
208
+
209
+ **Limitations:**
210
+ - Can only depend on a single array-returning step
211
+ - TypeScript may not track type transformations between chained maps (use type assertions if needed)
212
+ - Root maps require the entire flow input to be an array
213
+
214
+ ### Context Object
215
+
216
+ Step handlers can optionally receive a second parameter - the **context object** - which provides access to platform resources and runtime information.
217
+
218
+ ```typescript
219
+ .step(
220
+ { slug: 'saveToDb' },
221
+ async (input, context) => {
222
+ // Access platform resources through context
223
+ const result = await context.sql`SELECT * FROM users WHERE id = ${input.userId}`;
224
+ return result[0];
225
+ }
226
+ )
227
+ ```
228
+
229
+ #### Core Context Resources
230
+
231
+ All platforms provide these core resources:
232
+
233
+ - **`context.env`** - Environment variables (`Record<string, string | undefined>`)
234
+ - **`context.shutdownSignal`** - AbortSignal for graceful shutdown handling
235
+ - **`context.rawMessage`** - Original pgmq message with metadata
236
+ ```typescript
237
+ interface PgmqMessageRecord<T> {
238
+ msg_id: number;
239
+ read_ct: number;
240
+ enqueued_at: Date;
241
+ vt: Date;
242
+ message: T; // <-- this is your 'input'
243
+ }
244
+ ```
245
+ - **`context.stepTask`** - Current step task details (flow handlers only)
246
+ ```typescript
247
+ interface StepTaskRecord<TFlow> {
248
+ flow_slug: string;
249
+ run_id: string;
250
+ step_slug: string;
251
+ input: StepInput<TFlow, StepSlug>; // <-- this is handler 'input'
252
+ msg_id: number;
253
+ }
254
+ ```
255
+ - **`context.workerConfig`** - Resolved worker configuration with all defaults applied
256
+ ```typescript
257
+ // Provides access to worker settings like retry limits
258
+ const isLastAttempt = context.rawMessage.read_ct >= context.workerConfig.retry.limit;
259
+ ```
260
+
261
+ #### Supabase Platform Resources
262
+
263
+ When using the Supabase platform with EdgeWorker, additional resources are available:
264
+
265
+ - **`context.sql`** - PostgreSQL client (postgres.js)
266
+ - **`context.supabase`** - Supabase client with service role key for full database access
267
+
268
+ To use Supabase resources, import the `Flow` class from the Supabase preset:
269
+
270
+ ```typescript
271
+ import { Flow } from '@pgflow/dsl/supabase';
272
+
273
+ const MyFlow = new Flow<{ userId: string }>({
274
+ slug: 'myFlow',
275
+ }).step({ slug: 'process' }, async (input, context) => {
276
+ // TypeScript knows context includes Supabase resources
277
+ const { data } = await context.supabase
278
+ .from('users')
279
+ .select('*')
280
+ .eq('id', input.userId);
281
+
282
+ // Use SQL directly
283
+ const stats = await context.sql`
284
+ SELECT COUNT(*) as total FROM events
285
+ WHERE user_id = ${input.userId}
286
+ `;
287
+
288
+ return { user: data[0], eventCount: stats[0].total };
289
+ });
290
+ ```
291
+
292
+ > [!NOTE]
293
+ > Context is optional - handlers that don't need platform resources can omit the second parameter for backward compatibility.
294
+
295
+ For more details on available resources and platform configuration, see the [@pgflow/edge-worker documentation](https://github.com/pgflow-org/pgflow/tree/main/pkgs/edge-worker#context-resources).
296
+
297
+ ### Flow Configuration
298
+
299
+ Configure flows and steps with runtime options:
300
+
301
+ ```typescript
302
+ new Flow<Input>({
303
+ slug: 'myFlow', // Required: Unique flow identifier
304
+ maxAttempts: 3, // Optional: Maximum retry attempts (default: 1)
305
+ baseDelay: 5, // Optional: Base delay in seconds for retries (default: 1)
306
+ timeout: 10, // Optional: Task timeout in seconds (default: 30)
307
+ });
308
+ ```
309
+
310
+ ## Compiling Flows
311
+
312
+ Use the `compileFlow` utility to convert a flow definition into SQL statements:
313
+
314
+ ```typescript
315
+ import { compileFlow } from '@pgflow/dsl';
316
+
317
+ const sqlStatements = compileFlow(MyFlow);
318
+ console.log(sqlStatements.join('\n'));
319
+ ```
320
+
321
+ Alternatively, use the pgflow CLI to compile flows directly to migration files:
322
+
323
+ ```bash
324
+ npx pgflow compile path/to/flow.ts
325
+ ```
326
+
327
+ ## Requirements
328
+
329
+ - All step inputs and outputs MUST be JSON-serializable
330
+ - Use only: primitive types, plain objects, and arrays
331
+ - Convert dates to ISO strings (`new Date().toISOString()`)
332
+ - Avoid: class instances, functions, symbols, undefined values, and circular references
333
+
334
+ ## Building
335
+
336
+ Run `nx build dsl` to build the library.
337
+
338
+ ## Running unit tests
339
+
340
+ Run `nx test dsl` to execute the unit tests via [Vitest](https://vitest.dev/).
341
+
342
+ ## Documentation
343
+
344
+ For detailed documentation on the Flow DSL, visit:
345
+
346
+ - [Understanding the Flow DSL](https://pgflow.dev/explanations/flow-dsl/)