dynamo-bao 0.10.0 → 0.12.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 CHANGED
@@ -9,6 +9,83 @@ Each version heading links to the tag that was published to npm. Entries before
9
9
 
10
10
  ## [Unreleased]
11
11
 
12
+ ## [0.12.0] - 2026-12-03
13
+
14
+ Semver minor (0.12.0). Adds the `quiet: true` option on `Model.updateOp()` and
15
+ `Model.update()` for bookkeeping updates that write only the named plain
16
+ attributes; nothing existing changes behavior.
17
+
18
+ **Key format: no key code changed.** Primary keys, GSI keys, unique
19
+ constraint keys, iteration keys, `_searchText`, and tenant prefixes are built
20
+ identically to 0.11.0.
21
+
22
+ ### Added
23
+
24
+ - **`quiet: true` option on `Model.updateOp()` and `Model.update()`**:
25
+ - Writes only the named plain attributes (`ADD`, `SET`, `REMOVE`), skipping
26
+ `updateBeforeSave` field stamps (`ModifiedDateField`, `VersionField`, etc.)
27
+ and `_iter_*` rewrites — avoiding unwanted `modifiedAt` bumps and
28
+ unnecessary GSI pre-reads when `modifiedAt` is indexed.
29
+ - Skips `beforeSave` and `afterSave` hooks (and any `afterSave` read-back in
30
+ `transact()`) for that op while leaving other ops in the same transaction
31
+ unaffected.
32
+ - Preserves `condition`, the `attribute_exists` existence guard on missing
33
+ items, and request batch context cache eviction/priming.
34
+ - Refuses with `ValidationError` before sending if any named field is a
35
+ primary key, index key, unique-constraint field, search-text source,
36
+ server-generated (`VersionField`), immutable (`CreateDateField`), unknown,
37
+ empty, or combined with `forceReindex: true`. Also refused on `create()`,
38
+ `createOp()`, and `save()`.
39
+ - Handles no-op `StringSetField` quiet updates cleanly via `ConditionCheck`
40
+ without emitting an empty `UpdateExpression`.
41
+ - Updated `tutorials/12-transactions.md`, `README.md`, and generated JSDoc.
42
+
43
+ ## [0.11.0] - 2026-12-03
44
+
45
+ Semver minor (0.11.0). Adds multi-model atomic transactions via
46
+ `transact([...ops])` and model op builders; nothing existing changes behavior.
47
+
48
+ **Key format: no key code changed.** Primary keys, GSI keys, unique
49
+ constraint keys, iteration keys, `_searchText`, and tenant prefixes are built
50
+ identically to 0.10.0.
51
+
52
+ ### Added
53
+
54
+ - **`transact(ops, options?)`** exported from the root `dynamo-bao` entry point
55
+ for committing writes across multiple models atomically in a single DynamoDB
56
+ `TransactWriteItems` call.
57
+ - Enforces single-tenant transactions (refusing mixed ambient tenants or
58
+ mixed app/admin tenant-bound models), matching `documentClient` instances,
59
+ DynamoDB's 100-item flattened limit (counting unique-constraint items), and
60
+ distinct flattened `(TableName, _pk, _sk)` keys before sending.
61
+ - Reuses a single `ClientRequestToken` (caller-supplied or generated ULID)
62
+ and frozen `TransactItems` payload across network retries and jittered
63
+ backoff retries on pure `TransactionConflict` cancellations (default
64
+ `maxAttempts: 3`, `baseDelayMs: 25`). Condition check failures and mixed
65
+ conflict/condition cancellations are not retried.
66
+ - Accumulates write capacity into `getBatchContextCapacity().write`,
67
+ invalidates request batch context loader cache entries for mutated items
68
+ (including clearing cached `ObjectNotFound` misses on `createOp` and
69
+ propagating out of `fresh()`), and fires `afterSave` / `afterDelete` hooks
70
+ once per op in order only after commit (avoiding read-back on blind/atomic
71
+ updates unless an `afterSave` hook is registered).
72
+ - **Model op builders**: `Model.createOp(data, options?)`,
73
+ `Model.updateOp(id, changes, options?)`, `Model.deleteOp(id, options?)`, and
74
+ `Model.conditionCheckOp(id, condition)`. Each snapshots the active tenant
75
+ context at construction time (failing closed when tenancy is enabled without
76
+ a tenant) and shares write preparation with single-item `create()`,
77
+ `update()`, and `delete()`.
78
+ - **`Model.create(data, options?)`** now accepts optional `{ condition }` for
79
+ symmetry with `createOp`.
80
+ - **`TransactionCanceledError`** (exported on `exceptions`), mapping DynamoDB's
81
+ flat `CancellationReasons` back to logical `opIndex` with `code`/`reason`,
82
+ `failures` (including `role`, `constraintField`, and `itemNotFound`), and the
83
+ unmarshalled `ReturnValuesOnConditionCheckFailure` `item`.
84
+ - **Bundled DynamoDB client** (`src/dynamodb-client.js`): added
85
+ `ConditionCheck` marshalling in `TransactWriteCommand` and unmarshalling of
86
+ `CancellationReasons[i].Item` on `TransactionCanceledException`.
87
+ - **`tutorials/12-transactions.md`** and README documentation.
88
+
12
89
  ## [0.10.0] - 2026-11-07
