dynamo-bao 0.2.8 → 0.2.10

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/README.md CHANGED
@@ -23,10 +23,12 @@ DynamoBao is the tool I wish I had when I started.
23
23
  - Built-in multi-tenancy support with complete data isolation and concurrency safety
24
24
  - Return total read/write consumed capacity (even when multiple operations were performed)
25
25
  - Easily iterate over all items in a model for batch processing or migrations
26
+ - ESM (ECMAScript Modules) support for modern JavaScript projects
26
27
 
27
28
  ## Requirements
28
29
 
29
30
  - **Node.js 12.17.0+** (for AsyncLocalStorage support in multi-tenant features)
31
+ - Node.js 14+ recommended for native ESM support
30
32
  - AWS credentials configured for DynamoDB access
31
33
 
32
34
  ## Example 1: Simple model
@@ -252,6 +254,51 @@ npx bao-codegen
252
254
 
253
255
  You should now have generated models in the `models` directory.
254
256
 
257
+ ### ESM Support
258
+
259
+ DynamoBao supports generating models as ESM (ECMAScript Modules) for modern JavaScript projects. To enable ESM code generation, add the `codegen` configuration to your `config.js`:
260
+
261
+ ```javascript
262
+ // config.js
263
+ module.exports = {
264
+ aws: {
265
+ region: "us-west-2",
266
+ },
267
+ db: {
268
+ tableName: "your-table-name",
269
+ },
270
+ codegen: {
271
+ moduleSystem: "esm", // Options: 'commonjs' (default) or 'esm'
272
+ },
273
+ // ... other config
274
+ };
275
+ ```
276
+
277
+ When ESM is enabled, generated models will use:
278
+
279
+ - `import` / `export` syntax instead of `require` / `module.exports`
280
+ - `.js` extensions in import paths for ESM compatibility
281
+
282
+ For ESM config files, you can use `.mjs` extension:
283
+
284
+ ```javascript
285
+ // dynamo-bao.config.mjs
286
+ export default {
287
+ codegen: {
288
+ moduleSystem: "esm",
289
+ },
290
+ // ... other config
291
+ };
292
+ ```
293
+
294
+ Then use the generated ESM models:
295
+
296
+ ```javascript
297
+ // With ESM enabled
298
+ import { User } from "./models/user.js";
299
+ import { Post } from "./models/post.js";
300
+ ```
301
+
255
302
  Let's try using the models. Add the following code to a file called `example.js`.
256
303
 
