@photon-grove/evt 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +122 -2
  3. package/dist/aggregate.d.ts +83 -0
  4. package/dist/aggregate.d.ts.map +1 -0
  5. package/dist/aggregate.js +92 -0
  6. package/dist/aggregate.js.map +1 -0
  7. package/dist/base64.d.ts +8 -0
  8. package/dist/base64.d.ts.map +1 -0
  9. package/dist/base64.js +67 -0
  10. package/dist/base64.js.map +1 -0
  11. package/dist/codec.d.ts +56 -0
  12. package/dist/codec.d.ts.map +1 -0
  13. package/dist/codec.js +90 -0
  14. package/dist/codec.js.map +1 -0
  15. package/dist/commit-id.d.ts +3 -0
  16. package/dist/commit-id.d.ts.map +1 -0
  17. package/dist/commit-id.js +43 -0
  18. package/dist/commit-id.js.map +1 -0
  19. package/dist/dynamodb/head.d.ts +34 -0
  20. package/dist/dynamodb/head.d.ts.map +1 -0
  21. package/dist/dynamodb/head.js +62 -0
  22. package/dist/dynamodb/head.js.map +1 -0
  23. package/dist/dynamodb/index.d.ts +2 -0
  24. package/dist/dynamodb/index.d.ts.map +1 -0
  25. package/dist/dynamodb/index.js +4 -0
  26. package/dist/dynamodb/index.js.map +1 -0
  27. package/dist/dynamodb/item.d.ts +68 -0
  28. package/dist/dynamodb/item.d.ts.map +1 -0
  29. package/dist/dynamodb/item.js +263 -0
  30. package/dist/dynamodb/item.js.map +1 -0
  31. package/dist/envelope.d.ts +15 -0
  32. package/dist/envelope.d.ts.map +1 -0
  33. package/dist/envelope.js +59 -0
  34. package/dist/envelope.js.map +1 -0
  35. package/dist/errors.d.ts +111 -0
  36. package/dist/errors.d.ts.map +1 -0
  37. package/dist/errors.js +139 -0
  38. package/dist/errors.js.map +1 -0
  39. package/dist/event.d.ts +47 -0
  40. package/dist/event.d.ts.map +1 -0
  41. package/dist/event.js +64 -0
  42. package/dist/event.js.map +1 -0
  43. package/dist/fields.d.ts +31 -0
  44. package/dist/fields.d.ts.map +1 -0
  45. package/dist/fields.js +105 -0
  46. package/dist/fields.js.map +1 -0
  47. package/dist/index.d.ts +14 -0
  48. package/dist/index.d.ts.map +1 -0
  49. package/dist/index.js +16 -0
  50. package/dist/index.js.map +1 -0
  51. package/dist/json.d.ts +47 -0
  52. package/dist/json.d.ts.map +1 -0
  53. package/dist/json.js +458 -0
  54. package/dist/json.js.map +1 -0
  55. package/dist/memory/index.d.ts +2 -0
  56. package/dist/memory/index.d.ts.map +1 -0
  57. package/dist/memory/index.js +3 -0
  58. package/dist/memory/index.js.map +1 -0
  59. package/dist/memory/repository.d.ts +34 -0
  60. package/dist/memory/repository.d.ts.map +1 -0
  61. package/dist/memory/repository.js +219 -0
  62. package/dist/memory/repository.js.map +1 -0
  63. package/dist/metadata.d.ts +47 -0
  64. package/dist/metadata.d.ts.map +1 -0
  65. package/dist/metadata.js +75 -0
  66. package/dist/metadata.js.map +1 -0
  67. package/dist/repository.d.ts +102 -0
  68. package/dist/repository.d.ts.map +1 -0
  69. package/dist/repository.js +131 -0
  70. package/dist/repository.js.map +1 -0
  71. package/dist/retry.d.ts +25 -0
  72. package/dist/retry.d.ts.map +1 -0
  73. package/dist/retry.js +50 -0
  74. package/dist/retry.js.map +1 -0
  75. package/dist/snapshots.d.ts +21 -0
  76. package/dist/snapshots.d.ts.map +1 -0
  77. package/dist/snapshots.js +35 -0
  78. package/dist/snapshots.js.map +1 -0
  79. package/dist/store.d.ts +103 -0
  80. package/dist/store.d.ts.map +1 -0
  81. package/dist/store.js +246 -0
  82. package/dist/store.js.map +1 -0
  83. package/dist/testing/equal.d.ts +22 -0
  84. package/dist/testing/equal.d.ts.map +1 -0
  85. package/dist/testing/equal.js +121 -0
  86. package/dist/testing/equal.js.map +1 -0
  87. package/dist/testing/index.d.ts +3 -0
  88. package/dist/testing/index.d.ts.map +1 -0
  89. package/dist/testing/index.js +5 -0
  90. package/dist/testing/index.js.map +1 -0
  91. package/dist/testing/scenario.d.ts +136 -0
  92. package/dist/testing/scenario.d.ts.map +1 -0
  93. package/dist/testing/scenario.js +307 -0
  94. package/dist/testing/scenario.js.map +1 -0
  95. package/dist/utf8.d.ts +17 -0
  96. package/dist/utf8.d.ts.map +1 -0
  97. package/dist/utf8.js +82 -0
  98. package/dist/utf8.js.map +1 -0
  99. package/package.json +56 -4
  100. package/src/aggregate.ts +196 -0
  101. package/src/base64.ts +80 -0
  102. package/src/codec.ts +139 -0
  103. package/src/commit-id.ts +50 -0
  104. package/src/dynamodb/head.ts +93 -0
  105. package/src/dynamodb/index.ts +21 -0
  106. package/src/dynamodb/item.ts +332 -0
  107. package/src/envelope.ts +67 -0
  108. package/src/errors.ts +214 -0
  109. package/src/event.ts +117 -0
  110. package/src/fields.ts +134 -0
  111. package/src/globals.d.ts +39 -0
  112. package/src/index.ts +75 -0
  113. package/src/json.ts +546 -0
  114. package/src/memory/index.ts +3 -0
  115. package/src/memory/repository.ts +313 -0
  116. package/src/metadata.ts +120 -0
  117. package/src/repository.ts +247 -0
  118. package/src/retry.ts +74 -0
  119. package/src/snapshots.ts +42 -0
  120. package/src/store.ts +377 -0
  121. package/src/testing/equal.ts +146 -0
  122. package/src/testing/index.ts +14 -0
  123. package/src/testing/scenario.ts +406 -0
  124. package/src/utf8.ts +92 -0