13
90
 
14
91
  Semver minor (0.10.0). Adds the `dynamo-bao/remote` entry point; nothing
@@ -653,7 +730,9 @@ Initial release: single-table models with fields, GSIs, unique constraints,
653
730
  related fields, counters, TTL, filters, pagination, batch loading, hooks,
654
731
  YAML codegen and a table creation tool.
655
732
 
656
- [Unreleased]: https://github.com/aag1024/dynamo-bao/compare/v0.10.0...HEAD
733
+ [Unreleased]: https://github.com/aag1024/dynamo-bao/compare/v0.12.0...HEAD
734
+ [0.12.0]: https://github.com/aag1024/dynamo-bao/compare/v0.11.0...v0.12.0
735
+ [0.11.0]: https://github.com/aag1024/dynamo-bao/compare/v0.10.0...v0.11.0
657
736
  [0.10.0]: https://github.com/aag1024/dynamo-bao/compare/v0.9.0...v0.10.0
658
737
  [0.9.0]: https://github.com/aag1024/dynamo-bao/compare/v0.8.2...v0.9.0
659
738
  [0.8.2]: https://github.com/aag1024/dynamo-bao/compare/v0.8.1...v0.8.2
package/README.md CHANGED
@@ -21,6 +21,7 @@ Release notes are in [CHANGELOG.md](https://github.com/aag1024/dynamo-bao/blob/m
21
21
  - Model 1:1, 1:N, N:M relationships between objects
22
22
  - Efficiently load data: load related objects in parallel, cache data using loading contexts
23
23
  - Minimize race conditions: save diffs, version checks on save, atomic counters
24
+ - Atomic multi-model transactions with `transact([...ops])`, op builders (`createOp`, `updateOp`, `deleteOp`, `conditionCheckOp`), and conflict retries
24
25
  - Enforce unique constraints and use them for lookups
25
26
  - Built-in multi-tenancy support with complete data isolation and concurrency safety
26
27
  - Return total read/write consumed capacity (even when multiple operations were performed)
@@ -219,6 +220,37 @@ if ("ok" in r) console.log(r.ok.name);
219
220
 
220
221
  See [tutorial 11](tutorials/11-remote-procedures.md) for the contract (context, actor, outcomes, replay classes) and [`examples/cloudflare-remote-executor/`](examples/cloudflare-remote-executor/) for a complete Worker. TypeScript declarations ship with the entry point.
221
222
 
223
+ ### Multi-Model Transactions (`transact`)
224
+
225
+ Commit changes across multiple models atomically in a single DynamoDB `TransactWriteItems` call using op builders (`createOp`, `updateOp`, `deleteOp`, `conditionCheckOp`):
226
+
227
+ ```javascript
228
+ const { transact } = require("dynamo-bao");
229
+ const { TransactionCanceledError } = require("dynamo-bao").exceptions;
230
+
231
+ try {
232
+ await transact([
233
+ Document.updateOp(
234
+ docId,
235
+ { directShareCount: "+1" },
236
+ { condition: { directShareCount: { $lt: 1000 } }, quiet: true },
237
+ ),
238
+ DocumentPermission.createOp({ docId, userId, role: "editor" }),
239
+ ]);
240
+ } catch (err) {
241
+ if (err instanceof TransactionCanceledError) {
242
+ console.log("Cancelled at op", err.opIndex, err.code, err.item);
243
+ }
244
+ }
245
+ ```
246
+
247
+ - All-or-nothing commit with unique-constraint items, GSI keys, iteration keys, generated fields, and tenant prefixes built identically to single-item writes.
248
+ - Maps `TransactionCanceledException` reasons back to logical op indexes (including `ReturnValuesOnConditionCheckFailure` items) and retries `TransactionConflict` with jittered backoff.
249
+ - Runs `afterSave`/`afterDelete` hooks once per op in order only after commit, invalidates the request batch context cache, and refuses mixed tenants, duplicate keys, or more than 100 items.
250
+ - Pass `quiet: true` on `updateOp` or `update` to write only named plain attributes without touching `modifiedAt`/`version` or firing `beforeSave`/`afterSave` hooks.
251
+
252
+ See [tutorial 12](tutorials/12-transactions.md) for full details, options, error shapes, and limits.
253
+
222
254
  ### Batch Context Configuration
223
255
 
224
256
  DynamoBao provides flexible batch context behavior that can be configured based on your application's needs:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dynamo-bao",
3
- "version": "0.10.0",
3
+ "version": "0.12.0",
4
4
  "description": "Simple powerful data modeling primitives for DynamoDB in JavaScript.",
5
5
  "main": "src/index.js",
6
6
  "exports": {
@@ -238,7 +238,12 @@ class DynamoDBClient {
238
238
 
239
239
  // Add specific properties based on error type
240
240
  if (errorName === 'TransactionCanceledException' && errorBody.CancellationReasons) {
241
- error.CancellationReasons = errorBody.CancellationReasons;
241
+ error.CancellationReasons = errorBody.CancellationReasons.map(reason => {
242
+ if (reason && reason.Item) {
243
+ return { ...reason, Item: unmarshallItem(reason.Item) };
244
+ }
245
+ return reason;
246
+ });
242
247
  }
243
248
 
244
249
  // With ReturnValuesOnConditionCheckFailure, a failed condition check
@@ -421,6 +426,23 @@ class DynamoDBDocumentClient {
421
426
  newItem.Delete.ExpressionAttributeValues = marshalledValues;
422
427
  }
423
428
  }
429
+ if (item.ConditionCheck) {
430
+ const checkKey = {};
431
+ Object.keys(item.ConditionCheck.Key).forEach(key => {
432
+ checkKey[key] = marshall(item.ConditionCheck.Key[key]);
433
+ });
434
+ newItem.ConditionCheck = {
435
+ ...item.ConditionCheck,
436
+ Key: checkKey
437
+ };
438
+ if (item.ConditionCheck.ExpressionAttributeValues) {
439
+ const marshalledValues = {};
440
+ Object.keys(item.ConditionCheck.ExpressionAttributeValues).forEach(key => {
441
+ marshalledValues[key] = marshall(item.ConditionCheck.ExpressionAttributeValues[key]);
442
+ });
443
+ newItem.ConditionCheck.ExpressionAttributeValues = marshalledValues;
444
+ }
445
+ }
424
446
  return newItem;
425
447
  });
