hierarchical-approval 1.9.0 → 2.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/CHANGELOG.md +76 -0
- package/README.md +52 -0
- package/dist/{ApprovalEngine-a1jXglT3.d.ts → ApprovalEngine-CJwnpnpL.d.ts} +52 -7
- package/dist/{ApprovalEngine-BDI4r_KB.d.cts → ApprovalEngine-DqRIadYg.d.cts} +52 -7
- package/dist/{IAuditAdapter-UJNdJanq.d.cts → IAuditAdapter-BHVKMMv6.d.cts} +1 -1
- package/dist/{IAuditAdapter-DDV4Rf9F.d.ts → IAuditAdapter-C4OASS6u.d.ts} +1 -1
- package/dist/{IAuthorizationPolicy-CFJ-gXKl.d.ts → IAuthorizationPolicy-BA_m2Dg9.d.ts} +1 -1
- package/dist/{IAuthorizationPolicy-CN6LAaKg.d.cts → IAuthorizationPolicy-CtLkwQ8I.d.cts} +1 -1
- package/dist/{INotificationAdapter-Dv_MuYwS.d.ts → INotificationAdapter-BdgfUrIn.d.ts} +12 -2
- package/dist/{INotificationAdapter-Dy2d0JKy.d.cts → INotificationAdapter-JJAiMyMd.d.cts} +12 -2
- package/dist/{IOperationMiddleware-DWYXVuJD.d.ts → IOperationMiddleware-BGYrAqep.d.ts} +1 -1
- package/dist/{IOperationMiddleware-DGG-guxK.d.cts → IOperationMiddleware-D0ksiFM3.d.cts} +1 -1
- package/dist/{IStorageAdapter-DMa5VNNz.d.ts → IStorageAdapter-Bk7ybd3z.d.cts} +21 -1
- package/dist/{IStorageAdapter-CRSfnH8U.d.cts → IStorageAdapter-DjRvHUF0.d.ts} +21 -1
- package/dist/adapters/MemoryAdapter.cjs +7 -0
- package/dist/adapters/MemoryAdapter.cjs.map +1 -1
- package/dist/adapters/MemoryAdapter.d.cts +3 -2
- package/dist/adapters/MemoryAdapter.d.ts +3 -2
- package/dist/adapters/MemoryAdapter.js +7 -0
- package/dist/adapters/MemoryAdapter.js.map +1 -1
- package/dist/adapters/PostgresAdapter.cjs +43 -0
- package/dist/adapters/PostgresAdapter.cjs.map +1 -1
- package/dist/adapters/PostgresAdapter.d.cts +3 -2
- package/dist/adapters/PostgresAdapter.d.ts +3 -2
- package/dist/adapters/PostgresAdapter.js +43 -0
- package/dist/adapters/PostgresAdapter.js.map +1 -1
- package/dist/index.cjs +284 -36
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +8 -8
- package/dist/index.d.ts +8 -8
- package/dist/index.js +284 -36
- package/dist/index.js.map +1 -1
- package/dist/{instance-BE0uJmg3.d.cts → instance-DUJY_Axf.d.cts} +41 -3
- package/dist/{instance-BE0uJmg3.d.ts → instance-DUJY_Axf.d.ts} +41 -3
- package/dist/nestjs.cjs +277 -36
- package/dist/nestjs.cjs.map +1 -1
- package/dist/nestjs.d.cts +7 -7
- package/dist/nestjs.d.ts +7 -7
- package/dist/nestjs.js +277 -36
- package/dist/nestjs.js.map +1 -1
- package/dist/plugins/audit.d.cts +2 -2
- package/dist/plugins/audit.d.ts +2 -2
- package/dist/plugins/notify.d.cts +2 -2
- package/dist/plugins/notify.d.ts +2 -2
- package/dist/plugins/resilience.d.cts +3 -3
- package/dist/plugins/resilience.d.ts +3 -3
- package/dist/plugins/tracing.d.cts +2 -2
- package/dist/plugins/tracing.d.ts +2 -2
- package/dist/plugins/webhook.d.cts +2 -2
- package/dist/plugins/webhook.d.ts +2 -2
- package/dist/testing.cjs +284 -36
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +7 -7
- package/dist/testing.d.ts +7 -7
- package/dist/testing.js +284 -36
- package/dist/testing.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,82 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
|
7
7
|
|
|
8
8
|
_Nothing yet._
|
|
9
9
|
|
|
10
|
+
## [2.1.0] - 2026-09-04
|
|
11
|
+
|
|
12
|
+
### Added — sub-workflows
|
|
13
|
+
|
|
14
|
+
- **A level can delegate to a whole separate approval.** "A capital request over
|
|
15
|
+
1M needs its own board approval before this purchase order can proceed" could
|
|
16
|
+
only be modelled by flattening the board's chain into the purchase order's —
|
|
17
|
+
duplicating it in every template that needed it, and losing the board approval
|
|
18
|
+
as a thing with its own identity, audit trail and lifecycle.
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
{ level: 2, name: 'Board approval', mode: 'any', approvers: [],
|
|
22
|
+
subWorkflow: { templateName: 'BOARD' } }
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
When the level opens, a child instance is submitted against the named
|
|
26
|
+
template, carrying the parent's document data so the child's own conditions
|
|
27
|
+
see the same document. The parent level stays open, with no approvers of its
|
|
28
|
+
own, until the child finishes.
|
|
29
|
+
|
|
30
|
+
- **An approved child advances the parent; any other terminal outcome rejects
|
|
31
|
+
it.** Rejected, cancelled and expired all collapse into one rejection
|
|
32
|
+
deliberately: a parent that treated a cancelled child as "carry on" would
|
|
33
|
+
advance past a gate nobody cleared.
|
|
34
|
+
|
|
35
|
+
- **Children are spawned outside the parent's optimistic write.** The child's own
|
|
36
|
+
`submit()` reads and writes; nesting that inside the parent's compare-and-set
|
|
37
|
+
would turn a slow child template into spurious version conflicts on the
|
|
38
|
+
decision the user just made. The same applies in reverse when a child returns
|
|
39
|
+
its outcome.
|
|
40
|
+
|
|
41
|
+
- **Nesting is capped at five levels**, and `validateTemplate()` rejects a
|
|
42
|
+
template that would spawn itself, sets both `approvers` and `subWorkflow`
|
|
43
|
+
(whose approvers would never be asked), or names no child template. A
|
|
44
|
+
sub-workflow level is exempt from the "must have at least one approver" rule,
|
|
45
|
+
since its child decides it.
|
|
46
|
+
|
|
47
|
+
New exports: `SubWorkflowConfig`, `SubWorkflowEvent`. `ApprovalInstance` gains
|
|
48
|
+
`parentLevel` and `subWorkflowDepth`; levels gain `childInstanceId` and
|
|
49
|
+
`subWorkflowTemplate`.
|
|
50
|
+
|
|
51
|
+
## [2.0.0] - 2026-09-04
|
|
52
|
+
|
|
53
|
+
### BREAKING — `IStorageAdapter` requires `countInstances`
|
|
54
|
+
|
|
55
|
+
**Only affects custom storage adapters.** The bundled `MemoryAdapter` and
|
|
56
|
+
`PostgresAdapter` implement it; if you use those, upgrading needs no code
|
|
57
|
+
change (run `migrate()` if you have not since 1.7.0).
|
|
58
|
+
|
|
59
|
+
Reporting needs counts far more often than rows. `getStatistics()` alone issued
|
|
60
|
+
`4N + 5` count queries for a tenant with N templates, and every one of them went
|
|
61
|
+
through `getInstancesByFilter(…, { limit: 1 })` — making the database compute the
|
|
62
|
+
count *and* serialise a complete instance row, JSONB levels and document data
|
|
63
|
+
included, only to discard it. `healthCheck()` did the same.
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
countInstances(tenantId: string, filter: InstanceFilter): Promise<number>;
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
`PostgresAdapter` answers it with a bare `SELECT COUNT(*)`: no row payload, no
|
|
70
|
+
`COUNT(*) OVER()` window, and the planner is free to satisfy it from an index
|
|
71
|
+
rather than touching the JSONB columns at all. Every filter — including the
|
|
72
|
+
`data` dot-path matching from 1.4.0 — is supported and parameterised.
|
|
73
|
+
|
|
74
|
+
**Migrating a custom adapter.** One line restores the previous behaviour, and
|
|
75
|
+
you can replace it with a real count query whenever it suits:
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
countInstances = (tenantId, filter) =>
|
|
79
|
+
this.getInstancesByFilter(tenantId, filter, { limit: 1, offset: 0 }).then((r) => r.total);
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
No behaviour changes for callers: `getStatistics()` and `healthCheck()` return
|
|
83
|
+
exactly what they did, computed without fetching rows nobody reads. The
|
|
84
|
+
cycle-time sweep still reads rows, because it needs their timestamps.
|
|
85
|
+
|
|
10
86
|
## [1.9.0] - 2026-09-04
|
|
11
87
|
|
|
12
88
|
### Added — `getWorkload()`
|
package/README.md
CHANGED
|
@@ -399,6 +399,24 @@ engine.registerConditionOperator('between', (actual, expected) => {
|
|
|
399
399
|
});
|
|
400
400
|
```
|
|
401
401
|
|
|
402
|
+
### Writing a custom storage adapter
|
|
403
|
+
|
|
404
|
+
Implement `IStorageAdapter`. Most methods map straightforwardly onto a table;
|
|
405
|
+
one deserves a note:
|
|
406
|
+
|
|
407
|
+
```ts
|
|
408
|
+
countInstances(tenantId: string, filter: InstanceFilter): Promise<number>;
|
|
409
|
+
```
|
|
410
|
+
|
|
411
|
+
Reporting asks for counts far more often than rows, so this exists to let the
|
|
412
|
+
database answer with a real `COUNT(*)` rather than fetching a page and reading
|
|
413
|
+
its total. If you have nothing better to hand, one line is a valid start:
|
|
414
|
+
|
|
415
|
+
```ts
|
|
416
|
+
countInstances = (tenantId, filter) =>
|
|
417
|
+
this.getInstancesByFilter(tenantId, filter, { limit: 1, offset: 0 }).then((r) => r.total);
|
|
418
|
+
```
|
|
419
|
+
|
|
402
420
|
### Who is holding things up
|
|
403
421
|
|
|
404
422
|
`getStatistics()` answers how the tenant is doing; `getWorkload()` answers who
|
|
@@ -450,6 +468,40 @@ The sweep is **not atomic**: it reports per-instance failures rather than rollin
|
|
|
450
468
|
back. A partial transfer is the useful outcome — the approvals that can move
|
|
451
469
|
should move, and the ones that cannot are named so a human can look at them.
|
|
452
470
|
|
|
471
|
+
### Sub-workflows
|
|
472
|
+
|
|
473
|
+
A level can delegate to a whole separate approval instead of to a list of
|
|
474
|
+
approvers — "a capital request over 1M needs its own board approval before this
|
|
475
|
+
purchase order can proceed" — without flattening the board's chain into the
|
|
476
|
+
purchase order's:
|
|
477
|
+
|
|
478
|
+
```ts
|
|
479
|
+
levels: [
|
|
480
|
+
{ level: 1, name: 'Manager', approvers: [{ type: 'user', userId: 'mgr' }], mode: 'any' },
|
|
481
|
+
{ level: 2, name: 'Board approval', mode: 'any', approvers: [],
|
|
482
|
+
subWorkflow: { templateName: 'BOARD' } },
|
|
483
|
+
{ level: 3, name: 'CEO', approvers: [{ type: 'user', userId: 'ceo' }], mode: 'any' },
|
|
484
|
+
]
|
|
485
|
+
```
|
|
486
|
+
|
|
487
|
+
When level 2 opens, a child instance is submitted against `BOARD`, carrying the
|
|
488
|
+
parent's document data so the child's own conditions see the same document. The
|
|
489
|
+
parent level stays open, with no approvers of its own, until the child finishes.
|
|
490
|
+
|
|
491
|
+
| Child outcome | Parent |
|
|
492
|
+
|---|---|
|
|
493
|
+
| `approved` | Level approved; the chain advances |
|
|
494
|
+
| `rejected`, `cancelled`, `expired` | Parent rejected |
|
|
495
|
+
|
|
496
|
+
Collapsing the non-approved outcomes into one rejection is deliberate: a parent
|
|
497
|
+
that treated a cancelled child as "carry on" would advance past a gate nobody
|
|
498
|
+
cleared.
|
|
499
|
+
|
|
500
|
+
Children link back via `parentInstanceId` and `parentLevel`, and the level
|
|
501
|
+
records `childInstanceId`. Nesting is allowed up to five levels deep, and
|
|
502
|
+
`validateTemplate()` rejects a template that would spawn itself. Emits
|
|
503
|
+
`approval:subworkflow_started` / `approval:subworkflow_completed`.
|
|
504
|
+
|
|
453
505
|
### Attachments
|
|
454
506
|
|
|
455
507
|
Attach supporting evidence — a quote PDF, a signed contract, a screenshot of a
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import { I as IStorageAdapter, P as PaginationOpts, a as PaginatedResult, b as InstanceFilter, C as CursorPaginationOpts, c as CursorPaginatedResult } from './IStorageAdapter-
|
|
2
|
-
import { l as ConditionExpression, p as ResolverFn, g as ApprovalTemplateConfig, A as ApprovalTemplate, k as AuditContext, a as ApprovalInstance, e as ApprovalMode, b as AuditEntry } from './instance-
|
|
3
|
-
import { I as INotificationAdapter, b as ApprovalEventName, a as ApprovalEventMap } from './INotificationAdapter-
|
|
1
|
+
import { I as IStorageAdapter, P as PaginationOpts, a as PaginatedResult, b as InstanceFilter, C as CursorPaginationOpts, c as CursorPaginatedResult } from './IStorageAdapter-DjRvHUF0.js';
|
|
2
|
+
import { l as ConditionExpression, p as ResolverFn, g as ApprovalTemplateConfig, A as ApprovalTemplate, k as AuditContext, a as ApprovalInstance, e as ApprovalMode, b as AuditEntry } from './instance-DUJY_Axf.js';
|
|
3
|
+
import { I as INotificationAdapter, b as ApprovalEventName, a as ApprovalEventMap } from './INotificationAdapter-BdgfUrIn.js';
|
|
4
4
|
import { z } from 'zod';
|
|
5
5
|
import { L as Logger } from './Logger-BplhlU7l.js';
|
|
6
6
|
import { C as Clock } from './Clock-3FnOczFJ.js';
|
|
7
|
-
import { I as IOperationMiddleware, a as ApprovalError } from './IOperationMiddleware-
|
|
8
|
-
import { I as IAuditAdapter } from './IAuditAdapter-
|
|
7
|
+
import { I as IOperationMiddleware, a as ApprovalError } from './IOperationMiddleware-BGYrAqep.js';
|
|
8
|
+
import { I as IAuditAdapter } from './IAuditAdapter-C4OASS6u.js';
|
|
9
9
|
import { I as IMetricsAdapter } from './IMetricsAdapter-DWq8IFaf.js';
|
|
10
10
|
import { I as ISchedulerAdapter } from './ISchedulerAdapter-DKv_QjVN.js';
|
|
11
|
-
import { I as IAuthorizationPolicy } from './IAuthorizationPolicy-
|
|
11
|
+
import { I as IAuthorizationPolicy } from './IAuthorizationPolicy-BA_m2Dg9.js';
|
|
12
12
|
|
|
13
13
|
declare const SubmitOptionsSchema: z.ZodObject<{
|
|
14
14
|
templateName: z.ZodString;
|
|
@@ -470,7 +470,18 @@ declare class ApprovalEngine {
|
|
|
470
470
|
updateTemplate(config: ApprovalTemplateConfig): Promise<string>;
|
|
471
471
|
getTemplate(name: string): Promise<ApprovalTemplate>;
|
|
472
472
|
listTemplates(): Promise<ApprovalTemplate[]>;
|
|
473
|
-
submit(raw: SubmitOptions, auditCtx?: AuditContext
|
|
473
|
+
submit(raw: SubmitOptions, auditCtx?: AuditContext,
|
|
474
|
+
/**
|
|
475
|
+
* @internal Set only when the engine spawns a sub-workflow child. Passed at
|
|
476
|
+
* creation rather than stamped afterwards, because the child spawns its own
|
|
477
|
+
* children before any post-submit update could reach it — which is how a
|
|
478
|
+
* grandchild ended up recorded at depth 1.
|
|
479
|
+
*/
|
|
480
|
+
link?: {
|
|
481
|
+
parentInstanceId: string;
|
|
482
|
+
parentLevel: number;
|
|
483
|
+
depth: number;
|
|
484
|
+
}): Promise<ApprovalInstance>;
|
|
474
485
|
approve(instanceId: string, raw: ApproveOptions, auditCtx?: AuditContext): Promise<ApprovalInstance>;
|
|
475
486
|
reject(instanceId: string, raw: RejectOptions, auditCtx?: AuditContext): Promise<ApprovalInstance>;
|
|
476
487
|
delegate(instanceId: string, raw: DelegateOptions, auditCtx?: AuditContext): Promise<void>;
|
|
@@ -736,6 +747,40 @@ declare class ApprovalEngine {
|
|
|
736
747
|
* half-decided quorum level stops pestering the approvers who did their part.
|
|
737
748
|
*/
|
|
738
749
|
private sendReminder;
|
|
750
|
+
/**
|
|
751
|
+
* Start child approvals for any open level that delegates to a sub-workflow.
|
|
752
|
+
*
|
|
753
|
+
* Run after the parent has been persisted, never inside the same optimistic
|
|
754
|
+
* write: the child's own `submit()` performs its own reads and writes, and
|
|
755
|
+
* nesting them under the parent's compare-and-set would make a slow child
|
|
756
|
+
* template a source of spurious version conflicts on the parent.
|
|
757
|
+
*/
|
|
758
|
+
private startSubWorkflows;
|
|
759
|
+
/**
|
|
760
|
+
* Return a finished child's outcome to the parent level that is waiting on it.
|
|
761
|
+
*
|
|
762
|
+
* An approved child approves its parent level and lets the chain advance; any
|
|
763
|
+
* other terminal outcome — rejected, cancelled, expired — rejects the parent,
|
|
764
|
+
* because the approval the parent was waiting for did not happen. Collapsing
|
|
765
|
+
* those into one rejection is deliberate: a parent that treated a cancelled
|
|
766
|
+
* child as "carry on" would advance past a gate nobody cleared.
|
|
767
|
+
*/
|
|
768
|
+
private propagateToParent;
|
|
769
|
+
/** Mark a sub-workflow level approved and advance the parent chain. */
|
|
770
|
+
private completeSubWorkflowLevel;
|
|
771
|
+
/** Reject a parent because the child approval it was waiting on did not succeed. */
|
|
772
|
+
private rejectFromSubWorkflow;
|
|
773
|
+
/**
|
|
774
|
+
* Work that must happen after a decision is durably recorded, not inside it.
|
|
775
|
+
*
|
|
776
|
+
* Both branches touch other instances — a newly opened level may spawn a
|
|
777
|
+
* child approval, and a finished instance may be a child that owes its
|
|
778
|
+
* outcome to a parent. Doing either inside the deciding instance's
|
|
779
|
+
* compare-and-set would nest writes under a version guard that knows nothing
|
|
780
|
+
* about them, so a slow child template would surface as a spurious conflict
|
|
781
|
+
* on the decision the user just made.
|
|
782
|
+
*/
|
|
783
|
+
private afterDecision;
|
|
739
784
|
private findNextLevel;
|
|
740
785
|
private findPreviousLevel;
|
|
741
786
|
private guardBulkSize;
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import { I as IStorageAdapter, P as PaginationOpts, a as PaginatedResult, b as InstanceFilter, C as CursorPaginationOpts, c as CursorPaginatedResult } from './IStorageAdapter-
|
|
2
|
-
import { l as ConditionExpression, p as ResolverFn, g as ApprovalTemplateConfig, A as ApprovalTemplate, k as AuditContext, a as ApprovalInstance, e as ApprovalMode, b as AuditEntry } from './instance-
|
|
3
|
-
import { I as INotificationAdapter, b as ApprovalEventName, a as ApprovalEventMap } from './INotificationAdapter-
|
|
1
|
+
import { I as IStorageAdapter, P as PaginationOpts, a as PaginatedResult, b as InstanceFilter, C as CursorPaginationOpts, c as CursorPaginatedResult } from './IStorageAdapter-Bk7ybd3z.cjs';
|
|
2
|
+
import { l as ConditionExpression, p as ResolverFn, g as ApprovalTemplateConfig, A as ApprovalTemplate, k as AuditContext, a as ApprovalInstance, e as ApprovalMode, b as AuditEntry } from './instance-DUJY_Axf.cjs';
|
|
3
|
+
import { I as INotificationAdapter, b as ApprovalEventName, a as ApprovalEventMap } from './INotificationAdapter-JJAiMyMd.cjs';
|
|
4
4
|
import { z } from 'zod';
|
|
5
5
|
import { L as Logger } from './Logger-BplhlU7l.cjs';
|
|
6
6
|
import { C as Clock } from './Clock-3FnOczFJ.cjs';
|
|
7
|
-
import { I as IOperationMiddleware, a as ApprovalError } from './IOperationMiddleware-
|
|
8
|
-
import { I as IAuditAdapter } from './IAuditAdapter-
|
|
7
|
+
import { I as IOperationMiddleware, a as ApprovalError } from './IOperationMiddleware-D0ksiFM3.cjs';
|
|
8
|
+
import { I as IAuditAdapter } from './IAuditAdapter-BHVKMMv6.cjs';
|
|
9
9
|
import { I as IMetricsAdapter } from './IMetricsAdapter-DWq8IFaf.cjs';
|
|
10
10
|
import { I as ISchedulerAdapter } from './ISchedulerAdapter-DKv_QjVN.cjs';
|
|
11
|
-
import { I as IAuthorizationPolicy } from './IAuthorizationPolicy-
|
|
11
|
+
import { I as IAuthorizationPolicy } from './IAuthorizationPolicy-CtLkwQ8I.cjs';
|
|
12
12
|
|
|
13
13
|
declare const SubmitOptionsSchema: z.ZodObject<{
|
|
14
14
|
templateName: z.ZodString;
|
|
@@ -470,7 +470,18 @@ declare class ApprovalEngine {
|
|
|
470
470
|
updateTemplate(config: ApprovalTemplateConfig): Promise<string>;
|
|
471
471
|
getTemplate(name: string): Promise<ApprovalTemplate>;
|
|
472
472
|
listTemplates(): Promise<ApprovalTemplate[]>;
|
|
473
|
-
submit(raw: SubmitOptions, auditCtx?: AuditContext
|
|
473
|
+
submit(raw: SubmitOptions, auditCtx?: AuditContext,
|
|
474
|
+
/**
|
|
475
|
+
* @internal Set only when the engine spawns a sub-workflow child. Passed at
|
|
476
|
+
* creation rather than stamped afterwards, because the child spawns its own
|
|
477
|
+
* children before any post-submit update could reach it — which is how a
|
|
478
|
+
* grandchild ended up recorded at depth 1.
|
|
479
|
+
*/
|
|
480
|
+
link?: {
|
|
481
|
+
parentInstanceId: string;
|
|
482
|
+
parentLevel: number;
|
|
483
|
+
depth: number;
|
|
484
|
+
}): Promise<ApprovalInstance>;
|
|
474
485
|
approve(instanceId: string, raw: ApproveOptions, auditCtx?: AuditContext): Promise<ApprovalInstance>;
|
|
475
486
|
reject(instanceId: string, raw: RejectOptions, auditCtx?: AuditContext): Promise<ApprovalInstance>;
|
|
476
487
|
delegate(instanceId: string, raw: DelegateOptions, auditCtx?: AuditContext): Promise<void>;
|
|
@@ -736,6 +747,40 @@ declare class ApprovalEngine {
|
|
|
736
747
|
* half-decided quorum level stops pestering the approvers who did their part.
|
|
737
748
|
*/
|
|
738
749
|
private sendReminder;
|
|
750
|
+
/**
|
|
751
|
+
* Start child approvals for any open level that delegates to a sub-workflow.
|
|
752
|
+
*
|
|
753
|
+
* Run after the parent has been persisted, never inside the same optimistic
|
|
754
|
+
* write: the child's own `submit()` performs its own reads and writes, and
|
|
755
|
+
* nesting them under the parent's compare-and-set would make a slow child
|
|
756
|
+
* template a source of spurious version conflicts on the parent.
|
|
757
|
+
*/
|
|
758
|
+
private startSubWorkflows;
|
|
759
|
+
/**
|
|
760
|
+
* Return a finished child's outcome to the parent level that is waiting on it.
|
|
761
|
+
*
|
|
762
|
+
* An approved child approves its parent level and lets the chain advance; any
|
|
763
|
+
* other terminal outcome — rejected, cancelled, expired — rejects the parent,
|
|
764
|
+
* because the approval the parent was waiting for did not happen. Collapsing
|
|
765
|
+
* those into one rejection is deliberate: a parent that treated a cancelled
|
|
766
|
+
* child as "carry on" would advance past a gate nobody cleared.
|
|
767
|
+
*/
|
|
768
|
+
private propagateToParent;
|
|
769
|
+
/** Mark a sub-workflow level approved and advance the parent chain. */
|
|
770
|
+
private completeSubWorkflowLevel;
|
|
771
|
+
/** Reject a parent because the child approval it was waiting on did not succeed. */
|
|
772
|
+
private rejectFromSubWorkflow;
|
|
773
|
+
/**
|
|
774
|
+
* Work that must happen after a decision is durably recorded, not inside it.
|
|
775
|
+
*
|
|
776
|
+
* Both branches touch other instances — a newly opened level may spawn a
|
|
777
|
+
* child approval, and a finished instance may be a child that owes its
|
|
778
|
+
* outcome to a parent. Doing either inside the deciding instance's
|
|
779
|
+
* compare-and-set would nest writes under a version guard that knows nothing
|
|
780
|
+
* about them, so a slow child template would surface as a spurious conflict
|
|
781
|
+
* on the decision the user just made.
|
|
782
|
+
*/
|
|
783
|
+
private afterDecision;
|
|
739
784
|
private findNextLevel;
|
|
740
785
|
private findPreviousLevel;
|
|
741
786
|
private guardBulkSize;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as ApprovalInstance, d as ApprovalLevelInstance } from './instance-
|
|
1
|
+
import { a as ApprovalInstance, d as ApprovalLevelInstance } from './instance-DUJY_Axf.js';
|
|
2
2
|
|
|
3
3
|
interface AuthorizationContext {
|
|
4
4
|
operation: 'submit' | 'approve' | 'reject' | 'delegate' | 'reassign' | 'cancel' | 'escalate' | 'override' | 'resubmit' | 'addComment' | 'updateData' | 'requestInfo' | 'provideInfo' | 'addAttachment' | 'removeAttachment';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as ApprovalInstance, d as ApprovalLevelInstance } from './instance-
|
|
1
|
+
import { a as ApprovalInstance, d as ApprovalLevelInstance } from './instance-DUJY_Axf.cjs';
|
|
2
2
|
|
|
3
3
|
interface AuthorizationContext {
|
|
4
4
|
operation: 'submit' | 'approve' | 'reject' | 'delegate' | 'reassign' | 'cancel' | 'escalate' | 'override' | 'resubmit' | 'addComment' | 'updateData' | 'requestInfo' | 'provideInfo' | 'addAttachment' | 'removeAttachment';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as ApprovalInstance, b as AuditEntry } from './instance-
|
|
1
|
+
import { a as ApprovalInstance, b as AuditEntry } from './instance-DUJY_Axf.js';
|
|
2
2
|
|
|
3
3
|
interface ApprovalEvent {
|
|
4
4
|
instanceId: string;
|
|
@@ -112,6 +112,14 @@ interface AttachmentEvent extends ApprovalEvent {
|
|
|
112
112
|
uri: string;
|
|
113
113
|
level?: number;
|
|
114
114
|
}
|
|
115
|
+
/** Emitted when a level hands off to a child approval, and when that child returns. */
|
|
116
|
+
interface SubWorkflowEvent extends ApprovalEvent {
|
|
117
|
+
level: number;
|
|
118
|
+
childInstanceId: string;
|
|
119
|
+
childTemplateName: string;
|
|
120
|
+
/** Set on completion: the outcome the child returned. */
|
|
121
|
+
outcome?: 'approved' | 'rejected' | 'cancelled' | 'expired';
|
|
122
|
+
}
|
|
115
123
|
interface ApprovalEventMap {
|
|
116
124
|
'approval:submitted': SubmittedEvent;
|
|
117
125
|
'approval:approved': ApprovedEvent;
|
|
@@ -132,6 +140,8 @@ interface ApprovalEventMap {
|
|
|
132
140
|
'approval:info_provided': InfoProvidedEvent;
|
|
133
141
|
'approval:attachment_added': AttachmentEvent;
|
|
134
142
|
'approval:attachment_removed': AttachmentEvent;
|
|
143
|
+
'approval:subworkflow_started': SubWorkflowEvent;
|
|
144
|
+
'approval:subworkflow_completed': SubWorkflowEvent;
|
|
135
145
|
}
|
|
136
146
|
type ApprovalEventName = keyof ApprovalEventMap;
|
|
137
147
|
interface HistoryEntry extends AuditEntry {
|
|
@@ -155,4 +165,4 @@ interface INotificationAdapter {
|
|
|
155
165
|
notify(event: NotificationEvent): Promise<void>;
|
|
156
166
|
}
|
|
157
167
|
|
|
158
|
-
export type { ApprovalEvent as A, CancelledEvent as C, DataUpdatedEvent as D, EscalatedEvent as E, HistoryEntry as H, INotificationAdapter as I, LevelAdvancedEvent as L, NotificationEvent as N, OverriddenEvent as O, ReassignedEvent as R, SlaBreachedEvent as S, ApprovalEventMap as a, ApprovalEventName as b, ApprovedEvent as c, AttachmentEvent as d, DelegatedEvent as e, ExpiredEvent as f, InfoProvidedEvent as g, InfoRequestedEvent as h, RejectedEvent as i, ReminderEvent as j, ResubmittedEvent as k,
|
|
168
|
+
export type { ApprovalEvent as A, CancelledEvent as C, DataUpdatedEvent as D, EscalatedEvent as E, HistoryEntry as H, INotificationAdapter as I, LevelAdvancedEvent as L, NotificationEvent as N, OverriddenEvent as O, ReassignedEvent as R, SlaBreachedEvent as S, ApprovalEventMap as a, ApprovalEventName as b, ApprovedEvent as c, AttachmentEvent as d, DelegatedEvent as e, ExpiredEvent as f, InfoProvidedEvent as g, InfoRequestedEvent as h, RejectedEvent as i, ReminderEvent as j, ResubmittedEvent as k, SubWorkflowEvent as l, SubmittedEvent as m };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as ApprovalInstance, b as AuditEntry } from './instance-
|
|
1
|
+
import { a as ApprovalInstance, b as AuditEntry } from './instance-DUJY_Axf.cjs';
|
|
2
2
|
|
|
3
3
|
interface ApprovalEvent {
|
|
4
4
|
instanceId: string;
|
|
@@ -112,6 +112,14 @@ interface AttachmentEvent extends ApprovalEvent {
|
|
|
112
112
|
uri: string;
|
|
113
113
|
level?: number;
|
|
114
114
|
}
|
|
115
|
+
/** Emitted when a level hands off to a child approval, and when that child returns. */
|
|
116
|
+
interface SubWorkflowEvent extends ApprovalEvent {
|
|
117
|
+
level: number;
|
|
118
|
+
childInstanceId: string;
|
|
119
|
+
childTemplateName: string;
|
|
120
|
+
/** Set on completion: the outcome the child returned. */
|
|
121
|
+
outcome?: 'approved' | 'rejected' | 'cancelled' | 'expired';
|
|
122
|
+
}
|
|
115
123
|
interface ApprovalEventMap {
|
|
116
124
|
'approval:submitted': SubmittedEvent;
|
|
117
125
|
'approval:approved': ApprovedEvent;
|
|
@@ -132,6 +140,8 @@ interface ApprovalEventMap {
|
|
|
132
140
|
'approval:info_provided': InfoProvidedEvent;
|
|
133
141
|
'approval:attachment_added': AttachmentEvent;
|
|
134
142
|
'approval:attachment_removed': AttachmentEvent;
|
|
143
|
+
'approval:subworkflow_started': SubWorkflowEvent;
|
|
144
|
+
'approval:subworkflow_completed': SubWorkflowEvent;
|
|
135
145
|
}
|
|
136
146
|
type ApprovalEventName = keyof ApprovalEventMap;
|
|
137
147
|
interface HistoryEntry extends AuditEntry {
|
|
@@ -155,4 +165,4 @@ interface INotificationAdapter {
|
|
|
155
165
|
notify(event: NotificationEvent): Promise<void>;
|
|
156
166
|
}
|
|
157
167
|
|
|
158
|
-
export type { ApprovalEvent as A, CancelledEvent as C, DataUpdatedEvent as D, EscalatedEvent as E, HistoryEntry as H, INotificationAdapter as I, LevelAdvancedEvent as L, NotificationEvent as N, OverriddenEvent as O, ReassignedEvent as R, SlaBreachedEvent as S, ApprovalEventMap as a, ApprovalEventName as b, ApprovedEvent as c, AttachmentEvent as d, DelegatedEvent as e, ExpiredEvent as f, InfoProvidedEvent as g, InfoRequestedEvent as h, RejectedEvent as i, ReminderEvent as j, ResubmittedEvent as k,
|
|
168
|
+
export type { ApprovalEvent as A, CancelledEvent as C, DataUpdatedEvent as D, EscalatedEvent as E, HistoryEntry as H, INotificationAdapter as I, LevelAdvancedEvent as L, NotificationEvent as N, OverriddenEvent as O, ReassignedEvent as R, SlaBreachedEvent as S, ApprovalEventMap as a, ApprovalEventName as b, ApprovedEvent as c, AttachmentEvent as d, DelegatedEvent as e, ExpiredEvent as f, InfoProvidedEvent as g, InfoRequestedEvent as h, RejectedEvent as i, ReminderEvent as j, ResubmittedEvent as k, SubWorkflowEvent as l, SubmittedEvent as m };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as ApprovalTemplate, a as ApprovalInstance, f as ApprovalStatus, b as AuditEntry } from './instance-
|
|
1
|
+
import { A as ApprovalTemplate, a as ApprovalInstance, f as ApprovalStatus, b as AuditEntry } from './instance-DUJY_Axf.cjs';
|
|
2
2
|
|
|
3
3
|
interface PaginationOpts {
|
|
4
4
|
limit: number;
|
|
@@ -51,6 +51,26 @@ interface IStorageAdapter {
|
|
|
51
51
|
/** Optional cursor-based pagination — more efficient than offset at scale. */
|
|
52
52
|
getInstancesByCursor?(tenantId: string, filter: InstanceFilter, opts: CursorPaginationOpts): Promise<CursorPaginatedResult<ApprovalInstance>>;
|
|
53
53
|
getOverdueInstances(tenantId: string, asOf: Date, filter?: InstanceFilter): Promise<ApprovalInstance[]>;
|
|
54
|
+
/**
|
|
55
|
+
* Count instances matching a filter, without fetching any of them.
|
|
56
|
+
*
|
|
57
|
+
* Reporting needs counts far more often than rows: `getStatistics()` alone
|
|
58
|
+
* issues `4N + 5` of them for a tenant with N templates. Answering those
|
|
59
|
+
* through `getInstancesByFilter` made the database compute the count *and*
|
|
60
|
+
* serialise a full instance row — JSONB levels, document data and all — for
|
|
61
|
+
* every one, only to discard it.
|
|
62
|
+
*
|
|
63
|
+
* A custom adapter with nothing better available can satisfy this in one line:
|
|
64
|
+
*
|
|
65
|
+
* ```ts
|
|
66
|
+
* countInstances = (tenantId, filter) =>
|
|
67
|
+
* this.getInstancesByFilter(tenantId, filter, { limit: 1, offset: 0 })
|
|
68
|
+
* .then((r) => r.total);
|
|
69
|
+
* ```
|
|
70
|
+
*
|
|
71
|
+
* @since 2.0.0 — required. See the release notes for the migration.
|
|
72
|
+
*/
|
|
73
|
+
countInstances(tenantId: string, filter: InstanceFilter): Promise<number>;
|
|
54
74
|
getIdempotentInstance(tenantId: string, idempotencyKey: string): Promise<ApprovalInstance | null>;
|
|
55
75
|
appendAuditEntry(tenantId: string, instanceId: string, entry: AuditEntry): Promise<void>;
|
|
56
76
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as ApprovalTemplate, a as ApprovalInstance, f as ApprovalStatus, b as AuditEntry } from './instance-
|
|
1
|
+
import { A as ApprovalTemplate, a as ApprovalInstance, f as ApprovalStatus, b as AuditEntry } from './instance-DUJY_Axf.js';
|
|
2
2
|
|
|
3
3
|
interface PaginationOpts {
|
|
4
4
|
limit: number;
|
|
@@ -51,6 +51,26 @@ interface IStorageAdapter {
|
|
|
51
51
|
/** Optional cursor-based pagination — more efficient than offset at scale. */
|
|
52
52
|
getInstancesByCursor?(tenantId: string, filter: InstanceFilter, opts: CursorPaginationOpts): Promise<CursorPaginatedResult<ApprovalInstance>>;
|
|
53
53
|
getOverdueInstances(tenantId: string, asOf: Date, filter?: InstanceFilter): Promise<ApprovalInstance[]>;
|
|
54
|
+
/**
|
|
55
|
+
* Count instances matching a filter, without fetching any of them.
|
|
56
|
+
*
|
|
57
|
+
* Reporting needs counts far more often than rows: `getStatistics()` alone
|
|
58
|
+
* issues `4N + 5` of them for a tenant with N templates. Answering those
|
|
59
|
+
* through `getInstancesByFilter` made the database compute the count *and*
|
|
60
|
+
* serialise a full instance row — JSONB levels, document data and all — for
|
|
61
|
+
* every one, only to discard it.
|
|
62
|
+
*
|
|
63
|
+
* A custom adapter with nothing better available can satisfy this in one line:
|
|
64
|
+
*
|
|
65
|
+
* ```ts
|
|
66
|
+
* countInstances = (tenantId, filter) =>
|
|
67
|
+
* this.getInstancesByFilter(tenantId, filter, { limit: 1, offset: 0 })
|
|
68
|
+
* .then((r) => r.total);
|
|
69
|
+
* ```
|
|
70
|
+
*
|
|
71
|
+
* @since 2.0.0 — required. See the release notes for the migration.
|
|
72
|
+
*/
|
|
73
|
+
countInstances(tenantId: string, filter: InstanceFilter): Promise<number>;
|
|
54
74
|
getIdempotentInstance(tenantId: string, idempotencyKey: string): Promise<ApprovalInstance | null>;
|
|
55
75
|
appendAuditEntry(tenantId: string, instanceId: string, entry: AuditEntry): Promise<void>;
|
|
56
76
|
}
|
|
@@ -167,6 +167,13 @@ var MemoryAdapter = class {
|
|
|
167
167
|
return hasOverdueEscalation || isExpired || hasSLABreach || hasDelegationExpiry || hasDueReminder;
|
|
168
168
|
}).map((i) => reviveDates(deepClone(i)));
|
|
169
169
|
}
|
|
170
|
+
async countInstances(tenantId, filter) {
|
|
171
|
+
let count = 0;
|
|
172
|
+
for (const instance of this.instances.values()) {
|
|
173
|
+
if (instance.tenantId === tenantId && applyFilter(instance, filter)) count++;
|
|
174
|
+
}
|
|
175
|
+
return count;
|
|
176
|
+
}
|
|
170
177
|
async getInstancesByCursor(tenantId, filter, opts) {
|
|
171
178
|
const all = [...this.instances.values()].filter((i) => i.tenantId === tenantId && applyFilter(i, filter)).map((i) => reviveDates(deepClone(i))).sort((a, b) => {
|
|
172
179
|
const ta = a.updatedAt.getTime();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/errors.ts","../../src/adapters/MemoryAdapter.ts"],"names":[],"mappings":";;;AAAO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvC,WAAA,CACE,SACgB,IAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;A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AAA,OAAO,IAAA;AAAA,EACT;AAAA,EAEA,MAAM,gBAAA,CACJ,SAAA,EACA,WAAA,EACA,MAAA,EACe;AAAA,EAMjB;AAAA;AAAA,EAGA,IAAI,IAAA,GAAe;AACjB,IAAA,OAAO,KAAK,SAAA,CAAU,IAAA;AAAA,EACxB;AACF;AAEA,SAAS,QAAA,CAAY,OAAY,IAAA,EAA2C;AAC1E,EAAA,MAAM,QAAQ,KAAA,CAAM,MAAA;AACpB,EAAA,IAAI,CAAC,IAAA,EAAM,OAAO,EAAE,OAAO,KAAA,EAAM;AACjC,EAAA,OAAO,EAAE,KAAA,EAAO,KAAA,CAAM,KAAA,CAAM,IAAA,CAAK,MAAA,EAAQ,IAAA,CAAK,MAAA,GAAS,IAAA,CAAK,KAAK,CAAA,EAAG,KAAA,EAAM;AAC5E;AAEA,SAAS,aAAa,QAAA,EAAoC;AACxD,EAAA,OAAO,MAAA,CAAO,IAAA,CAAK,CAAA,EAAG,QAAA,CAAS,SAAA,CAAU,OAAA,EAAS,CAAA,CAAA,EAAI,QAAA,CAAS,EAAE,CAAA,CAAE,CAAA,CAAE,SAAS,QAAQ,CAAA;AACxF;AAEA,SAAS,aAAa,MAAA,EAAkC;AACtD,EAAA,MAAM,UAAU,MAAA,CAAO,IAAA,CAAK,QAAQ,QAAQ,CAAA,CAAE,SAAS,MAAM,CAAA;AAC7D,EAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,OAAA,CAAQ,GAAG,CAAA;AACnC,EAAA,OAAO,CAAC,MAAA,CAAO,OAAA,CAAQ,KAAA,CAAM,CAAA,EAAG,OAAO,CAAC,CAAA,EAAG,OAAA,CAAQ,KAAA,CAAM,OAAA,GAAU,CAAC,CAAC,CAAA;AACvE","file":"MemoryAdapter.cjs","sourcesContent":["export class ApprovalError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n ) {\n super(message);\n this.name = 'ApprovalError';\n }\n\n toJSON(): { code: string; message: string; name: string } {\n return { code: this.code, message: this.message, name: this.name };\n }\n\n toHttpStatus(): number {\n const map: Record<string, number> = {\n NOT_FOUND: 404,\n CONFLICT: 409,\n FORBIDDEN: 403,\n VALIDATION: 422,\n TEMPLATE_NOT_FOUND: 404,\n };\n return map[this.code] ?? 500;\n }\n}\n\nexport class ApprovalNotFoundError extends ApprovalError {\n constructor(resource: string, id: string) {\n super(`${resource} \"${id}\" not found.`, 'NOT_FOUND');\n this.name = 'ApprovalNotFoundError';\n }\n}\n\nexport class ApprovalConflictError extends ApprovalError {\n constructor(instanceId: string) {\n super(\n `Concurrent modification detected on instance \"${instanceId}\". The record was updated by another process. Please retry.`,\n 'CONFLICT',\n );\n this.name = 'ApprovalConflictError';\n }\n}\n\nexport class ApprovalForbiddenError extends ApprovalError {\n constructor(message: string) {\n super(message, 'FORBIDDEN');\n this.name = 'ApprovalForbiddenError';\n }\n}\n\nexport class ApprovalValidationError extends ApprovalError {\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message, 'VALIDATION');\n this.name = 'ApprovalValidationError';\n }\n}\n\nexport class ApprovalTemplateNotFoundError extends ApprovalError {\n constructor(name: string) {\n super(`Template \"${name}\" not found.`, 'TEMPLATE_NOT_FOUND');\n this.name = 'ApprovalTemplateNotFoundError';\n }\n}\n","import type {\n IStorageAdapter,\n PaginationOpts,\n PaginatedResult,\n InstanceFilter,\n CursorPaginationOpts,\n CursorPaginatedResult,\n} from './IStorageAdapter.js';\nimport type { ApprovalTemplate, ApprovalInstance, AuditEntry } from '../types/index.js';\nimport { ApprovalConflictError } from '../errors.js';\n\nfunction deepClone<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\nfunction reviveDates(instance: ApprovalInstance): ApprovalInstance {\n return {\n ...instance,\n createdAt: new Date(instance.createdAt),\n updatedAt: new Date(instance.updatedAt),\n expiresAt: instance.expiresAt ? new Date(instance.expiresAt) : undefined,\n slaDeadlineAt: instance.slaDeadlineAt ? new Date(instance.slaDeadlineAt) : undefined,\n slaBreachedAt: instance.slaBreachedAt ? new Date(instance.slaBreachedAt) : undefined,\n auditLog: instance.auditLog.map((e) => ({ ...e, timestamp: new Date(e.timestamp) })),\n levels: instance.levels.map((l) => {\n const level: typeof l = { ...l };\n if (l.escalationDueAt) level.escalationDueAt = new Date(l.escalationDueAt);\n if (l.delegatedUntil) level.delegatedUntil = new Date(l.delegatedUntil);\n return level;\n }),\n };\n}\n\nfunction reviveTemplateDates(template: ApprovalTemplate): ApprovalTemplate {\n return { ...template, createdAt: new Date(template.createdAt) };\n}\n\n/**\n * Read a dot-path from a document, over **own** properties only.\n *\n * Mirrors how conditions resolve field paths, so a filter and a condition\n * written against the same path agree about what that path means — and an\n * inherited prototype member can never make an instance match a query.\n */\nfunction readPath(data: Record<string, unknown>, path: string): unknown {\n return path.split('.').reduce<unknown>((obj, key) => {\n if (obj !== null && typeof obj === 'object' && Object.prototype.hasOwnProperty.call(obj, key)) {\n return (obj as Record<string, unknown>)[key];\n }\n return undefined;\n }, data);\n}\n\n/** Structural equality, so a filter can match an object or array value. */\nfunction deepEquals(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n const aKeys = Object.keys(a as Record<string, unknown>);\n const bKeys = Object.keys(b as Record<string, unknown>);\n if (aKeys.length !== bKeys.length) return false;\n return aKeys.every(\n (k) =>\n Object.prototype.hasOwnProperty.call(b, k) &&\n deepEquals((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]),\n );\n}\n\nfunction applyFilter(instance: ApprovalInstance, filter: InstanceFilter): boolean {\n if (filter.status && instance.status !== filter.status) return false;\n if (filter.documentType && instance.documentType !== filter.documentType) return false;\n if (filter.submittedBy && instance.submittedBy !== filter.submittedBy) return false;\n if (filter.templateName && instance.templateName !== filter.templateName) return false;\n // Stored instances carry string dates (deepClone JSON round-trip), so wrap before comparing.\n if (filter.fromDate && new Date(instance.createdAt) < filter.fromDate) return false;\n if (filter.toDate && new Date(instance.createdAt) > filter.toDate) return false;\n if (filter.data) {\n for (const [path, expected] of Object.entries(filter.data)) {\n if (!deepEquals(readPath(instance.data ?? {}, path), expected)) return false;\n }\n }\n return true;\n}\n\nexport class MemoryAdapter implements IStorageAdapter {\n // keyed by `${tenantId}:${template.name}`\n private templates = new Map<string, ApprovalTemplate>();\n // keyed by `${tenantId}:${instance.id}`\n private instances = new Map<string, ApprovalInstance>();\n\n async saveTemplate(template: ApprovalTemplate): Promise<void> {\n this.templates.set(`${template.tenantId}:${template.name}`, deepClone(template));\n }\n\n async getTemplate(tenantId: string, name: string): Promise<ApprovalTemplate | null> {\n const template = this.templates.get(`${tenantId}:${name}`);\n return template ? reviveTemplateDates(deepClone(template)) : null;\n }\n\n async listTemplates(tenantId: string): Promise<ApprovalTemplate[]> {\n const result: ApprovalTemplate[] = [];\n for (const [key, template] of this.templates) {\n if (key.startsWith(`${tenantId}:`)) {\n result.push(reviveTemplateDates(deepClone(template)));\n }\n }\n return result;\n }\n\n async saveInstance(instance: ApprovalInstance): Promise<void> {\n this.instances.set(`${instance.tenantId}:${instance.id}`, deepClone(instance));\n }\n\n async updateInstance(instance: ApprovalInstance, expectedVersion: number): Promise<void> {\n const key = `${instance.tenantId}:${instance.id}`;\n const stored = this.instances.get(key);\n if (!stored) throw new ApprovalConflictError(instance.id);\n if (stored.version !== expectedVersion) throw new ApprovalConflictError(instance.id);\n const updated = deepClone(instance);\n updated.version = expectedVersion + 1;\n this.instances.set(key, updated);\n }\n\n async getInstance(tenantId: string, id: string): Promise<ApprovalInstance | null> {\n const raw = this.instances.get(`${tenantId}:${id}`);\n if (!raw) return null;\n return reviveDates(deepClone(raw));\n }\n\n async getInstancesByApprover(\n tenantId: string,\n approverId: string,\n opts?: PaginationOpts,\n ): Promise<PaginatedResult<ApprovalInstance>> {\n const all = [...this.instances.values()].filter((i) => {\n if (i.tenantId !== tenantId || i.status !== 'pending') return false;\n // Use .find() by level number, not array index (level numbers may not be consecutive)\n const currentLevel = i.levels.find((l) => l.level === i.currentLevel);\n return currentLevel?.approverIds.includes(approverId) ?? false;\n });\n return paginate(\n all.map((i) => reviveDates(deepClone(i))),\n opts,\n );\n }\n\n async getInstancesByFilter(\n tenantId: string,\n filter: InstanceFilter,\n opts?: PaginationOpts,\n ): Promise<PaginatedResult<ApprovalInstance>> {\n const all = [...this.instances.values()].filter(\n (i) => i.tenantId === tenantId && applyFilter(i, filter),\n );\n return paginate(\n all.map((i) => reviveDates(deepClone(i))),\n opts,\n );\n }\n\n async getOverdueInstances(\n tenantId: string,\n asOf: Date,\n filter: InstanceFilter = {},\n ): Promise<ApprovalInstance[]> {\n return [...this.instances.values()]\n .filter((i) => {\n if (i.tenantId !== tenantId || i.status !== 'pending') return false;\n if (filter.documentType && i.documentType !== filter.documentType) return false;\n if (filter.submittedBy && i.submittedBy !== filter.submittedBy) return false;\n // Escalation overdue on ANY open branch. Filtering to i.currentLevel\n // would miss the upper branches of a parallel group entirely, and left\n // this adapter disagreeing with PostgresAdapter, which already scans\n // every level.\n const hasOverdueEscalation = i.levels.some(\n (l) => l.escalationDueAt != null && new Date(l.escalationDueAt) <= asOf,\n );\n // Instance deadline expired\n const isExpired = i.expiresAt != null && new Date(i.expiresAt) <= asOf;\n // SLA breach (not yet recorded)\n const hasSLABreach =\n i.slaDeadlineAt != null && new Date(i.slaDeadlineAt) <= asOf && !i.slaBreachedAt;\n // Delegation expiry on any pending level\n const hasDelegationExpiry = i.levels.some(\n (l) =>\n l.status === 'pending' &&\n l.delegatedUntil != null &&\n new Date(l.delegatedUntil) <= asOf &&\n l.delegatedFrom != null,\n );\n // Reminder due on any open branch. Without this the scheduler never\n // sees the instance and no reminder is ever sent.\n const hasDueReminder = i.levels.some(\n (l) =>\n l.status === 'pending' && l.reminderDueAt != null && new Date(l.reminderDueAt) <= asOf,\n );\n return (\n hasOverdueEscalation || isExpired || hasSLABreach || hasDelegationExpiry || hasDueReminder\n );\n })\n .map((i) => reviveDates(deepClone(i)));\n }\n\n async getInstancesByCursor(\n tenantId: string,\n filter: InstanceFilter,\n opts: CursorPaginationOpts,\n ): Promise<CursorPaginatedResult<ApprovalInstance>> {\n const all = [...this.instances.values()]\n .filter((i) => i.tenantId === tenantId && applyFilter(i, filter))\n .map((i) => reviveDates(deepClone(i)))\n .sort((a, b) => {\n const ta = a.updatedAt.getTime();\n const tb = b.updatedAt.getTime();\n return ta !== tb ? ta - tb : a.id.localeCompare(b.id);\n });\n\n const { cursor, limit, direction = 'forward' } = opts;\n let startIdx = 0;\n\n if (cursor) {\n const [ts, id] = decodeCursor(cursor);\n const idx = all.findIndex(\n (i) => i.updatedAt.getTime() > ts || (i.updatedAt.getTime() === ts && i.id > id),\n );\n startIdx = idx === -1 ? all.length : idx;\n }\n\n if (direction === 'backward' && startIdx > 0) {\n startIdx = Math.max(0, startIdx - limit - 1);\n }\n\n const slice = all.slice(startIdx, startIdx + limit);\n const hasMore = startIdx + limit < all.length;\n const nextCursor = hasMore ? encodeCursor(slice[slice.length - 1]!) : undefined;\n const prevCursor = startIdx > 0 ? encodeCursor(all[startIdx - 1]!) : undefined;\n\n return { items: slice, nextCursor, prevCursor, hasMore };\n }\n\n async getIdempotentInstance(\n tenantId: string,\n idempotencyKey: string,\n ): Promise<ApprovalInstance | null> {\n for (const instance of this.instances.values()) {\n if (instance.tenantId === tenantId && instance.idempotencyKey === idempotencyKey) {\n return reviveDates(deepClone(instance));\n }\n }\n return null;\n }\n\n async appendAuditEntry(\n _tenantId: string,\n _instanceId: string,\n _entry: AuditEntry,\n ): Promise<void> {\n // No-op by design. The engine already pushes each entry onto instance.auditLog\n // and persists the whole instance via saveInstance()/updateInstance(), so the\n // embedded log is the source of truth for this adapter. Pushing here too would\n // duplicate every entry (as a dedicated, append-only audit table would in\n // PostgresAdapter, this method exists to satisfy that separate-sink contract).\n }\n\n /** Test helper — total stored instances across all tenants. */\n get size(): number {\n return this.instances.size;\n }\n}\n\nfunction paginate<T>(items: T[], opts?: PaginationOpts): PaginatedResult<T> {\n const total = items.length;\n if (!opts) return { items, total };\n return { items: items.slice(opts.offset, opts.offset + opts.limit), total };\n}\n\nfunction encodeCursor(instance: ApprovalInstance): string {\n return Buffer.from(`${instance.updatedAt.getTime()}|${instance.id}`).toString('base64');\n}\n\nfunction decodeCursor(cursor: string): [number, string] {\n const decoded = Buffer.from(cursor, 'base64').toString('utf8');\n const pipeIdx = decoded.indexOf('|');\n return [Number(decoded.slice(0, pipeIdx)), decoded.slice(pipeIdx + 1)];\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/errors.ts","../../src/adapters/MemoryAdapter.ts"],"names":[],"mappings":";;;AAAO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvC,WAAA,CACE,SACgB,IAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAFG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AAAA,EACd;AAAA,EAEA,MAAA,GAA0D;AACxD,IAAA,OAAO,EAAE,MAAM,IAAA,CAAK,IAAA,EAAM,SAAS,IAAA,CAAK,OAAA,EAAS,IAAA,EAAM,IAAA,CAAK,IAAA,EAAK;AAAA,EACnE;AAAA,EAEA,YAAA,GAAuB;AACrB,IAAA,MAAM,GAAA,GAA8B;AAAA,MAClC,SAAA,EAAW,GAAA;AAAA,MACX,QAAA,EAAU,GAAA;AAAA,MACV,SAAA,EAAW,GAAA;AAAA,MACX,UAAA,EAAY,GAAA;AAAA,MACZ,kBAAA,EAAoB;AAAA,KACtB;AACA,IAAA,OAAO,GAAA,CAAI,IAAA,CAAK,IAAI,CAAA,IAAK,GAAA;AAAA,EAC3B;AACF,CAAA;AASO,IAAM,qBAAA,GAAN,cAAoC,aAAA,CAAc;AAAA,EACvD,YAAY,UAAA,EAAoB;AAC9B,IAAA,KAAA;AAAA,MACE,iDAAiD,UAAU,CAAA,2DAAA,CAAA;AAAA,MAC3D;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,EAAO,KAAA,CAAM,KAAA,CAAM,IAAA,CAAK,MAAA,EAAQ,IAAA,CAAK,MAAA,GAAS,IAAA,CAAK,KAAK,CAAA,EAAG,KAAA,EAAM;AAC5E;AAEA,SAAS,aAAa,QAAA,EAAoC;AACxD,EAAA,OAAO,MAAA,CAAO,IAAA,CAAK,CAAA,EAAG,QAAA,CAAS,SAAA,CAAU,OAAA,EAAS,CAAA,CAAA,EAAI,QAAA,CAAS,EAAE,CAAA,CAAE,CAAA,CAAE,SAAS,QAAQ,CAAA;AACxF;AAEA,SAAS,aAAa,MAAA,EAAkC;AACtD,EAAA,MAAM,UAAU,MAAA,CAAO,IAAA,CAAK,QAAQ,QAAQ,CAAA,CAAE,SAAS,MAAM,CAAA;AAC7D,EAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,OAAA,CAAQ,GAAG,CAAA;AACnC,EAAA,OAAO,CAAC,MAAA,CAAO,OAAA,CAAQ,KAAA,CAAM,CAAA,EAAG,OAAO,CAAC,CAAA,EAAG,OAAA,CAAQ,KAAA,CAAM,OAAA,GAAU,CAAC,CAAC,CAAA;AACvE","file":"MemoryAdapter.cjs","sourcesContent":["export class ApprovalError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n ) {\n super(message);\n this.name = 'ApprovalError';\n }\n\n toJSON(): { code: string; message: string; name: string } {\n return { code: this.code, message: this.message, name: this.name };\n }\n\n toHttpStatus(): number {\n const map: Record<string, number> = {\n NOT_FOUND: 404,\n CONFLICT: 409,\n FORBIDDEN: 403,\n VALIDATION: 422,\n TEMPLATE_NOT_FOUND: 404,\n };\n return map[this.code] ?? 500;\n }\n}\n\nexport class ApprovalNotFoundError extends ApprovalError {\n constructor(resource: string, id: string) {\n super(`${resource} \"${id}\" not found.`, 'NOT_FOUND');\n this.name = 'ApprovalNotFoundError';\n }\n}\n\nexport class ApprovalConflictError extends ApprovalError {\n constructor(instanceId: string) {\n super(\n `Concurrent modification detected on instance \"${instanceId}\". The record was updated by another process. Please retry.`,\n 'CONFLICT',\n );\n this.name = 'ApprovalConflictError';\n }\n}\n\nexport class ApprovalForbiddenError extends ApprovalError {\n constructor(message: string) {\n super(message, 'FORBIDDEN');\n this.name = 'ApprovalForbiddenError';\n }\n}\n\nexport class ApprovalValidationError extends ApprovalError {\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message, 'VALIDATION');\n this.name = 'ApprovalValidationError';\n }\n}\n\nexport class ApprovalTemplateNotFoundError extends ApprovalError {\n constructor(name: string) {\n super(`Template \"${name}\" not found.`, 'TEMPLATE_NOT_FOUND');\n this.name = 'ApprovalTemplateNotFoundError';\n }\n}\n","import type {\n IStorageAdapter,\n PaginationOpts,\n PaginatedResult,\n InstanceFilter,\n CursorPaginationOpts,\n CursorPaginatedResult,\n} from './IStorageAdapter.js';\nimport type { ApprovalTemplate, ApprovalInstance, AuditEntry } from '../types/index.js';\nimport { ApprovalConflictError } from '../errors.js';\n\nfunction deepClone<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\nfunction reviveDates(instance: ApprovalInstance): ApprovalInstance {\n return {\n ...instance,\n createdAt: new Date(instance.createdAt),\n updatedAt: new Date(instance.updatedAt),\n expiresAt: instance.expiresAt ? new Date(instance.expiresAt) : undefined,\n slaDeadlineAt: instance.slaDeadlineAt ? new Date(instance.slaDeadlineAt) : undefined,\n slaBreachedAt: instance.slaBreachedAt ? new Date(instance.slaBreachedAt) : undefined,\n auditLog: instance.auditLog.map((e) => ({ ...e, timestamp: new Date(e.timestamp) })),\n levels: instance.levels.map((l) => {\n const level: typeof l = { ...l };\n if (l.escalationDueAt) level.escalationDueAt = new Date(l.escalationDueAt);\n if (l.delegatedUntil) level.delegatedUntil = new Date(l.delegatedUntil);\n return level;\n }),\n };\n}\n\nfunction reviveTemplateDates(template: ApprovalTemplate): ApprovalTemplate {\n return { ...template, createdAt: new Date(template.createdAt) };\n}\n\n/**\n * Read a dot-path from a document, over **own** properties only.\n *\n * Mirrors how conditions resolve field paths, so a filter and a condition\n * written against the same path agree about what that path means — and an\n * inherited prototype member can never make an instance match a query.\n */\nfunction readPath(data: Record<string, unknown>, path: string): unknown {\n return path.split('.').reduce<unknown>((obj, key) => {\n if (obj !== null && typeof obj === 'object' && Object.prototype.hasOwnProperty.call(obj, key)) {\n return (obj as Record<string, unknown>)[key];\n }\n return undefined;\n }, data);\n}\n\n/** Structural equality, so a filter can match an object or array value. */\nfunction deepEquals(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n const aKeys = Object.keys(a as Record<string, unknown>);\n const bKeys = Object.keys(b as Record<string, unknown>);\n if (aKeys.length !== bKeys.length) return false;\n return aKeys.every(\n (k) =>\n Object.prototype.hasOwnProperty.call(b, k) &&\n deepEquals((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]),\n );\n}\n\nfunction applyFilter(instance: ApprovalInstance, filter: InstanceFilter): boolean {\n if (filter.status && instance.status !== filter.status) return false;\n if (filter.documentType && instance.documentType !== filter.documentType) return false;\n if (filter.submittedBy && instance.submittedBy !== filter.submittedBy) return false;\n if (filter.templateName && instance.templateName !== filter.templateName) return false;\n // Stored instances carry string dates (deepClone JSON round-trip), so wrap before comparing.\n if (filter.fromDate && new Date(instance.createdAt) < filter.fromDate) return false;\n if (filter.toDate && new Date(instance.createdAt) > filter.toDate) return false;\n if (filter.data) {\n for (const [path, expected] of Object.entries(filter.data)) {\n if (!deepEquals(readPath(instance.data ?? {}, path), expected)) return false;\n }\n }\n return true;\n}\n\nexport class MemoryAdapter implements IStorageAdapter {\n // keyed by `${tenantId}:${template.name}`\n private templates = new Map<string, ApprovalTemplate>();\n // keyed by `${tenantId}:${instance.id}`\n private instances = new Map<string, ApprovalInstance>();\n\n async saveTemplate(template: ApprovalTemplate): Promise<void> {\n this.templates.set(`${template.tenantId}:${template.name}`, deepClone(template));\n }\n\n async getTemplate(tenantId: string, name: string): Promise<ApprovalTemplate | null> {\n const template = this.templates.get(`${tenantId}:${name}`);\n return template ? reviveTemplateDates(deepClone(template)) : null;\n }\n\n async listTemplates(tenantId: string): Promise<ApprovalTemplate[]> {\n const result: ApprovalTemplate[] = [];\n for (const [key, template] of this.templates) {\n if (key.startsWith(`${tenantId}:`)) {\n result.push(reviveTemplateDates(deepClone(template)));\n }\n }\n return result;\n }\n\n async saveInstance(instance: ApprovalInstance): Promise<void> {\n this.instances.set(`${instance.tenantId}:${instance.id}`, deepClone(instance));\n }\n\n async updateInstance(instance: ApprovalInstance, expectedVersion: number): Promise<void> {\n const key = `${instance.tenantId}:${instance.id}`;\n const stored = this.instances.get(key);\n if (!stored) throw new ApprovalConflictError(instance.id);\n if (stored.version !== expectedVersion) throw new ApprovalConflictError(instance.id);\n const updated = deepClone(instance);\n updated.version = expectedVersion + 1;\n this.instances.set(key, updated);\n }\n\n async getInstance(tenantId: string, id: string): Promise<ApprovalInstance | null> {\n const raw = this.instances.get(`${tenantId}:${id}`);\n if (!raw) return null;\n return reviveDates(deepClone(raw));\n }\n\n async getInstancesByApprover(\n tenantId: string,\n approverId: string,\n opts?: PaginationOpts,\n ): Promise<PaginatedResult<ApprovalInstance>> {\n const all = [...this.instances.values()].filter((i) => {\n if (i.tenantId !== tenantId || i.status !== 'pending') return false;\n // Use .find() by level number, not array index (level numbers may not be consecutive)\n const currentLevel = i.levels.find((l) => l.level === i.currentLevel);\n return currentLevel?.approverIds.includes(approverId) ?? false;\n });\n return paginate(\n all.map((i) => reviveDates(deepClone(i))),\n opts,\n );\n }\n\n async getInstancesByFilter(\n tenantId: string,\n filter: InstanceFilter,\n opts?: PaginationOpts,\n ): Promise<PaginatedResult<ApprovalInstance>> {\n const all = [...this.instances.values()].filter(\n (i) => i.tenantId === tenantId && applyFilter(i, filter),\n );\n return paginate(\n all.map((i) => reviveDates(deepClone(i))),\n opts,\n );\n }\n\n async getOverdueInstances(\n tenantId: string,\n asOf: Date,\n filter: InstanceFilter = {},\n ): Promise<ApprovalInstance[]> {\n return [...this.instances.values()]\n .filter((i) => {\n if (i.tenantId !== tenantId || i.status !== 'pending') return false;\n if (filter.documentType && i.documentType !== filter.documentType) return false;\n if (filter.submittedBy && i.submittedBy !== filter.submittedBy) return false;\n // Escalation overdue on ANY open branch. Filtering to i.currentLevel\n // would miss the upper branches of a parallel group entirely, and left\n // this adapter disagreeing with PostgresAdapter, which already scans\n // every level.\n const hasOverdueEscalation = i.levels.some(\n (l) => l.escalationDueAt != null && new Date(l.escalationDueAt) <= asOf,\n );\n // Instance deadline expired\n const isExpired = i.expiresAt != null && new Date(i.expiresAt) <= asOf;\n // SLA breach (not yet recorded)\n const hasSLABreach =\n i.slaDeadlineAt != null && new Date(i.slaDeadlineAt) <= asOf && !i.slaBreachedAt;\n // Delegation expiry on any pending level\n const hasDelegationExpiry = i.levels.some(\n (l) =>\n l.status === 'pending' &&\n l.delegatedUntil != null &&\n new Date(l.delegatedUntil) <= asOf &&\n l.delegatedFrom != null,\n );\n // Reminder due on any open branch. Without this the scheduler never\n // sees the instance and no reminder is ever sent.\n const hasDueReminder = i.levels.some(\n (l) =>\n l.status === 'pending' && l.reminderDueAt != null && new Date(l.reminderDueAt) <= asOf,\n );\n return (\n hasOverdueEscalation || isExpired || hasSLABreach || hasDelegationExpiry || hasDueReminder\n );\n })\n .map((i) => reviveDates(deepClone(i)));\n }\n\n async countInstances(tenantId: string, filter: InstanceFilter): Promise<number> {\n let count = 0;\n for (const instance of this.instances.values()) {\n if (instance.tenantId === tenantId && applyFilter(instance, filter)) count++;\n }\n return count;\n }\n\n async getInstancesByCursor(\n tenantId: string,\n filter: InstanceFilter,\n opts: CursorPaginationOpts,\n ): Promise<CursorPaginatedResult<ApprovalInstance>> {\n const all = [...this.instances.values()]\n .filter((i) => i.tenantId === tenantId && applyFilter(i, filter))\n .map((i) => reviveDates(deepClone(i)))\n .sort((a, b) => {\n const ta = a.updatedAt.getTime();\n const tb = b.updatedAt.getTime();\n return ta !== tb ? ta - tb : a.id.localeCompare(b.id);\n });\n\n const { cursor, limit, direction = 'forward' } = opts;\n let startIdx = 0;\n\n if (cursor) {\n const [ts, id] = decodeCursor(cursor);\n const idx = all.findIndex(\n (i) => i.updatedAt.getTime() > ts || (i.updatedAt.getTime() === ts && i.id > id),\n );\n startIdx = idx === -1 ? all.length : idx;\n }\n\n if (direction === 'backward' && startIdx > 0) {\n startIdx = Math.max(0, startIdx - limit - 1);\n }\n\n const slice = all.slice(startIdx, startIdx + limit);\n const hasMore = startIdx + limit < all.length;\n const nextCursor = hasMore ? encodeCursor(slice[slice.length - 1]!) : undefined;\n const prevCursor = startIdx > 0 ? encodeCursor(all[startIdx - 1]!) : undefined;\n\n return { items: slice, nextCursor, prevCursor, hasMore };\n }\n\n async getIdempotentInstance(\n tenantId: string,\n idempotencyKey: string,\n ): Promise<ApprovalInstance | null> {\n for (const instance of this.instances.values()) {\n if (instance.tenantId === tenantId && instance.idempotencyKey === idempotencyKey) {\n return reviveDates(deepClone(instance));\n }\n }\n return null;\n }\n\n async appendAuditEntry(\n _tenantId: string,\n _instanceId: string,\n _entry: AuditEntry,\n ): Promise<void> {\n // No-op by design. The engine already pushes each entry onto instance.auditLog\n // and persists the whole instance via saveInstance()/updateInstance(), so the\n // embedded log is the source of truth for this adapter. Pushing here too would\n // duplicate every entry (as a dedicated, append-only audit table would in\n // PostgresAdapter, this method exists to satisfy that separate-sink contract).\n }\n\n /** Test helper — total stored instances across all tenants. */\n get size(): number {\n return this.instances.size;\n }\n}\n\nfunction paginate<T>(items: T[], opts?: PaginationOpts): PaginatedResult<T> {\n const total = items.length;\n if (!opts) return { items, total };\n return { items: items.slice(opts.offset, opts.offset + opts.limit), total };\n}\n\nfunction encodeCursor(instance: ApprovalInstance): string {\n return Buffer.from(`${instance.updatedAt.getTime()}|${instance.id}`).toString('base64');\n}\n\nfunction decodeCursor(cursor: string): [number, string] {\n const decoded = Buffer.from(cursor, 'base64').toString('utf8');\n const pipeIdx = decoded.indexOf('|');\n return [Number(decoded.slice(0, pipeIdx)), decoded.slice(pipeIdx + 1)];\n}\n"]}
|