257
304
  ```
@@ -1,7 +1,7 @@
1
- const path = require("path");
2
- const fs = require("fs").promises;
3
- const os = require("os");
4
- const chokidar = require("chokidar");
1
+ import path from "path";
2
+ import { promises as fs } from "fs";
3
+ import os from "os";
4
+ import chokidar from "chokidar";
5
5
 
6
6
  async function testChokidar() {
7
7
  let tempDir = path.join(os.tmpdir(), "chokidar-test-" + Date.now());
package/bin/codegen.js CHANGED
@@ -7,10 +7,13 @@ const { generateModelFiles } = require("./generators/model");
7
7
  const { generateManifestFile } = require("./generators/manifest");
8
8
  const { createLogger } = require("./utils/scriptLogger");
9
9
  const FieldResolver = require("../src/fieldResolver");
10
+ const { initConfig } = require("../src/config");
11
+
12
+ // const __dirname = __dirname;
13
+
10
14
  const logger = createLogger("CodeGen");
11
- const config = require("../src/config");
12
15
 
13
- function loadModelDefinitions(definitionsPath, fieldResolver) {
16
+ async function loadModelDefinitions(definitionsPath, fieldResolver) {
14
17
  const models = {};
15
18
 
16
19
  if (fs.statSync(definitionsPath).isDirectory()) {
@@ -97,9 +100,12 @@ function loadModelDefinitions(definitionsPath, fieldResolver) {
97
100
  return { models, fieldResolver };
98
101
  }
99
102
 
100
- function main() {
103
+ async function main() {
101
104
  const args = process.argv.slice(2);
102
105
 
106
+ // Initialize config first
107
+ const config = await initConfig();
108
+
103
109
  // Paths should be pre-resolved by the config loader.
104
110
  let definitionsPath =
105
111
  config?.paths?.modelsDefinitionPath ||
@@ -121,16 +127,20 @@ function main() {
121
127
  // Built-in fields are in fields.js
122
128
  const builtInFieldsPath = path.resolve(__dirname, "../src/fields.js");
123
129
 
130
+ // Load built-in fields directly for CommonJS compatibility
131
+ const builtInFields = require(builtInFieldsPath);
132
+
124
133
  const fieldResolver = new FieldResolver(
125
- builtInFieldsPath,
134
+ builtInFields,
126
135
  config?.paths?.fieldsDir,
127
136
  );
128
137
 
129
- const definitions = loadModelDefinitions(definitionsPath, fieldResolver);
138
+ const definitions = await loadModelDefinitions(definitionsPath, fieldResolver);
130
139
  generateModelFiles(
131
140
  definitions.models,
132
141
  outputDir,
133
142
  definitions.fieldResolver,
143
+ config?.codegen?.moduleSystem || 'commonjs',
134
144
  );
135
145
 
136
146
  // After generating models, generate the manifest file
@@ -149,10 +159,11 @@ function main() {
149
159
  }
150
160
  }
151
161
 
152
- function run() {
153
- main();
162
+ async function run() {
163
+ await main();
154
164
  }
155
165
 
166
+ // Check if this is the main module in CommonJS
156
167
  if (require.main === module) {
157
168
  run();
158
169
  }
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- const {
3
+ import {
4
4
  DynamoDBClient,
5
5
  CreateTableCommand,
6
6
  ListTablesCommand,
7
- } = require("../src/dynamodb-client");
8
- const readline = require("readline");
9
- const fs = require("fs");
10
- const path = require("path");
7
+ } from "../src/dynamodb-client.js";
8
+ import readline from "readline";
9
+ import fs from "fs";
10
+ import path from "path";
11
11
 
12
12
  // Create DynamoDB client at the top level
13
13
  const client = new DynamoDBClient();
@@ -44,7 +44,9 @@ function generateManifestFile(modelsDir, manifestPath) {
44
44
  const imports = modelFiles
45
45
  .map((file, index) => {
46
46
  const relativePath = path.relative(manifestDir, file).replace(/\\/g, "/");
47
- return `import * as model${index} from '${relativePath}';`;
47
+ // Ensure .js extension for ESM imports
48
+ const importPath = relativePath.endsWith('.js') ? relativePath : `${relativePath}.js`;
49
+ return `import * as model${index} from '${importPath}';`;
48
50
  })
49
51
  .join("\n");
50
52
 
@@ -1,6 +1,8 @@
1
1
  const path = require("path");
2
2
  const fs = require("fs");
3
3
  const { createLogger } = require("../utils/scriptLogger");
4
+
5
+ // const __dirname = __dirname;
4
6
  const logger = createLogger("ModelGen");
5
7
 
6
8
  const codeGenPrefix = ""; // "cg";
@@ -11,7 +13,13 @@ function generateModelClass(
11
13
  allModels,
12
14
  fieldResolver,
13
15
  outputDir,
16
+ moduleSystem = 'commonjs',
14
17
  ) {
18
+ // Calculate relative path to src directory from output directory
19
+ const projectRoot = path.resolve(__dirname, '../..');
20
+ const srcPath = path.join(projectRoot, 'src');
21
+ const relativeSrcPath = path.relative(outputDir, srcPath).replace(/\\/g, '/');
22
+ const srcImportPrefix = relativeSrcPath.startsWith('.') ? relativeSrcPath : './' + relativeSrcPath;
15
23
  if (!modelConfig || !modelConfig.fields) {
16
24
  throw new Error(
17
25
  `Invalid model configuration for ${modelName}: missing fields`,
@@ -150,47 +158,73 @@ function generateModelClass(
150
158
  outputDir,
151
159
  fieldResolver.customFieldsPath,
152
160
  );
153
- return `const { ${fieldType} } = require('${relativePath}/${kebabName}-field');`;
161
+
162
+ if (moduleSystem === 'esm') {
163
+ return `import { ${fieldType} } from '${relativePath}/${kebabName}-field.js';`;
164
+ } else {
165
+ return `const { ${fieldType} } = require('${relativePath}/${kebabName}-field.js');`;
166
+ }
154
167
  })
155
168
  .join("\n")
156
169
  : "";
157
170
 
158
- // Generate the final code with separated imports
159
- return `// 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨
160
- // DO NOT EDIT: Generated by model-codegen
161
- // 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨
162
- const {
171
+ // Generate imports/requires based on module system
172
+ const baseImportSection = moduleSystem === 'esm'
173
+ ? `import {
174
+ ${baseImportStr}
175
+ } from '${srcImportPrefix}/model.js';`
176
+ : `const {
163
177
  ${baseImportStr}
164
- } = require('dynamo-bao');
178
+ } = require('${srcImportPrefix}/model.js');`;
165
179
 
166
- ${
167
- constantImports.size > 0
168
- ? `const {
180
+ const constantImportSection = constantImports.size > 0
181
+ ? moduleSystem === 'esm'
182
+ ? `import {
169
183
  ${constantImportStr}
170
- } = require('dynamo-bao').constants;
184
+ } from '${srcImportPrefix}/constants.js';`
185
+ : `const {
186
+ ${constantImportStr}
187
+ } = require('${srcImportPrefix}/constants.js');`
188
+ : "";
171
189
 
172
- `
173
- : ""
174
- }
175
- ${
176
- usedFields.size > 0
177
- ? `const {
190
+ const fieldImportSection = usedFields.size > 0
191
+ ? moduleSystem === 'esm'
192
+ ? `import {
178
193
  ${fieldImports}
179
- } = require('dynamo-bao').fields;
194
+ } from '${srcImportPrefix}/fields.js';`
195
+ : `const {
196
+ ${fieldImports}
197
+ } = require('${srcImportPrefix}/fields.js');`
198
+ : "";
180
199
 
181
- `
182
- : ""
183
- }
184
- ${customFieldImports}
200
+ const relatedModelImports = Array.from(relatedModels)
201
+ .map((model) => {
202
+ const kebabName = model
203
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
204
+ .toLowerCase();
205
+
206
+ if (moduleSystem === 'esm') {
207
+ return `import { ${model} } from './${kebabName}.js';`;
208
+ } else {
209
+ return `const { ${model} } = require('./${kebabName}.js');`;
210
+ }
211
+ })
212
+ .join("\n");
185
213
 