426
448
  }
package/src/exceptions.js CHANGED
@@ -102,6 +102,26 @@ class DetachedInstanceError extends BaoError {
102
102
  }
103
103
  }
104
104
 
105
+ /**
106
+ * Thrown when a DynamoDB TransactWriteItems call is cancelled (e.g.
107
+ * ConditionalCheckFailed, TransactionConflict). Maps DynamoDB's flat
108
+ * CancellationReasons back to the caller's logical op indexes.
109
+ */
110
+ class TransactionCanceledError extends BaoError {
111
+ constructor(message, { failures = [], cancellationReasons = [], cause = null } = {}) {
112
+ const primary = failures[0] || null;
113
+ super(message, primary ? primary.code : null);
114
+ this.failures = failures;
115
+ this.cancellationReasons = cancellationReasons;
116
+ this.opIndex = primary ? primary.opIndex : null;
117
+ this.reason = primary ? primary.code : null;
118
+ this.item = primary && primary.item !== undefined ? primary.item : undefined;
119
+ if (cause) {
120
+ this.cause = cause;
121
+ }
122
+ }
123
+ }
124
+
105
125
  module.exports = {
106
126
  BaoError,
107
127
  ConfigurationError,
@@ -111,4 +131,5 @@ module.exports = {
111
131
  ConditionalError,
112
132
  DataFormatError,
113
133
  DetachedInstanceError,
134
+ TransactionCanceledError,
114
135
  };
package/src/index.js CHANGED
@@ -21,6 +21,7 @@ const {
21
21
  runWithBatchContext,
22
22
  getBatchContextCapacity,
23
23
  } = require("./mixins/batch-loading-mixin");
24
+ const { transact } = require("./transact");
24
25
 
25
26
  function findModelFiles(dir) {
26
27
  let results = [];
@@ -229,6 +230,9 @@ const firstExport = {
229
230
  runWithBatchContext,
230
231
  getBatchContextCapacity,
231
232
 
233
+ // Multi-model transactions
234
+ transact,
235
+
232
236
  // Configurations
233
237
  PrimaryKeyConfig,
234
238
  IndexConfig,