package/LICENSE ADDED
@@ -0,0 +1,176 @@
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, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
package/README.md CHANGED
@@ -1,3 +1,123 @@
1
- # Temporary Holding Version
1
+ # @photon-grove/evt
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Event sourcing for TypeScript, wire-compatible with evt's Go module and its Rust crate. Event
4
+ sourcing means the log of events is the record of truth, and an aggregate's state is whatever you
5
+ get by folding its events in order. This package isn't a binding to the Go or Rust code. It's a
6
+ third native implementation of the same
7
+ [storage format](https://github.com/photon-grove/evt/blob/main/docs/reference/storage-format.md),
8
+ held to the fixtures Go and Rust generate, byte for byte.
9
+
10
+ ```sh
11
+ npm install @photon-grove/evt
12
+ ```
13
+
14
+ So far it has the core, the in-memory backend and the testing helpers. The DynamoDB and
15
+ PostgreSQL backends, command outcomes and multi-stream transactions come in later releases, and the
16
+ [feature matrix](https://github.com/photon-grove/evt/blob/main/docs/reference/feature-matrix.md)
17
+ tracks each one. The
18
+ [getting started guide](https://github.com/photon-grove/evt/blob/main/docs/guide/getting-started.md#the-same-model-in-typescript)
19
+ builds a bank account aggregate with it, end to end.
20
+
21
+ ## Entry points
22
+
23
+ | Import | Contents |
24
+ | ---------------------------- | --------------------------------------------------------------------------- |
25
+ | `@photon-grove/evt` | Aggregates, codecs, upcasters, the `Store`, retry, and the wire codecs |
26
+ | `@photon-grove/evt/memory` | `MemRepository`, the in-memory backend for tests and local development |
27
+ | `@photon-grove/evt/testing` | `scenario` and `Fixture`, the given/when/then helpers over `MemRepository` |
28
+ | `@photon-grove/evt/dynamodb` | The DynamoDB item codec, with no SDK. The repository comes with the backend |
29
+
30
+ ## Runtimes
31
+
32
+ The package is ESM only and has no runtime dependencies. CI runs it on Node 24, Node 22.12, Bun and
33
+ Deno. Its code uses only web-standard globals (`TextEncoder`, `TextDecoder`, Web Crypto,
34
+ `AbortSignal`, timers), never Node's built-ins, so it should run on edge runtimes and in browsers
35
+ too, though CI doesn't run them yet. It never uses top-level await, so CommonJS code on Node 22.12
36
+ and later can `require()` it. Its type declarations need TypeScript 5.7 or later and a declaration
37
+ of `AbortSignal`, which the DOM library, `@types/node`, and Bun's and Deno's types all provide.
38
+
39
+ ## The model
40
+
41
+ - **Events.** `defineEvents` gives each event type a version, a codec and, optionally, upcasters.
42
+ The type string, the version and the payload bytes are the durable contract. `EventOf<typeof
43
+ events>` is the union of `{type, data}` objects the aggregate works with.
44
+ - **Codecs.** `json()` writes plain objects with evt's own JSON writer, in property order, and
45
+ decodes them back. It refuses an integer past `Number.MAX_SAFE_INTEGER` rather than round it,
46
+ when encoding as well as decoding. It takes an optional synchronous
47
+ [Standard Schema](https://standardschema.dev) validator (Zod, Valibot, ArkType), checked on both
48
+ sides. Any `{encode, decode}` pair of bytes works as a codec.
49
+ - **Aggregates.** `defineAggregate` names the type, the events, the state's codec and its initial
50
+ value. `handle(state, command)` returns a decision, `{kind: 'accept', events}` or
51
+ `{kind: 'reject', rejection: {code, message}}`, and may be async. `apply(state, event)` returns
52
+ the next state and never validates.
53
+ - **The store.** `new Store(repository, options)` loads an aggregate from its latest snapshot and
54
+ the events after it, runs a command, and commits the decided events with optimistic concurrency:
55
+ the commit fails with a `ConflictError` if another writer moved the stream first.
56
+ `executeWithRetry` loads and runs the command again after a conflict, with a jittered backoff
57
+ (`DEFAULT_RETRY_POLICY`, the same as Go's and Rust's). A rejection commits nothing.
58
+ - **Snapshots.** The store writes a snapshot every five events by default (the `snapshotInterval`
59
+ option, or the aggregate's own). A snapshot too large for one DynamoDB item is skipped rather
60
+ than failing the commit, and later loads replay from the one before.
61
+ - **Duplicate commands.** A command whose metadata carries a command ID already seen since the
62
+ latest snapshot doesn't run, and `execute` resolves to `{kind: 'duplicate'}`. The window ends at
63
+ the snapshot, so once a snapshot covers the first run, a retry runs the command again.
64
+ - **Upcasting.** An event type's upcasters migrate a stored payload from older versions to the
65
+ current one as it's read, in the order they're declared. `jsonUpcaster(from, to, migrate)` does
66
+ it on the parsed JSON, losslessly. A stored version the upcasters don't bring to the declared one
67
+ fails the load with a `ReplayError` rather than decoding into the wrong shape.
68
+ - **Sequences** are `bigint`s, because Go and Rust store them as 64-bit integers.
69
+
70
+ Errors are `EvtError`s with a `code`. `isConflict` and `isRetryable` tell them apart.
71
+
72
+ ## Testing
73
+
74
+ `scenario` runs one command through a real `Store` over `MemRepository` and checks what it did:
75
+
76
+ ```ts
77
+ await scenario(account)
78
+ .given({type: 'bank_account.opened', data: {accountId: 'acct-1', balance: 100}})
79
+ .when({type: 'deposit', amount: 25})
80
+ .thenEvents({type: 'bank_account.money_deposited', data: {accountId: 'acct-1', amount: 25}})
81
+ ```
82
+
83
+ The other checks are `thenNoEvents`, `thenRejected` (with a code or a predicate), `thenDuplicate`,
84
+ `thenError` and `thenState`. `run()` resolves to the outcome itself instead. `.entity()`,
85
+ `.metadata()` and `.options()` change the stream, the command's metadata and the store's options.
86
+ Each returns a new scenario, so one can be the base of several tests. `.on(fixture)` runs on a
87
+ shared `Fixture`, where every run seeds its given events and runs its command again.
88
+
89
+ `Fixture` seeds streams of any aggregate (`given`), reads them back decoded (`events`,
90
+ `assertEvents`) and loads them (`load`). After a snapshot and a compaction, seeding continues from
91
+ the snapshot. A failed check throws an `AssertionError` with `actual` and `expected`, so it works in
92
+ any test runner, and Vitest and Jest show a diff.
93
+
94
+ ## Sharing streams with Go and Rust
95
+
96
+ A TypeScript writer and a Go or Rust writer can share a stream once the TypeScript backends ship, as
97
+ long as they agree on these:
98
+
99
+ - The event type strings, versions and payload JSON, and the aggregate state's JSON, because each
100
+ language reads the others' snapshots. `json()` writes an object's properties in order, so declare
101
+ them in the order of the Go struct's fields.
102
+ - Maps whose keys Go writes sorted. A Go map is a `Map` here, and it needs a codec of its own that
103
+ decodes it back as a `Map`, since `json()` decodes plain objects.
104
+ - Integral payload numbers (cents, for example), because the languages format some floats
105
+ differently.
106
+ - Event versions. Like Rust, TypeScript refuses a stored version it can't upcast to the declared
107
+ one, and Go decodes it anyway, so deploy readers before writers when you bump a version.
108
+
109
+ Until the TypeScript package has commit-wide projectors and command outcomes, two more rules apply:
110
+
111
+ - Don't write an entity type that has commit-wide projectors registered in a Go or Rust service.
112
+ Its commits would land without their view rows.
113
+ - Don't share a store whose Go or Rust writers record command outcomes. A command retried through
114
+ TypeScript would find no outcome and could run twice.
115
+
116
+ The [known differences](https://github.com/photon-grove/evt/blob/main/docs/reference/storage-format.md#known-differences)
117
+ between the languages are in the storage format, and
118
+ [ADR 0009](https://github.com/photon-grove/evt/blob/main/docs/adr/0009-typescript-implementation.md)
119
+ explains how this package is built and tested.
120
+
121
+ ## License
122
+
123
+ Apache-2.0.
@@ -0,0 +1,83 @@
1
+ import type { Codec } from './codec.js';
2
+ import type { SerializedEvent } from './event.js';
3
+ import { type JsonValue } from './json.js';
4
+ /**
5
+ * Migrates a stored payload of its event type before it is decoded, taking an event at the
6
+ * upcaster's from version to its to version. An event type's upcasters run in declaration order,
7
+ * each once, and each sees the output of the ones before it, so a 1 → 2 upcaster followed by a
8
+ * 2 → 3 one takes a version 1 event to version 3. Stored events are never rewritten.
9
+ */
10
+ export interface Upcaster {
11
+ readonly from: number;
12
+ readonly to: number;
13
+ upcast(payload: Uint8Array): Uint8Array;
14
+ }
15
+ /**
16
+ * An upcaster that rewrites a JSON payload. `migrate` gets it losslessly, as {@link parseJson}
17
+ * reads it (objects as `Map`s in their stored order, numbers as {@link JsonNumber}s), and returns
18
+ * the new payload, which is written with {@link stringifyJson}. What the migration doesn't touch
19
+ * is written back exactly, whatever its integers or keys.
20
+ */
21
+ export declare function jsonUpcaster(from: number, to: number, migrate: (payload: JsonValue) => unknown): Upcaster;
22
+ /** How one event type is stored: its current version, its payload codec, and its upcasters. */
23
+ export interface EventDefinition<T> {
24
+ /** The version new events are written with, and the one stored events are upcast to. */
25
+ readonly version: number;
26
+ readonly codec: Codec<T>;
27
+ readonly upcasters?: readonly Upcaster[] | undefined;
28
+ }
29
+ export type EventDefinitions = Readonly<Record<string, EventDefinition<any>>>;
30
+ /** The events a set of definitions describes: `{type, data}` for each event type. */
31
+ export type EventOf<D extends EventDefinitions> = {
32
+ [K in keyof D & string]: {
33
+ type: K;
34
+ data: D[K] extends EventDefinition<infer T> ? T : never;
35
+ };
36
+ }[keyof D & string];
37
+ /** Declares an aggregate's event types, checking each version and upcaster. */
38
+ export declare function defineEvents<const D extends EventDefinitions>(definitions: D): D;
39
+ /** A domain refusal of a command: a code to branch on, a message, and optional JSON details. */
40
+ export interface Rejection {
41
+ code: string;
42
+ message: string;
43
+ details?: unknown;
44
+ }
45
+ /** What a command handler decides: accept with events (possibly none), or reject. */
46
+ export type Decision<E> = {
47
+ kind: 'accept';
48
+ events: readonly E[];
49
+ } | {
50
+ kind: 'reject';
51
+ rejection: Rejection;
52
+ };
53
+ /** An aggregate type, as {@link defineAggregate} takes it. */
54
+ export interface AggregateDefinition<S, C, D extends EventDefinitions> {
55
+ /** The stored entity type, such as `account`. */
56
+ readonly type: string;
57
+ readonly events: D;
58
+ /** The snapshot codec: how the state is stored. */
59
+ readonly state: Codec<S>;
60
+ /** The state of an entity with no events. */
61
+ initial(): S;
62
+ /** Decides what a command does. It must not change `state`. */
63
+ handle(state: S, command: C): Decision<EventOf<D>> | Promise<Decision<EventOf<D>>>;
64
+ /** Folds one event into the state, returning the next state. It must not fail. */
65
+ apply(state: S, event: EventOf<D>): S;
66
+ /**
67
+ * This type's own number of events between snapshots, overriding the store's. 0 disables its
68
+ * snapshots.
69
+ */
70
+ readonly snapshotInterval?: number | undefined;
71
+ }
72
+ /** A checked aggregate type. */
73
+ export type Aggregate<S, C, D extends EventDefinitions> = Readonly<AggregateDefinition<S, C, D>>;
74
+ /** Declares an aggregate type. */
75
+ export declare function defineAggregate<S, C, D extends EventDefinitions>(definition: AggregateDefinition<S, C, D>): Aggregate<S, C, D>;
76
+ /** Encodes one event's data with its type's codec, as the payload and version to store. */
77
+ export declare function encodeEventData<D extends EventDefinitions>(events: D, event: EventOf<D>): {
78
+ version: number;
79
+ payload: Uint8Array;
80
+ };
81
+ /** Upcasts and decodes a stored event, failing closed with a {@link ReplayError}. */
82
+ export declare function replayEvent<D extends EventDefinitions>(events: D, stored: SerializedEvent): EventOf<D>;
83
+ //# sourceMappingURL=aggregate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aggregate.d.ts","sourceRoot":"","sources":["../src/aggregate.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAC,KAAK,EAAC,MAAM,YAAY,CAAA;AAErC,OAAO,KAAK,EAAC,eAAe,EAAC,MAAM,YAAY,CAAA;AAC/C,OAAO,EAAC,KAAK,SAAS,EAA2B,MAAM,WAAW,CAAA;AAGlE;;;;;GAKG;AACH,MAAM,WAAW,QAAQ;IACvB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;IACnB,MAAM,CAAC,OAAO,EAAE,UAAU,GAAG,UAAU,CAAA;CACxC;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAC1B,IAAI,EAAE,MAAM,EACZ,EAAE,EAAE,MAAM,EACV,OAAO,EAAE,CAAC,OAAO,EAAE,SAAS,KAAK,OAAO,GACvC,QAAQ,CAUV;AAED,+FAA+F;AAC/F,MAAM,WAAW,eAAe,CAAC,CAAC;IAChC,wFAAwF;IACxF,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC,CA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+ // Aggregates: an entity's state folded from its events, the commands it decides on, and the typed
2
+ // events it records, each with its stored version, payload codec and upcasters.
3
+ import { EvtError, ReplayError, messageOf } from './errors.js';
4
+ import { parseJson, stringifyJson } from './json.js';
5
+ import { utf8Decode, utf8Encode } from './utf8.js';
6
+ /**
7
+ * An upcaster that rewrites a JSON payload. `migrate` gets it losslessly, as {@link parseJson}
8
+ * reads it (objects as `Map`s in their stored order, numbers as {@link JsonNumber}s), and returns
9
+ * the new payload, which is written with {@link stringifyJson}. What the migration doesn't touch
10
+ * is written back exactly, whatever its integers or keys.
11
+ */
12
+ export function jsonUpcaster(from, to, migrate) {
13
+ return {
14
+ from,
15
+ to,
16
+ upcast(payload) {
17
+ const migrated = migrate(parseJson(utf8Decode(payload, 'payload')));
18
+ return utf8Encode(stringifyJson(migrated));
19
+ },
20
+ };
21
+ }
22
+ /** Declares an aggregate's event types, checking each version and upcaster. */
23
+ export function defineEvents(definitions) {
24
+ for (const [type, definition] of Object.entries(definitions)) {
25
+ positive(definition.version, `${type} version`);
26
+ for (const upcaster of definition.upcasters ?? []) {
27
+ positive(upcaster.from, `${type} upcaster from`);
28
+ positive(upcaster.to, `${type} upcaster to`);
29
+ }
30
+ }
31
+ return definitions;
32
+ }
33
+ /** Declares an aggregate type. */
34
+ export function defineAggregate(definition) {
35
+ if (definition.type === '') {
36
+ throw new EvtError('invalidArgument', 'an aggregate type must have a name');
37
+ }
38
+ if (definition.snapshotInterval !== undefined) {
39
+ const interval = definition.snapshotInterval;
40
+ if (!Number.isSafeInteger(interval) || interval < 0) {
41
+ throw new EvtError('invalidArgument', `${definition.type} snapshot interval must be a whole number of events: ${interval}`);
42
+ }
43
+ }
44
+ return definition;
45
+ }
46
+ /** Encodes one event's data with its type's codec, as the payload and version to store. */
47
+ export function encodeEventData(events, event) {
48
+ const definition = definitionOf(events, event.type);
49
+ if (definition === undefined) {
50
+ throw new EvtError('invalidArgument', `${event.type} is not one of the aggregate's event types`);
51
+ }
52
+ return { version: definition.version, payload: definition.codec.encode(event.data) };
53
+ }
54
+ /** Upcasts and decodes a stored event, failing closed with a {@link ReplayError}. */
55
+ export function replayEvent(events, stored) {
56
+ const definition = definitionOf(events, stored.type);
57
+ if (definition === undefined) {
58
+ throw new ReplayError(stored.type, stored.version, 'decode', 'unknown event type');
59
+ }
60
+ let payload = stored.payload ?? new Uint8Array();
61
+ let version = stored.version;
62
+ for (const upcaster of definition.upcasters ?? []) {
63
+ if (upcaster.from !== version) {
64
+ continue;
65
+ }
66
+ try {
67
+ payload = upcaster.upcast(payload);
68
+ }
69
+ catch (error) {
70
+ throw new ReplayError(stored.type, version, 'upcast', messageOf(error), error);
71
+ }
72
+ version = upcaster.to;
73
+ }
74
+ if (version !== definition.version) {
75
+ throw new ReplayError(stored.type, version, 'decode', `no upcaster takes it to version ${definition.version}`);
76
+ }
77
+ try {
78
+ return { type: stored.type, data: definition.codec.decode(payload) };
79
+ }
80
+ catch (error) {
81
+ throw new ReplayError(stored.type, version, 'decode', messageOf(error), error);
82
+ }
83
+ }
84
+ function definitionOf(events, type) {
85
+ return Object.hasOwn(events, type) ? events[type] : undefined;
86
+ }
87
+ function positive(value, what) {
88
+ if (!Number.isSafeInteger(value) || value < 1) {
89
+ throw new EvtError('invalidArgument', `${what} must be a whole number of at least 1: ${value}`);
90
+ }
91
+ }
92
+ //# sourceMappingURL=aggregate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aggregate.js","sourceRoot":"","sources":["../src/aggregate.ts"],"names":[],"mappings":"AAAA,kGAAkG;AAClG,gFAAgF;AAGhF,OAAO,EAAC,QAAQ,EAAE,WAAW,EAAE,SAAS,EAAC,MAAM,aAAa,CAAA;AAE5D,OAAO,EAAiB,SAAS,EAAE,aAAa,EAAC,MAAM,WAAW,CAAA;AAClE,OAAO,EAAC,UAAU,EAAE,UAAU,EAAC,MAAM,WAAW,CAAA;AAchD;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAC1B,IAAY,EACZ,EAAU,EACV,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array): string;
3
+ /**
4
+ * Decodes standard, padded base64 the way Go does: `\r` and `\n` are skipped, and anything else
5
+ * outside the alphabet, missing padding, or padding before the end is refused.
6
+ */
7
+ export declare function base64Decode(text: string): Uint8Array<ArrayBuffer>;
8
+ //# sourceMappingURL=base64.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base64.d.ts","sourceRoot":"","sources":["../src/base64.ts"],"names":[],"mappings":"AAWA,gDAAgD;AAChD,wBAAgB,YAAY,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAetD;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,UAAU,CAAC,WAAW,CAAC,CA0ClE"}
package/dist/base64.js ADDED
@@ -0,0 +1,67 @@
1
+ // Standard, padded base64 (Go's base64.StdEncoding), which is how a Go []byte appears in JSON.
2
+ // It's our own code because Buffer is Node-only and Uint8Array.fromBase64 isn't on every runtime.
3
+ import { EvtError } from './errors.js';
4
+ const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
5
+ const SYMBOLS = new Map(Array.from(ALPHABET, (symbol, value) => [symbol.charCodeAt(0), value]));
6
+ const PAD = 0x3d; // '='
7
+ /** Encodes bytes as standard, padded base64. */
8
+ export function base64Encode(bytes) {
9
+ let out = '';
10
+ for (let i = 0; i < bytes.length; i += 3) {
11
+ const b0 = bytes[i] ?? 0;
12
+ const b1 = bytes[i + 1] ?? 0;
13
+ const b2 = bytes[i + 2] ?? 0;
14
+ const triple = (b0 << 16) | (b1 << 8) | b2;
15
+ out += ALPHABET.charAt((triple >> 18) & 63);
16
+ out += ALPHABET.charAt((triple >> 12) & 63);
17
+ out += i + 1 < bytes.length ? ALPHABET.charAt((triple >> 6) & 63) : '=';
18
+ out += i + 2 < bytes.length ? ALPHABET.charAt(triple & 63) : '=';
19
+ }
20
+ return out;
21
+ }
22
+ /**
23
+ * Decodes standard, padded base64 the way Go does: `\r` and `\n` are skipped, and anything else
24
+ * outside the alphabet, missing padding, or padding before the end is refused.
25
+ */
26
+ export function base64Decode(text) {
27
+ const symbols = [];
28
+ for (let i = 0; i < text.length; i++) {
29
+ const unit = text.charCodeAt(i);
30
+ if (unit !== 0x0d && unit !== 0x0a) {
31
+ symbols.push(unit);
32
+ }
33
+ }
34
+ if (symbols.length % 4 !== 0) {
35
+ throw invalid(`length ${symbols.length}`);
36
+ }
37
+ const quads = symbols.length / 4;
38
+ const last = symbols.slice(-2);
39
+ const padding = last[1] === PAD ? (last[0] === PAD ? 2 : 1) : 0;
40
+ const out = new Uint8Array(quads * 3 - padding);
41
+ for (let quad = 0; quad < quads; quad++) {
42
+ let triple = 0;
43
+ for (let offset = 0; offset < 4; offset++) {
44
+ const index = quad * 4 + offset;
45
+ const symbol = symbols[index] ?? PAD;
46
+ const isPadding = quad === quads - 1 && offset >= 4 - padding;
47
+ const value = isPadding ? 0 : SYMBOLS.get(symbol);
48
+ if (value === undefined) {
49
+ throw invalid(`at input byte ${index}`);
50
+ }
51
+ triple = (triple << 6) | value;
52
+ }
53
+ const at = quad * 3;
54
+ out[at] = triple >> 16;
55
+ if (at + 1 < out.length) {
56
+ out[at + 1] = (triple >> 8) & 0xff;
57
+ }
58
+ if (at + 2 < out.length) {
59
+ out[at + 2] = triple & 0xff;
60
+ }
61
+ }
62
+ return out;
63
+ }
64
+ function invalid(where) {
65
+ return new EvtError('invalidRecord', `illegal base64 data ${where}`);
66
+ }
67
+ //# sourceMappingURL=base64.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base64.js","sourceRoot":"","sources":["../src/base64.ts"],"names":[],"mappings":"AAAA,+FAA+F;AAC/F,kGAAkG;AAElG,OAAO,EAAC,QAAQ,EAAC,MAAM,aAAa,CAAA;AAEpC,MAAM,QAAQ,GAAG,kEAAkE,CAAA;AAEnF,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,MA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AM,KAAK,GAAG,IAAI,GAAG,CAAC,GAAG,MAAM,CAAA;YAC/B,MAAM,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,IAAI,GAAG,CAAA;YACpC,MAAM,SAAS,GAAG,IAAI,KAAK,KAAK,GAAG,CAAC,IAAI,MAAM,IAAI,CAAC,GAAG,OAAO,CAAA;YAC7D,MAAM,KAAK,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;YACjD,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;gBACxB,MAAM,OAAO,CAAC,iBAAiB,KAAK,EAAE,CAAC,CAAA;YACzC,CAAC;YAED,MAAM,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC,GAAG,KAAK,CAAA;QAChC,CAAC;QAED,MAAM,EAAE,GAAG,IAAI,GAAG,CAAC,CAAA;QACnB,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,IAAI,EAAE,CAAA;QACtB,IAAI,EAAE,GAAG,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC;YACxB,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC,GAAG,IAAI,CAAA;QACpC,CAAC;QACD,IAAI,EAAE,GAAG,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC;YACxB,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,GAAG,MAAM,GAAG,IAAI,CAAA;QAC7B,CAAC;IACH,CAAC;IAED,OAAO,GAAG,CAAA;AACZ,CAAC;AAED,SAAS,OAAO,CAAC,KAAa;IAC5B,OAAO,IAAI,QAAQ,CAAC,eAAe,EAAE,uBAAuB,KAAK,EAAE,CAAC,CAAA;AACtE,CAAC"}
@@ -0,0 +1,56 @@
1
+ import { type JsonValue } from './json.js';
2
+ /** Encodes values of `T` to stored bytes and decodes them back. */
3
+ export interface Codec<T> {
4
+ encode(value: T): Uint8Array;
5
+ decode(bytes: Uint8Array): T;
6
+ }
7
+ /**
8
+ * The part of a [Standard Schema](https://standardschema.dev) validator evt calls, so Zod,
9
+ * Valibot, ArkType and the rest work without evt depending on any of them.
10
+ */
11
+ export interface StandardSchemaV1<Input = unknown, Output = Input> {
12
+ readonly '~standard': {
13
+ readonly version: 1;
14
+ readonly vendor: string;
15
+ readonly validate: (value: unknown) => StandardResult<Output> | Promise<StandardResult<Output>>;
16
+ readonly types?: {
17
+ readonly input: Input;
18
+ readonly output: Output;
19
+ } | undefined;
20
+ };
21
+ }
22
+ /** A Standard Schema validation result: the value, or the issues that refused it. */
23
+ export type StandardResult<Output> = {
24
+ readonly value: Output;
25
+ readonly issues?: undefined;
26
+ } | {
27
+ readonly issues: readonly {
28
+ readonly message: string;
29
+ }[];
30
+ };
31
+ /** Options for {@link json}. */
32
+ export interface JsonOptions<T> {
33
+ /** Validates each value before it's encoded and after it's decoded, synchronously. */
34
+ schema?: StandardSchemaV1<unknown, T> | undefined;
35
+ }
36
+ /**
37
+ * A JSON codec written with evt's encoder (the one Go's `encoding/json` output is reproduced
38
+ * with). Plain objects encode in property order.
39
+ *
40
+ * Decoding gives plain objects, arrays and numbers, so `T` must be plain JSON: a `Map`, a `bigint`
41
+ * or a `Date` doesn't decode back to itself. A domain that must match a Go or Rust one byte for
42
+ * byte, with a map whose keys are written sorted, needs a codec of its own that decodes the map as
43
+ * a `Map`. An integer past `Number.MAX_SAFE_INTEGER` is refused rather than rounded.
44
+ *
45
+ * Encoding refuses a value decoding would refuse, and with a `schema`, each value is validated
46
+ * before it's encoded and after it's decoded, so an event or a snapshot that couldn't be read back
47
+ * fails its commit instead of every later load. The schema must not transform values: the value
48
+ * is encoded as given.
49
+ */
50
+ export declare function json<T>(options?: JsonOptions<T>): Codec<T>;
51
+ /**
52
+ * A JSON value as plain JavaScript: objects as plain objects, numbers as `number`. An integer past
53
+ * the safe range is refused, because `number` would round it.
54
+ */
55
+ export declare function plainJson(value: JsonValue): unkn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