@awsless/dynamodb-server 0.0.12 → 0.1.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/README.MD ADDED
@@ -0,0 +1,149 @@
1
+ # @awsless/dynamodb-server
2
+
3
+ A local DynamoDB server for testing and development. Provides both a fast in-memory implementation and a Java-based implementation using the official AWS DynamoDB Local.
4
+
5
+ ## Features
6
+
7
+ - **Fast In-Memory Engine** - Lightning fast in-memory implementation for rapid testing
8
+ - **Java Engine** - Full compatibility mode using the official AWS DynamoDB Local
9
+ - **DynamoDB Streams** - Support for stream callbacks on item changes
10
+ - **TTL Support** - Time-to-live expiration for items
11
+ - **GSI/LSI Support** - Global and Local Secondary Index support
12
+
13
+ ## Setup
14
+
15
+ Install with (NPM):
16
+
17
+ ```
18
+ npm i @awsless/dynamodb-server
19
+ ```
20
+
21
+ ## Basic Usage
22
+
23
+ ```ts
24
+ import { DynamoDBServer } from "@awsless/dynamodb-server"
25
+
26
+ // Create a server with the fast in-memory engine (default)
27
+ const server = new DynamoDBServer()
28
+
29
+ // Or use the Java engine for full compatibility
30
+ const server = new DynamoDBServer({ engine: "java" })
31
+
32
+ // Start the server
33
+ await server.listen(8000)
34
+
35
+ // Get a DynamoDB client configured to use the local server
36
+ const client = server.getClient()
37
+
38
+ // Get a DynamoDB Document client
39
+ const documentClient = server.getDocumentClient()
40
+
41
+ // Stop the server when done
42
+ await server.stop()
43
+ ```
44
+
45
+ ## Engines
46
+
47
+ ### Memory Engine (Default)
48
+
49
+ The in-memory engine is optimized for speed and is perfect for unit tests. It implements the core DynamoDB operations without requiring Java.
50
+
51
+ ```ts
52
+ const server = new DynamoDBServer({ engine: "memory" })
53
+ ```
54
+
55
+ ### Java Engine
56
+
57
+ The Java engine uses AWS DynamoDB Local for full compatibility with DynamoDB behavior. Requires Java to be installed.
58
+
59
+ ```ts
60
+ const server = new DynamoDBServer({ engine: "java" })
61
+ ```
62
+
63
+ ## Configuration Options
64
+
65
+ ```ts
66
+ const server = new DynamoDBServer({
67
+ // Engine type: "memory" (default) or "java"
68
+ engine: "memory",
69
+
70
+ // Hostname to bind to (default: "localhost")
71
+ hostname: "localhost",
72
+
73
+ // Port to listen on (default: auto-assigned)
74
+ port: 8000,
75
+
76
+ // AWS region (default: "us-east-1")
77
+ region: "us-east-1",
78
+ })
79
+ ```
80
+
81
+ ## Stream Support
82
+
83
+ You can subscribe to item changes using stream callbacks:
84
+
85
+ ```ts
86
+ const unsubscribe = server.onStreamRecord("my-table", record => {
87
+ console.log("Stream event:", record.eventName) // INSERT, MODIFY, or REMOVE
88
+ console.log("Keys:", record.dynamodb.Keys)
89
+ console.log("New Image:", record.dynamodb.NewImage)
90
+ console.log("Old Image:", record.dynamodb.OldImage)
91
+ })
92
+
93
+ // Unsubscribe when done
94
+ unsubscribe()
95
+ ```
96
+
97
+ ## Testing with Vitest/Jest
98
+
99
+ ```ts
100
+ import { DynamoDBServer } from "@awsless/dynamodb-server"
101
+ import { CreateTableCommand } from "@aws-sdk/client-dynamodb"
102
+ import { PutCommand, GetCommand } from "@aws-sdk/lib-dynamodb"
103
+
104
+ describe("My DynamoDB Tests", () => {
105
+ const server = new DynamoDBServer()
106
+
107
+ beforeAll(async () => {
108
+ await server.listen()
109
+
110
+ // Create your tables
111
+ await server.getClient().send(
112
+ new CreateTableCommand({
113
+ TableName: "users",
114
+ KeySchema: [{ AttributeName: "id", KeyType: "HASH" }],
115
+ AttributeDefinitions: [{ AttributeName: "id", AttributeType: "N" }],
116
+ BillingMode: "PAY_PER_REQUEST",
117
+ })
118
+ )
119
+ })
120
+
121
+ afterAll(async () => {
122
+ await server.stop()
123
+ })
124
+
125
+ it("should store and retrieve items", async () => {
126
+ const client = server.getDocumentClient()
127
+
128
+ await client.send(
129
+ new PutCommand({
130
+ TableName: "users",
131
+ Item: { id: 1, name: "John" },
132
+ })
133
+ )
134
+
135
+ const result = await client.send(
136
+ new GetCommand({
137
+ TableName: "users",
138
+ Key: { id: 1 },
139
+ })
140
+ )
141
+
142
+ expect(result.Item).toEqual({ id: 1, name: "John" })
143
+ })
144
+ })
145
+ ```
146
+
147
+ ## License
148
+
149
+ MIT
package/dist/index.d.ts CHANGED
@@ -1,24 +1,395 @@
1
1
  import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
