@adobe-commerce/aio-toolkit 1.1.1 → 1.2.1

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
@@ -5,6 +5,100 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.2.1] - 2026-03-31
9
+
10
+ ### ✨ Features
11
+
12
+ - **feat(abdb): Add `AbdbRepository` — generic CRUD repository for `AbdbCollection`**
13
+
14
+ A typed, token-aware repository layer that wraps any `AbdbCollection` and exposes a clean CRUD surface without requiring callers to manage tokens, regions, or raw DB connections per call.
15
+
16
+ #### `AbdbRepository`
17
+
18
+ Generic repository class that holds the IMS token and region for its lifetime, auto-stamps `_created_at` / `_updated_at`, and validates every payload against the collection schema before touching the database.
19
+
20
+ **Single-document operations:**
21
+
22
+ - `save(payload)` — insert with full schema validation; stamps `_created_at` and `_updated_at`; returns new `_id`
23
+ - `save(payload, id)` — partial update by `_id`; stamps `_updated_at`; only validates fields present in the payload (absent required fields are not re-enforced); returns the same `id`
24
+ - `findOne(filter)` — returns the first document matching an arbitrary filter (e.g. `{ _id: 'x' }` or `{ email: 'a@b.com' }`), or `null`
25
+ - `find(filter?)` — returns all documents matching an optional filter; defaults to all documents
26
+ - `exists(id)` — lightweight existence check via `countDocuments`; returns `boolean`
27
+ - `delete(id)` — deletes by `_id`; no-ops silently for empty id
28
+ - `count(filter?)` — counts matching documents; defaults to all documents
29
+
30
+ **Bulk operations (single DB round-trip each):**
31
+
32
+ - `insertAll(payloads[])` — bulk insert via `insertMany`; each payload is stamped and fully validated before the DB call; returns array of inserted ids
33
+ - `updateAll(payload, filter?)` — bulk partial update via `updateMany`; stamps `_updated_at`; partial validation on present fields only
34
+ - `deleteAll(filter?)` — bulk delete via `deleteMany`; defaults to all documents
35
+
36
+ **Accessors:**
37
+
38
+ - `getName()` — returns the underlying collection name
39
+ - `getCollection()` — returns the underlying `AbdbCollection` instance
40
+
41
+ #### Automatic timestamp management
42
+
43
+ The constructor registers `_created_at` and `_updated_at` columns on the collection exactly once — re-using the same collection across multiple repository instances (e.g. different tokens or regions) is safe.
44
+
45
+ #### Partial update validation
46
+
47
+ The update path (`save(payload, id)` and `updateAll`) uses `_validatePartial`, which checks only the columns present in the payload. Required columns that are absent are not re-enforced because they already exist in the stored document. This prevents spurious validation failures when doing field-level patches.
48
+
49
+ ### 📖 Documentation
50
+
51
+ - **`@adobe/aio-lib-db` declared as required peer dependency** — added to the top-level installation command, peer dependencies table, individual install steps, App Builder `npm list` check command, and ERESOLVE upgrade guide in the README
52
+ - **Database provisioning guide added** — declarative `app.config.yaml` provisioning and `aio app db provision` CLI command documented as step 1 of the `AbdbCollection` usage guide
53
+ - **Authentication guide added** — `generateAccessToken` pattern with `include-ims-credentials` annotation documented as step 2; runtime action example updated to use real token generation instead of a placeholder comment
54
+ - **`AbdbRepository` section added to README** — covers basic usage, automatic timestamps, full API reference tables (single-document and bulk operations), custom region, and bulk operation examples
55
+ - **Fixed `RuntimeApiGatewayService` constructor call** in `test/framework/index.test.ts` — was passing 7 arguments copied from `ImsToken`; corrected to the actual 3-argument signature `(namespace, imsOrgId, imsToken)`
56
+
57
+ ## [1.2.0] - 2026-03-30
58
+
59
+ ### ✨ Features
60
+
61
+ - **feat(abdb): Add `AbdbColumn` and `AbdbCollection` framework components**
62
+
63
+ Two new framework components that provide a typed schema definition layer and managed database connectivity via `@adobe/aio-lib-db`.
64
+
65
+ #### `AbdbColumn`
66
+
67
+ Immutable field definition class for describing a single column in an ABDB document schema.
68
+
69
+ - Supports four value types: `STRING`, `NUMBER`, `BOOLEAN`, `DATETIME`
70
+ - Comprehensive type coercion rules — accepts numeric strings, `"true"/"false"` strings, ISO 8601 date strings, finite numeric timestamps, and `Date` objects
71
+ - Required field enforcement via `isRequired` flag
72
+ - `validate(value)` — throws on the first type or requiredness violation
73
+ - `clone(overrides?)` — derives a new immutable instance with overridden fields
74
+ - `toJSON()` — serializes to a plain `AbdbColumnJson` object
75
+ - Fully immutable after construction (`Object.freeze`)
76
+ - Exhaustive `switch` guard via TypeScript `never` — compile-time safety if a new type is added without updating the validator
77
+
78
+ #### `AbdbCollection`
79
+
80
+ Named schema container with fluent column registration, validation, and a managed Adobe I/O DB lifecycle.
81
+
82
+ - `addColumn(name, type, description?, isRequired?)` — **positional form** (backward-compatible short syntax)
83
+ - `addColumn(name, type, options?)` — **options-object form** — no `undefined` placeholder needed to set only `isRequired`
84
+ - `getColumn(name)` — O(1) single-column lookup; returns `undefined` if not found
85
+ - `hasColumn(name)` — O(1) existence check
86
+ - `getColumns()` — defensive copy in insertion order
87
+ - `validate(record)` — fail-fast; throws on the **first** failing column
88
+ - `validateAll(record)` — collects **all** column errors; returns `string[]` — ideal for API error responses
89
+ - `run<T>(callback, token, region?)` — opens `@adobe/aio-lib-db` connection, invokes callback with `(collection, client)`, closes in `finally`
90
+
91
+ #### Types exported
92
+
93
+ | Type | Description |
94
+ |---|---|
95
+ | `AbdbColumnType` | String enum: `STRING \| NUMBER \| BOOLEAN \| DATETIME` |
96
+ | `AbdbColumnOptions` | Constructor input shape for `AbdbColumn` |
97
+ | `AbdbColumnJson` | `toJSON()` output shape |
98
+ | `AddColumnOptions` | `Omit<AbdbColumnOptions, 'name' \| 'type'>` — options-object form for `addColumn` |
99
+ | `AbdbCollectionCallback` | Constructor setup callback `(collection: AbdbCollection) => void` |
100
+ | `AbdbRunCallback<T>` | Async work callback for `run()` |
101
+
8
102
  ## [1.1.1] - 2026-03-28
