mollie-ecommerce 0.0.0-stage → 0.5.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 ADDED
@@ -0,0 +1,237 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here, following
4
+ [Semantic Versioning](https://semver.org/spec/v2.0.0.html) — pre-1.0, breaking
5
+ changes go in the minor slot.
6
+
7
+ Entries from 0.5.0 onwards are generated by
8
+ [changesets](https://github.com/changesets/changesets) at release time;
9
+ unreleased changes live as files in [`.changeset/`](.changeset) until then.
10
+ Earlier entries were written by hand.
11
+
12
+ ## 0.5.0
13
+
14
+ ### Minor Changes
15
+
16
+ - Publish built JavaScript instead of TypeScript source. The package now ships
17
+ `dist/` — ESM plus type declarations, bundled with
18
+ [tsdown](https://tsdown.dev) — so it works on Node, Bun, Deno and bundlers
19
+ alike.
20
+
21
+ Shipping source made the package Bun-only in practice: Node refuses to strip
22
+ types for anything under `node_modules` (`ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING`),
23
+ and many bundlers skip transpiling dependencies. It also meant every consumer
24
+ typechecked the library's internals under their own `tsconfig`; now they get
25
+ declarations we checked ourselves.
26
+
27
+ `zod` and `mollie-api-typescript` stay external, so nothing is duplicated.
28
+ Import paths are unchanged. The `mollie-ecommerce/conformance` entry still
29
+ needs Bun, since it builds on `bun:test`.
30
+
31
+ ## 0.4.0 — 2026-11-04
32
+
33
+ **Breaking.** `createCommerce` no longer performs storage work, and the package
34
+ no longer ships storage adapters. It opens no transaction, issues no query, and
35
+ knows nothing about tables: it calls seven handlers you fulfil, and persistence
36
+ is yours — your migrations, your pool, your naming.
37
+
38
+ ### Added
39
+
40
+ - `CommerceStorage` — the handler contract: `loadSkus`, `findOrder`,
41
+ `findOrderByPaymentId`, `findOrderByIdempotencyKey`, `listOrders`, plus the
42
+ two write handlers `createOrder` (order and stock together, returning
43
+ `{ status: "out_of_stock", shortages }` rather than throwing) and
44
+ `mutateOrder` (read, apply a mutation, persist atomically with any
45
+ `releaseStock`). Atomicity and concurrency are now the handler's contract,
46
+ documented per handler.
47
+ - `examples/memory-storage.ts` — a complete handler implementation over two
48
+ maps, published with the package as a copy-paste starting point, and covered
49
+ by this repo's lifecycle tests so it cannot drift.
50
+ - `describeCommerceStorage` in `mollie-ecommerce/conformance` — 11
51
+ contract tests for a handler implementation, covering the cases that are easy
52
+ to get subtly wrong: a shortage must not persist the order, `releaseStock`
53
+ must land in the same write as its mutation, and a throwing mutator must
54
+ leave nothing behind.
55
+ - **Runtime contract enforcement, always on.** `createCommerce` validates every
56
+ argument and return value crossing the storage boundary with
57
+ [zod](https://zod.dev), failing at the offending call with
58
+ `CommerceError("storage_contract")` instead of corrupting an order later.
59
+ Roughly 2µs per order, and nothing to switch on. It also checks what a schema
60
+ cannot express:
61
+ `loadSkus` returning only requested SKUs and none twice, `createOrder`
62
+ returning the order it was given with a version, and `mutateOrder` calling
63
+ the mutator and returning a *higher* version — a silent lost write is
64
+ otherwise invisible. Validated values pass through unchanged, never zod's
65
+ parsed copy. The checks are internal — there is nothing to import or switch
66
+ on — and `describeCommerceStorage` runs the same ones, so conformance
67
+ verifies what production enforces.
68
+ - Exported zod schemas for everything crossing the boundary — `OrderSchema`,
69
+ `SkuSchema`, `MoneySchema`, `OrderQuerySchema` and the rest — useful for
70
+ validating rows you rebuilt from JSON columns. A compile-time check keeps
71
+ them in step with the TypeScript types.
72
+ - `createCommerce({ onStorageError })` and `withStorageErrorHandler` — one
73
+ place to see errors thrown inside handlers. Return a `CommerceError` to
74
+ translate a driver error into the library's vocabulary (a serialization
75
+ failure into `version_conflict`, a unique violation into `duplicate_order`),
76
+ return nothing to observe only, or throw your own. The context names the
77
+ handler and what it was working on, including contract violations. It cannot
78
+ swallow an error.
79
+ - `storageError` — helpers for the errors a handler is expected to raise:
80
+ `outOfStock`, `orderNotFound`, `versionConflict`, `duplicateOrder` and
81
+ `failed`, so handlers speak the same vocabulary as the rest of the library
82
+ and your error mapping only needs `CommerceError.code`.
83
+ - `createOrder` may now **throw** `storageError.outOfStock(shortages)` instead
84
+ of returning `{ status: "out_of_stock" }`. Both reach the caller as
85
+ `out_of_stock`, and throwing is usually simpler since a transaction aborts by
86
+ throwing anyway. `describeCommerceStorage` accepts either.
87
+ - `CommerceError` accepts `{ cause }`, so a handler can wrap a driver error
88
+ without losing it.
89
+ - `CommerceError` code `storage_contract`.
90
+ - README: a "Persistence" section with the contract and a worked example, a
91
+ "Reference schema" section (the SQL the test suites use, as a starting point
92
+ you own), and a revised map of how the data sits next to your catalog.
93
+
94
+ ### Fixed
95
+
96
+ - A failed compensating write no longer hides the error that caused it. If
97
+ `createPayment` fails and releasing the stock fails too, the thrown error is
98
+ a `storage_error` that says the reservation is still held, carrying the
99
+ gateway error as its `cause` and both in `details` — previously the storage
100
+ error replaced the gateway one, losing the reason the payment failed.
101
+
102
+ ### Changed
103
+
104
+ - New dependency: `zod` (^4), for the exported schemas and the internal
105
+ contract checks.
106
+ - The standalone `versionConflict()` helper is now `storageError.versionConflict`.
107
+
108
+ ### Removed
109
+
110
+ - **All storage adapters and their exports.** `InMemoryDatabase`,
111
+ `SqliteDatabase`, the Postgres stores, `storageFromDatabase`, the `Database`
112
+ / `SkuStore` / `OrderStore` ports, the row mappers, `SCHEMA_SQL`,
113
+ `describeDatabase`, and the `./storage/*` subpaths are gone from the package.
114
+ They live on under `test/` as fixtures, so the lifecycle suite still runs
115
+ against in-memory, SQLite and Postgres storage.
116
+ - `createCommerce({ db })`. Pass `storage` instead; to keep the old behavior,
117
+ copy `test/storage/from-database.ts` into your project.
118
+
119
+ ### Changed
120
+
121
+ - `commerce.db` → `commerce.storage`, exposing the handlers you passed in.
122
+ - The `./conformance` subpath replaces `./storage/conformance`.
123
+
124
+ ## 0.3.0 — 2026-11-03
125
+
126
+ **Breaking.** The sellable unit is now a SKU rather than a product, because a
127
+ product has no single price or stock level and a purchasable variant does. This
128
+ removes the need to model variants at all: register one SKU per combination and
129
+ keep products, options and images in your own catalog.
130
+
131
+ ### Changed
132
+
133
+ - `Product` → `Sku`, with a new optional `productId` grouping key (indexed,
134
+ never interpreted by the library) and `ProductKind` → `SkuKind`. `kind` now
135
+ lives per SKU, so one product can ship physically and download digitally.
136
+ - `CartItem.productId` → `skuId`; `refund({ lines })` takes `{ skuId }`;
137
+ `OrderLine.productId` → `skuId`, plus an optional `productId` copied from the
138
+ SKU at purchase time.
139
+ - `Database.products` → `Database.skus`; `ProductStore` → `SkuStore`;
140
+ `ProductQuery` → `SkuQuery`, which gained a `productId` filter for listing a
141
+ product's variants. Adapter classes follow: `InMemorySkuStore`,
142
+ `SqliteSkuStore`, `PostgresSkuStore`.
143
+ - `StockChange.productId` → `skuId`; `StockShortage.productId` → `skuId`.
144
+ - Error codes `product_not_found` → `sku_not_found` and `product_inactive` →
145
+ `sku_inactive`.
146
+ - Row mappers `productToRow` / `rowToProduct` → `skuToRow` / `rowToSku`;
147
+ `ProductRow` → `SkuRow` with a `product_id` column.
148
+ - Database schema: table `products` → `skus`, with a nullable `product_id`
149
+ column and a `skus_product_id` index.
150
+
151
+ ### Migration
152
+
153
+ Rename the table and add the grouping column; existing rows need no other
154
+ change, since every other column keeps its name and meaning:
155
+
156
+ ```sql
157
+ ALTER TABLE products RENAME TO skus;
158
+ ALTER TABLE skus ADD COLUMN product_id TEXT;
159
+ CREATE INDEX IF NOT EXISTS skus_product_id ON skus (product_id);
160
+ ```
161
+
162
+ Stored orders need no migration: `OrderLine.productId` becomes `skuId`, and the
163
+ JSON already holds the id of the thing that was sold. If you want old orders to
164
+ read back with the new field name:
165
+
166
+ ```sql
167
+ -- Postgres
168
+ UPDATE orders SET lines = replace(lines, '"productId"', '"skuId"');
169
+ ```
170
+
171
+ In code, rename `productId` to `skuId` at your call sites — your existing
172
+ product ids are valid SKU ids, so nothing needs re-keying. To adopt variants,
173
+ add one SKU per combination and set `productId` on each.
174
+
175
+ ## 0.2.0 — 2026-11-03
176
+
177
+ ### Added
178
+
179
+ - **Postgres storage** (`mollie-ecommerce/storage/postgres`):
180
+ `createPostgresDatabase(pool)`, `PostgresProductStore`,
181
+ `PostgresOrderStore`, and `applyPostgresSchema`. The module imports no
182
+ driver — you pass a connection, so anything with node-postgres' shape works
183
+ (`query(sql, params) → { rows }` plus `connect()`). Transactions check out
184
+ one connection and run `BEGIN`/`COMMIT` on it; a nested call joins the
185
+ outer transaction instead of taking a second connection.
186
+ - `aggregateStock` helper, exported for storage adapters.
187
+ - README: a "Using Postgres" guide (driver install, schema and migrations,
188
+ pool and pooler behavior, column-type rationale, conformance verification,
189
+ operating notes) and an end-to-end "real-world shop" walkthrough covering
190
+ checkout, webhook, redirect return, fulfillment, and reconciliation.
191
+
192
+ ### Fixed
193
+
194
+ - **`reserveStock` could oversell when the same product appeared twice in one
195
+ call.** The in-memory and SQLite adapters checked each entry against the
196
+ full stock independently and then decremented both, so `[{mug, 2}, {mug, 2}]`
197
+ against a stock of 3 succeeded and left −1. All adapters now aggregate
198
+ repeated product ids via `aggregateStock`, and the conformance suite covers
199
+ it. Checkout was never affected, since it merges cart lines first; direct
200
+ callers of the port were.
201
+
202
+ ### Changed
203
+
204
+ - `describeDatabase` now runs 18 contract tests (was 17), and the lifecycle
205
+ suite runs against all three storage adapters. Postgres is exercised with
206
+ [PGlite](https://pglite.dev) through a pool shim, plus a compile-time guard
207
+ that node-postgres satisfies the adapter's ports — both devDependencies
208
+ only.
209
+
210
+ ## 0.1.0 — 2026-11-03
211
+
212
+ First release. Pre-1.0, so the public API may still change in minor versions
213
+ (see [Versioning](README.md#versioning)).
214
+
215
+ ### Added
216
+
217
+ - `createCommerce({ gateway, db, ... })` — the commerce API: `checkout`,
218
+ `syncOrder`, `handleWebhook`, `refund`, `markReady`, `markShipped`,
219
+ `markDelivered`, `markReturned`, `cancelOrder`, `getOrder`, `findOrders`.
220
+ - Product and order model: `Product`, `Order`, `OrderLine`, `Refund`,
221
+ `Customer`, with payment state mirroring Mollie's and a separate delivery
222
+ state machine (`not_started → ready → shipped → delivered → returned`, plus
223
+ `canceled`).
224
+ - `Money` as integer minor units plus currency, converted to and from Mollie's
225
+ decimal strings at the API boundary (`money`, `add`, `subtract`, `multiply`,
226
+ `sum`, `toMollieAmount`, `fromMollieAmount`, `formatMoney`).
227
+ - Idempotent checkout: replaying an `idempotencyKey` returns the original order
228
+ instead of charging twice.
229
+ - Stock reservation at checkout, released exactly once when a payment is
230
+ canceled, expires, or fails — or on `markReturned({ restock: true })`.
231
+ - `createMollieGateway({ apiKey })` over `mollie-api-typescript`, and
232
+ `FakePaymentGateway` for tests and local development.
233
+ - Storage ports (`Database`, `ProductStore`, `OrderStore`) with optimistic
234
+ concurrency, batched reads, atomic stock, and transactions.
235
+ - `InMemoryDatabase`, `SqliteDatabase` (`bun:sqlite`), row mappers plus
236
+ `SCHEMA_SQL`, and `describeDatabase` — 17 contract tests to verify your own
237
+ adapter.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 mollie-ecommerce contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.