@backendkit-labs/pipeline 0.1.0 → 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 (3) hide show
  1. package/LICENSE +184 -0
  2. package/README.md +447 -447
  3. package/package.json +61 -35
package/LICENSE ADDED
@@ -0,0 +1,184 @@
1
+  Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and the Work's derivative works.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of discussing and
55
+ improving the Work, but excluding communication that is conspicuously
56
+ marked or designated in writing by the copyright owner as
57
+ "Not a Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and subsequently
61
+ incorporated within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by the combination of their Contribution(s)
78
+ with the Work to which such Contribution(s) was submitted. If You
79
+ institute patent litigation against any entity (including a cross-claim
80
+ or counterclaim in a lawsuit) alleging that the Work or any
81
+ Contribution embodied within the Work constitutes direct or contributory
82
+ patent infringement, then any patent licenses granted to You under
83
+ this License for that Work shall terminate as of the date such
84
+ litigation is filed.
85
+
86
+ 4. Redistribution. You may reproduce and distribute copies of the
87
+ Work or Derivative Works thereof in any medium, with or without
88
+ modifications, and in Source or Object form, provided that You
89
+ meet the following conditions:
90
+
91
+ (a) You must give any other recipients of the Work or Derivative
92
+ Works a copy of this License; and
93
+
94
+ (b) You must cause any modified files to carry prominent notices
95
+ stating that You changed the files; and
96
+
97
+ (c) You must retain, in the Source form of any Derivative Works
98
+ that You distribute, all copyright, patent, trademark, and
99
+ attribution notices from the Source form of the Work,
100
+ excluding those notices that do not pertain to any part of
101
+ the Derivative Works; and
102
+
103
+ (d) If the Work includes a "NOTICE" text file as part of its
104
+ distribution, You must include a readable copy of the
105
+ attribution notices contained within such NOTICE file, in
106
+ at least one of the following places: within a NOTICE text
107
+ file distributed as part of the Derivative Works; within
108
+ the Source form or documentation, if provided along with the
109
+ Derivative Works; or, within a display generated by the
110
+ Derivative Works, if and wherever such third-party notices
111
+ normally appear. The contents of the NOTICE file are for
112
+ informational purposes only and do not modify the License.
113
+ You may add Your own attribution notices within Derivative
114
+ Works that You distribute, alongside or in addition to the
115
+ NOTICE text from the Work, provided that such additional
116
+ attribution notices cannot be construed as modifying the License.
117
+
118
+ You may add Your own license statement for Your modifications and
119
+ may provide additional grant of rights to use, copy, modify, and
120
+ distribute Your modifications, or for such Derivative Works as a
121
+ whole, subject to the terms and conditions of this License.
122
+
123
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
124
+ any Contribution intentionally submitted for inclusion in the Work
125
+ by You to the Licensor shall be under the terms and conditions of
126
+ this License, without any additional terms or conditions.
127
+ Notwithstanding the above, nothing herein shall supersede or modify
128
+ the terms of any separate license agreement you may have executed
129
+ with Licensor regarding such Contributions.
130
+
131
+ 6. Trademarks. This License does not grant permission to use the trade
132
+ names, trademarks, service marks, or product names of the Licensor,
133
+ except as required for reasonable and customary use in describing the
134
+ origin of the Work and reproducing the content of the NOTICE file.
135
+
136
+ 7. Disclaimer of Warranty. Unless required by applicable law or
137
+ agreed to in writing, Licensor provides the Work (and each
138
+ Contributor provides its Contributions) on an "AS IS" BASIS,
139
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
140
+ implied, including, without limitation, any warranties or conditions
141
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
142
+ PARTICULAR PURPOSE. You are solely responsible for determining the
143
+ appropriateness of using or reproducing the Work and assume any
144
+ risks associated with Your exercise of permissions under this License.
145
+
146
+ 8. Limitation of Liability. In no event and under no legal theory,
147
+ whether in tort (including negligence), contract, or otherwise,
148
+ unless required by applicable law (such as deliberate and grossly
149
+ negligent acts) or agreed to in writing, shall any Contributor be
150
+ liable to You for damages, including any direct, indirect, special,
151
+ incidental, or exemplary damages of any character arising as a
152
+ result of this License or out of the use or inability to use the
153
+ Work (including but not limited to damages for loss of goodwill,
154
+ work stoppage, computer failure or malfunction, or all other
155
+ commercial damages or losses), even if such Contributor has been
156
+ advised of the possibility of such damages.
157
+
158
+ 9. Accepting Warranty or Additional Liability. While redistributing
159
+ the Work or Derivative Works thereof, You may choose to offer,
160
+ and charge a fee for, acceptance of support, warranty, indemnity,
161
+ or other liability obligations and/or rights consistent with this
162
+ License. However, in accepting such obligations, You may act only
163
+ on Your own behalf and on Your sole responsibility, not on behalf
164
+ of any other Contributor, and only if You agree to indemnify,
165
+ defend, and hold each Contributor harmless for any liability
166
+ incurred by, or claims asserted against, such Contributor by reason
167
+ of your accepting any such warranty or additional liability.
168
+
169
+ END OF TERMS AND CONDITIONS
170
+
171
+ Copyright 2024-2026 Mairon José Cuello Martínez
172
+
173
+ Licensed under the Apache License, Version 2.0 (the "License");
174
+ you may not use this file except in compliance with the License.
175
+ You may obtain a copy of the License at
176
+
177
+ http://www.apache.org/licenses/LICENSE-2.0
178
+
179
+ Unless required by applicable law or agreed to in writing, software
180
+ distributed under the License is distributed on an "AS IS" BASIS,
181
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
182
+ See the License for the specific language governing permissions and
183
+ limitations under the License.
184
+
package/README.md CHANGED
@@ -1,447 +1,447 @@
1
- # @backendkit-labs/pipeline
2
-
3
- [![npm version](https://img.shields.io/npm/v/@backendkit-labs/pipeline?style=flat-square&color=cb3837)](https://www.npmjs.com/package/@backendkit-labs/pipeline)
4
- [![CI](https://img.shields.io/github/actions/workflow/status/backendkit-dev/backendkit-monorepo/ci.yml?style=flat-square&label=CI)](https://github.com/backendkit-dev/backendkit-monorepo/actions/workflows/ci.yml)
5
- [![License](https://img.shields.io/npm/l/@backendkit-labs/pipeline?style=flat-square)](LICENSE)
6
- [![Node](https://img.shields.io/node/v/@backendkit-labs/pipeline?style=flat-square)](package.json)
7
-
8
- > Type-safe async pipeline for Node.js — Chain of Responsibility pattern with stop-on-first / collect-all modes, conditional steps, observability hooks, and optional NestJS integration.
9
-
10
- Each step in the pipeline receives the current context, transforms it, and returns a typed result. If a step fails, the pipeline can stop immediately or continue collecting all errors — your choice per pipeline.
11
-
12
- ---
13
-
14
- ## Installation
15
-
16
- ```bash
17
- npm install @backendkit-labs/pipeline
18
- ```
19
-
20
- NestJS peer dependencies (only for the `/nestjs` subpath):
21
-
22
- ```bash
23
- npm install @nestjs/common @nestjs/core rxjs
24
- ```
25
-
26
- ---
27
-
28
- ## TypeScript Configuration
29
-
30
- ### Subpath exports (`/nestjs`)
31
-
32
- This package uses the `exports` field in `package.json` to expose the `/nestjs` subpath. TypeScript's ability to resolve it depends on the `moduleResolution` setting in your `tsconfig.json`.
33
-
34
- **Modern resolution (recommended) — no extra config needed:**
35
-
36
- ```json
37
- // tsconfig.json
38
- {
39
- "compilerOptions": {
40
- "moduleResolution": "bundler"
41
- }
42
- }
43
- ```
44
-
45
- `"bundler"`, `"node16"`, and `"nodenext"` all understand the `exports` field natively. This is the recommended setting for any project using a bundler (Webpack, esbuild, Vite) or for NestJS projects on TypeScript ≥ 5.
46
-
47
- **Legacy resolution (`"node"`) — add `paths` aliases:**
48
-
49
- NestJS projects generated before ~2024 default to `"moduleResolution": "node"`, which ignores the `exports` field entirely. TypeScript won't find the types for `@backendkit-labs/pipeline/nestjs` unless you add explicit path aliases:
50
-
51
- ```json
52
- // tsconfig.json
53
- {
54
- "compilerOptions": {
55
- "moduleResolution": "node",
56
- "paths": {
57
- "@backendkit-labs/pipeline/nestjs": [
58
- "./node_modules/@backendkit-labs/pipeline/dist/nestjs/index"
59
- ]
60
- }
61
- }
62
- }
63
- ```
64
-
65
- > **Why does this happen?** The `"node"` resolver was designed before subpath exports existed. It only knows how to find `main` and `types` at the root of a package — it does not read the `exports` map. The `paths` alias manually points TypeScript to the right `.d.ts` file for the subpath.
66
- >
67
- > The `splitting: true` tsup option (which this package uses) and this `paths` configuration solve completely different problems. `splitting` fixes a **runtime** class identity issue — ensuring there is only one copy of a class in memory across both bundles. The `paths` alias fixes a **compile-time** issue — helping TypeScript find the types. Both may be needed in a legacy project.
68
-
69
- ---
70
-
71
- ### NestJS decorator support
72
-
73
- NestJS requires two compiler options to be enabled:
74
-
75
- ```json
76
- // tsconfig.json
77
- {
78
- "compilerOptions": {
79
- "experimentalDecorators": true,
80
- "emitDecoratorMetadata": true
81
- }
82
- }
83
- ```
84
-
85
- And `reflect-metadata` must be imported once at application startup, before any NestJS module is loaded:
86
-
87
- ```typescript
88
- // main.ts
89
- import 'reflect-metadata';
90
- import { NestFactory } from '@nestjs/core';
91
- import { AppModule } from './app.module';
92
-
93
- async function bootstrap() {
94
- const app = await NestFactory.create(AppModule);
95
- await app.listen(3000);
96
- }
97
- bootstrap();
98
- ```
99
-
100
- > NestJS CLI scaffolds both of these automatically. You only need to check this if you are setting up a project manually or if decorator-related DI errors appear at runtime.
101
-
102
- ---
103
-
104
- ## Quick Start — Framework-agnostic
105
-
106
- ```typescript
107
- import { pipeline, Ok, Err } from '@backendkit-labs/pipeline';
108
- import type { PipelineStep, StepResult } from '@backendkit-labs/pipeline';
109
-
110
- interface OrderCtx {
111
- productId: string;
112
- quantity: number;
113
- stock: number;
114
- price: number;
115
- total: number;
116
- }
117
-
118
- interface OrderError {
119
- code: string;
120
- message: string;
121
- }
122
-
123
- class StockStep implements PipelineStep<OrderCtx, OrderError> {
124
- async handle(ctx: OrderCtx): Promise<StepResult<OrderCtx, OrderError>> {
125
- if (ctx.stock < ctx.quantity) {
126
- return Err({ code: 'INSUFFICIENT_STOCK', message: 'Not enough stock' });
127
- }
128
- return Ok(ctx);
129
- }
130
- }
131
-
132
- class PricingStep implements PipelineStep<OrderCtx, OrderError> {
133
- async handle(ctx: OrderCtx): Promise<StepResult<OrderCtx, OrderError>> {
134
- return Ok({ ...ctx, total: ctx.price * ctx.quantity });
135
- }
136
- }
137
-
138
- // Build and run
139
- const result = await pipeline<OrderCtx, OrderError>()
140
- .pipe(new StockStep())
141
- .pipe(new PricingStep())
142
- .run({ productId: 'p1', quantity: 2, stock: 10, price: 50, total: 0 });
143
-
144
- if (result.ok) {
145
- console.log(result.value.total); // 100
146
- console.log(result.executedSteps); // ['StockStep', 'PricingStep']
147
- } else {
148
- console.log(result.error.failedStep); // 'StockStep'
149
- console.log(result.error.cause); // { code: 'INSUFFICIENT_STOCK', ... }
150
- }
151
- ```
152
-
153
- ---
154
-
155
- ## Quick Start — NestJS
156
-
157
- ```typescript
158
- // order.pipeline.ts
159
- import { definePipeline } from '@backendkit-labs/pipeline';
160
- import type { OrderCtx, OrderError } from './order.types';
161
-
162
- export const ORDER_PIPELINE = definePipeline<OrderCtx, OrderError>('order');
163
- ```
164
-
165
- ```typescript
166
- // app.module.ts
167
- import { Module } from '@nestjs/common';
168
- import { PipelineModule } from '@backendkit-labs/pipeline/nestjs';
169
- import { ORDER_PIPELINE } from './order.pipeline';
170
- import { StockStep, PricingStep, NotifyStep } from './steps';
171
-
172
- @Module({
173
- imports: [
174
- PipelineModule.forRoot({
175
- pipelines: [
176
- {
177
- token: ORDER_PIPELINE,
178
- steps: [StockStep, PricingStep, NotifyStep],
179
- options: {
180
- onError: (step, err) => logger.error(`Pipeline failed at ${step}`, err),
181
- },
182
- },
183
- ],
184
- }),
185
- ],
186
- })
187
- export class AppModule {}
188
- ```
189
-
190
- ```typescript
191
- // order.service.ts
192
- import { Injectable } from '@nestjs/common';
193
- import { InjectPipeline } from '@backendkit-labs/pipeline/nestjs';
194
- import { Pipeline } from '@backendkit-labs/pipeline';
195
- import { ORDER_PIPELINE } from './order.pipeline';
196
- import type { OrderCtx, OrderError } from './order.types';
197
-
198
- @Injectable()
199
- export class OrderService {
200
- constructor(
201
- @InjectPipeline(ORDER_PIPELINE)
202
- private readonly pipeline: Pipeline<OrderCtx, OrderError>,
203
- ) {}
204
-
205
- async processOrder(ctx: OrderCtx) {
206
- return this.pipeline.run(ctx);
207
- }
208
- }
209
- ```
210
-
211
- ---
212
-
213
- ## API
214
-
215
- ### `pipeline(options?)`
216
-
217
- Creates a new pipeline builder.
218
-
219
- ```typescript
220
- const p = pipeline<TContext, TError>(options?);
221
- ```
222
-
223
- #### Options
224
-
225
- ```typescript
226
- pipeline<Ctx, Err>({
227
- // 'stop-on-first' — stop and return on the first failure (default)
228
- // 'collect-all' — run all steps, accumulate every failure
229
- mode: 'stop-on-first',
230
-
231
- onStep(stepName, ctx) {
232
- logger.debug(`[pipeline] → ${stepName}`);
233
- },
234
-
235
- onStepComplete(stepName, ctx, durationMs) {
236
- metrics.timing(`step.${stepName}`, durationMs);
237
- },
238
-
239
- onError(stepName, error) {
240
- logger.error(`[pipeline] ✗ ${stepName}`, error);
241
- },
242
-
243
- onComplete(ctx, durationMs) {
244
- metrics.timing('pipeline.total', durationMs);
245
- },
246
- });
247
- ```
248
-
249
- ---
250
-
251
- ### `.pipe(step)`
252
-
253
- Adds a step that always runs.
254
-
255
- ```typescript
256
- p.pipe(new StockStep())
257
- .pipe(new PricingStep());
258
- ```
259
-
260
- ---
261
-
262
- ### `.pipeIf(condition, step)`
263
-
264
- Adds a step that runs only when `condition(ctx)` returns `true`. The condition receives the context **after** all previous steps have transformed it.
265
-
266
- ```typescript
267
- p.pipe(new BaseStep())
268
- .pipeIf(ctx => ctx.hasDiscount, new DiscountStep())
269
- .pipe(new FinalStep());
270
- ```
271
-
272
- ---
273
-
274
- ### `.run(ctx)`
275
-
276
- Executes the pipeline and returns a `PipelineRunResult`.
277
-
278
- ```typescript
279
- const result = await p.run(initialCtx);
280
-
281
- // Success
282
- result.ok // true
283
- result.value // final context
284
- result.executedSteps // ['StockStep', 'PricingStep']
285
- result.durationMs // total duration
286
-
287
- // Failure
288
- result.ok // false
289
- result.error.failedStep // 'StockStep'
290
- result.error.cause // original typed error
291
- result.error.executedSteps // steps that ran before the failure
292
- result.error.durationMs // total duration
293
- result.error.failures // all failures — one entry for stop-on-first, N for collect-all
294
- result.error.mode // 'stop-on-first' | 'collect-all'
295
- ```
296
-
297
- ---
298
-
299
- ### `Ok(value)` / `Err(error)`
300
-
301
- Helpers for returning step results.
302
-
303
- ```typescript
304
- import { Ok, Err } from '@backendkit-labs/pipeline';
305
-
306
- async handle(ctx): Promise<StepResult<Ctx, Err>> {
307
- if (!valid) return Err({ code: 'INVALID' });
308
- return Ok({ ...ctx, validated: true });
309
- }
310
- ```
311
-
312
- ---
313
-
314
- ### `PipelineStep<TContext, TError>`
315
-
316
- Interface your step classes implement.
317
-
318
- ```typescript
319
- import type { PipelineStep, StepResult } from '@backendkit-labs/pipeline';
320
-
321
- class MyStep implements PipelineStep<Ctx, MyError> {
322
- // Optional — overrides constructor.name in error reports and hook calls
323
- readonly stepName = 'MyStep';
324
-
325
- async handle(ctx: Ctx): Promise<StepResult<Ctx, MyError>> {
326
- // ...
327
- }
328
- }
329
- ```
330
-
331
- ---
332
-
333
- ## Error Modes
334
-
335
- ### `stop-on-first` (default)
336
-
337
- Stops at the first failure. Use when later steps depend on earlier ones being successful.
338
-
339
- ```typescript
340
- pipeline({ mode: 'stop-on-first' })
341
- .pipe(new AuthStep()) // if this fails → stop, PaymentStep never runs
342
- .pipe(new PaymentStep())
343
- .run(ctx);
344
- ```
345
-
346
- ### `collect-all`
347
-
348
- Runs every step regardless of failures. Use when steps are independent and you want to report all errors at once — e.g., form validation.
349
-
350
- ```typescript
351
- pipeline({ mode: 'collect-all' })
352
- .pipe(new ValidateNameStep())
353
- .pipe(new ValidateEmailStep())
354
- .pipe(new ValidatePhoneStep())
355
- .run(formData);
356
-
357
- // result.error.failures → [{ step: 'ValidateEmailStep', cause: ... }, { step: 'ValidatePhoneStep', cause: ... }]
358
- ```
359
-
360
- ---
361
-
362
- ## NestJS Integration
363
-
364
- ### `definePipeline<TContext, TError>(name)`
365
-
366
- Creates a typed injection token. Define it once and share across module and service.
367
-
368
- ```typescript
369
- export const ORDER_PIPELINE = definePipeline<OrderCtx, OrderError>('order');
370
- // PipelineToken<OrderCtx, OrderError>
371
- ```
372
-
373
- ### `PipelineModule.forRoot(options)`
374
-
375
- Registers pipelines globally. Each step class is resolved via NestJS DI, so steps can inject other services.
376
-
377
- ```typescript
378
- PipelineModule.forRoot({
379
- pipelines: [
380
- {
381
- token: ORDER_PIPELINE,
382
- steps: [StockStep, PricingStep, NotifyStep], // resolved via DI
383
- options: { mode: 'stop-on-first', onError: ... },
384
- },
385
- ],
386
- })
387
- ```
388
-
389
- ### `@InjectPipeline(token)`
390
-
391
- Parameter decorator for injecting a pipeline into a service.
392
-
393
- ```typescript
394
- constructor(
395
- @InjectPipeline(ORDER_PIPELINE)
396
- private readonly orderPipeline: Pipeline<OrderCtx, OrderError>,
397
- ) {}
398
- ```
399
-
400
- ---
401
-
402
- ## Use Cases
403
-
404
- | Scenario | Mode |
405
- |---|---|
406
- | Order processing (stock → payment → notify) | `stop-on-first` |
407
- | Form / DTO validation (collect all field errors) | `collect-all` |
408
- | User onboarding (KYC → plan → welcome email) | `stop-on-first` |
409
- | File processing (validate → scan → compress → upload) | `stop-on-first` |
410
- | Webhook processing (verify signature → parse → deduplicate → route) | `stop-on-first` |
411
- | Pricing pipeline (base → volume discount → tax → currency) | `stop-on-first` |
412
-
413
- ---
414
-
415
- ## Design Notes
416
-
417
- ### Context is immutable by convention
418
-
419
- Each step returns a **new** context object rather than mutating the existing one. This makes each step's input/output explicit and easy to trace in logs.
420
-
421
- ```typescript
422
- // Do this
423
- return Ok({ ...ctx, total: ctx.price * ctx.quantity });
424
-
425
- // Not this
426
- ctx.total = ctx.price * ctx.quantity;
427
- return Ok(ctx);
428
- ```
429
-
430
- ### Steps are plain classes
431
-
432
- Steps don't extend a base class or require special decorators. They just implement `PipelineStep<TContext, TError>`. This makes them easy to test in isolation:
433
-
434
- ```typescript
435
- const result = await new StockStep().handle({ stock: 0, quantity: 5, ... });
436
- expect(result.ok).toBe(false);
437
- ```
438
-
439
- ### NestJS DI class identity
440
-
441
- `PipelineModule.forRoot()` resolves step classes via NestJS DI and wires them into the pipeline at startup. All steps share the same DI context — no class identity issues.
442
-
443
- ---
444
-
445
- ## License
446
-
447
- MIT — [BackendKit Labs](https://github.com/backendkit-dev)
1
+ # @backendkit-labs/pipeline
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@backendkit-labs/pipeline?style=flat-square&color=cb3837)](https://www.npmjs.com/package/@backendkit-labs/pipeline)
4
+ [![CI](https://img.shields.io/github/actions/workflow/status/backendkit-dev/backendkit-monorepo/ci.yml?style=flat-square&label=CI)](https://github.com/backendkit-dev/backendkit-monorepo/actions/workflows/ci.yml)
5
+ [![License](https://img.shields.io/npm/l/@backendkit-labs/pipeline?style=flat-square)](LICENSE)
6
+ [![Node](https://img.shields.io/node/v/@backendkit-labs/pipeline?style=flat-square)](package.json)
7
+
8
+ > Type-safe async pipeline for Node.js — Chain of Responsibility pattern with stop-on-first / collect-all modes, conditional steps, observability hooks, and optional NestJS integration.
9
+
10
+ Each step in the pipeline receives the current context, transforms it, and returns a typed result. If a step fails, the pipeline can stop immediately or continue collecting all errors — your choice per pipeline.
11
+
12
+ ---
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ npm install @backendkit-labs/pipeline
18
+ ```
19
+
20
+ NestJS peer dependencies (only for the `/nestjs` subpath):
21
+
22
+ ```bash
23
+ npm install @nestjs/common @nestjs/core rxjs
24
+ ```
25
+
26
+ ---
27
+
28
+ ## TypeScript Configuration
29
+
30
+ ### Subpath exports (`/nestjs`)
31
+
32
+ This package uses the `exports` field in `package.json` to expose the `/nestjs` subpath. TypeScript's ability to resolve it depends on the `moduleResolution` setting in your `tsconfig.json`.
33
+
34
+ **Modern resolution (recommended) — no extra config needed:**
35
+
36
+ ```json
37
+ // tsconfig.json
38
+ {
39
+ "compilerOptions": {
40
+ "moduleResolution": "bundler"
41
+ }
42
+ }
43
+ ```
44
+
45
+ `"bundler"`, `"node16"`, and `"nodenext"` all understand the `exports` field natively. This is the recommended setting for any project using a bundler (Webpack, esbuild, Vite) or for NestJS projects on TypeScript ≥ 5.
46
+
47
+ **Legacy resolution (`"node"`) — add `paths` aliases:**
48
+
49
+ NestJS projects generated before ~2024 default to `"moduleResolution": "node"`, which ignores the `exports` field entirely. TypeScript won't find the types for `@backendkit-labs/pipeline/nestjs` unless you add explicit path aliases:
50
+
51
+ ```json
52
+ // tsconfig.json
53
+ {
54
+ "compilerOptions": {
55
+ "moduleResolution": "node",
56
+ "paths": {
57
+ "@backendkit-labs/pipeline/nestjs": [
58
+ "./node_modules/@backendkit-labs/pipeline/dist/nestjs/index"
59
+ ]
60
+ }
61
+ }
62
+ }
63
+ ```
64
+
65
+ > **Why does this happen?** The `"node"` resolver was designed before subpath exports existed. It only knows how to find `main` and `types` at the root of a package — it does not read the `exports` map. The `paths` alias manually points TypeScript to the right `.d.ts` file for the subpath.
66
+ >
67
+ > The `splitting: true` tsup option (which this package uses) and this `paths` configuration solve completely different problems. `splitting` fixes a **runtime** class identity issue — ensuring there is only one copy of a class in memory across both bundles. The `paths` alias fixes a **compile-time** issue — helping TypeScript find the types. Both may be needed in a legacy project.
68
+
69
+ ---
70
+
71
+ ### NestJS decorator support
72
+
73
+ NestJS requires two compiler options to be enabled:
74
+
75
+ ```json
76
+ // tsconfig.json
77
+ {
78
+ "compilerOptions": {
79
+ "experimentalDecorators": true,
80
+ "emitDecoratorMetadata": true
81
+ }
82
+ }
83
+ ```
84
+
85
+ And `reflect-metadata` must be imported once at application startup, before any NestJS module is loaded:
86
+
87
+ ```typescript
88
+ // main.ts
89
+ import 'reflect-metadata';
90
+ import { NestFactory } from '@nestjs/core';
91
+ import { AppModule } from './app.module';
92
+
93
+ async function bootstrap() {
94
+ const app = await NestFactory.create(AppModule);
95
+ await app.listen(3000);
96
+ }
97
+ bootstrap();
98
+ ```
99
+
100
+ > NestJS CLI scaffolds both of these automatically. You only need to check this if you are setting up a project manually or if decorator-related DI errors appear at runtime.
101
+
102
+ ---
103
+
104
+ ## Quick Start — Framework-agnostic
105
+
106
+ ```typescript
107
+ import { pipeline, Ok, Err } from '@backendkit-labs/pipeline';
108
+ import type { PipelineStep, StepResult } from '@backendkit-labs/pipeline';
109
+
110
+ interface OrderCtx {
111
+ productId: string;
112
+ quantity: number;
113
+ stock: number;
114
+ price: number;
115
+ total: number;
116
+ }
117
+
118
+ interface OrderError {
119
+ code: string;
120
+ message: string;
121
+ }
122
+
123
+ class StockStep implements PipelineStep<OrderCtx, OrderError> {
124
+ async handle(ctx: OrderCtx): Promise<StepResult<OrderCtx, OrderError>> {
125
+ if (ctx.stock < ctx.quantity) {
126
+ return Err({ code: 'INSUFFICIENT_STOCK', message: 'Not enough stock' });
127
+ }
128
+ return Ok(ctx);
129
+ }
130
+ }
131
+
132
+ class PricingStep implements PipelineStep<OrderCtx, OrderError> {
133
+ async handle(ctx: OrderCtx): Promise<StepResult<OrderCtx, OrderError>> {
134
+ return Ok({ ...ctx, total: ctx.price * ctx.quantity });
135
+ }
136
+ }
137
+
138
+ // Build and run
139
+ const result = await pipeline<OrderCtx, OrderError>()
140
+ .pipe(new StockStep())
141
+ .pipe(new PricingStep())
142
+ .run({ productId: 'p1', quantity: 2, stock: 10, price: 50, total: 0 });
143
+
144
+ if (result.ok) {
145
+ console.log(result.value.total); // 100
146
+ console.log(result.executedSteps); // ['StockStep', 'PricingStep']
147
+ } else {
148
+ console.log(result.error.failedStep); // 'StockStep'
149
+ console.log(result.error.cause); // { code: 'INSUFFICIENT_STOCK', ... }
150
+ }
151
+ ```
152
+
153
+ ---
154
+
155
+ ## Quick Start — NestJS
156
+
157
+ ```typescript
158
+ // order.pipeline.ts
159
+ import { definePipeline } from '@backendkit-labs/pipeline';
160
+ import type { OrderCtx, OrderError } from './order.types';
161
+
162
+ export const ORDER_PIPELINE = definePipeline<OrderCtx, OrderError>('order');
163
+ ```
164
+
165
+ ```typescript
166
+ // app.module.ts
167
+ import { Module } from '@nestjs/common';
168
+ import { PipelineModule } from '@backendkit-labs/pipeline/nestjs';
169
+ import { ORDER_PIPELINE } from './order.pipeline';
170
+ import { StockStep, PricingStep, NotifyStep } from './steps';
171
+
172
+ @Module({
173
+ imports: [
174
+ PipelineModule.forRoot({
175
+ pipelines: [
176
+ {
177
+ token: ORDER_PIPELINE,
178
+ steps: [StockStep, PricingStep, NotifyStep],
179
+ options: {
180
+ onError: (step, err) => logger.error(`Pipeline failed at ${step}`, err),
181
+ },
182
+ },
183
+ ],
184
+ }),
185
+ ],
186
+ })
187
+ export class AppModule {}
188
+ ```
189
+
190
+ ```typescript
191
+ // order.service.ts
192
+ import { Injectable } from '@nestjs/common';
193
+ import { InjectPipeline } from '@backendkit-labs/pipeline/nestjs';
194
+ import { Pipeline } from '@backendkit-labs/pipeline';
195
+ import { ORDER_PIPELINE } from './order.pipeline';
196
+ import type { OrderCtx, OrderError } from './order.types';
197
+
198
+ @Injectable()
199
+ export class OrderService {
200
+ constructor(
201
+ @InjectPipeline(ORDER_PIPELINE)
202
+ private readonly pipeline: Pipeline<OrderCtx, OrderError>,
203
+ ) {}
204
+
205
+ async processOrder(ctx: OrderCtx) {
206
+ return this.pipeline.run(ctx);
207
+ }
208
+ }
209
+ ```
210
+
211
+ ---
212
+
213
+ ## API
214
+
215
+ ### `pipeline(options?)`
216
+
217
+ Creates a new pipeline builder.
218
+
219
+ ```typescript
220
+ const p = pipeline<TContext, TError>(options?);
221
+ ```
222
+
223
+ #### Options
224
+
225
+ ```typescript
226
+ pipeline<Ctx, Err>({
227
+ // 'stop-on-first' — stop and return on the first failure (default)
228
+ // 'collect-all' — run all steps, accumulate every failure
229
+ mode: 'stop-on-first',
230
+
231
+ onStep(stepName, ctx) {
232
+ logger.debug(`[pipeline] → ${stepName}`);
233
+ },
234
+
235
+ onStepComplete(stepName, ctx, durationMs) {
236
+ metrics.timing(`step.${stepName}`, durationMs);
237
+ },
238
+
239
+ onError(stepName, error) {
240
+ logger.error(`[pipeline] ✗ ${stepName}`, error);
241
+ },
242
+
243
+ onComplete(ctx, durationMs) {
244
+ metrics.timing('pipeline.total', durationMs);
245
+ },
246
+ });
247
+ ```
248
+
249
+ ---
250
+
251
+ ### `.pipe(step)`
252
+
253
+ Adds a step that always runs.
254
+
255
+ ```typescript
256
+ p.pipe(new StockStep())
257
+ .pipe(new PricingStep());
258
+ ```
259
+
260
+ ---
261
+
262
+ ### `.pipeIf(condition, step)`
263
+
264
+ Adds a step that runs only when `condition(ctx)` returns `true`. The condition receives the context **after** all previous steps have transformed it.
265
+
266
+ ```typescript
267
+ p.pipe(new BaseStep())
268
+ .pipeIf(ctx => ctx.hasDiscount, new DiscountStep())
269
+ .pipe(new FinalStep());
270
+ ```
271
+
272
+ ---
273
+
274
+ ### `.run(ctx)`
275
+
276
+ Executes the pipeline and returns a `PipelineRunResult`.
277
+
278
+ ```typescript
279
+ const result = await p.run(initialCtx);
280
+
281
+ // Success
282
+ result.ok // true
283
+ result.value // final context
284
+ result.executedSteps // ['StockStep', 'PricingStep']
285
+ result.durationMs // total duration
286
+
287
+ // Failure
288
+ result.ok // false
289
+ result.error.failedStep // 'StockStep'
290
+ result.error.cause // original typed error
291
+ result.error.executedSteps // steps that ran before the failure
292
+ result.error.durationMs // total duration
293
+ result.error.failures // all failures — one entry for stop-on-first, N for collect-all
294
+ result.error.mode // 'stop-on-first' | 'collect-all'
295
+ ```
296
+
297
+ ---
298
+
299
+ ### `Ok(value)` / `Err(error)`
300
+
301
+ Helpers for returning step results.
302
+
303
+ ```typescript
304
+ import { Ok, Err } from '@backendkit-labs/pipeline';
305
+
306
+ async handle(ctx): Promise<StepResult<Ctx, Err>> {
307
+ if (!valid) return Err({ code: 'INVALID' });
308
+ return Ok({ ...ctx, validated: true });
309
+ }
310
+ ```
311
+
312
+ ---
313
+
314
+ ### `PipelineStep<TContext, TError>`
315
+
316
+ Interface your step classes implement.
317
+
318
+ ```typescript
319
+ import type { PipelineStep, StepResult } from '@backendkit-labs/pipeline';
320
+
321
+ class MyStep implements PipelineStep<Ctx, MyError> {
322
+ // Optional — overrides constructor.name in error reports and hook calls
323
+ readonly stepName = 'MyStep';
324
+
325
+ async handle(ctx: Ctx): Promise<StepResult<Ctx, MyError>> {
326
+ // ...
327
+ }
328
+ }
329
+ ```
330
+
331
+ ---
332
+
333
+ ## Error Modes
334
+
335
+ ### `stop-on-first` (default)
336
+
337
+ Stops at the first failure. Use when later steps depend on earlier ones being successful.
338
+
339
+ ```typescript
340
+ pipeline({ mode: 'stop-on-first' })
341
+ .pipe(new AuthStep()) // if this fails → stop, PaymentStep never runs
342
+ .pipe(new PaymentStep())
343
+ .run(ctx);
344
+ ```
345
+
346
+ ### `collect-all`
347
+
348
+ Runs every step regardless of failures. Use when steps are independent and you want to report all errors at once — e.g., form validation.
349
+
350
+ ```typescript
351
+ pipeline({ mode: 'collect-all' })
352
+ .pipe(new ValidateNameStep())
353
+ .pipe(new ValidateEmailStep())
354
+ .pipe(new ValidatePhoneStep())
355
+ .run(formData);
356
+
357
+ // result.error.failures → [{ step: 'ValidateEmailStep', cause: ... }, { step: 'ValidatePhoneStep', cause: ... }]
358
+ ```
359
+
360
+ ---
361
+
362
+ ## NestJS Integration
363
+
364
+ ### `definePipeline<TContext, TError>(name)`
365
+
366
+ Creates a typed injection token. Define it once and share across module and service.
367
+
368
+ ```typescript
369
+ export const ORDER_PIPELINE = definePipeline<OrderCtx, OrderError>('order');
370
+ // PipelineToken<OrderCtx, OrderError>
371
+ ```
372
+
373
+ ### `PipelineModule.forRoot(options)`
374
+
375
+ Registers pipelines globally. Each step class is resolved via NestJS DI, so steps can inject other services.
376
+
377
+ ```typescript
378
+ PipelineModule.forRoot({
379
+ pipelines: [
380
+ {
381
+ token: ORDER_PIPELINE,
382
+ steps: [StockStep, PricingStep, NotifyStep], // resolved via DI
383
+ options: { mode: 'stop-on-first', onError: ... },
384
+ },
385
+ ],
386
+ })
387
+ ```
388
+
389
+ ### `@InjectPipeline(token)`
390
+
391
+ Parameter decorator for injecting a pipeline into a service.
392
+
393
+ ```typescript
394
+ constructor(
395
+ @InjectPipeline(ORDER_PIPELINE)
396
+ private readonly orderPipeline: Pipeline<OrderCtx, OrderError>,
397
+ ) {}
398
+ ```
399
+
400
+ ---
401
+
402
+ ## Use Cases
403
+
404
+ | Scenario | Mode |
405
+ |---|---|
406
+ | Order processing (stock → payment → notify) | `stop-on-first` |
407
+ | Form / DTO validation (collect all field errors) | `collect-all` |
408
+ | User onboarding (KYC → plan → welcome email) | `stop-on-first` |
409
+ | File processing (validate → scan → compress → upload) | `stop-on-first` |
410
+ | Webhook processing (verify signature → parse → deduplicate → route) | `stop-on-first` |
411
+ | Pricing pipeline (base → volume discount → tax → currency) | `stop-on-first` |
412
+
413
+ ---
414
+
415
+ ## Design Notes
416
+
417
+ ### Context is immutable by convention
418
+
419
+ Each step returns a **new** context object rather than mutating the existing one. This makes each step's input/output explicit and easy to trace in logs.
420
+
421
+ ```typescript
422
+ // Do this
423
+ return Ok({ ...ctx, total: ctx.price * ctx.quantity });
424
+
425
+ // Not this
426
+ ctx.total = ctx.price * ctx.quantity;
427
+ return Ok(ctx);
428
+ ```
429
+
430
+ ### Steps are plain classes
431
+
432
+ Steps don't extend a base class or require special decorators. They just implement `PipelineStep<TContext, TError>`. This makes them easy to test in isolation:
433
+
434
+ ```typescript
435
+ const result = await new StockStep().handle({ stock: 0, quantity: 5, ... });
436
+ expect(result.ok).toBe(false);
437
+ ```
438
+
439
+ ### NestJS DI class identity
440
+
441
+ `PipelineModule.forRoot()` resolves step classes via NestJS DI and wires them into the pipeline at startup. All steps share the same DI context — no class identity issues.
442
+
443
+ ---
444
+
445
+ ## License
446
+
447
+ Apache-2.0 — [BackendKit Labs](https://github.com/backendkit-dev)
package/package.json CHANGED
@@ -1,71 +1,97 @@
1
1
  {
2
2
  "name": "@backendkit-labs/pipeline",
3
- "version": "0.1.0",
4
- "description": "Type-safe async pipeline — Chain of Responsibility with stop-on-first / collect-all modes, conditional steps, observability hooks, and optional NestJS integration",
3
+ "version": "0.1.1",
4
+ "license": "Apache-2.0",
5
+ "author": {
6
+ "name": "BackendKit Labs",
7
+ "email": "backendkit.dev@gmail.com"
8
+ },
9
+ "description": "Type-safe async pipeline — Chain of Responsibility with stop-on-first / collect-all modes, conditional steps, observability hooks, and optional NestJS integration",
5
10
  "type": "module",
6
11
  "main": "./dist/index.cjs",
7
12
  "module": "./dist/index.js",
8
13
  "types": "./dist/index.d.ts",
9
14
  "exports": {
10
15
  ".": {
11
- "types": "./dist/index.d.ts",
12
- "import": "./dist/index.js",
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.js",
13
18
  "require": "./dist/index.cjs"
14
19
  },
15
20
  "./nestjs": {
16
- "types": "./dist/nestjs/index.d.ts",
17
- "import": "./dist/nestjs/index.js",
21
+ "types": "./dist/nestjs/index.d.ts",
22
+ "import": "./dist/nestjs/index.js",
18
23
  "require": "./dist/nestjs/index.cjs"
19
24
  }
20
25
  },
21
- "files": ["dist", "README.md", "LICENSE"],
26
+ "files": [
27
+ "dist",
28
+ "README.md",
29
+ "LICENSE"
30
+ ],
22
31
  "scripts": {
23
- "build": "tsup",
24
- "dev": "tsup --watch",
25
- "test": "vitest run",
26
- "test:watch": "vitest",
32
+ "build": "tsup",
33
+ "dev": "tsup --watch",
34
+ "test": "vitest run",
35
+ "test:watch": "vitest",
27
36
  "test:coverage": "vitest run --coverage",
28
- "typecheck": "tsc --noEmit",
29
- "lint": "eslint src/",
37
+ "typecheck": "tsc --noEmit",
38
+ "lint": "eslint src/",
30
39
  "prepublishOnly": "npm run build && npm run test && npm run lint"
31
40
  },
32
41
  "keywords": [
33
- "pipeline", "chain-of-responsibility", "middleware", "handler",
34
- "async", "typescript", "nestjs", "node", "pattern"
42
+ "pipeline",
43
+ "chain-of-responsibility",
44
+ "middleware",
45
+ "handler",
46
+ "async",
47
+ "typescript",
48
+ "nestjs",
49
+ "node",
50
+ "pattern"
35
51
  ],
36
- "author": "Mairon José Cuello Martínez",
37
- "license": "MIT",
38
52
  "homepage": "https://github.com/backendkit-dev/backendkit-monorepo/tree/master/packages/pipeline#readme",
39
53
  "repository": {
40
54
  "type": "git",
41
55
  "url": "git+https://github.com/backendkit-dev/backendkit-monorepo.git",
42
56
  "directory": "packages/pipeline"
43
57
  },
44
- "bugs": { "url": "https://github.com/backendkit-dev/backendkit-monorepo/issues" },
45
- "publishConfig": { "access": "public" },
58
+ "bugs": {
59
+ "url": "https://github.com/backendkit-dev/backendkit-monorepo/issues"
60
+ },
61
+ "publishConfig": {
62
+ "access": "public"
63
+ },
46
64
  "sideEffects": false,
47
- "engines": { "node": ">=18" },
65
+ "engines": {
66
+ "node": ">=18"
67
+ },
48
68
  "peerDependencies": {
49
69
  "@nestjs/common": ">=10.0.0",
50
- "@nestjs/core": ">=10.0.0",
51
- "rxjs": ">=7.0.0"
70
+ "@nestjs/core": ">=10.0.0",
71
+ "rxjs": ">=7.0.0"
52
72
  },
53
73
  "peerDependenciesMeta": {
54
- "@nestjs/common": { "optional": true },
55
- "@nestjs/core": { "optional": true },
56
- "rxjs": { "optional": true }
74
+ "@nestjs/common": {
75
+ "optional": true
76
+ },
77
+ "@nestjs/core": {
78
+ "optional": true
79
+ },
80
+ "rxjs": {
81
+ "optional": true
82
+ }
57
83
  },
58
84
  "devDependencies": {
59
- "@eslint/js": "^9.39.4",
60
- "@nestjs/common": "^10.0.0",
61
- "@nestjs/core": "^10.0.0",
62
- "@types/node": "^22.0.0",
63
- "eslint": "^9.0.0",
64
- "reflect-metadata": "^0.2.0",
65
- "rxjs": "^7.8.0",
66
- "tsup": "^8.0.0",
67
- "typescript": "^5.5.0",
85
+ "@eslint/js": "^9.39.4",
86
+ "@nestjs/common": "^10.0.0",
87
+ "@nestjs/core": "^10.0.0",
88
+ "@types/node": "^22.0.0",
89
+ "eslint": "^9.0.0",
90
+ "reflect-metadata": "^0.2.0",
91
+ "rxjs": "^7.8.0",
92
+ "tsup": "^8.0.0",
93
+ "typescript": "^5.5.0",
68
94
  "typescript-eslint": "^8.59.3",
69
- "vitest": "^2.0.0"
95
+ "vitest": "^2.0.0"
70
96
  }
71
97
  }