9
103
 
10
104
  ### 🐛 Bug Fixes
package/README.md CHANGED
@@ -9,6 +9,7 @@ A comprehensive TypeScript toolkit for Adobe App Builder applications providing
9
9
  ```bash
10
10
  npm install @adobe-commerce/aio-toolkit \
11
11
  @adobe/aio-sdk \
12
+ @adobe/aio-lib-db \
12
13
  @adobe/aio-lib-ims \
13
14
  @adobe/aio-lib-telemetry \
14
15
  @opentelemetry/resources \
@@ -675,6 +676,275 @@ This approach provides:
675
676
  - **Flexible ID management**: Support for explicit IDs, payload IDs, and auto-generation
676
677
  - **Automatic sanitization**: IDs are cleaned to ensure file system compatibility
677
678
 
679
+ #### `AbdbColumn` & `AbdbCollection`
680
+
681
+ Typed schema definition and managed database connectivity via `@adobe/aio-lib-db`.
682
+
683
+ The recommended pattern is to create a dedicated collection class per entity by extending `AbdbCollection`, then use it directly inside runtime actions.
684
+
685
+ ##### 1. Provision a database
686
+
687
+ A database must be provisioned before any collection can connect. There are two ways to do this:
688
+
689
+ **Declarative provisioning via `app.config.yaml`** (runs on `aio app deploy`):
690
+
691
+ ```yaml
692
+ application:
693
+ runtimeManifest:
694
+ database:
695
+ auto-provision: true
696
+ region: emea
697
+ ```
698
+
699
+ When the application is deployed with `aio app deploy`, a database is provisioned in the specified region unless one is already present. Declarative provisioning does **not** run during `aio app run` or `aio app dev`, so the database must be provisioned manually for local development (see below).
700
+
701
+ **Manual provisioning via the AIO CLI:**
702
+
703
+ ```bash
704
+ aio app db provision [--region <area>]
705
+ ```
706
+
707
+ ##### 2. Configure authentication
708
+
709
+ Every `@adobe/aio-lib-db` call requires an IMS access token. The recommended approach is to use `@adobe/aio-sdk`, which handles token caching and refresh automatically:
710
+
711
+ ```javascript
712
+ const { generateAccessToken } = require('@adobe/aio-sdk').Core.AuthClient;
713
+ const libDb = require('@adobe/aio-lib-db');
714
+
715
+ async function main(params) {
716
+ const token = await generateAccessToken(params);
717
+ const db = await libDb.init({ token: token.access_token });
718
+ }
719
+ ```
720
+
721
+ **Requirements:**
722
+
723
+ - The AIO project workspace must include the **App Builder Data Services API**.
724
+ - The runtime action must have the `include-ims-credentials` annotation set to `true` in `app.config.yaml`:
725
+
726
+ ```yaml
727
+ actions:
728
+ action:
729
+ function: actions/generic/action.js
730
+ annotations:
731
+ include-ims-credentials: true
732
+ ```
733
+
734
+ > `@adobe/aio-sdk` transparently manages token caching and refresh — you do not need to implement this yourself.
735
+
736
+ ##### 3. Define a custom collection
737
+
738
+ Create a reusable collection class that declares the schema once:
739
+
740
+ ```javascript
741
+ // src/collections/UserCollection.js
742
+ 'use strict';
743
+
744
+ const { AbdbCollection, AbdbColumnType } = require('@adobe-commerce/aio-toolkit');
745
+
746
+ /**
747
+ * ABDB collection for the `users` table.
748
+ *
749
+ * Columns:
750
+ * - `first_name` (STRING, required)
751
+ * - `last_name` (STRING, required)
752
+ * - `email` (STRING, required)
753
+ */
754
+ class UserCollection extends AbdbCollection {
755
+ constructor() {
756
+ super('users', (c) => {
757
+ c.addColumn('first_name', AbdbColumnType.STRING, 'First name', true)
758
+ .addColumn('last_name', AbdbColumnType.STRING, 'Last name', true)
759
+ .addColumn('email', AbdbColumnType.STRING, 'Email address', true);
760
+ });
761
+ }
762
+ }
763
+
764
+ module.exports = UserCollection;
765
+ ```
766
+
767
+ ##### 4. Use it in a runtime action
768
+
769
+ ```javascript
770
+ const { HttpMethod, RuntimeAction, RuntimeActionResponse } = require('@adobe-commerce/aio-toolkit');
771
+ const { generateAccessToken } = require('@adobe/aio-sdk').Core.AuthClient;
772
+ const UserCollection = require('@lib/UserCollection');
773
+
774
+ exports.main = RuntimeAction.execute(
775
+ 'users-create',
776
+ [HttpMethod.POST],
777
+ ['first_name', 'last_name', 'email'],
778
+ ['Authorization'],
779
+ async (params, ctx) => {
780
+ const { first_name, last_name, email } = params;
781
+ const { logger } = ctx;
782
+
783
+ const token = await generateAccessToken(params);
784
+ const accessToken = token.access_token;
785
+
786
+ const users = new UserCollection();
787
+
788
+ // Fail-fast validation — throws before touching the DB
789
+ users.validate({ first_name, last_name, email });
790
+
791
+ // Open DB connection, run the operation, close in finally
792
+ const result = await users.run(async (collection) => {
793
+ return await collection.insertOne({ first_name, last_name, email });
794
+ }, accessToken);
795
+
796
+ logger.info(`User inserted: ${result.insertedId}`);
797
+
798
+ return RuntimeActionResponse.success(result);
799
+ }
800
+ );
801
+ ```
802
+
803
+ ##### 5. API surface reference
804
+
805
+ **`addColumn` call forms:**
806
+
807
+ ```javascript
808
+ // Positional (short form) — description and isRequired are optional positional args
809
+ c.addColumn('email', AbdbColumnType.STRING, 'Email address', true);
810
+
811
+ // Options-object form — no undefined placeholder needed when setting only one option
812
+ c.addColumn('email', AbdbColumnType.STRING, { isRequired: true });
813
+ c.addColumn('note', AbdbColumnType.STRING, { description: 'An optional note' });
814
+ ```
815
+
816
+ **Supported types (`AbdbColumnType`):**
817
+
818
+ | Value | Accepts |
819
+ |---|---|
820
+ | `STRING` | Primitive string |
821
+ | `NUMBER` | Finite number, or numeric string (e.g. `"3.14"`) |
822
+ | `BOOLEAN` | `true`/`false`, or `"true"`/`"false"` (case-insensitive) |
823
+ | `DATETIME` | `Date`, finite timestamp (ms), or ISO 8601 string |
824
+
825
+ **Validation strategies:**
826
+
827
+ ```javascript
828
+ // Fail-fast — throws on the first error (use before DB writes)
829
+ users.validate({ first_name: 'Jane', last_name: 'Doe', email: 'jane@example.com' });
830
+
831
+ // Collect all errors — ideal for API validation responses
832
+ const errors = users.validateAll({ first_name: '', email: 'not-an-email' });
833
+ // errors → ['"first_name" expects a string', '"last_name" is required']
834
+ ```
835
+
836
+ **Column introspection:**
837
+
838
+ ```javascript
839
+ users.hasColumn('email'); // true
840
+ users.getColumn('email'); // AbdbColumn instance (or undefined)
841
+ users.getColumns(); // Map<string, AbdbColumn> in insertion order
842
+ ```
843
+
844
+ #### `AbdbRepository`
845
+
846
+ A generic CRUD repository that wraps an `AbdbCollection` and holds the IMS token and region for the lifetime of the instance. All write methods validate payloads against the collection schema before touching the database, and `_created_at` / `_updated_at` timestamps are stamped automatically.
847
+
848
+ ##### Basic usage
849
+
850
+ ```javascript
851
+ const { AbdbRepository, AbdbColumnType } = require('@adobe-commerce/aio-toolkit');
852
+ const { generateAccessToken } = require('@adobe/aio-sdk').Core.AuthClient;
853
+ const UserCollection = require('@lib/UserCollection');
854
+
855
+ exports.main = async (params) => {
856
+ const token = await generateAccessToken(params);
857
+ const accessToken = token.access_token;
858
+
859
+ const repo = new AbdbRepository(new UserCollection(), accessToken);
860
+
861
+ // Insert — returns the new document _id
862
+ const id = await repo.save({ first_name: 'Jane', last_name: 'Doe', email: 'jane@example.com' });
863
+
864
+ // Read one by _id
865
+ const doc = await repo.findOne({ _id: id });
866
+
867
+ // Read one by any field
868
+ const byEmail = await repo.findOne({ email: 'jane@example.com' });
869
+
870
+ // Read all (optional filter)
871
+ const all = await repo.find();
872
+ const active = await repo.find({ active: true });
873
+
874
+ // Partial update — only provided fields are validated; required fields already in the DB are not re-checked
875
+ await repo.save({ first_name: 'Janet' }, id);
876
+
877
+ // Delete
878
+ await repo.delete(id);
879
+ };
880
+ ```
881
+
882
+ ##### Automatic timestamps
883
+
884
+ The repository automatically registers two extra columns on the collection:
885
+
886
+ | Column | Set on | Value |
887
+ |---|---|---|
888
+ | `_created_at` | First insert only | ISO 8601 UTC string |
889
+ | `_updated_at` | Every insert and update | ISO 8601 UTC string |
890
+
891
+ These are added once per collection instance, so re-using the same collection across multiple repository instances is safe.
892
+
893
+ ##### API reference
894
+
895
+ **Single-document operations:**
896
+
897
+ | Method | Description | Returns |
898
+ |---|---|---|
899
+ | `save(payload)` | Insert a new document (full validation) | `Promise<string>` — new `_id` |
900
+ | `save(payload, id)` | Partial update by `_id` (only present fields validated) | `Promise<string>` — same `id` |
901
+ | `findOne(filter)` | First document matching filter, e.g. `{ _id: 'x' }` | `Promise<T \| null>` |
902
+ | `find(filter?)` | All documents matching filter (default: all) | `Promise<T[]>` |
903
+ | `exists(id)` | Lightweight existence check via `countDocuments` | `Promise<boolean>` |
904
+ | `delete(id)` | Delete document by `_id`; no-ops for empty id | `Promise<void>` |
905
+ | `count(filter?)` | Count matching documents (default: all) | `Promise<number>` |
906
+
907
+ **Bulk operations (single DB round-trip each):**
908
+
909
+ | Method | Description | Returns |
910
+ |---|---|---|
911
+ | `insertAll(payloads[])` | Bulk insert via `insertMany` — each payload stamped and validated | `Promise<string[]>` — inserted ids |
912
+ | `updateAll(payload, filter?)` | Bulk partial update via `updateMany` — stamps `_updated_at` | `Promise<void>` |
913
+ | `deleteAll(filter?)` | Bulk delete via `deleteMany` (default: all documents) | `Promise<void>` |
914
+
915
+ **Accessors:**
916
+
917
+ | Method | Description |
918
+ |---|---|
919
+ | `getName()` | Returns the underlying collection name |
920
+ | `getCollection()` | Returns the underlying `AbdbCollection` instance |
921
+
922
+ ##### Custom region
923
+
924
+ ```javascript
925
+ // Default region is 'amer'. Pass a third argument to override:
926
+ const repo = new AbdbRepository(new UserCollection(), accessToken, 'emea');
927
+ ```
928
+
929
+ ##### Bulk operations
930
+
931
+ ```javascript
932
+ // Insert multiple documents in one DB call
933
+ const ids = await repo.insertAll([
934
+ { first_name: 'Alice', last_name: 'Smith', email: 'alice@example.com' },
935
+ { first_name: 'Bob', last_name: 'Jones', email: 'bob@example.com' },
936
+ ]);
937
+
938
+ // Update all matching documents in one DB call
939
+ await repo.updateAll({ active: false }, { email: 'bob@example.com' });
940
+
941
+ // Delete all matching documents in one DB call
942
+ await repo.deleteAll({ active: false });
943
+
944
+ // Delete everything in the collection
945
+ await repo.deleteAll();
946
+ ```
947
+
678
948
  ### 🏪 Commerce Components
679
949
 
680
950
  **Adobe Commerce API integration and authentication**
@@ -1780,12 +2050,13 @@ Packages that maintain **singleton state or shared registries** — if two copie
1780
2050
  | Package | Why it must be shared |
1781
2051
  |---|---|
1782
2052
  | `@adobe/aio-sdk` | Singleton services — logger, config, state are shared across the app |
2053
+ | `@adobe/aio-lib-db` | Database client singleton — connection state and collection registry must be shared |
1783
2054
  | `graphql` | Schema registry is a singleton — `instanceof GraphQLSchema` and type checks fail with two copies |
1784
2055
  | `@adobe/aio-lib-ims` | Token cache and auth context must be the same shared instance |
1785
2056
  | `@adobe/aio-lib-telemetry` | Single telemetry pipeline — two copies split traces and logs |
1786
2057
  | `@opentelemetry/resources` | Resource object tied to the telemetry pipeline instance |
1787
2058
 
1788
- All five are **required** — they are unconditionally imported when the package loads (`export * from './framework'` and `export * from './commerce'` in the root `index.ts`). If any is missing, the entire package will fail to load with a `Cannot find module` error.
2059
+ All six are **required** — they are unconditionally imported when the package loads (`export * from './framework'` and `export * from './commerce'` in the root `index.ts`). If any is missing, the entire package will fail to load with a `Cannot find module` error.
1789
2060
 
1790
2061
  ### Installing peer dependencies
1791
2062
 
@@ -1794,6 +2065,7 @@ Install the toolkit and all required peer dependencies in one command:
1794
2065
  ```bash
