@cardonjs/testing 0.0.0-stage → 0.7.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 (89) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +537 -2
  3. package/THIRD_PARTY_NOTICES.md +72 -0
  4. package/dist/access-token-contract.d.ts +26 -0
  5. package/dist/access-token-contract.d.ts.map +1 -0
  6. package/dist/access-token-contract.js +252 -0
  7. package/dist/access-token-contract.js.map +1 -0
  8. package/dist/assertion.d.ts +7 -0
  9. package/dist/assertion.d.ts.map +1 -0
  10. package/dist/assertion.js +11 -0
  11. package/dist/assertion.js.map +1 -0
  12. package/dist/audit-contract.d.ts +52 -0
  13. package/dist/audit-contract.d.ts.map +1 -0
  14. package/dist/audit-contract.js +522 -0
  15. package/dist/audit-contract.js.map +1 -0
  16. package/dist/contract.d.ts +14 -0
  17. package/dist/contract.d.ts.map +1 -0
  18. package/dist/contract.js +8 -0
  19. package/dist/contract.js.map +1 -0
  20. package/dist/envelopes.d.ts +33 -0
  21. package/dist/envelopes.d.ts.map +1 -0
  22. package/dist/envelopes.js +121 -0
  23. package/dist/envelopes.js.map +1 -0
  24. package/dist/idempotency-contract.d.ts +19 -0
  25. package/dist/idempotency-contract.d.ts.map +1 -0
  26. package/dist/idempotency-contract.js +234 -0
  27. package/dist/idempotency-contract.js.map +1 -0
  28. package/dist/index.d.ts +10 -0
  29. package/dist/index.d.ts.map +1 -0
  30. package/dist/index.js +10 -0
  31. package/dist/index.js.map +1 -0
  32. package/dist/logs.d.ts +18 -0
  33. package/dist/logs.d.ts.map +1 -0
  34. package/dist/logs.js +20 -0
  35. package/dist/logs.js.map +1 -0
  36. package/dist/miniflare/bindings.d.ts +43 -0
  37. package/dist/miniflare/bindings.d.ts.map +1 -0
  38. package/dist/miniflare/bindings.js +90 -0
  39. package/dist/miniflare/bindings.js.map +1 -0
  40. package/dist/miniflare/broken.d.ts +12 -0
  41. package/dist/miniflare/broken.d.ts.map +1 -0
  42. package/dist/miniflare/broken.js +27 -0
  43. package/dist/miniflare/broken.js.map +1 -0
  44. package/dist/miniflare/executor-channel.d.ts +37 -0
  45. package/dist/miniflare/executor-channel.d.ts.map +1 -0
  46. package/dist/miniflare/executor-channel.js +144 -0
  47. package/dist/miniflare/executor-channel.js.map +1 -0
  48. package/dist/miniflare/executor.d.ts +42 -0
  49. package/dist/miniflare/executor.d.ts.map +1 -0
  50. package/dist/miniflare/executor.js +121 -0
  51. package/dist/miniflare/executor.js.map +1 -0
  52. package/dist/miniflare/index.d.ts +10 -0
  53. package/dist/miniflare/index.d.ts.map +1 -0
  54. package/dist/miniflare/index.js +10 -0
  55. package/dist/miniflare/index.js.map +1 -0
  56. package/dist/miniflare/migrations.d.ts +23 -0
  57. package/dist/miniflare/migrations.d.ts.map +1 -0
  58. package/dist/miniflare/migrations.js +43 -0
  59. package/dist/miniflare/migrations.js.map +1 -0
  60. package/dist/miniflare/one-call-d1.d.ts +12 -0
  61. package/dist/miniflare/one-call-d1.d.ts.map +1 -0
  62. package/dist/miniflare/one-call-d1.js +223 -0
  63. package/dist/miniflare/one-call-d1.js.map +1 -0
  64. package/dist/miniflare/statements.d.ts +18 -0
  65. package/dist/miniflare/statements.d.ts.map +1 -0
  66. package/dist/miniflare/statements.js +175 -0
  67. package/dist/miniflare/statements.js.map +1 -0
  68. package/dist/miniflare/storage.d.ts +58 -0
  69. package/dist/miniflare/storage.d.ts.map +1 -0
  70. package/dist/miniflare/storage.js +129 -0
  71. package/dist/miniflare/storage.js.map +1 -0
  72. package/dist/miniflare/types.d.ts +25 -0
  73. package/dist/miniflare/types.d.ts.map +1 -0
  74. package/dist/miniflare/types.js +2 -0
  75. package/dist/miniflare/types.js.map +1 -0
  76. package/dist/miniflare/worker.d.ts +70 -0
  77. package/dist/miniflare/worker.d.ts.map +1 -0
  78. package/dist/miniflare/worker.js +137 -0
  79. package/dist/miniflare/worker.js.map +1 -0
  80. package/dist/push-subscription-contract.d.ts +54 -0
  81. package/dist/push-subscription-contract.d.ts.map +1 -0
  82. package/dist/push-subscription-contract.js +735 -0
  83. package/dist/push-subscription-contract.js.map +1 -0
  84. package/dist/routes.d.ts +72 -0
  85. package/dist/routes.d.ts.map +1 -0
  86. package/dist/routes.js +196 -0
  87. package/dist/routes.js.map +1 -0
  88. package/llms.txt +234 -0
  89. package/package.json +69 -3
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Matias Terradas
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.
package/README.md CHANGED
@@ -1,3 +1,538 @@
1
- # Temporary Holding Version
1
+ # @cardonjs/testing
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
+ Test helpers for Cardón apps: a guard that every route is documented in the OpenAPI spec, an
4
+ in-memory logger to assert on logs, and assertions for the `{ data }` and `{ error }` envelopes
5
+ of `@cardonjs/core`, plus the building blocks of shared adapter contract suites (`defineContract`,
6
+ `fail`) the contract of core's idempotency store (`idempotencyStoreContract`) and the contract of
7
+ the `@cardonjs/access-tokens` store (`accessTokenStoreContract`), the contract of the
8
+ `@cardonjs/audit` store (`auditStoreContract`) and the contract of the
9
+ `@cardonjs/notify-webpush` push subscription store (`pushSubscriptionStoreContract`). They do
10
+ not depend on a test runner: a failed assertion throws a plain `Error` named `AssertionError`
11
+ whose message lists every problem, so they work in Vitest, `node:test` or anything else. Standard web APIs only (Workers, Node, Bun, Deno).
12
+
13
+ Peer dependencies: `@cardonjs/core`, `hono`, `@hono/zod-openapi`; optional, for
14
+ `@cardonjs/testing/miniflare` only: `miniflare`, `rolldown` and `@cloudflare/workers-types`.
15
+
16
+ For coding agents: `llms.txt`, shipped next to this README in the package, is a compact usage guide (public API, a minimal example, common mistakes).
17
+
18
+ A second entry point, `@cardonjs/testing/miniflare`, gives tests real Cloudflare bindings (D1,
19
+ R2, Durable Objects, Workflows) from Miniflare running in Node: see
20
+ [Real bindings](#real-bindings-cardonjstestingminiflare). It is the only part that needs
21
+ `miniflare` (and `rolldown` for `startWorker`); the main entry works without them.
22
+
23
+ ## Example
24
+
25
+ ```ts
26
+ import { createApp } from "@cardonjs/core";
27
+ import { assertRoutesDocumented, captureLogs, expectData, expectError } from "@cardonjs/testing";
28
+ import { expect, it } from "vitest";
29
+ import { ordersModule } from "./orders.js";
30
+
31
+ const { logger, records, clear } = captureLogs();
32
+ const app = createApp(() => ({}), { logger }).register(ordersModule);
33
+
34
+ it("documents every route", () => {
35
+ assertRoutesDocumented(app, { ignore: ["POST /webhooks/legacy"] });
36
+ });
37
+
38
+ it("gets an order", async () => {
39
+ const { data } = await expectData<{ id: string }>(await app.request("/v1/orders/1"), {
40
+ status: 200,
41
+ });
42
+ expect(data.id).toBe("1");
43
+ });
44
+
45
+ it("answers 404 for an unknown order", async () => {
46
+ clear();
47
+ const error = await expectError(await app.request("/v1/orders/nope"), {
48
+ status: 404,
49
+ code: "NOT_FOUND",
50
+ });
51
+ expect(records.find((r) => r.msg === "request")?.requestId).toBe(error.requestId);
52
+ });
53
+ ```
54
+
55
+ ## API
56
+
57
+ ### `assertRoutesDocumented(app, { ignore?, errorResponses? })`
58
+
59
+ Throws if a route is registered outside OpenAPI or its operation lacks the required metadata.
60
+ Works on any `OpenAPIHono`, a `CardonApp` included, and reads the spec from the app
61
+ (`getOpenAPI31Document`), never over HTTP, so the docs `access` and the environment do not matter.
62
+
63
+ - Checks every entry of `app.routes` with an HTTP method, once per method and path, with its
64
+ full path (module prefixes included). Entries with method `ALL` are skipped: that is how Hono
65
+ lists `use()` middleware, and `all()` and `mount()` routes look the same, so **they are not
66
+ checked**. Routes on methods OpenAPI cannot describe (e.g. `PURGE`) are reported.
67
+ - Each problem is one line, `METHOD /path: <problem>`, with the path as registered in Hono:
68
+ `undocumented`, `missing summary`, `missing tag`, `missing responses`. The shared error
69
+ responses a Cardón app adds to every operation (`$ref`s to `components.responses`) do not
70
+ count as the operation's own responses.
71
+ - Hono path params map to OpenAPI: `:id` and `:id{regex}` → `{id}`. A trailing optional param
72
+ (`/files/:name?`) answers two paths, so both `/files` and `/files/{name}` must be documented.
73
+ Wildcards (`/static/*`) cannot be documented: list them in `ignore`.
74
+ - `ignore`: `"METHOD /path"` strings in Hono path syntax, exactly as registered
75
+ (`"GET /legacy/:id"`); the method is case-insensitive.
76
+ - `errorResponses: true` (default `false`) also requires every operation that is not public
77
+ (its `security` is not `[]`) to document `500`, and `401` when it has security
78
+ requirements (`missing error responses (401, 500)`). A status counts when the operation has
79
+ it, its range (`5XX`) or `default`. A Cardón app documents these itself, so the check
80
+ catches routes or apps that do not.
81
+
82
+ ### `undocumentedRoutes(routes, document, { ignore? })`
83
+
84
+ The part of `assertRoutesDocumented` that decides which routes are undocumented, as a pure
85
+ function over data: `routes` is `app.routes` (or any `{ method, path }` list, e.g. from a route
86
+ manifest) and `document` an OpenAPI document (only its `paths` is read). Returns, in route order
87
+ and once each, `{ method, path, describable, missing }`: `missing` lists the OpenAPI paths the
88
+ route answers that have no operation for its method; `describable` is `false` for a method
89
+ OpenAPI cannot describe (e.g. `PURGE`). Same rules as the assertion: `ALL` entries are skipped,
90
+ `ignore` works the same way, and system routes need no exception (a Cardón app documents them).
91
+ `cardon doctor` applies the same rule to a project's route manifest. `toOpenApiPaths(path)` is
92
+ exported too: the OpenAPI path(s) a Hono path answers.
93
+
94
+ ### `captureLogs({ level?, fields? })`
95
+
96
+ Returns `{ logger, records, clear() }`: a core `Logger` (level `"debug"` by default, `fields` as
97
+ in `createLogger`) and the live array of `LogRecord`s it wrote. `clear()` empties that same array.
98
+
99
+ ### `expectData(res, { status? })`
100
+
101
+ Asserts a success envelope and resolves to its parsed body `{ data, meta? }`: the status (any 2xx
102
+ by default), a JSON content type (`application/json` or `+json`), a `data` key and no `error`
103
+ key. The type parameters (`expectData<T, M>`) are not validated.
104
+
105
+ ### `expectError(res, { status, code })`
106
+
107
+ Asserts a core error envelope and resolves to its `error` object `{ code, message, details?,
108
+ requestId }`: the status, a JSON content type, `error.code` (typed as core's `ErrorCode`), a
109
+ non-empty `error.message`, and `error.requestId` equal to the `X-Request-Id` response header.
110
+
111
+ Both envelope helpers read the response body.
112
+
113
+ ### `fail(title, problems?)`
114
+
115
+ Throws the same `AssertionError` the helpers above throw: the message is `title` followed by one
116
+ line per problem. Use it in your own assertions and in contract cases.
117
+
118
+ ### `defineContract(cases)` and `ContractCase<H>`
119
+
120
+ A shared contract suite is a list of cases, `{ name, run(harness) }`, that every adapter of an
121
+ interface must pass. `H` is the harness the adapter provides (how to create a fresh instance, a
122
+ broken one, and so on); a case fails by throwing, usually with `fail`. `defineContract` only types
123
+ the list. The suite does not pick a runner: each adapter runs the cases with its own.
124
+
125
+ ```ts
126
+ import { defineContract, fail } from "@cardonjs/testing";
127
+
128
+ interface CounterHarness {
129
+ create(): { value(): number; increment(): void };
130
+ }
131
+
132
+ export const counterContract = defineContract<CounterHarness>([
133
+ {
134
+ name: "starts at zero",
135
+ run: (h) => {
136
+ const value = h.create().value();
137
+ if (value !== 0) fail("a new counter must start at zero", [`got ${value}`]);
138
+ },
139
+ },
140
+ {
141
+ name: "increment adds one",
142
+ run: (h) => {
143
+ const counter = h.create();
144
+ counter.increment();
145
+ if (counter.value() !== 1) fail("increment must add one");
146
+ },
147
+ },
148
+ ]);
149
+
150
+ // In an adapter's tests (Vitest):
151
+ it.each(counterContract.map((c) => [c.name, c] as const))("%s", (_, c) => c.run(harness));
152
+ ```
153
+
154
+ ### `idempotencyStoreContract`
155
+
156
+ The cases every `IdempotencyStore` (the store behind core's `idempotency` middleware) must
157
+ pass, with the harness `IdempotencyStoreContractHarness` (`{ create() }`, a fresh empty store
158
+ per call). It lives here rather than in core because this package already depends on core. The
159
+ cases cover `begin` (started with a token, `in_progress` while the lock holds, `mismatch` for
160
+ another fingerprint, `completed` with the stored response byte for byte, a new token when an
161
+ expired lock is taken over, the TTL counted from `complete`), `complete` with the owning token
162
+ after the lock expired but before a takeover (it succeeds), `complete` and `release` with a
163
+ stale token, concurrent `begin` calls (exactly one `started`, also when taking over an expired
164
+ record), `purge` (only expired records, at most `limit`) and independent keys. Dates are passed
165
+ in, so no case waits. The concurrency case only tests atomicity on a store whose `begin` awaits
166
+ I/O between reading and writing (D1, a database); an in-memory store that never awaits inside
167
+ `begin` cannot interleave, so it passes that case trivially.
168
+
169
+ ```ts
170
+ import { memoryIdempotencyStore } from "@cardonjs/core";
171
+ import { idempotencyStoreContract } from "@cardonjs/testing";
172
+
173
+ it.each(idempotencyStoreContract.map((c) => [c.name, c] as const))("%s", (_, c) =>
174
+ c.run({ create: () => memoryIdempotencyStore() }),
175
+ );
176
+ ```
177
+
178
+ ### `accessTokenStoreContract`
179
+
180
+ The cases every `AccessTokenStore` (the store behind `@cardonjs/access-tokens`) must pass, with
181
+ the harness `AccessTokenStoreContractHarness` (`{ create() }`, a fresh empty store per call). The
182
+ store and record types are repeated here structurally (`AccessTokenStoreUnderTest`,
183
+ `AccessTokenStoreRecord`), so this package does not depend on `@cardonjs/access-tokens`. The
184
+ cases cover `insert` and `findByHash` (every field back, dates to the millisecond, scopes in
185
+ order; nothing for an unknown hash), duplicate hashes and ids rejected, expired and revoked
186
+ records still found until purged, `revoke` (once, on that record only, the first `revokedAt`
187
+ kept), `revokeForResource` (every unrevoked record of exactly that resource, counted), no
188
+ cross-resource leak (other types, ids, case, `LIKE` wildcards and prefixes untouched),
189
+ `purgeExpired` (records expired at or before the time, counted; revoked live ones kept) and
190
+ copies (changing a record after `insert` or `findByHash` changes nothing stored).
191
+
192
+ ```ts
193
+ import { memoryAccessTokenStore } from "@cardonjs/access-tokens/testing";
194
+ import { accessTokenStoreContract } from "@cardonjs/testing";
195
+
196
+ it.each(accessTokenStoreContract.map((c) => [c.name, c] as const))("%s", (_, c) =>
197
+ c.run({ create: () => memoryAccessTokenStore() }),
198
+ );
199
+ ```
200
+
201
+ ### `auditStoreContract`
202
+
203
+ The cases every `AuditStore` (the store behind `@cardonjs/audit`) must pass, with the harness
204
+ `AuditStoreContractHarness` (`{ create() }`, a fresh empty store per call). The store and event
205
+ types are repeated here structurally (`AuditStoreUnderTest`, `AuditStoreEvent`,
206
+ `AuditStoreRef`, `AuditStoreListFilter`), so this package does not depend on `@cardonjs/audit`.
207
+ Every event the cases insert is valid by `validateAuditEvent`'s rules (a UUIDv7 whose
208
+ timestamp is `at`, names, refs, strict JSON data), so a store may rely on id order being `at`
209
+ order. The cases cover `insert` and `list` (every field back, `at` to the millisecond,
210
+ `truncated`, JSON data compared whatever its key order, optional fields left out rather than
211
+ `null`), a duplicate id rejected with `reason: "DuplicateId"` and the first event kept, newest
212
+ first by `id` (same millisecond included, not insertion order), same-millisecond events paged
213
+ one by one, each filter alone (action, actor, actor type, resource, resource type) and combined,
214
+ `from` inclusive and `to` exclusive, no leak between resources or actors (other types, ids,
215
+ case, `LIKE` wildcards, prefixes, an actor never matching a resource filter), cursor pages
216
+ without gaps or repeats that keep every filter, `limit` bounds (1, the exact count, 200;
217
+ `nextCursor` only when more are left), `purge(before, { limit })` (at most `limit`, oldest
218
+ first, strictly before the time, counted), the cursor of a purged event, unusual keys and
219
+ strings (`__proto__`, empty and dotted keys, U+0000, astral characters) round-tripped, a field
220
+ of exactly 512 KiB kept and one byte more refused, malformed events refused with a `TypeError`
221
+ (a store calls `validateAuditEvent` from `@cardonjs/audit`) without breaking `list`, and
222
+ copies.
223
+
224
+ ```ts
225
+ import { memoryAuditStore } from "@cardonjs/audit/testing";
226
+ import { auditStoreContract } from "@cardonjs/testing";
227
+
228
+ it.each(auditStoreContract.map((c) => [c.name, c] as const))("%s", (_, c) =>
229
+ c.run({ create: () => memoryAuditStore() }),
230
+ );
231
+ ```
232
+
233
+ ### `pushSubscriptionStoreContract`
234
+
235
+ The cases every `PushSubscriptionStore` (`@cardonjs/notify-webpush`) must pass, with the harness
236
+ `PushSubscriptionStoreContractHarness` (`{ create({ now }) }`: a fresh empty store per call,
237
+ whose saves are dated, and expiry decided, by `now`, the clock the cases move). The store types
238
+ are repeated here structurally (`PushSubscriptionStoreUnderTest`, `PushSubscriptionStoreOwner`,
239
+ `PushSubscriptionStoreSubscription`, `PushSubscriptionStoreSaveOptions`,
240
+ `PushSubscriptionStoreSaveResult`, `PushSubscriptionStoreRefusal`), so this package does not depend on
241
+ `@cardonjs/notify-webpush`. The cases cover: `save` and `listForOwner` (newest first, ties by
242
+ endpoint, the keys back, nothing for another owner); one endpoint under several owners (all list
243
+ it; `deleteForOwner` leaves the others; `delete` removes it for all); another `auth` for a stored
244
+ endpoint refused as `taken` under any owner, the same one included, and an `auth` differing only
245
+ in letter case, changing nothing; the same `auth` with a new `p256dh` updating what every owner
246
+ lists, and `=` padding being the same secret; `whenFull: "evict"` (the newest `max`, default 10,
247
+ the saved one always kept, never another owner's) and `"refuse"` (`owner_full`, nothing changed;
248
+ re-saving one's own never refused); a refused save never evicting at the cap; `owner_full` with
249
+ `exclusive` running no exclusive delete; the per-endpoint cap of 50 owners (`endpoint_full`,
250
+ nothing evicted, nor with `exclusive` and `max: 1`; answered before `source_full`); the cap per
251
+ source (`maxPerSource` answering `source_full` and changing nothing with either `whenFull`, with
252
+ `exclusive` and with `max: 1`, while the owner is not full; answered after `taken` and before
253
+ `owner_full`; counting only the owner's live subscriptions with that source, never the endpoint
254
+ saved again; a re-save moving the endpoint to another source, or clearing it, freeing the slot;
255
+ the source never listed); `exclusive` (other owners of the same type only); expiry (skipped by `listForOwner`, not counted against `max`, deleted by `purgeExpired`,
256
+ replaced by a new save); `purgeExpired` bounded by `limit`, earliest expiry first, keeping a
257
+ browser another owner uses; deletes matching endpoints exactly and an endpoint no owner uses any more
258
+ being free for other keys; `deleteAllForOwner` scoped to exactly that owner (counted); no leak
259
+ between owners of different types with the same id; and malformed owners, subscriptions, options
260
+ (a malformed `source`, `maxPerSource` without one) and dates rejected with a `TypeError` that never holds the value. Failure messages name
261
+ subscriptions by a label, never by their endpoint or keys.
262
+
263
+ ```ts
264
+ import { memoryPushSubscriptionStore } from "@cardonjs/notify-webpush/testing";
265
+ import { pushSubscriptionStoreContract } from "@cardonjs/testing";
266
+
267
+ it.each(pushSubscriptionStoreContract.map((c) => [c.name, c] as const))("%s", (_, c) =>
268
+ c.run({ create: ({ now }) => memoryPushSubscriptionStore({ now }) }),
269
+ );
270
+ ```
271
+
272
+ ## Real bindings (`@cardonjs/testing/miniflare`)
273
+
274
+ Tests against real bindings catch what a mock cannot: SQL that SQLite refuses, a batch that is
275
+ not atomic, a Durable Object that loses its state when it hibernates. This entry point starts
276
+ them from Miniflare, in Node, with plain async functions (no test runner involved).
277
+
278
+ ```sh
279
+ pnpm add -D @cardonjs/testing miniflare # startBindings, applyMigrations
280
+ pnpm add -D rolldown # startWorker, to bundle a Worker entry
281
+ ```
282
+
283
+ The harness works with Miniflare 4 (`^4.20260730.0`) and with Miniflare 5, a beta today.
284
+ Cardón's own suites run on Miniflare 4 in CI; Miniflare 5 was checked by hand on
285
+ `5.20261119.0-beta` on 2026-11-22 (Windows), not in CI. Wrangler releases after 4.116.0 bring
286
+ Miniflare 5, so a project on Miniflare 4 installs two copies and `wrangler dev` runs a newer
287
+ runtime than its tests. A project that wants one copy and one runtime can pin, in its
288
+ `devDependencies`, the Miniflare version its Wrangler brings.
289
+
290
+ The peer range is `^4.20260730.0 || ^5.20261119.0-beta`: Miniflare 4, the beta that was
291
+ checked, and Miniflare 5 once it is stable. A semver range cannot cover every beta (a
292
+ prerelease only matches a range that names its exact version), so with any other Miniflare 5
293
+ beta npm refuses the install (`ERESOLVE`) unless the project adds an `overrides` entry for
294
+ `miniflare` or installs with `--legacy-peer-deps`; pnpm installs it. Other betas were not
295
+ checked.
296
+
297
+ `miniflare` and `rolldown` are optional peer dependencies: only this entry point imports
298
+ `miniflare`, and only `startWorker` imports `rolldown` (when it bundles an `entry`). The helpers
299
+ return the types a Worker receives (`D1Database`, `R2Bucket`, `DurableObjectNamespace`),
300
+ imported from `@cloudflare/workers-types` (an optional peer dependency too, needed by this entry
301
+ only), so they are the same types whether or not the project's `tsconfig.json` lists the
302
+ Workers types as ambient. Without the package installed, a binding's type is
303
+ `WorkersTypesMissing` and the first use of it fails to type-check, rather than becoming `any`
304
+ (which `skipLibCheck` would hide). The main entry's types do not use it.
305
+
306
+ ```ts
307
+ import { applyMigrations, startBindings, type TestBindings } from "@cardonjs/testing/miniflare";
308
+ import { afterAll, beforeAll, expect, it } from "vitest";
309
+
310
+ let bindings: TestBindings;
311
+ beforeAll(async () => {
312
+ bindings = await startBindings({ d1: 8, r2: 2 }); // one Miniflare per test file
313
+ });
314
+ afterAll(async () => {
315
+ await bindings?.dispose();
316
+ });
317
+
318
+ it("stores a note", async () => {
319
+ const db = await bindings.d1(); // a new, empty database
320
+ await applyMigrations(db, { dir: new URL("../migrations/", import.meta.url) });
321
+ await db.prepare("INSERT INTO notes (id, body) VALUES (?, ?)").bind("n1", "hello").run();
322
+ expect(await db.prepare("SELECT body FROM notes").first("body")).toBe("hello");
323
+ });
324
+ ```
325
+
326
+ ### `startBindings({ d1?, r2?, d1Binding? })`
327
+
328
+ Starts one Miniflare with a pool of `d1` D1 databases and `r2` R2 buckets (0 each by default;
329
+ at least one in total) and resolves to `{ d1(), r2(), directory, dispose() }`. Each `d1()` or
330
+ `r2()` call resolves to a binding no one used before: a new, empty database or bucket. Asking
331
+ for more than the pool holds rejects with an error that says so (`the pool of 8 D1 databases is
332
+ used up; ask for more with { d1: n }`); a used binding is never handed out again. Size the pool
333
+ for the file: every database is created when Miniflare starts.
334
+
335
+ The databases `d1()` hands out are **one-call D1s** by default: a `D1Database` whose `prepare`
336
+ and `bind` run in Node and whose every execution (`all`, `run`, `raw`, `first`, `batch`,
337
+ `exec`) is one request to a small Worker in the same Miniflare, which runs it on the real D1
338
+ binding. The SQL still runs on D1 and SQLite in workerd; only the way Node reaches it changes.
339
+ Miniflare's own binding object is a proxy on which every call, `prepare` and `bind` included,
340
+ is a blocking round trip to workerd: a Drizzle query (`prepare().bind().raw()`) costs several
341
+ of them, about 80 ms on Windows and 12 ms on Linux, against 5 and 3 ms as one request.
342
+
343
+ - Every execution runs on the real D1 binding in workerd: results and `meta`, `raw` with and
344
+ without column names, `batch` (in order, and atomic: a failing statement rolls the batch
345
+ back), `exec`, BLOBs (arrays of bytes, as from D1) and D1's errors, with the same messages
346
+ (`D1_ERROR: UNIQUE constraint failed: ...`) and causes.
347
+ - What D1's binding does before a query leaves a Worker runs in Node, with the same code:
348
+ `bind` checks and converts the values with D1's rules and throws `D1_TYPE_ERROR` at once for
349
+ one D1 refuses (`ArrayBuffer`s and views become arrays of bytes, booleans 1 and 0, a plain
350
+ array is kept, not copied, as D1 keeps it); a statement has D1's `statement` and `params`
351
+ fields; each execution sends them as D1 serialises them, when the method is called; `first`
352
+ looks the column up on the row as D1 does.
353
+ - Executions on one database are sent one at a time, in the order they were called, as they
354
+ reach D1 from a Worker (`Promise.all` of a write and a read sees the write).
355
+ - A parity suite in this package runs the same scenarios inside a Worker on its real binding
356
+ and on a one-call D1 and compares every step's value or error (and the scenarios Miniflare's
357
+ binding can carry also on that binding).
358
+
359
+ What differs from D1 in a Worker:
360
+
361
+ - `withSession` and `dump` are not supported: they throw an error that says how to get the
362
+ direct binding.
363
+ - Errors are rebuilt in Node: the same standard class, name, message and causes, with the stack
364
+ of your call, not workerd's. Values come from Node's realm (`first("constructor")` gives
365
+ Node's `Object`, as a Worker gives its own).
366
+ - A statement has no `dbSession` field (D1's points to its session object), and `batch` takes
367
+ only statements of a one-call D1 (D1 reads `statement` and `params` from any object).
368
+ - A value whose text depends on the time zone (binding a `Date`, which D1 refuses with the date
369
+ in its message) reads in Node's time zone; workerd's is UTC.
370
+
371
+ Where Miniflare's own binding (below) and a Worker differ, the one-call D1 does what the Worker
372
+ does: a lone surrogate in a string reaches D1 as it is (the proxy turns it into U+FFFD), and a
373
+ `SharedArrayBuffer` gets D1's `D1_TYPE_ERROR` (the proxy cannot carry it); a bound array
374
+ changed before the execution, or a sparse one, also behaves as in a Worker (the proxy copies
375
+ the values at `bind`).
376
+
377
+ `d1Binding: "direct"` (`startBindings({ d1: 4, d1Binding: "direct" })`) hands out Miniflare's
378
+ own binding object instead. Use it to test code against the binding object itself (an adapter's
379
+ own suite, as `@cardonjs/db-d1`'s are) or to use `withSession` or `dump`; it is slower for
380
+ everything else.
381
+
382
+ The one-call D1 reaches its Worker on a socket of that Worker's own in workerd, over a few
383
+ connections kept open between requests (one per database sending at the same moment, closed
384
+ after 2 seconds idle). That Worker answers only the harness that started it (anything else on
385
+ the machine, a web page included, is refused), and a one-call D1 used after `dispose()` rejects
386
+ with `startBindings: the harness was disposed; ...` (or `startWorker: ...`). Everything else reaches workerd through Miniflare, which opens a new
387
+ connection for each asynchronous call and closes it: a request with `fetch` of `startWorker`,
388
+ an `await` on an R2 bucket, a Durable Object or the direct D1 binding (see "Many connections on
389
+ Windows" below).
390
+
391
+ Storage lives in a temporary directory of its own (`directory`, `cardon-XXXXXX` under the OS
392
+ temp folder, a short name: on Windows, a deep path makes local Workflows lose instances past the
393
+ 260-character limit), removed by `dispose()`. Miniflare listens on a random port, so test files
394
+ run in parallel. A second `dispose()` does nothing.
395
+
396
+ When a process ends without reaching `dispose()` (a crash, Ctrl+C in watch mode, a `beforeAll`
397
+ that timed out, a missing `afterAll`), one `exit` listener removes the directories that process
398
+ created and has not removed (never another process's `cardon-*` folders: another test run may be
399
+ using them). It adds no signal handlers; a process killed outright (SIGKILL) leaves its
400
+ directories behind. If `dispose()` cannot remove the directory after its retries (on Windows,
401
+ workerd or an antivirus may still hold a file), it resolves anyway and emits one process warning
402
+ (`CARDON_TEST_STORAGE`) naming it; the `exit` listener tries again.
403
+
404
+ ### `applyMigrations(db, { dir } | { files })`
405
+
406
+ Applies migration files to a D1 database as `wrangler d1 migrations apply` does, and resolves to
407
+ the file names in the order applied:
408
+
409
+ - `dir`: a folder (a path, or a file URL such as `new URL("../migrations/", import.meta.url)`);
410
+ its `.sql` files are read, other files are ignored. `files`: file name → SQL, for migrations
411
+ loaded another way (a bundler's glob import).
412
+ - Files run in name order, each one in a single `batch`, so a file applies whole or not at all.
413
+ On a one-call D1 that is one request per file, whatever its number of statements; on the
414
+ direct binding each statement's `prepare` is a round trip too.
415
+ - A failing file rejects with `applyMigrations: <file> failed: <reason>` (the database's error is
416
+ its `cause`); the files after it are not applied. No files at all is an error too (a wrong
417
+ folder, say).
418
+
419
+ `statementsOf(sql)` is the split it uses, exported for code that runs a migration (or a seed
420
+ file) another way. It reads the file as SQL and follows Wrangler's split for Drizzle Kit output
421
+ and hand-written SQLite migrations:
422
+
423
+ - Strings (`'...'`, with `''` inside), quoted names (`"..."`, `` `...` ``, `[...]`), `--` line
424
+ comments and `/* */` block comments are recognised. Comments are dropped, outside strings
425
+ only: a `--` line inside a multi-line string stays, and a `;` inside a string, a name or a
426
+ comment never splits.
427
+ - A file with Drizzle Kit's `--> statement-breakpoint` is split on those only (each statement
428
+ keeps its `;`). A file without any is split on every `;`, except inside the `BEGIN ... END` of
429
+ a `CREATE TRIGGER`, so a trigger with several statements in its body is one statement.
430
+ - Windows line endings and a byte order mark are accepted; empty statements are skipped.
431
+ - It never throws: an unterminated string, name or block comment makes the rest of the file one
432
+ statement, so the database reports the error.
433
+
434
+ What it does not do: record the files applied (Wrangler's `d1_migrations` table), so
435
+ `applyMigrations` is for a fresh test database, applied once; and remove `BEGIN TRANSACTION` /
436
+ `COMMIT` (D1 refuses them in a migration).
437
+
438
+ ### `startWorker(options)`
439
+
440
+ Bundles a Worker entry with rolldown and runs it in workerd through Miniflare, for what only the
441
+ runtime has: Durable Objects (hibernation included), Workflows, `nodejs_compat`.
442
+
443
+ ```ts
444
+ import { startWorker, type TestWorker } from "@cardonjs/testing/miniflare";
445
+
446
+ let worker: TestWorker;
447
+ beforeAll(async () => {
448
+ worker = await startWorker({
449
+ entry: new URL("./test-worker.ts", import.meta.url),
450
+ compatibilityDate: "2026-07-01",
451
+ compatibilityFlags: ["nodejs_compat"], // only if the Worker needs it
452
+ durableObjects: { COUNTERS: "Counter" }, // binding → exported class
453
+ workflows: { ECHO: { name: "echo", className: "Echo" } },
454
+ d1: ["DB"],
455
+ bindings: { LABEL: "test-env" }, // vars
456
+ });
457
+ }, 60_000); // bundling and starting workerd take a few seconds
458
+ afterAll(async () => {
459
+ await worker?.dispose();
460
+ });
461
+
462
+ it("counts", async () => {
463
+ const res = await worker.fetch("/count/a", { method: "POST" }); // relative to worker.url
464
+ expect(await res.json()).toEqual({ value: 1 });
465
+ });
466
+ ```
467
+
468
+ - Options: `entry` (a file URL or a path; bundled as Wrangler would for workerd: `cloudflare:*`
469
+ and `node:*` stay external, the `workerd` export condition first) or `script` (one ES module,
470
+ bundled already: no bundling); `compatibilityDate` (required, so a test does not change with
471
+ the runtime) and `compatibilityFlags`; `bindings` (string vars), `d1` and `r2` (binding
472
+ names, each a new, empty database or bucket; a D1 binding may not be named
473
+ `CARDON_ONE_CALL_D1_TOKEN`, which the one-call D1 reserves), `durableObjects` (binding → class name,
474
+ SQLite-backed) and `workflows` (binding → `{ name, className }`).
475
+ - The result: `fetch(input, init?)` (Miniflare's `dispatchFetch`; a relative URL is resolved
476
+ against `url`; a WebSocket upgrade answers with `response.webSocket`), `url` (where workerd
477
+ listens, for clients over real HTTP or raw TCP), `d1(name)`, `r2(name)` and
478
+ `durableObject(name)` (the Worker's bindings seen from Node), `script` (the bundle: start the
479
+ same Worker with other options without bundling again), `directory` and `dispose()`.
480
+ - `d1(name)` is a one-call D1 over the Worker's database (its executor runs next to the Worker,
481
+ with the same databases bound and the Worker's compatibility date and flags), unless
482
+ `d1Binding: "direct"` is set; the Worker itself always uses the real binding.
483
+ - It rejects when workerd refuses the Worker (a `node:` import without `nodejs_compat`, for
484
+ example), and leaves nothing running then.
485
+
486
+ A relative string `entry`, or a relative `dir` of `applyMigrations`, is resolved against the
487
+ process's working directory (where the test runner was started), not against the test file:
488
+ prefer a URL relative to the file, `new URL("./test-worker.ts", import.meta.url)`.
489
+
490
+ Vitest's watch mode re-runs a test when a module it imports changes. Migrations read from disk
491
+ (`{ dir }`) are not modules, so add them to `forceRerunTriggers` in `vitest.config.ts` to re-run
492
+ the tests when one changes (the starter does):
493
+
494
+ ```ts
495
+ import { configDefaults, defineConfig } from "vitest/config";
496
+
497
+ export default defineConfig({
498
+ test: {
499
+ forceRerunTriggers: [...configDefaults.forceRerunTriggers, "**/migrations/**/*.sql"],
500
+ },
501
+ });
502
+ ```
503
+
504
+ ### `brokenD1()` and `brokenR2()`
505
+
506
+ Bindings with the shape of the real ones whose every call rejects (`D1_ERROR: Network
507
+ connection lost.`, `R2_ERROR: ...`), like a database or bucket that lost its connection: for
508
+ the error paths of code that uses them (a readiness check, a store that must report a failure
509
+ without leaking it). A binding from a disposed Miniflare cannot stand in: it throws on any
510
+ property access.
511
+
512
+ ### Many connections on Windows
513
+
514
+ Every closed connection stays in the operating system's `TIME_WAIT` state for a while (up to a
515
+ few minutes on Windows), holding a local port. Miniflare closes the connection after each
516
+ asynchronous call it carries (its `dispatchFetch` marks every request to workerd
517
+ `connection: close`; a caller cannot change it), so a suite that makes many such calls (R2,
518
+ Durable Objects, the direct D1 binding, requests to a test Worker) leaves that many connections
519
+ behind. The one-call D1 does not go through it, so D1 executions, usually most of the calls,
520
+ leave almost none.
521
+
522
+ On Windows, several heavy runs back to back can still use up the local ports. Tests that pass
523
+ alone then fail with `connect EADDRINUSE`, `fetch failed` or an error from Miniflare's proxy,
524
+ in tests that have nothing to do with the change, and at different places from one run to the
525
+ next. To tell it from a real failure, count the connections waiting (PowerShell
526
+ `(Get-NetTCPConnection -State TimeWait).Count`, or `netstat -an -p tcp | find /c "TIME_WAIT"`):
527
+ in the thousands, wait until it drops (a few minutes) and run again. A failure that stays at the
528
+ same test once the count is low is a real one.
529
+
530
+ ### When a fake is the better choice
531
+
532
+ Real bindings are for code whose correctness depends on the platform: SQL and migrations,
533
+ atomic batches, conditional writes, R2 metadata and ranges, Durable Object storage. Use the
534
+ in-memory fakes each interface package ships at `./testing` (`@cardonjs/storage/testing`,
535
+ `@cardonjs/realtime-do/testing`, `@cardonjs/workflows-cf/testing`, ...) when the test is about
536
+ your own logic around a binding: a route that publishes to a room, a workflow driven step by
537
+ step with `settle` and `timeOut`, a provider that leaves the machine (payments, email, push).
538
+ They are faster, need no Miniflare and let a test control time.
@@ -0,0 +1,72 @@
1
+ # Third-party notices
2
+
3
+ `@cardonjs/testing` is licensed under the MIT licence (see `LICENSE`). One part of it is adapted
4
+ from another project and stays under that project's licence.
5
+
6
+ ## workerd
7
+
8
+ The one-call D1 of `@cardonjs/testing/miniflare` (`dist/miniflare/one-call-d1.js`) reproduces in
9
+ Node what D1's binding does before a query leaves a Worker. Its parameter conversion (`d1Value`)
10
+ and the way `first` looks up a column are adapted from the D1 binding of
11
+ [workerd](https://github.com/cloudflare/workerd) (`src/cloudflare/internal/d1-api.ts`),
12
+ Copyright (c) Cloudflare, Inc., licensed under the Apache License, Version 2.0. The adapted code
13
+ was rewritten in this package's style and typed for Node; its behaviour is kept the same on
14
+ purpose.
15
+
16
+ ```
17
+ Apache License
18
+
19
+ Version 2.0, January 2004
20
+
21
+ http://www.apache.org/licenses/
22
+
23
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
24
+
25
+ 1. Definitions.
26
+
27
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
28
+
29
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
30
+
31
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
32
+
33
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
34
+
35
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
36
+
37
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
38
+
39
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
42
+
43
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
44
+
45
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
46
+
47
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
48
+
49
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
50
+
51
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
52
+
53
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
54
+
55
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
56
+
57
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
58
+
59
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
60
+
61
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
62
+
63
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
64
+
65
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
66
+
67
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
68
+
69
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
70
+
71
+ END OF TERMS AND CONDITIONS
72
+ ```