186
- ${Array.from(relatedModels)
187
- .map((model) => {
188
- const kebabName = model
189
- .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
190
- .toLowerCase();
191
- return `const { ${model} } = require('./${kebabName}');`;
192
- })
193
- .join("\n")}
214
+ const exportSection = moduleSystem === 'esm'
215
+ ? `export { ${modelName} };`
216
+ : `module.exports = { ${modelName} };`;
217
+
218
+ // Generate the final code with separated imports
219
+ return `// 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨
220
+ // DO NOT EDIT: Generated by model-codegen
221
+ // 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨
222
+ ${baseImportSection}
223
+
224
+ ${constantImportSection ? constantImportSection + '\n' : ''}
225
+ ${fieldImportSection ? fieldImportSection + '\n' : ''}
226
+ ${customFieldImports ? customFieldImports + '\n' : ''}
227
+ ${relatedModelImports ? relatedModelImports + '\n' : ''}
194
228
 
195
229
  class ${modelName} extends BaoModel {
196
230
  static modelPrefix = '${modelConfig.modelPrefix}';
@@ -209,7 +243,7 @@ ${uniqueConstraintMethods}
209
243
  ${relatedFieldMethods}
210
244
  }
211
245
 
212
- module.exports = { ${modelName} };
246
+ ${exportSection}
213
247
  `;
214
248
  }
215
249
 
@@ -227,7 +261,7 @@ function generateUniqueConstraintMethods(modelConfig) {
227
261
  .join("\n");
228
262
  }
229
263
 