1795
2066
  npm install @adobe-commerce/aio-toolkit \
1796
2067
  @adobe/aio-sdk \
2068
+ @adobe/aio-lib-db \
1797
2069
  @adobe/aio-lib-ims \
1798
2070
  @adobe/aio-lib-telemetry \
1799
2071
  @opentelemetry/resources \
@@ -1806,14 +2078,15 @@ Or individually if you prefer to control versions:
1806
2078
  npm install @adobe-commerce/aio-toolkit
1807
2079
 
1808
2080
  # Required peer dependencies
1809
- npm install @adobe/aio-sdk@^5.0.0
2081
+ npm install @adobe/aio-sdk@^6.0.0
2082
+ npm install @adobe/aio-lib-db@^1.0.0
1810
2083
  npm install @adobe/aio-lib-ims@^7.0.0
1811
2084
  npm install @adobe/aio-lib-telemetry@^1.0.0
1812
2085
  npm install @opentelemetry/resources@^2.0.0
1813
2086
  npm install graphql@^16.0.0
1814
2087
  ```
1815
2088
 
1816
- > **Note for App Builder projects:** `@adobe/aio-sdk`, `graphql`, and `@adobe/aio-lib-ims` are almost always already present in a standard App Builder project. Run `npm list @adobe/aio-sdk graphql @adobe/aio-lib-ims` to check before installing.
2089
+ > **Note for App Builder projects:** `@adobe/aio-sdk`, `graphql`, and `@adobe/aio-lib-ims` are almost always already present in a standard App Builder project. Run `npm list @adobe/aio-sdk @adobe/aio-lib-db graphql @adobe/aio-lib-ims` to check before installing.
1817
2090
 
1818
2091
  ### Resolving `ERESOLVE` errors
1819
2092
 
@@ -1828,9 +2101,12 @@ npm install @adobe-commerce/aio-toolkit 2>&1 | grep "Found:"
1828
2101
  **Upgrade the conflicting package to a compatible version:**
1829
2102
 
1830
2103
  ```bash