2
2
  import { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb';
3
3
 
4
- declare class DynamoDBServer {
4
+ type AttributeValue = {
5
+ S: string;
6
+ } | {
7
+ N: string;
8
+ } | {
9
+ B: string;
10
+ } | {
11
+ SS: string[];
12
+ } | {
13
+ NS: string[];
14
+ } | {
15
+ BS: string[];
16
+ } | {
17
+ M: AttributeMap;
18
+ } | {
19
+ L: AttributeValue[];
20
+ } | {
21
+ NULL: true;
22
+ } | {
23
+ BOOL: boolean;
24
+ };
25
+ type AttributeMap = Record<string, AttributeValue>;
26
+ interface KeySchemaElement {
27
+ AttributeName: string;
28
+ KeyType: 'HASH' | 'RANGE';
29
+ }
30
+ interface AttributeDefinition {
31
+ AttributeName: string;
32
+ AttributeType: 'S' | 'N' | 'B';
33
+ }
34
+ interface Projection {
35
+ ProjectionType?: 'ALL' | 'KEYS_ONLY' | 'INCLUDE';
36
+ NonKeyAttributes?: string[];
37
+ }
38
+ interface ProvisionedThroughput {
39
+ ReadCapacityUnits: number;
40
+ WriteCapacityUnits: number;
41
+ }
42
+ interface GlobalSecondaryIndex {
43
+ IndexName: string;
44
+ KeySchema: KeySchemaElement[];
45
+ Projection: Projection;
46
+ ProvisionedThroughput?: ProvisionedThroughput;
47
+ }
48
+ interface LocalSecondaryIndex {
49
+ IndexName: string;
50
+ KeySchema: KeySchemaElement[];
51
+ Projection: Projection;
52
+ }
53
+ type StreamViewType = 'KEYS_ONLY' | 'NEW_IMAGE' | 'OLD_IMAGE' | 'NEW_AND_OLD_IMAGES';
54
+ interface StreamSpecification {
55
+ StreamEnabled: boolean;
56
+ StreamViewType?: StreamViewType;
57
+ }
58
+ interface TimeToLiveSpecification {
59
+ AttributeName: string;
60
+ Enabled: boolean;
61
+ }
62
+ interface TableDescription {
63
+ TableName: string;
64
+ TableStatus: 'CREATING' | 'ACTIVE' | 'DELETING' | 'UPDATING';
65
+ CreationDateTime: number;
66
+ TableArn: string;
67
+ TableId: string;
68
+ KeySchema: KeySchemaElement[];
69
+ AttributeDefinitions: AttributeDefinition[];
70
+ ProvisionedThroughput?: {
71
+ ReadCapacityUnits: number;
72
+ WriteCapacityUnits: number;
73
+ LastIncreaseDateTime?: number;
74
+ LastDecreaseDateTime?: number;
75
+ NumberOfDecreasesToday?: number;
76
+ };
77
+ BillingModeSummary?: {
78
+ BillingMode: 'PROVISIONED' | 'PAY_PER_REQUEST';
79
+ LastUpdateToPayPerRequestDateTime?: number;
80
+ };
81
+ GlobalSecondaryIndexes?: GlobalSecondaryIndexDescription[];
82
+ LocalSecondaryIndexes?: LocalSecondaryIndexDescription[];
83
+ StreamSpecification?: StreamSpecification;
84
+ LatestStreamArn?: string;
85
+ LatestStreamLabel?: string;
86
+ ItemCount: number;
87
+ TableSizeBytes: number;
88
+ }
89
+ interface GlobalSecondaryIndexDescription {
90
+ IndexName: string;
91
+ KeySchema: KeySchemaElement[];
92
+ Projection: Projection;
93
+ IndexStatus: 'CREATING' | 'ACTIVE' | 'DELETING' | 'UPDATING';
94
+ ProvisionedThroughput?: ProvisionedThroughput;
95
+ IndexSizeBytes: number;
96
+ ItemCount: number;
97
+ IndexArn: string;
98
+ }
99
+ interface LocalSecondaryIndexDescription {
100
+ IndexName: string;
101
+ KeySchema: KeySchemaElement[];
102
+ Projection: Projection;
103
+ IndexSizeBytes: number;
104
+ ItemCount: number;
105
+ IndexArn: string;
106
+ }
107
+ interface StreamRecord {
108
+ eventID: string;
109
+ eventName: 'INSERT' | 'MODIFY' | 'REMOVE';
110
+ eventVersion: string;
111
+ eventSource: string;
112
+ awsRegion: string;
113
+ dynamodb: {
114
+ ApproximateCreationDateTime: number;
115
+ Keys: AttributeMap;
116
+ NewImage?: AttributeMap;
117
+ OldImage?: AttributeMap;
118
+ SequenceNumber: string;
119
+ SizeBytes: number;
120
+ StreamViewType: StreamViewType;
121
+ };
122
+ }
123
+ type StreamCallback = (record: StreamRecord) => void;
124
+ interface ConsumedCapacity {
125
+ TableName: string;
126
+ CapacityUnits: number;
127
+ ReadCapacityUnits?: number;
128
+ WriteCapacityUnits?: number;
129
+ Table?: {
130
+ CapacityUnits: number;
131
+ ReadCapacityUnits?: number;
132
+ WriteCapacityUnits?: number;
133
+ };
134
+ GlobalSecondaryIndexes?: Record<string, {
135
+ CapacityUnits: number;
136
+ ReadCapacityUnits?: number;
137
+ WriteCapacityUnits?: number;
138
+ }>;
139
+ LocalSecondaryIndexes?: Record<string, {
140
+ CapacityUnits: number;
141
+ ReadCapacityUnits?: number;
142
+ WriteCapacityUnits?: number;
143
+ }>;
144
+ }
145
+
146
+ declare class Table {
147
+ readonly name: string;
148
+ readonly keySchema: KeySchemaElement[];
149
+ readonly attributeDefinitions: AttributeDefinition[];
150
+ readonly provisionedThroughput?: ProvisionedThroughput;
151
+ readonly billingMode: 'PROVISIONED' | 'PAY_PER_REQUEST';
152
+ readonly createdAt: number;
153
+ readonly tableId: string;
154
+ readonly streamSpecification?: StreamSpecification;
155
+ readonly latestStreamArn?: string;
156
+ readonly latestStreamLabel?: string;
157
+ private ttlSpecification?;
158
+ private items;
159
+ private globalSecondaryIndexes;
160
+ private localSecondaryIndexes;
161
+ private streamCallbacks;
5
162
  private region;
163
+ constructor(options: {
164
+ tableName: string;
165
+ keySchema: KeySchemaElement[];
166
+ attributeDefinitions: AttributeDefinition[];
167
+ provisionedThroughput?: ProvisionedThroughput;
168
+ billingMode?: 'PROVISIONED' | 'PAY_PER_REQUEST';
169
+ globalSecondaryIndexes?: GlobalSecondaryIndex[];
170
+ localSecondaryIndexes?: LocalSecondaryIndex[];
171
+ streamSpecification?: StreamSpecification;
172
+ timeToLiveSpecification?: TimeToLiveSpecification;
173
+ }, region?: string);
174
+ getHashKeyName(): string;
175
+ getRangeKeyName(): string | undefined;
176
+ getTtlAttributeName(): string | undefined;
177
+ setTtlSpecification(spec: TimeToLiveSpecification): void;
178
+ getTtlSpecification(): TimeToLiveSpecification | undefined;
179
+ describe(): TableDescription;
180
+ private describeGlobalSecondaryIndexes;
181
+ private describeLocalSecondaryIndexes;
182
+ private estimateTableSize;
183
+ getItem(key: AttributeMap): AttributeMap | undefined;
184
+ putItem(item: AttributeMap): AttributeMap | undefined;
185
+ deleteItem(key: AttributeMap): AttributeMap | undefined;
186
+ updateItem(key: AttributeMap, updatedItem: AttributeMap): AttributeMap | undefined;
187
+ private updateIndexes;
188
+ private addToIndexes;
189
+ private removeFromIndexes;
190
+ private buildIndexKey;
191
+ scan(limit?: number, exclusiveStartKey?: AttributeMap): {
192
+ items: AttributeMap[];
193
+ lastEvaluatedKey?: AttributeMap;
194
+ };
195
+ queryByHashKey(hashValue: AttributeMap, options?: {
196
+ limit?: number;
197
+ scanIndexForward?: boolean;
198
+ exclusiveStartKey?: AttributeMap;
199
+ }): {
200
+ items: AttributeMap[];
201
+ lastEvaluatedKey?: AttributeMap;
202
+ };
203
+ queryIndex(indexName: string, hashValue: AttributeMap, options?: {
204
+ limit?: number;
205
+ scanIndexForward?: boolean;
206
+ exclusiveStartKey?: AttributeMap;
207
+ }): {
208
+ items: AttributeMap[];
209
+ lastEvaluatedKey?: AttributeMap;
210
+ indexKeySchema: KeySchemaElement[];
211
+ };
212
+ scanIndex(indexName: string, limit?: number, exclusiveStartKey?: AttributeMap): {
213
+ items: AttributeMap[];
214
+ lastEvaluatedKey?: AttributeMap;
215
+ indexKeySchema: KeySchemaElement[];
216
+ };
217
+ hasIndex(indexName: string): boolean;
218
+ getIndexKeySchema(indexName: string): KeySchemaElement[] | undefined;
219
+ private attributeEquals;
220
+ private compareAttributes;
221
+ getAllItems(): AttributeMap[];
222
+ clear(): void;
223
+ onStreamRecord(callback: StreamCallback): () => void;
224
+ private emitStreamRecord;
225
+ expireTtlItems(currentTimeSeconds: number): AttributeMap[];
226
+ }
227
+
228
+ interface CreateTableInput {
229
+ TableName: string;
230
+ KeySchema: KeySchemaElement[];
231
+ AttributeDefinitions: AttributeDefinition[];
232
+ ProvisionedThroughput?: ProvisionedThroughput;
233
+ BillingMode?: 'PROVISIONED' | 'PAY_PER_REQUEST';
234
+ GlobalSecondaryIndexes?: GlobalSecondaryIndex[];
235
+ LocalSecondaryIndexes?: LocalSecondaryIndex[];
236
+ StreamSpecification?: StreamSpecification;
237
+ TimeToLiveSpecification?: TimeToLiveSpecification;
238
+ }
239
+ declare class TableStore {
240
+ private tables;
241
+ private region;
242
+ constructor(region?: string);
243
+ createTable(input: CreateTableInput): Table;
244
+ getTable(tableName: string): Table;
245
+ hasTable(tableName: string): boolean;
246
+ deleteTable(tableName: string): Table;
247
+ listTables(exclusiveStartTableName?: string, limit?: number): {
248
+ tableNames: string[];
249
+ lastEvaluatedTableName?: string;
250
+ };
251
+ clear(): void;
252
+ expireTtlItems(currentTimeSeconds: number): void;
253
+ }
254
+
255
+ type Engine = 'memory' | 'java';
256
+ interface DynamoDBServerConfig {
257
+ port?: number;
258
+ region?: string;
259
+ hostname?: string;
260
+ /**
261
+ * The engine to use for the DynamoDB server.
262
+ * - 'memory': Fast in-memory implementation (default)
263
+ * - 'java': Java-based DynamoDB Local (requires dynamo-db-local package)
264
+ */
265
+ engine?: Engine;
266
+ }
267
+ interface MutableEndpoint {
268
+ protocol: string;
269
+ hostname: string;
270
+ port?: number;
271
+ path: string;
272
+ }
273
+ declare class DynamoDBServer {
274
+ private server?;
275
+ private javaServer?;
276
+ private store;
277
+ private clock;
278
+ private config;
279
+ private endpoint;
6
280
  private client?;
7
281
  private documentClient?;
8
- private endpoint;
9
- private process;
10
- constructor(region?: string);
11
- listen(port: number): Promise<void>;
12
- /** Kill the DynamoDB server. */
13
- kill(): Promise<void>;
14
- /** Ping the DynamoDB server if its ready. */
15
- ping(): Promise<boolean>;
16
- /** Ping the DynamoDB server untill its ready. */
17
- wait(times?: number): Promise<void>;
18
- /** Get DynamoDBClient connected to dynamodb local. */
282
+ private streamCallbacks;
283
+ constructor(config?: DynamoDBServerConfig);
284
+ listen(port?: number): Promise<void>;
285
+ stop(): Promise<void>;
286
+ get port(): number;
287
+ get engine(): Engine;
288
+ getEndpoint(): MutableEndpoint;
19
289
  getClient(): DynamoDBClient;
20
- /** Get DynamoDBDocumentClient connected to dynamodb local. */
21
290
  getDocumentClient(): DynamoDBDocumentClient;
291
+ /**
292
+ * Advance the virtual clock by the specified number of milliseconds.
293
+ * This triggers TTL processing for expired items.
294
+ * Only available when using the 'memory' engine.
295
+ */
296
+ advanceTime(ms: number): void;
297
+ /**
298
+ * Set the virtual clock to the specified timestamp.
299
+ * This triggers TTL processing for expired items.
300
+ * Only available when using the 'memory' engine.
301
+ */
302
+ setTime(timestamp: number): void;
303
+ /**
304
+ * Get the current virtual clock time.
305
+ * Only available when using the 'memory' engine.
306
+ */
307
+ getTime(): number;
308
+ private processTTL;
309
+ /**
310
+ * Register a callback for stream records on a specific table.
311
+ * Only available when using the 'memory' engine.
312
+ */
313
+ onStreamRecord(tableName: string, callback: StreamCallback): () => void;
314
+ /**
315
+ * Reset the server, clearing all tables and data.
316
+ * Only available when using the 'memory' engine.
317
+ */
318
+ reset(): void;
319
+ /**
320
+ * Get the internal table store.
321
+ * Only available when using the 'memory' engine.
322
+ */
323
+ getTableStore(): TableStore;
324
+ }
325
+
326
+ declare class VirtualClock {
327
+ private offset;
328
+ now(): number;
329
+ nowInSeconds(): number;
330
+ advance(ms: number): void;
331
+ set(timestamp: number): void;
332
+ reset(): void;
333
+ }
334
+
335
+ declare class DynamoDBError extends Error {
336
+ readonly __type: string;
337
+ readonly statusCode: number;
338
+ constructor(type: string, message: string, statusCode?: number);
339
+ toJSON(): {
340
+ __type: string;
341
+ message: string;
342
+ };
343
+ }
344
+ declare class ValidationException extends DynamoDBError {
345
+ constructor(message: string);
346
+ }
347
+ declare class ResourceNotFoundException extends DynamoDBError {
348
+ constructor(message: string);
349
+ }
350
+ declare class ResourceInUseException extends DynamoDBError {
351
+ constructor(message: string);
352
+ }
353
+ declare class ConditionalCheckFailedException extends DynamoDBError {
354
+ readonly Item?: Record<string, unknown>;
355
+ constructor(message?: string, item?: Record<string, unknown>);
356
+ toJSON(): {
357
+ Item?: Record<string, unknown> | undefined;
358
+ __type: string;
359
+ message: string;
360
+ };
361
+ }
362
+ interface CancellationReason {
363
+ Code: 'None' | 'ConditionalCheckFailed' | 'ItemCollectionSizeLimitExceeded' | 'TransactionConflict' | 'ProvisionedThroughputExceeded' | 'ThrottlingError' | 'ValidationError';
364
+ Message?: string | null;
365
+ Item?: Record<string, unknown>;
366
+ }
367
+ declare class TransactionCanceledException extends DynamoDBError {
368
+ readonly CancellationReasons: CancellationReason[];
369
+ constructor(message: string, reasons: CancellationReason[]);
370
+ toJSON(): {
371
+ __type: string;
372
+ message: string;
373
+ CancellationReasons: CancellationReason[];
374
+ };
375
+ }
376
+ declare class TransactionConflictException extends DynamoDBError {
377
+ constructor(message?: string);
378
+ }
379
+ declare class ProvisionedThroughputExceededException extends DynamoDBError {
380
+ constructor(message?: string);
381
+ }
382
+ declare class ItemCollectionSizeLimitExceededException extends DynamoDBError {
383
+ constructor(message?: string);
384
+ }
385
+ declare class InternalServerError extends DynamoDBError {
386
+ constructor(message?: string);
387
+ }
388
+ declare class SerializationException extends DynamoDBError {
389
+ constructor(message: string);
390
+ }
391
+ declare class IdempotentParameterMismatchException extends DynamoDBError {
392
+ constructor(message?: string);
22
393
  }
23
394
 
24
- export { DynamoDBServer };
395
+ export { type AttributeDefinition, type AttributeMap, type AttributeValue, type CancellationReason, ConditionalCheckFailedException, type ConsumedCapacity, DynamoDBError, DynamoDBServer, type DynamoDBServerConfig, type Engine, type GlobalSecondaryIndex, type GlobalSecondaryIndexDescription, IdempotentParameterMismatchException, InternalServerError, ItemCollectionSizeLimitExceededException, type KeySchemaElement, type LocalSecondaryIndex, type LocalSecondaryIndexDescription, type Projection, type ProvisionedThroughput, ProvisionedThroughputExceededException, ResourceInUseException, ResourceNotFoundException, SerializationException, type StreamCallback, type StreamRecord, type StreamSpecification, type StreamViewType, type TableDescription, type TimeToLiveSpecification, TransactionCanceledException, TransactionConflictException, ValidationException, VirtualClock };