230
- function generateModelFiles(models, outputDir, fieldResolver) {
264
+ function generateModelFiles(models, outputDir, fieldResolver, moduleSystem = 'commonjs') {
231
265
  if (!fs.existsSync(outputDir)) {
232
266
  fs.mkdirSync(outputDir, { recursive: true });
233
267
  }
@@ -251,6 +285,7 @@ function generateModelFiles(models, outputDir, fieldResolver) {
251
285
  models,
252
286
  fieldResolver,
253
287
  outputDir,
288
+ moduleSystem,
254
289
  );
255
290
 
256
291
  fs.writeFileSync(filePath, code);
package/package.json CHANGED
@@ -1,8 +1,12 @@
1
1
  {
2
2
  "name": "dynamo-bao",
3
- "version": "0.2.8",
3
+ "version": "0.2.10",
4
4
  "description": "Simple powerful data modeling primitives for DynamoDB in JavaScript.",
5
5
  "main": "src/index.js",
6
+ "exports": {
7
+ ".": "./src/index.js",
8
+ "./package.json": "./package.json"
9
+ },
6
10
  "scripts": {
7
11
  "test": "LOG_LEVEL=OFF jest",
8
12
  "test:debug": "LOG_LEVEL=DEBUG jest",
package/src/config.js CHANGED
@@ -2,7 +2,7 @@ const fs = require("fs");
2
2
  const path = require("path");
3
3
  const dotenv = require("dotenv");
4
4
 
5
- function findConfig() {
5
+ async function findConfig() {
6
6
  // First check environment variable
7
7
  if (process.env.DYNAMO_BAO_CONFIG) {
8
8
  const configPath = path.resolve(
@@ -10,7 +10,7 @@ function findConfig() {
10
10
  process.env.DYNAMO_BAO_CONFIG,
11
11
  );
12
12
  if (fs.existsSync(configPath)) {
13
- const rawConfig = require(configPath);
13
+ const rawConfig = await loadConfigFile(configPath);
14
14
  const configDir = path.dirname(configPath);
15
15
  return normalizeConfig(rawConfig, configDir);
16
16
  }
@@ -18,9 +18,12 @@ function findConfig() {
18
18
 
19
19
  const possibleNames = [
20
20
  "dynamo-bao.config.js",
21
+ "dynamo-bao.config.mjs",
21
22
  "dynamo-bao.config.cjs",
22
23
  ".dynamo-bao/config.js",
24
+ ".dynamo-bao/config.mjs",
23
25
  "config.js",
26
+ "config.mjs",
24
27
  "config.cjs",
25
28
  ];
26
29
  const searchPaths = [
@@ -32,7 +35,7 @@ function findConfig() {
32
35
  for (const name of possibleNames) {
33
36
  const configPath = path.join(searchPath, name);
34
37
  if (fs.existsSync(configPath)) {
35
- const rawConfig = require(configPath);
38
+ const rawConfig = await loadConfigFile(configPath);
36
39
  const configDir = path.dirname(configPath);
37
40
  return normalizeConfig(rawConfig, configDir);
38
41
  }
@@ -48,6 +51,9 @@ function findConfig() {
48
51
  db: {
49
52
  tableName: process.env.TABLE_NAME || "dynamo-bao-dev",
50
53
  },
54
+ codegen: {
55
+ moduleSystem: 'commonjs',
56
+ },
51
57
  logging: {
52
58
  level: process.env.LOG_LEVEL || "ERROR",
53
59
  },
@@ -62,10 +68,30 @@ function findConfig() {
62
68
  };
63
69
  }
64
70
 
71
+ async function loadConfigFile(configPath) {
72
+ if (configPath.endsWith('.cjs')) {
73
+ // Use require for CommonJS files
74
+ return require(configPath);
75
+ } else if (configPath.endsWith('.mjs') || configPath.endsWith('.js')) {
76
+ // Use dynamic import for ESM files
77
+ const fileUrl = 'file://' + configPath;
78
+ const module = await import(fileUrl);
79
+ return module.default || module;
80
+ } else {
81
+ // Default to require for legacy files
82
+ return require(configPath);
83
+ }
84
+ }
85
+
86
+
65
87
  function normalizeConfig(rawConfig, configDir) {
66
88
  return {
67
89
  ...rawConfig,
68
90
  models: rawConfig.models || null,
91
+ codegen: {
92
+ moduleSystem: 'commonjs',
93
+ ...(rawConfig.codegen || {}),
94
+ },
69
95
  paths: {
70
96
  ...(rawConfig.paths || {}),
71
97
  modelsDir: rawConfig.paths?.modelsDir
@@ -93,6 +119,59 @@ function normalizeConfig(rawConfig, configDir) {
93
119
  };
94
120
  }
95
121
 
96
- // Load config once at module level
97
- const config = findConfig();
98
- module.exports = config;
122
+ // Synchronous initialization
123
+ let config = null;
124
+
125
+ function getConfig() {
126
+ if (!config) {
127
+ throw new Error('Config not initialized. Call initConfig() first.');
128
+ }
129
+ return config;
130
+ }
131
+
132
+ async function initConfig() {
133
+ config = await findConfig();
134
+ return config;
135
+ }
136
+
137
+ // For backward compatibility - try to load config synchronously
138
+ try {
139
+ // For now, create a basic synchronous config
140
+ const dotenvResult = dotenv.config();
141
+ config = {
142
+ aws: {
143
+ region: process.env.AWS_REGION || "us-west-2",
144
+ },
145
+ db: {
146
+ tableName: process.env.TABLE_NAME || "dynamo-bao-dev",
147
+ },
148
+ codegen: {
149
+ moduleSystem: 'commonjs',
150
+ },
151
+ logging: {
152
+ level: process.env.LOG_LEVEL || "ERROR",
153
+ },
154
+ paths: {
155
+ modelsDir: process.env.MODELS_DIR
156
+ ? path.resolve(process.cwd(), process.env.MODELS_DIR)
157
+ : null,
158
+ },
159
+ tenancy: {
160
+ enabled: process.env.DYNAMO_BAO_TENANCY_ENABLED === "true" || false,
161
+ },
162
+ };
163
+ } catch (err) {
164
+ console.error('Error loading config:', err);
165
+ }
166
+
167
+ module.exports = config || {
168
+ aws: { region: "us-west-2" },
169
+ db: { tableName: "dynamo-bao-dev" },
170
+ codegen: { moduleSystem: 'commonjs' },
171
+ logging: { level: "ERROR" },
172
+ paths: { modelsDir: null },
173
+ tenancy: { enabled: false }
174
+ };
175
+
176
+ module.exports.initConfig = initConfig;
177
+ module.exports.getConfig = getConfig;
@@ -2,13 +2,13 @@ const path = require("path");
2
2
  const fs = require("fs");
3
3
 
4
4
  class FieldResolver {
5
- constructor(builtInFieldsPath, customFieldsPath) {
6
- this.builtInFields = require(builtInFieldsPath);
5
+ constructor(builtInFields, customFieldsPath) {
6
+ this.builtInFields = builtInFields;
7
7
  this.customFieldsPath = customFieldsPath;
8
8
  this.fieldDefinitionCache = new Map();
9
9
 
10
10
  console.log("FieldResolver constructor:", {
11
- builtInFieldsPath,
11
+ builtInFields: typeof builtInFields,
12
12
  customFieldsPath,
13
13
  });
14
14
 
package/src/index.js CHANGED
@@ -16,6 +16,8 @@ const {
16
16
  UniqueConstraintConfig,
17
17
  } = require("./model");
18
18
 
19
+ const { TenantContext } = require("./tenant-context");
20
+
19
21
  function findModelFiles(dir) {
20
22
  let results = [];
21
23
  const items = fs.readdirSync(dir);
@@ -171,14 +173,12 @@ function initModels(userConfig = {}) {
171
173
 
172
174
  // Validate tenant context if tenancy enabled
173
175
  if (finalConfig.tenancy?.enabled) {
174
- const { TenantContext } = require("./tenant-context");
175
176
  TenantContext.validateTenantRequired(finalConfig);
176
177
  }
177
178
 
178
179
  const modelsDir = finalConfig.paths.modelsDir;
179
180
 
180
181
  // Get/create manager instance with tenantId
181
- const { TenantContext } = require("./tenant-context");
182
182
  const tenantId = TenantContext.getCurrentTenant() || finalConfig.testId;
183
183
  const manager = ModelManager.getInstance(tenantId);
184
184
 
@@ -200,8 +200,6 @@ function initModels(userConfig = {}) {
200
200
  return manager;
201
201
  }
202
202
 
203
- const { TenantContext } = require("./tenant-context");
204
-
205
203
  const firstExport = {
206
204
  // Initialize function
207
205
  initModels,
@@ -40,8 +40,4 @@ class UniqueConstraintConfig {
40
40
  }
41
41
  }
42
42
 
43
- module.exports = {
44
- PrimaryKeyConfig,
45
- IndexConfig,
46
- UniqueConstraintConfig,
47
- };
43
+ module.exports = { PrimaryKeyConfig, IndexConfig, UniqueConstraintConfig };
@@ -25,7 +25,7 @@ class ModelManager {
25
25
  return ModelManager._instances.get(key);
26
26
  }
27
27
 
28
- init(config = {}) {
28
+ async init(config = {}) {
29
29
  // Validate tenant requirement
30
30
  const { TenantContext } = require('./tenant-context');
31
31
  TenantContext.validateTenantRequired(config);
package/src/model.js CHANGED
@@ -18,9 +18,9 @@ const {
18
18
  } = require("./mixins/batch-loading-mixin");
19
19
 
20
20
  const {
21
- PrimaryKeyConfig,
22
- IndexConfig,
23
- UniqueConstraintConfig,
21
+ PrimaryKeyConfig: PrimaryKeyConfigClass,
22
+ IndexConfig: IndexConfigClass,
23
+ UniqueConstraintConfig: UniqueConstraintConfigClass,
24
24
  } = require("./model-config");
25
25
 
26
26
  const GID_SEPARATOR = "##__SK__##";
@@ -76,8 +76,8 @@ class BaoModel {
76
76
  * prevent data from being shared between tests/tests to run in parallel.
77
77
  * However, it should not be used outside of this context. For examples,
78
78
  * showing how to use this, see the tests.
79
- *
80
- * @deprecated Use TenantContext.setCurrentTenant() with the new multi-tenancy
79
+ *
80
+ * @deprecated Use TenantContext.setCurrentTenant() with the new multi-tenancy
81
81
  * system for both testing and production tenant isolation. See tutorial 08-multi-tenancy.
82
82
  * @param {string} testId - The ID of the test.
83
83
  */
@@ -90,7 +90,7 @@ class BaoModel {
90
90
  }
91
91
 
92
92
  static get manager() {
93
- const { TenantContext } = require('./tenant-context');
93
+ const { TenantContext } = require("./tenant-context");
94
94
  const tenantId = TenantContext.getCurrentTenant();
95
95
  return ModelManager.getInstance(tenantId || this._tenantId);
96
96
  }
@@ -192,25 +192,25 @@ class BaoModel {
192
192
  if (!this.iterable) {
193
193
  return {};
194
194
  }
195
-
195
+
196
196
  const tenantId = this.manager.getTenantId();
197
197
  let iterPk;
198
-
198
+
199
199
  if (this.iterationBuckets === 1) {
200
- iterPk = tenantId ?
201
- `[${tenantId}]#${this.modelPrefix}#iter` :
202
- `${this.modelPrefix}#iter`;
200
+ iterPk = tenantId
201
+ ? `[${tenantId}]#${this.modelPrefix}#iter`
202
+ : `${this.modelPrefix}#iter`;
203
203
  } else {
204
204
  const bucketNum = this._hashObjectId(objectId) % this.iterationBuckets;
205
- const bucket = bucketNum.toString().padStart(3, '0');
206
- iterPk = tenantId ?
207
- `[${tenantId}]#${this.modelPrefix}#iter#${bucket}` :
208
- `${this.modelPrefix}#iter#${bucket}`;
205
+ const bucket = bucketNum.toString().padStart(3, "0");
206
+ iterPk = tenantId
207
+ ? `[${tenantId}]#${this.modelPrefix}#iter#${bucket}`
208
+ : `${this.modelPrefix}#iter#${bucket}`;
209
209
  }
210
-
210
+
211
211
  return {
212
212
  [ITERATION_PK_FIELD]: iterPk,
213
- [ITERATION_SK_FIELD]: objectId
213
+ [ITERATION_SK_FIELD]: objectId,
214
214
  };
215
215
  }
216
216
 
@@ -218,7 +218,7 @@ class BaoModel {
218
218
  let hash = 0;
219
219
  for (let i = 0; i < objectId.length; i++) {
220
220
  const char = objectId.charCodeAt(i);
221
- hash = ((hash << 5) - hash) + char;
221
+ hash = (hash << 5) - hash + char;
222
222
  hash = hash & hash;
223
223
  }
224
224
  return Math.abs(hash);
@@ -228,92 +228,110 @@ class BaoModel {
228
228
  return this.iterable ? this.iterationBuckets : 1;
229
229
  }
230
230
 
231
- static async* iterateAll(options = {}) {
231
+ static async *iterateAll(options = {}) {
232
232
  if (!this.iterable) {
233
233
  throw new Error(`Model ${this.name} is not configured as iterable`);
234
234
  }
235
-
235
+
236
236
  const { batchSize = 100, filter = null, loaderContext = null } = options;
237
-
237
+
238
238
  if (this.iterationBuckets === 1) {
239
- yield* this._iterateSingleBucket(null, { batchSize, filter, loaderContext });
239
+ yield* this._iterateSingleBucket(null, {
240
+ batchSize,
241
+ filter,
242
+ loaderContext,
243
+ });
240
244
  } else {
241
245
  for (let bucket = 0; bucket < this.iterationBuckets; bucket++) {
242
- yield* this._iterateSingleBucket(bucket, { batchSize, filter, loaderContext });
246
+ yield* this._iterateSingleBucket(bucket, {
247
+ batchSize,
248
+ filter,
249
+ loaderContext,
250
+ });
243
251
  }
244
252
  }
245
253
  }
246
254
 
247
- static async* iterateBucket(bucketNum, options = {}) {
255
+ static async *iterateBucket(bucketNum, options = {}) {
248
256
  if (!this.iterable) {
249
257
  throw new Error(`Model ${this.name} is not configured as iterable`);
250
258
  }
251
-
259
+
252
260
  if (bucketNum < 0 || bucketNum >= this.iterationBuckets) {
253
- throw new Error(`Invalid bucket number ${bucketNum}. Must be 0-${this.iterationBuckets - 1}`);
261
+ throw new Error(
262
+ `Invalid bucket number ${bucketNum}. Must be 0-${this.iterationBuckets - 1}`,
263
+ );
254
264
  }
255
-
265
+
256
266
  yield* this._iterateSingleBucket(bucketNum, options);
257
267
  }
258
268
 
259
- static async* _iterateSingleBucket(bucketNum, options = {}) {
269
+ static async *_iterateSingleBucket(bucketNum, options = {}) {
260
270
  const { batchSize = 100, filter = null, loaderContext = null } = options;
261
271
  const tenantId = this.manager.getTenantId();
262
-
272
+
263
273
  let iterPk;
264
274
  if (this.iterationBuckets === 1) {
265
- iterPk = tenantId ?
266
- `[${tenantId}]#${this.modelPrefix}#iter` :
267
- `${this.modelPrefix}#iter`;
275
+ iterPk = tenantId
276
+ ? `[${tenantId}]#${this.modelPrefix}#iter`
277
+ : `${this.modelPrefix}#iter`;
268
278
  } else {
269
- const bucket = bucketNum.toString().padStart(3, '0');
270
- iterPk = tenantId ?
271
- `[${tenantId}]#${this.modelPrefix}#iter#${bucket}` :
272
- `${this.modelPrefix}#iter#${bucket}`;
279
+ const bucket = bucketNum.toString().padStart(3, "0");
280
+ iterPk = tenantId
281
+ ? `[${tenantId}]#${this.modelPrefix}#iter#${bucket}`
282
+ : `${this.modelPrefix}#iter#${bucket}`;
273
283
  }
274
-
284
+
275
285
  let lastEvaluatedKey = null;
276
-
286
+
277
287
  do {
278
288
  const { QueryCommand } = require("./dynamodb-client");
279
289
  const params = {
280
290
  TableName: this.table,
281
291
  IndexName: ITERATION_INDEX_NAME,
282
- KeyConditionExpression: '#pk = :pk',
283
- ExpressionAttributeNames: { '#pk': ITERATION_PK_FIELD },
284
- ExpressionAttributeValues: { ':pk': iterPk },
292
+ KeyConditionExpression: "#pk = :pk",
293
+ ExpressionAttributeNames: { "#pk": ITERATION_PK_FIELD },
294
+ ExpressionAttributeValues: { ":pk": iterPk },
285
295
  Limit: batchSize,
286
- ReturnConsumedCapacity: 'TOTAL'
296
+ ReturnConsumedCapacity: "TOTAL",
287
297
  };
288
-
298
+
289
299
  if (lastEvaluatedKey) {
290
300
  params.ExclusiveStartKey = lastEvaluatedKey;
291
301
  }
292
-
302
+
293
303
  if (filter) {
294
304
  const { FilterExpressionBuilder } = require("./filter-expression");
295
305
  const filterBuilder = new FilterExpressionBuilder();
296
306
  const filterExpression = filterBuilder.build(filter, this);
297
307
  if (filterExpression) {
298
308
  params.FilterExpression = filterExpression.FilterExpression;
299
- Object.assign(params.ExpressionAttributeNames, filterExpression.ExpressionAttributeNames);
300
- Object.assign(params.ExpressionAttributeValues, filterExpression.ExpressionAttributeValues);
309
+ Object.assign(
310
+ params.ExpressionAttributeNames,
311
+ filterExpression.ExpressionAttributeNames,
312
+ );
313
+ Object.assign(
314
+ params.ExpressionAttributeValues,
315
+ filterExpression.ExpressionAttributeValues,
316
+ );
301
317
  }
302
318
  }
303
-
319
+
304
320
  const response = await this.documentClient.send(new QueryCommand(params));
305
-
321
+
306
322
  if (response.Items && response.Items.length > 0) {
307
- const objectIds = response.Items.map(item => item[ITERATION_SK_FIELD]);
308
-
323
+ const objectIds = response.Items.map(
324
+ (item) => item[ITERATION_SK_FIELD],
325
+ );
326
+
309
327
  const { items } = await this.batchFind(objectIds, loaderContext);
310
328
  const batch = Object.values(items);
311
-
329
+
312
330
  if (batch.length > 0) {
313
331
  yield batch;
314
332
  }
315
333
  }
316
-
334
+
317
335
  lastEvaluatedKey = response.LastEvaluatedKey;
318
336
  } while (lastEvaluatedKey);
319
337
  }
@@ -392,46 +410,31 @@ class BaoModel {
392
410
  }
393
411
 
394
412
  const pkField = this._getField(this.primaryKey.pk);
395
- const skField = this._getField(this.primaryKey.sk);
413
+ const pkValue = pkField
414
+ ? pkField.toGsi(this._getPkValue(data))
415
+ : this._getPkValue(data);
396
416
 
397
- if (skField === undefined && this.primaryKey.sk !== "modelPrefix") {
398
- throw new ConfigurationError(
399
- `SK field is required for getPkSk call`,
400
- this.name,
401
- );
417
+ if (pkValue === undefined || pkValue === null) {
418
+ throw new ValidationError(`PK must be defined to get a PkSk`);
402
419
  }
403
420
 
404
- if (pkField === undefined && this.primaryKey.pk !== "modelPrefix") {
405
- throw new ConfigurationError(
406
- `PK field is required for getPkSk call`,
407
- this.name,
408
- );
409
- }
421
+ const key = { pk: pkValue };
410
422
 
411
- // If the field is set, use the GSI value, otherwise use the raw value
412
- const pkValue = pkField
413
- ? pkField.toGsi(this._getPkValue(data))
414
- : this._getPkValue(data);
415
- const skValue = skField
416
- ? skField.toGsi(this._getSkValue(data))
417
- : this._getSkValue(data);
418
-
419
- if (
420
- pkValue === undefined ||
421
- skValue === undefined ||
422
- pkValue === null ||
423
- skValue === null
424
- ) {
425
- throw new ValidationError(`PK and SK must be defined to get a PkSk`);
426
- }
427
-
428
- let key = {
429
- pk: pkValue,
430
- sk: skValue,
431
- };
423
+ if (this.primaryKey.sk) {
424
+ const skField = this._getField(this.primaryKey.sk);
425
+ const skValue = skField
426
+ ? skField.toGsi(this._getSkValue(data))
427
+ : this._getSkValue(data);
432
428
 
433
- logger.debug("_getPrimaryKeyValues", key);
429
+ if (skValue === undefined || skValue === null) {
430
+ throw new ValidationError(
431
+ `SK must be defined for a composite primary key`,
432
+ );
433
+ }
434
+ key.sk = skValue;
435
+ }
434
436
 
437
+ logger.debug("_getPrimaryKeyValues", key);
435
438
  return key;
436
439
  }
437
440
 
@@ -480,8 +483,17 @@ class BaoModel {
480
483
  }
481
484
 
482
485
  static _parsePrimaryId(primaryId) {
483
- if (!primaryId) {
484
- throw new DataFormatError("Primary ID is required to parse");
486
+ if (typeof primaryId === "object" && primaryId !== null) {
487
+ if (primaryId.pk !== undefined) {
488
+ return primaryId;
489
+ }
490
+ return this._getPrimaryKeyValues(primaryId);
491
+ }
492
+
493
+ if (typeof primaryId !== "string") {
494
+ throw new ValidationError(
495
+ `primaryId must be a string or an object. Got ${typeof primaryId}`,
496
+ );
485
497
  }
486
498
 
487
499
  if (primaryId.indexOf(GID_SEPARATOR) !== -1) {
@@ -492,9 +504,8 @@ class BaoModel {
492
504
  return { pk: this.modelPrefix, sk: primaryId };
493
505
  } else if (this.primaryKey.sk === "modelPrefix") {
494
506
  return { pk: primaryId, sk: this.modelPrefix };
495
- } else {
496
- throw new DataFormatError(`Invalid primary ID: ${primaryId}`);
497
507
  }
508
+ return { pk: primaryId };
498
509
  }
499
510
  }
500
511
 
@@ -739,7 +750,7 @@ class BaoModel {
739
750
  _sk: UNIQUE_CONSTRAINT_KEY,
740
751
  },
741
752
  ReturnConsumedCapacity: "TOTAL",
742
- })
753
+ }),
743
754
  );
744
755
 
745
756
  if (!result.Item) {
@@ -866,12 +877,17 @@ class BaoModel {
866
877
  }
867
878
  }
868
879
 
880
+ // Factory functions to maintain compatibility
881
+ const PrimaryKeyConfig = (pk, sk) => new PrimaryKeyConfigClass(pk, sk);
882
+ const IndexConfig = (pk, sk, indexId) => new IndexConfigClass(pk, sk, indexId);
883
+ const UniqueConstraintConfig = (field, constraintId) =>
884
+ new UniqueConstraintConfigClass(field, constraintId);
885
+
869
886
  module.exports = {
870
887
  BaoModel,
871
- PrimaryKeyConfig: (pk, sk) => new PrimaryKeyConfig(pk, sk),
872
- IndexConfig: (pk, sk, indexId) => new IndexConfig(pk, sk, indexId),
873
- UniqueConstraintConfig: (field, constraintId) =>
874
- new UniqueConstraintConfig(field, constraintId),
888
+ PrimaryKeyConfig,
889
+ IndexConfig,
890
+ UniqueConstraintConfig,
875
891
  BATCH_REQUEST_TIMEOUT,
876
892
  BATCH_REQUESTS,
877
893
  };
@@ -39,6 +39,4 @@ class ObjectNotFound {
39
39
  }
40
40
  }
41
41
 
42
- module.exports = {
43
- ObjectNotFound,
44
- };
42
+ module.exports = { ObjectNotFound };
@@ -1,5 +1,16 @@
1
1
  const { AsyncLocalStorage } = require('async_hooks');
2
2
 
3
+ // Lazy getter to avoid circular dependency
4
+ let _ModelManager = null;
5
+ function getModelManager() {
6
+ if (!_ModelManager) {
7
+ // Use require since this is called at runtime, not module load time
8
+ const { ModelManager } = require('./model-manager');
9
+ _ModelManager = ModelManager;
10
+ }
11
+ return _ModelManager;
12
+ }
13
+
3
14
  /**
4
15
  * @class TenantContext
5
16
  * @description Manages tenant context for multi-tenant applications using DynamoBao.
@@ -97,7 +108,7 @@ class TenantContext {
97
108
  * @returns {ModelManager} The ModelManager instance
98
109
  */
99
110
  static getInstance(tenantId = null) {
100
- const { ModelManager } = require('./model-manager');
111
+ const ModelManager = getModelManager();
101
112
  const effectiveTenantId = tenantId || this.getCurrentTenant();
102
113
  const key = effectiveTenantId || "default";
103
114
 
@@ -154,7 +165,7 @@ class TenantContext {
154
165
  this.clearTenant();
155
166
 
156
167
  // Also clear ModelManager instances to ensure clean state
157
- const { ModelManager } = require('./model-manager');
168
+ const ModelManager = getModelManager();
158
169
  if (ModelManager._instances) {
159
170
  ModelManager._instances.clear();
160
171
  }
@@ -1,4 +1,4 @@
1
- // require("dotenv").config();
1
+ // import("dotenv").then(dotenv => dotenv.config());
2
2
 
3
3
  const userConfig = require("../config");
4
4
 
@@ -48,7 +48,4 @@ class Logger {
48
48
  // Export a default logger with a generic context
49
49
  const defaultLogger = new Logger("Default");
50
50
 
51
- module.exports = {
52
- Logger,
53
- defaultLogger,
54
- };
51
+ module.exports = { Logger, defaultLogger };