1831
- # @adobe/aio-sdk must be >=5.0.0
2104
+ # @adobe/aio-sdk must be >=6.0.0
1832
2105
  npm install @adobe/aio-sdk@latest
1833
2106
 
2107
+ # @adobe/aio-lib-db must be >=1.0.0
2108
+ npm install @adobe/aio-lib-db@latest
2109
+
1834
2110
  # graphql must be >=14.0.0
1835
2111
  npm install graphql@latest
1836
2112
 
package/dist/index.d.mts CHANGED
@@ -1,4 +1,5 @@
1
1
  import openwhisk, { Dict, Activation } from 'openwhisk';
2
+ import { DbCollection, DbClient } from '@adobe/aio-lib-db';
2
3
  import { EntrypointInstrumentationConfig } from '@adobe/aio-lib-telemetry';
3
4
  import { LogRecordProcessor } from '@opentelemetry/sdk-logs';
4
5
  import { SdkLogRecord } from '@adobe/aio-lib-telemetry/otel';
@@ -202,6 +203,94 @@ declare class FileRepository {
202
203
  private getFiles;
203
204
  }
204
205
 
206
+ declare enum AbdbColumnType {
207
+ STRING = "STRING",
208
+ NUMBER = "NUMBER",
209
+ BOOLEAN = "BOOLEAN",
210
+ DATETIME = "DATETIME"
211
+ }
212
+ interface AbdbColumnOptions {
213
+ name: string;
214
+ type: AbdbColumnType;
215
+ description?: string;
216
+ isRequired?: boolean;
217
+ }
218
+ interface AbdbColumnJson {
219
+ name: string;
220
+ type: AbdbColumnType;
221
+ description?: string;
222
+ isRequired?: true;
223
+ }
224
+
225
+ declare class AbdbColumn {
226
+ private readonly _name;
227
+ private readonly _type;
228
+ private readonly _description;
229
+ private readonly _isRequired;
230
+ constructor(options: AbdbColumnOptions);
231
+ getName(): string;
232
+ getType(): AbdbColumnType;
233
+ getDescription(): string | undefined;
234
+ getIsRequired(): boolean;
235
+ toJSON(): AbdbColumnJson;
236
+ clone(overrides?: Partial<AbdbColumnOptions>): AbdbColumn;
237
+ validate(value: unknown): void;
238
+ private _isMissingValue;
239
+ private _validateStringValue;
240
+ private _validateNumberValue;
241
+ private _validateBooleanValue;
242
+ private _validateDateTimeValue;
243
+ }
244
+
245
+ type AddColumnOptions = Omit<AbdbColumnOptions, 'name' | 'type'>;
246
+ type AbdbRunCallback<T = unknown> = (collection: DbCollection, client: DbClient) => Promise<T>;
247
+
248
+ type AbdbCollectionCallback = (collection: AbdbCollection) => void;
249
+ declare class AbdbCollection {
250
+ private readonly _name;
251
+ private readonly _columns;
252
+ constructor(name: string, callback?: AbdbCollectionCallback);
253
+ getName(): string;
254
+ addColumn(name: string, type: AbdbColumnType, options?: AddColumnOptions): this;
255
+ addColumn(name: string, type: AbdbColumnType, description?: string, isRequired?: boolean): this;
256
+ getColumns(): AbdbColumn[];
257
+ getColumn(name: string): AbdbColumn | undefined;
258
+ hasColumn(name: string): boolean;
259
+ validate(record: Record<string, unknown>): void;
260
+ validateAll(record: Record<string, unknown>): string[];
261
+ run<T>(callback: AbdbRunCallback<T>, token: string, region?: string): Promise<T>;
262
+ private _validateCollectionName;
263
+ private _validateColumnName;
264
+ private _validateIdentifier;
265
+ }
266
+
267
+ interface AbdbRecord {
268
+ _id?: string;
269
+ _created_at?: string;
270
+ _updated_at?: string;
271
+ [key: string]: unknown;
272
+ }
273
+ type AbdbRepositoryFilter = Record<string, unknown>;
274
+
275
+ declare class AbdbRepository<T extends AbdbRecord = AbdbRecord> {
276
+ private readonly _collection;
277
+ private readonly _token;
278
+ private readonly _region;
279
+ constructor(collection: AbdbCollection, token: string, region?: string);
280
+ getName(): string;
281
+ getCollection(): AbdbCollection;
282
+ find(filter?: AbdbRepositoryFilter): Promise<T[]>;
283
+ findOne(filter: AbdbRepositoryFilter): Promise<T | null>;
284
+ exists(id: string): Promise<boolean>;
285
+ count(filter?: AbdbRepositoryFilter): Promise<number>;
286
+ save(payload?: Partial<T>, id?: string): Promise<string>;
287
+ delete(id?: string): Promise<void>;
288
+ insertAll(payloads: Array<Partial<T>>): Promise<string[]>;
289
+ updateAll(payload: Partial<T>, filter?: AbdbRepositoryFilter): Promise<void>;
290
+ deleteAll(filter?: AbdbRepositoryFilter): Promise<void>;
291
+ private _validatePartial;
292
+ }
293
+
205
294
  interface EventData {
206
295
  type: string;
207
296
  data: any;
@@ -989,4 +1078,4 @@ declare class AdminUiSdk {
989
1078
  getRegistration(): AdminUiSdkRegistration;
990
1079
  }
991
1080
 
992
- export { AdminUiSdk, type AdminUiSdkRegistration, AdobeAuth, AdobeCommerceClient, type AdobeIMSConfig, type BaseTelemetry, type BaseTelemetryValidator, BasicAuthConnection, BearerToken, type BearerTokenInfo, type CommerceEvent, type CommerceEventConfig, type CommerceEventField, type Connection, type CreateEventResult, CreateEvents, type CreateProviderParams, type CreateProviderResult, type CreateRegistrationResult, CreateRegistrations, type ErrorResponse, EventConsumerAction, type EventData, type EventMetadata, type EventMetadataInputModel, type EventMetadataListResponse, EventMetadataManager, type ExtendedRequestError, type FileMetadata, type FileRecord, FileRepository, GenerateBasicAuthToken, type GetProviderQueryParams, type GetRegistrationQueryParams, GraphQlAction, type HALLink, type Headers, HttpMethod, HttpStatus, IOEventsApiError, type IOEventsError, ImsConnection, ImsToken, type ImsTokenResult, InfiniteLoopBreaker, type InfiniteLoopData, IoEventsGlobals, JsonMessageProcessor, type ListProvidersQueryParams, type ListRegistrationQueryParams, type MenuItem, Oauth1aConnection, OnboardCommerce, type OnboardCommerceConfig, type OnboardCommerceResult, OnboardEvents, type OnboardEventsInput, type OnboardEventsResponse, OnboardEvents as OnboardIOEvents, Openwhisk, OpenwhiskAction, type OpenwhiskConfig, type Page, Parameters, type Provider, type ProviderInputModel, ProviderManager, PublishEvent, type PublishEventResult, type Registration, type RegistrationCreateModel, type RegistrationListResponse, RegistrationManager, RestClient, RuntimeAction, RuntimeActionResponse, type RuntimeActionResponseType, RuntimeApiGatewayService, ShippingCarrier, type ShippingCarrierData, ShippingCarrierMethod, type ShippingCarrierMethodAdditionalData, type ShippingCarrierMethodData, ShippingCarrierResponse, SignatureVerification, SuccessChecker, type SuccessResponse, Telemetry, TelemetryInputError, type TokenResult, Validator, WebhookAction, type WebhookActionAddResponse, type WebhookActionExceptionResponse, WebhookActionOperation, type WebhookActionRemoveResponse, type WebhookActionReplaceResponse, WebhookActionResponse, type WebhookActionResponseType, type WebhookActionSuccessResponse, type WorkspaceConfig };
1081
+ export { AbdbCollection, type AbdbCollectionCallback, AbdbColumn, type AbdbColumnJson, type AbdbColumnOptions, AbdbColumnType, type AbdbRecord, AbdbRepository, type AbdbRepositoryFilter, type AbdbRunCallback, type AddColumnOptions, AdminUiSdk, type AdminUiSdkRegistration, AdobeAuth, AdobeCommerceClient, type AdobeIMSConfig, type BaseTelemetry, type BaseTelemetryValidator, BasicAuthConnection, BearerToken, type BearerTokenInfo, type CommerceEvent, type CommerceEventConfig, type CommerceEventField, type Connection, type CreateEventResult, CreateEvents, type CreateProviderParams, type CreateProviderResult, type CreateRegistrationResult, CreateRegistrations, type ErrorResponse, EventConsumerAction, type EventData, type EventMetadata, type EventMetadataInputModel, type EventMetadataListResponse, EventMetadataManager, type ExtendedRequestError, type FileMetadata, type FileRecord, FileRepository, GenerateBasicAuthToken, type GetProviderQueryParams, type GetRegistrationQueryParams, GraphQlAction, type HALLink, type Headers, HttpMethod, HttpStatus, IOEventsApiError, type IOEventsError, ImsConnection, ImsToken, type ImsTokenResult, InfiniteLoopBreaker, type InfiniteLoopData, IoEventsGlobals, JsonMessageProcessor, type ListProvidersQueryParams, type ListRegistrationQueryParams, type MenuItem, Oauth1aConnection, OnboardCommerce, type OnboardCommerceConfig, type OnboardCommerceResult, OnboardEvents, type OnboardEventsInput, type OnboardEventsResponse, OnboardEvents as OnboardIOEvents, Openwhisk, OpenwhiskAction, type OpenwhiskConfig, type Page, Parameters, type Provider, type ProviderInputModel, ProviderManager, PublishEvent, type PublishEventResult, type Registration, type RegistrationCreateModel, type RegistrationListResponse, RegistrationManager, RestClient, RuntimeAction, RuntimeActionResponse, type RuntimeActionResponseType, RuntimeApiGatewayService, ShippingCarrier, type ShippingCarrierData, ShippingCarrierMethod, type ShippingCarrierMethodAdditionalData, type ShippingCarrierMethodData, ShippingCarrierResponse, SignatureVerification, SuccessChecker, type SuccessResponse, Telemetry, TelemetryInputError, type TokenResult, Validator, WebhookAction, type WebhookActionAddResponse, type WebhookActionExceptionResponse, WebhookActionOperation, type WebhookActionRemoveResponse, type WebhookActionReplaceResponse, WebhookActionResponse, type WebhookActionResponseType, type WebhookActionSuccessResponse, type WorkspaceConfig };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import openwhisk, { Dict, Activation } from 'openwhisk';
2
+ import { DbCollection, DbClient } from '@adobe/aio-lib-db';
2
3
  import { EntrypointInstrumentationConfig } from '@adobe/aio-lib-telemetry';
3
4
  import { LogRecordProcessor } from '@opentelemetry/sdk-logs';
4
5
  import { SdkLogRecord } from '@adobe/aio-lib-telemetry/otel';
@@ -202,6 +203,94 @@ declare class FileRepository {
202
203
  private getFiles;
203
204
  }
204
205
 
206
+ declare enum AbdbColumnType {
207
+ STRING = "STRING",
208
+ NUMBER = "NUMBER",
209
+ BOOLEAN = "BOOLEAN",
210
+ DATETIME = "DATETIME"
211
+ }
212
+ interface AbdbColumnOptions {
213
+ name: string;
214
+ type: AbdbColumnType;
215
+ description?: string;
216
+ isRequired?: boolean;
217
+ }
218
+ interface AbdbColumnJson {
219
+ name: string;
220
+ type: AbdbColumnType;
221
+ description?: string;
222
+ isRequired?: true;
223
+ }
224
+
225
+ declare class AbdbColumn {
226
+ private readonly _name;
227
+ private readonly _type;
228
+ private readonly _description;
229
+ private readonly _isRequired;
230
+ constructor(options: AbdbColumnOptions);
231
+ getName(): string;
232
+ getType(): AbdbColumnType;
233
+ getDescription(): string | undefined;
234
+ getIsRequired(): boolean;
235
+ toJSON(): AbdbColumnJson;
236
+ clone(overrides?: Partial<AbdbColumnOptions>): AbdbColumn;
237
+ validate(value: unknown): void;
238
+ private _isMissingValue;
239
+ private _validateStringValue;
240
+ private _validateNumberValue;
241
+ private _validateBooleanValue;
242
+ private _validateDateTimeValue;
243
+ }
244
+
245
+ type AddColumnOptions = Omit<AbdbColumnOptions, 'name' | 'type'>;
246
+ type AbdbRunCallback<T = unknown> = (collection: DbCollection, client: DbClient) => Promise<T>;
247
+
248
+ type AbdbCollectionCallback = (collection: AbdbCollection) => void;
249
+ declare class AbdbCollection {
250
+ private readonly _name;
251
+ private readonly _columns;
252
+ constructor(name: string, callback?: AbdbCollectionCallback);
253
+ getName(): string;
254
+ addColumn(name: string, type: AbdbColumnType, options?: AddColumnOptions): this;
255
+ addColumn(name: string, type: AbdbColumnType, description?: string, isRequired?: boolean): this;
256
+ getColumns(): AbdbColumn[];
257
+ getColumn(name: string): AbdbColumn | undefined;
258
+ hasColumn(name: string): boolean;
259
+ validate(record: Record<string, unknown>): void;
260
+ validateAll(record: Record<string, unknown>): string[];
261
+ run<T>(callback: AbdbRunCallback<T>, token: string, region?: string): Promise<T>;
262
+ private _validateCollectionName;
263
+ private _validateColumnName;
264
+ private _validateIdentifier;
265
+ }
266
+
267
+ interface AbdbRecord {
268
+ _id?: string;
269
+ _created_at?: string;
270
+ _updated_at?: string;
271
+ [key: string]: unknown;
272
+ }
273
+ type AbdbRepositoryFilter = Record<string, unknown>;
274
+
275
+ declare class AbdbRepository<T extends AbdbRecord = AbdbRecord> {
276
+ private readonly _collection;
277
+ private readonly _token;
278
+ private readonly _region;
279
+ constructor(collection: AbdbCollection, token: string, region?: string);
280
+ getName(): string;
281
+ getCollection(): AbdbCollection;
282
+ find(filter?: AbdbRepositoryFilter): Promise<T[]>;
283
+ findOne(filter: AbdbRepositoryFilter): Promise<T | null>;
284
+ exists(id: string): Promise<boolean>;
285
+ count(filter?: AbdbRepositoryFilter): Promise<number>;
286
+ save(payload?: Partial<T>, id?: string): Promise<string>;
287
+ delete(id?: string): Promise<void>;
288
+ insertAll(payloads: Array<Partial<T>>): Promise<string[]>;
289
+ updateAll(payload: Partial<T>, filter?: AbdbRepositoryFilter): Promise<void>;
290
+ deleteAll(filter?: AbdbRepositoryFilter): Promise<void>;
291
+ private _validatePartial;
292
+ }
293
+
205
294
  interface EventData {
206
295
  type: string;
207
296
  data: any;
@@ -989,4 +1078,4 @@ declare class AdminUiSdk {
989
1078
  getRegistration(): AdminUiSdkRegistration;
990
1079
  }
991
1080
 
992
- export { AdminUiSdk, type AdminUiSdkRegistration, AdobeAuth, AdobeCommerceClient, type AdobeIMSConfig, type BaseTelemetry, type BaseTelemetryValidator, BasicAuthConnection, BearerToken, type BearerTokenInfo, type CommerceEvent, type CommerceEventConfig, type CommerceEventField, type Connection, type CreateEventResult, CreateEvents, type CreateProviderParams, type CreateProviderResult, type CreateRegistrationResult, CreateRegistrations, type ErrorResponse, EventConsumerAction, type EventData, type EventMetadata, type EventMetadataInputModel, type EventMetadataListResponse, EventMetadataManager, type ExtendedRequestError, type FileMetadata, type FileRecord, FileRepository, GenerateBasicAuthToken, type GetProviderQueryParams, type GetRegistrationQueryParams, GraphQlAction, type HALLink, type Headers, HttpMethod, HttpStatus, IOEventsApiError, type IOEventsError, ImsConnection, ImsToken, type ImsTokenResult, InfiniteLoopBreaker, type InfiniteLoopData, IoEventsGlobals, JsonMessageProcessor, type ListProvidersQueryParams, type ListRegistrationQueryParams, type MenuItem, Oauth1aConnection, OnboardCommerce, type OnboardCommerceConfig, type OnboardCommerceResult, OnboardEvents, type OnboardEventsInput, type OnboardEventsResponse, OnboardEvents as OnboardIOEvents, Openwhisk, OpenwhiskAction, type OpenwhiskConfig, type Page, Parameters, type Provider, type ProviderInputModel, ProviderManager, PublishEvent, type PublishEventResult, type Registration, type RegistrationCreateModel, type RegistrationListResponse, RegistrationManager, RestClient, RuntimeAction, RuntimeActionResponse, type RuntimeActionResponseType, RuntimeApiGatewayService, ShippingCarrier, type ShippingCarrierData, ShippingCarrierMethod, type ShippingCarrierMethodAdditionalData, type ShippingCarrierMethodData, ShippingCarrierResponse, SignatureVerification, SuccessChecker, type SuccessResponse, Telemetry, TelemetryInputError, type TokenResult, Validator, WebhookAction, type WebhookActionAddResponse, type WebhookActionExceptionResponse, WebhookActionOperation, type WebhookActionRemoveResponse, type WebhookActionReplaceResponse, WebhookActionResponse, type WebhookActionResponseType, type WebhookActionSuccessResponse, type WorkspaceConfig };
1081
+ export { AbdbCollection, type AbdbCollectionCallback, AbdbColumn, type AbdbColumnJson, type AbdbColumnOptions, AbdbColumnType, type AbdbRecord, AbdbRepository, type AbdbRepositoryFilter, type AbdbRunCallback, type AddColumnOptions, AdminUiSdk, type AdminUiSdkRegistration, AdobeAuth, AdobeCommerceClient, type AdobeIMSConfig, type BaseTelemetry, type BaseTelemetryValidator, BasicAuthConnection, BearerToken, type BearerTokenInfo, type CommerceEvent, type CommerceEventConfig, type CommerceEventField, type Connection, type CreateEventResult, CreateEvents, type CreateProviderParams, type CreateProviderResult, type CreateRegistrationResult, CreateRegistrations, type ErrorResponse, EventConsumerAction, type EventData, type EventMetadata, type EventMetadataInputModel, type EventMetadataListResponse, EventMetadataManager, type ExtendedRequestError, type FileMetadata, type FileRecord, FileRepository, GenerateBasicAuthToken, type GetProviderQueryParams, type GetRegistrationQueryParams, GraphQlAction, type HALLink, type Headers, HttpMethod, HttpStatus, IOEventsApiError, type IOEventsError, ImsConnection, ImsToken, type ImsTokenResult, InfiniteLoopBreaker, type InfiniteLoopData, IoEventsGlobals, JsonMessageProcessor, type ListProvidersQueryParams, type ListRegistrationQueryParams, type MenuItem, Oauth1aConnection, OnboardCommerce, type OnboardCommerceConfig, type OnboardCommerceResult, OnboardEvents, type OnboardEventsInput, type OnboardEventsResponse, OnboardEvents as OnboardIOEvents, Openwhisk, OpenwhiskAction, type OpenwhiskConfig, type Page, Parameters, type Provider, type ProviderInputModel, ProviderManager, PublishEvent, type PublishEventResult, type Registration, type RegistrationCreateModel, type RegistrationListResponse, RegistrationManager, RestClient, RuntimeAction, RuntimeActionResponse, type RuntimeActionResponseType, RuntimeApiGatewayService, ShippingCarrier, type ShippingCarrierData, ShippingCarrierMethod, type ShippingCarrierMethodAdditionalData, type ShippingCarrierMethodData, ShippingCarrierResponse, SignatureVerification, SuccessChecker, type SuccessResponse, Telemetry, TelemetryInputError, type TokenResult, Validator, WebhookAction, type WebhookActionAddResponse, type WebhookActionExceptionResponse, WebhookActionOperation, type WebhookActionRemoveResponse, type WebhookActionReplaceResponse, WebhookActionResponse, type WebhookActionResponseType, type WebhookActionSuccessResponse, type WorkspaceConfig };