dinah 0.5.0 → 0.6.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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/expression-builder.ts","../src/repo.ts","../src/db.ts","../src/table.ts"],"sourcesContent":["import type { Obj } from \"./types\";\n\nconst attrTypes = [\"S\", \"SS\", \"N\", \"NS\", \"B\", \"BS\", \"BOOL\", \"NULL\", \"L\", \"M\"] as const;\nconst comparatorOps: Obj<string> = {\n $eq: \"=\",\n $ne: \"<>\",\n $gt: \">\",\n $gte: \">=\",\n $lt: \"<\",\n $lte: \"<=\",\n};\n\n// TODO should { $eq: undefined } and { $ne: undefined } be converted into attribute_not_exists and attribute_exists ?\n\nexport const isOperation = (val: unknown): val is Obj => {\n if (!val || typeof val !== \"object\" || Array.isArray(val)) return false;\n return Object.keys(val).every((op) => op.startsWith(\"$\"));\n};\n\nexport class ExpressionBuilder {\n protected readonly attrNames = new Map<string, string>();\n protected readonly attrValues = new Map<unknown, string>();\n\n get attributeNames(): Obj<string> | undefined {\n return this.attrNames.size\n ? Object.fromEntries(\n [...this.attrNames.entries()].map(([name, placeholder]) => [placeholder, name]),\n )\n : undefined;\n }\n\n get attributeValues(): Obj | undefined {\n return this.attrValues.size\n ? Object.fromEntries(\n [...this.attrValues.entries()].map(([value, placeholder]) => [placeholder, value]),\n )\n : undefined;\n }\n\n reset(): void {\n this.attrNames.clear();\n this.attrValues.clear();\n }\n\n getPathSub(path: string): string {\n const segments = path.split(\".\");\n const placeholders: string[] = [];\n\n for (const segment of segments) {\n let placeholder = this.attrNames.get(segment);\n if (!placeholder) {\n placeholder = `#${this.attrNames.size}`;\n this.attrNames.set(segment, placeholder);\n }\n\n placeholders.push(placeholder);\n }\n\n return placeholders.join(\".\");\n }\n\n getValueSub(value: unknown): string {\n let placeholder = this.attrValues.get(value);\n if (!placeholder) {\n placeholder = `:${this.attrValues.size}`;\n this.attrValues.set(value, placeholder);\n }\n\n return placeholder;\n }\n\n getValueOrPathSub(pathOrValue: unknown): string {\n if (isOperation(pathOrValue)) {\n if (pathOrValue.$path) return this.getPathSub(pathOrValue.$path);\n throw new Error(\"Expected $path or operand.\");\n }\n\n return this.getValueSub(pathOrValue);\n }\n\n projection<T extends string[] | undefined>(paths: T): T extends undefined ? undefined : string {\n return paths?.map((path) => this.getPathSub(path)).join(\", \") as never;\n }\n\n condition<T extends Obj | undefined>(expression: T): T extends undefined ? undefined : string {\n if (!expression) return undefined as never;\n\n const expressions: string[] = [];\n for (const [key, val] of Object.entries(expression)) {\n if (key === \"$and\") {\n if (!Array.isArray(val)) throw new Error(\"$and expects an array operand.\");\n expressions.push(`(${val.map((v) => this.condition(v)).join(\" AND \")})`);\n } else if (key === \"$or\" && Array.isArray(val)) {\n if (!Array.isArray(val)) throw new Error(\"$or expects an array operand.\");\n expressions.push(`(${val.map((v) => this.condition(v)).join(\" OR \")})`);\n } else if (key === \"$not\") {\n if (!val || typeof val !== \"object\") throw new Error(\"$not expects an object operand.\");\n expressions.push(`NOT ${this.condition(val)}`);\n } else if (!key.startsWith(\"$\")) {\n expressions.push(this.resolveCondition(key, val));\n } else {\n throw new Error(\n `Unexpected operator \"${key}\". Expected attribute path or compound operator.`,\n );\n }\n }\n\n return expressions.join(\" AND \") as never;\n }\n\n update<T extends Obj | undefined>(expression: T): T extends undefined ? undefined : string {\n if (expression === undefined) return undefined as never;\n\n const setOperations: string[] = [];\n const removeOperations: string[] = [];\n const setAddOperations: string[] = [];\n const setDelOperations: string[] = [];\n\n for (const [path, valOrOperation] of Object.entries(expression)) {\n const placeholder = this.getPathSub(path);\n\n if (valOrOperation === undefined) {\n removeOperations.push(placeholder);\n } else if (isOperation(valOrOperation)) {\n if (valOrOperation.$remove === true) {\n removeOperations.push(placeholder);\n } else if (valOrOperation.$setAdd !== undefined || valOrOperation.$setDel !== undefined) {\n const operations = valOrOperation.$setAdd ? setAddOperations : setDelOperations;\n const operand = valOrOperation.$setAdd ?? valOrOperation.$setDel;\n operations.push(\n `${placeholder} ${this.getValueSub(operand instanceof Set ? operand : new Set([operand].flat()))}`,\n );\n } else {\n setOperations.push(`${placeholder} = ${this.resolveSetOperand(path, valOrOperation)}`);\n }\n } else {\n setOperations.push(`${placeholder} = ${this.getValueSub(valOrOperation)}`);\n }\n }\n\n let updateExpression = \"\";\n if (setOperations.length) {\n updateExpression += `SET ${setOperations.join(\", \")} `;\n }\n\n if (removeOperations.length) {\n updateExpression += `REMOVE ${removeOperations.join(\", \")} `;\n }\n\n if (setAddOperations.length) {\n updateExpression += `ADD ${setAddOperations.join(\", \")} `;\n }\n\n if (setDelOperations.length) {\n updateExpression += `DELETE ${setDelOperations.join(\", \")} `;\n }\n\n return updateExpression as never;\n }\n\n protected resolveCondition(path: string, exp: unknown): string {\n if (!exp || typeof exp !== \"object\" || !Object.keys(exp).at(0)?.startsWith(\"$\")) {\n return this.resolveCondition(path, { $eq: exp });\n }\n\n const placeholder = this.getPathSub(path);\n const [operator, operand] = Object.entries(exp).at(0) ?? [\"\"];\n\n if (comparatorOps[operator]) {\n if (isOperation(operand) && operand.$path) {\n return `${placeholder} ${comparatorOps[operator]} ${this.getPathSub(operand.$path)}`;\n }\n\n if (![\"string\", \"boolean\", \"number\"].includes(typeof operand)) {\n throw new Error(`${operator} expects a primitive/scalar operand.`);\n }\n return `${placeholder} ${comparatorOps[operator]} ${this.getValueSub(operand)}`;\n }\n\n switch (operator) {\n case \"$in\":\n if (!Array.isArray(operand)) {\n throw new Error(\"$in operator expects an array operand.\");\n }\n return `${placeholder} IN (${operand.map((op) => this.getValueSub(op)).join(\", \")})`;\n\n case \"$nin\":\n if (!Array.isArray(operand)) {\n throw new Error(\"$nin operator expects an array operand.\");\n }\n return `${placeholder} NOT IN (${operand.map((op) => this.getValueSub(op)).join(\", \")})`;\n\n case \"$prefix\":\n if (typeof operand !== \"string\") {\n throw new Error(\"$prefix operator expects a string operand.\");\n }\n return `begins_with(${placeholder}, ${this.getValueSub(operand)})`;\n\n case \"$includes\":\n return `contains(${placeholder}, ${this.getValueSub(operand)})`;\n\n case \"$between\":\n if (!Array.isArray(operand) || operand.length !== 2) {\n throw new Error(\"$between operator expects an array operand of exactly two values.\");\n }\n return `${placeholder} BETWEEN ${this.getValueSub(operand[0])} AND ${this.getValueSub(operand[1])}`;\n\n case \"$exists\":\n if (typeof operand !== \"boolean\") {\n throw new Error(\"$exists operator expects a boolean operand.\");\n }\n return operand\n ? `attribute_exists(${placeholder})`\n : `attribute_not_exists(${placeholder})`;\n\n case \"$type\":\n if (!attrTypes.includes(operand as any)) {\n throw new Error(`$type operator expects operand to be one of ${attrTypes.join(\",\")}`);\n }\n return `attribute_type(${placeholder})`;\n\n case \"$size\": {\n const sizeExp = typeof operand === \"number\" ? { $eq: operand } : operand;\n if (\n !sizeExp ||\n typeof sizeExp !== \"object\" ||\n !Object.keys(sizeExp).at(0)?.startsWith(\"$\")\n ) {\n throw new Error(\"$size operator expects a number operand or a comparator object.\");\n }\n const [sizeOperator, sizeOperand] = Object.entries(sizeExp).at(0) ?? [\"\"];\n\n if (!comparatorOps[sizeOperator]) {\n throw new Error(\"$size operator expects a number operand or a comparator object.\");\n }\n\n if (![\"string\", \"boolean\", \"number\"].includes(typeof sizeOperand)) {\n throw new Error(`${operator} expects a primitive/scalar operand.`);\n }\n\n return `size(${placeholder}) ${comparatorOps[sizeOperator]} ${this.getValueSub(sizeOperand)}`;\n }\n\n default:\n throw new Error(`Invalid operator \"${operator}\"`);\n }\n }\n\n protected resolveSetOperand(path: string, operand: unknown): string {\n if (isOperation(operand)) {\n if (operand.$ifNotExists) {\n const params = Array.isArray(operand.$ifNotExists)\n ? operand.$ifNotExists\n : [path, operand.$ifNotExists];\n return `if_not_exists(${this.getPathSub(params[0])}, ${this.resolveSetOperand(path, params[1])})`;\n }\n\n if (operand.$set) {\n return this.resolveSetOperand(path, operand.$set);\n }\n\n if (operand.$plus !== undefined || operand.$minus !== undefined) {\n const mathOperator = operand.$plus ? \"+\" : \"-\";\n const mathOperand = operand.$plus ?? operand.$minus;\n const params = Array.isArray(mathOperand) ? mathOperand : [{ $path: path }, mathOperand];\n return `${params.map((param) => this.resolveSetOperand(path, param)).join(` ${mathOperator} `)}`;\n }\n\n if (operand.$append !== undefined || operand.$prepend !== undefined) {\n const listOperand = operand.$append ?? operand.$prepend;\n const resolvedListOperand = isOperation(listOperand) ? listOperand : [listOperand].flat();\n const params = operand.$append\n ? [{ $path: path }, resolvedListOperand]\n : [resolvedListOperand, { $path: path }];\n return `list_append(${params.map((param) => this.resolveSetOperand(path, param)).join(\", \")})`;\n }\n }\n\n return this.getValueOrPathSub(operand);\n }\n}\n","import type { Db } from \"./db\";\nimport type { Table } from \"./table\";\nimport type {\n Condition,\n DbTrxGetRequest,\n DbTrxWriteRequest,\n ExtractTableDef,\n ExtractTableSchema,\n TableGsiNames,\n Obj,\n RepoBatchGetOptions,\n RepoBatchGetOrThrowResult,\n RepoBatchGetResult,\n RepoBatchWrite,\n RepoBatchWriteResult,\n RepoCreateOptions,\n RepoCreateItem,\n RepoCreateResult,\n RepoDeleteOptions,\n RepoDeleteOrThrowResult,\n RepoDeleteResult,\n RepoExistsOptions,\n RepoGetOptions,\n RepoGetOrThrowResult,\n RepoGetResult,\n RepoKey,\n RepoPutOptions,\n RepoPutItem,\n RepoPutResult,\n RepoQueryOptions,\n RepoQueryGsiOptions,\n RepoQueryGsiPagedResult,\n RepoQueryGsiResult,\n RepoQueryPagedResult,\n RepoQueryResult,\n RepoScanOptions,\n RepoScanGsiOptions,\n RepoScanGsiPagedResult,\n RepoScanGsiResult,\n RepoScanPagedResult,\n RepoScanResult,\n RepoTrxGetOptions,\n RepoTrxGetOrThrowResult,\n RepoTrxGetResult,\n RepoTrxWriteRequest,\n RepoUpdateOptions,\n RepoUpdateData,\n RepoUpdateResult,\n RepoQueryGsiQuery,\n RepoQueryQuery,\n} from \"./types\";\n\n// TODO: query/queryGsi needs strongly typed \"key\" argument\n// allows =,>,>=,<,<=,begins_with, between on sort key\n// util -> extractExclusiveStartKey(item)\n\nexport abstract class AbstractRepo<T extends Table> {\n // these phantom properties are used to pre-compute types derived from T\n // which allows easy lookups using the \"this\" AbstractRepo type\n declare readonly $schema: ExtractTableSchema<T>;\n declare readonly $def: ExtractTableDef<T>;\n\n abstract readonly table: T;\n readonly db: Db;\n constructor(db: Db) {\n this.db = db;\n }\n\n get tableName(): string {\n return `${this.db.config?.tableNamePrefix ?? \"\"}${this.table.def.name}`;\n }\n\n get defaultPutData(): Partial<ExtractTableSchema<T>> {\n return {};\n }\n\n get defaultUpdateData(): Partial<ExtractTableSchema<T>> {\n return {};\n }\n\n transformItem(item: ExtractTableSchema<T>): ExtractTableSchema<T> {\n return item;\n }\n\n // TODO: should this throw if pk is missing?\n // should return type by narrower?\n extractKey(item: RepoKey<this>): RepoKey<this> {\n const { partitionKey, sortKey } = this.table.def;\n if (sortKey) {\n return {\n [partitionKey]: item[partitionKey as keyof RepoKey<this>],\n [sortKey]: item[sortKey as keyof RepoKey<this>],\n } as RepoKey<this>;\n }\n\n return { [partitionKey]: item[partitionKey as keyof RepoKey<this>] } as RepoKey<this>;\n }\n\n async get<O extends RepoGetOptions<this>>(\n key: RepoKey<this>,\n options?: O,\n ): Promise<RepoGetResult<this, O>> {\n const item = await this.db.get({\n table: this.tableName,\n key: this.extractKey(key),\n ...options,\n });\n return item && this.applyTransformIfNeeded(item, options);\n }\n\n async getOrThrow<O extends RepoGetOptions<this>>(\n key: RepoKey<this>,\n options?: O,\n ): Promise<RepoGetOrThrowResult<this, O>> {\n const item = await this.db.getOrThrow({\n table: this.tableName,\n key: this.extractKey(key),\n ...options,\n });\n return this.applyTransformIfNeeded(item, options);\n }\n\n async put(item: RepoPutItem<this>, options?: RepoPutOptions<this>): Promise<RepoPutResult<this>> {\n const itemWithDefaults = { ...this.defaultPutData, ...item };\n const result = await this.db.put({ table: this.tableName, item: itemWithDefaults, ...options });\n return this.applyTransformIfNeeded(result);\n }\n\n async update(\n key: RepoKey<this>,\n update: RepoUpdateData,\n options?: RepoUpdateOptions<this>,\n ): Promise<RepoUpdateResult<this>> {\n const updateWithDefaults = { ...this.defaultUpdateData, ...update };\n const result = await this.db.update({\n table: this.tableName,\n key: this.extractKey(key),\n update: updateWithDefaults,\n ...options,\n });\n return this.applyTransformIfNeeded(result);\n }\n\n async create(\n item: RepoPutItem<this>,\n options?: RepoCreateOptions<this>,\n ): Promise<RepoCreateResult<this>> {\n const { condition: otherCondition, ...otherOptions } = options ?? {};\n\n const condition = { $and: [{ [this.table.def.partitionKey]: { $exists: false } }] } as any;\n\n if (otherCondition) {\n condition.$and.push(otherCondition);\n }\n\n return this.put(item, { condition, ...otherOptions });\n }\n\n async delete(\n key: RepoKey<this>,\n options?: RepoDeleteOptions<this>,\n ): Promise<RepoDeleteResult<this>> {\n const item = await this.db.delete({\n table: this.tableName,\n key: this.extractKey(key),\n ...options,\n });\n return item && this.applyTransformIfNeeded(item);\n }\n\n async deleteOrThrow(\n key: RepoKey<this>,\n options?: Omit<RepoDeleteOptions<this>, \"return\">,\n ): Promise<RepoDeleteOrThrowResult<this>> {\n const item = await this.db.deleteOrThrow({\n table: this.tableName,\n key: this.extractKey(key),\n ...options,\n });\n return this.applyTransformIfNeeded(item);\n }\n\n async query<O extends RepoQueryOptions<this>>(\n query: RepoQueryQuery<this>,\n options?: O,\n ): Promise<RepoQueryResult<this, O>> {\n const items = await this.db.query({ table: this.tableName, query, ...options });\n return this.applyTransformsIfNeeded(items, options);\n }\n\n async *queryPaged<O extends RepoQueryOptions<this>>(\n query: RepoQueryQuery<this>,\n options?: O,\n ): RepoQueryPagedResult<this, O> {\n for await (const page of this.db.queryPaged({ table: this.tableName, query, ...options })) {\n yield this.applyTransformsIfNeeded(page, options);\n }\n }\n\n async queryGsi<G extends TableGsiNames<T>, O extends RepoQueryGsiOptions<this, T, G>>(\n gsi: G,\n query: RepoQueryGsiQuery<T, G>,\n options?: O,\n ): Promise<RepoQueryGsiResult<this, O, G>> {\n const items = await this.db.query({ table: this.tableName, index: gsi, query, ...options });\n return this.applyTransformsIfNeeded(items, { ...options, gsi });\n }\n\n async *queryGsiPaged<G extends TableGsiNames<T>, O extends RepoQueryGsiOptions<this, T, G>>(\n gsi: G,\n query: RepoQueryGsiQuery<T, G>,\n options?: O,\n ): RepoQueryGsiPagedResult<this, O, G> {\n for await (const page of this.db.queryPaged({\n table: this.tableName,\n index: gsi,\n query,\n ...options,\n })) {\n yield this.applyTransformsIfNeeded(page, { ...options, gsi });\n }\n }\n\n async scan<O extends RepoScanOptions<this>>(options?: O): Promise<RepoScanResult<this, O>> {\n const items = await this.db.scan({ table: this.tableName, ...options });\n return this.applyTransformsIfNeeded(items, options);\n }\n\n async *scanPaged<O extends RepoScanOptions<this>>(options?: O): RepoScanPagedResult<this, O> {\n for await (const page of this.db.scanPaged({ table: this.tableName, ...options })) {\n yield this.applyTransformsIfNeeded(page, options);\n }\n }\n\n async scanGsi<G extends TableGsiNames<T>, O extends RepoScanGsiOptions<this, T, G>>(\n gsi: G,\n options?: O,\n ): Promise<RepoScanGsiResult<this, O, G>> {\n const items = await this.db.scan({ table: this.tableName, index: gsi, ...options });\n return this.applyTransformsIfNeeded(items, { ...options, gsi });\n }\n\n async *scanGsiPaged<G extends TableGsiNames<T>, O extends RepoScanGsiOptions<this, T, G>>(\n gsi: G,\n options?: O,\n ): RepoScanGsiPagedResult<this, O, G> {\n for await (const page of this.db.scanPaged({\n table: this.tableName,\n index: gsi,\n ...options,\n })) {\n yield this.applyTransformsIfNeeded(page, { ...options, gsi });\n }\n }\n\n async exists(options?: RepoExistsOptions<this>): Promise<boolean> {\n return this.db.exists({\n table: this.tableName,\n projection: [this.table.def.partitionKey],\n ...options,\n });\n }\n\n async existsGsi(gsi: TableGsiNames<T>, options?: RepoExistsOptions<this>): Promise<boolean> {\n return this.db.exists({\n table: this.tableName,\n index: gsi,\n projection: [this.table.def.partitionKey],\n ...options,\n });\n }\n\n async batchGet<O extends RepoBatchGetOptions<this>>(\n keys: RepoKey<this>[],\n options?: O,\n ): Promise<RepoBatchGetResult<this, O>> {\n const { items, unprocessed } = await this.db.batchGet({\n [this.tableName]: { keys: keys.map((key) => this.extractKey(key)), ...options },\n });\n const tableItems = items[this.tableName];\n return {\n items: tableItems && this.applyTransformsIfNeeded(tableItems, options),\n unprocessed: unprocessed?.[this.tableName]?.keys,\n } as RepoBatchGetResult<this, O>;\n }\n\n async batchGetOrThrow<O extends RepoBatchGetOptions<this>>(\n keys: RepoKey<this>[],\n options?: O,\n ): Promise<RepoBatchGetOrThrowResult<this, O>> {\n const result = await this.db.batchGetOrThrow({\n [this.tableName]: { keys: keys.map((key) => this.extractKey(key)), ...options },\n });\n return this.applyTransformsIfNeeded(result[this.tableName] ?? [], options);\n }\n\n async batchWrite(requests: RepoBatchWrite<this>): Promise<RepoBatchWriteResult<this>> {\n const { items, unprocessed } = await this.db.batchWrite({\n [this.tableName]: requests.map((request) => {\n if (request.type === \"DELETE\") {\n return { type: \"DELETE\", key: this.extractKey(request.key) };\n } else {\n const itemWithDefaults = { ...this.defaultPutData, ...request.item };\n return { type: \"PUT\", item: itemWithDefaults };\n }\n }),\n });\n\n return {\n items: items[this.tableName],\n unprocessed: unprocessed?.[this.tableName],\n } as RepoBatchWriteResult<this>;\n }\n\n async trxGet<O extends RepoTrxGetOptions<this>>(\n keys: RepoKey<this>[],\n options?: O,\n ): Promise<RepoTrxGetResult<this, O>> {\n const items = await this.db.trxGet(\n ...keys.map((key) => ({\n table: this.tableName,\n key: this.extractKey(key),\n ...options,\n })),\n );\n return items.map((item: any) => item && this.applyTransformIfNeeded(item, options)) as any;\n }\n\n async trxGetOrThrow<O extends RepoTrxGetOptions<this>>(\n keys: RepoKey<this>[],\n options?: O,\n ): Promise<RepoTrxGetOrThrowResult<this, O>> {\n const items = await this.db.trxGetOrThrow(\n ...keys.map((key) => ({\n table: this.tableName,\n key: this.extractKey(key),\n ...options,\n })),\n );\n return this.applyTransformsIfNeeded(items, options);\n }\n\n async trxWrite(...requests: RepoTrxWriteRequest<this>[]): Promise<void> {\n await this.db.trxWrite(\n ...requests.map((request) => {\n switch (request.type) {\n case \"CONDITION\": {\n const { key, condition, ...options } = request;\n return this.trxConditionRequest(key, condition, options);\n }\n\n case \"DELETE\": {\n const { key, ...options } = request;\n return this.trxDeleteRequest(key, options);\n }\n\n case \"PUT\": {\n const { item, ...options } = request;\n return this.trxPutRequest(item, options);\n }\n\n case \"UPDATE\": {\n const { key, update, ...options } = request;\n return this.trxUpdateRequest(key, update, options);\n }\n\n default:\n throw new Error(\"Unexpected request type.\");\n }\n }),\n );\n }\n\n async trxDelete(\n keys: RepoKey<this>[],\n options?: Omit<RepoDeleteOptions<this>, \"return\">,\n ): Promise<void> {\n return this.db.trxWrite(...keys.map((key) => this.trxDeleteRequest(key, options)));\n }\n\n // todo: return items\n async trxPut(\n items: RepoPutItem<this>[],\n options?: Omit<RepoPutOptions<this>, \"return\">,\n ): Promise<void> {\n return this.db.trxWrite(...items.map((item) => this.trxPutRequest(item, options)));\n }\n\n async trxUpdate(\n keys: RepoKey<this>[],\n update: RepoUpdateData,\n options?: Omit<RepoUpdateOptions<this>, \"return\">,\n ): Promise<void> {\n return this.db.trxWrite(...keys.map((key) => this.trxUpdateRequest(key, update, options)));\n }\n\n // todo: return items\n async trxCreate(items: RepoCreateItem<this>[], options?: RepoCreateOptions<this>): Promise<void> {\n return this.db.trxWrite(...items.map((item) => this.trxCreateRequest(item, options)));\n }\n\n trxGetRequest<O extends RepoGetOptions<this>>(\n key: RepoKey<this>,\n options?: O,\n ): DbTrxGetRequest<RepoGetOrThrowResult<this, O>> {\n return { table: this.tableName, key: this.extractKey(key), ...options };\n }\n\n trxDeleteRequest(\n key: RepoKey<this>,\n options?: Omit<RepoDeleteOptions<this>, \"return\">,\n ): DbTrxWriteRequest {\n return { table: this.tableName, type: \"DELETE\", key: this.extractKey(key), ...options };\n }\n\n trxConditionRequest(\n key: RepoKey<this>,\n condition: Condition<ExtractTableSchema<T>>,\n options?: Omit<RepoDeleteOptions<this>, \"return\" | \"condition\">,\n ): DbTrxWriteRequest {\n return {\n table: this.tableName,\n type: \"CONDITION\",\n key: this.extractKey(key),\n condition,\n ...options,\n };\n }\n\n trxPutRequest(\n item: RepoPutItem<this>,\n options?: Omit<RepoPutOptions<this>, \"return\">,\n ): DbTrxWriteRequest {\n const itemWithDefaults = { ...this.defaultPutData, ...item };\n return { table: this.tableName, type: \"PUT\", item: itemWithDefaults, ...options };\n }\n\n trxUpdateRequest(\n key: RepoKey<this>,\n update: RepoUpdateData,\n options?: Omit<RepoUpdateOptions<this>, \"return\">,\n ): DbTrxWriteRequest {\n const updateWithDefaults = { ...this.defaultUpdateData, ...update };\n return {\n table: this.tableName,\n type: \"UPDATE\",\n key: this.extractKey(key),\n update: updateWithDefaults,\n ...options,\n };\n }\n\n trxCreateRequest(\n item: RepoCreateItem<this>,\n options?: RepoCreateOptions<this>,\n ): DbTrxWriteRequest {\n const { condition: otherCondition, ...otherOptions } = options ?? {};\n\n const condition = { $and: [{ [this.table.def.partitionKey]: { $exists: false } }] } as any;\n\n if (otherCondition) {\n condition.$and.push(otherCondition);\n }\n\n const itemWithDefaults = { ...this.defaultPutData, ...item };\n\n return {\n table: this.tableName,\n type: \"PUT\",\n item: itemWithDefaults,\n condition,\n ...otherOptions,\n };\n }\n\n private applyTransformsIfNeeded(\n items: Obj[],\n options?: { projection?: any[]; gsi?: string },\n ): any[] {\n // transforms aren't applied when applying a projection\n if (options?.projection?.length) return items;\n if (options?.gsi) {\n // projections inherited to GSIs also prevent transformation\n const gsiProj = this.table.def.gsis?.[options.gsi]?.projection;\n if (gsiProj === \"KEYS_ONLY\" || Array.isArray(gsiProj)) return items;\n }\n\n return items.map((item) => this.transformItem(item as ExtractTableSchema<T>));\n }\n\n private applyTransformIfNeeded(item: Obj, options?: { projection?: any[]; gsi?: string }): any {\n const [transformedItem] = this.applyTransformsIfNeeded([item], options);\n return transformedItem;\n }\n}\n\nexport class Repo<T extends Table<any, any>> extends AbstractRepo<T> {\n readonly table: T;\n\n constructor(db: Db, table: T) {\n super(db);\n this.table = table;\n }\n}\n","import {\n type BatchGetItemInput,\n type BatchWriteItemInput,\n CreateTableCommand,\n DeleteTableCommand,\n DynamoDB,\n DynamoDBClient,\n type DynamoDBClientConfig,\n ListTablesCommand,\n type WriteRequest,\n} from \"@aws-sdk/client-dynamodb\";\n//import { DynamoDBStreams } from '@aws-sdk/client-dynamodb-streams';\nimport type { TransactGetCommandInput, TransactWriteCommandInput } from \"@aws-sdk/lib-dynamodb\";\nimport * as Lib from \"@aws-sdk/lib-dynamodb\";\nimport { ExpressionBuilder } from \"./expression-builder\";\nimport { Repo } from \"./repo\";\nimport type { Table } from \"./table\";\nimport type {\n DbBatchGet,\n DbBatchGetResponse,\n DbBatchWrite,\n DbBatchWriteResponse,\n DbConfig,\n DbDelete,\n DbExists,\n DbGet,\n DbListTables,\n DbPut,\n DbQuery,\n DbScan,\n DbTrxGetOrThrowResult,\n DbTrxGetRequest,\n DbTrxGetResult,\n DbTrxWriteRequest,\n DbUpdate,\n Obj,\n} from \"./types\";\nimport { extractTableDesc, removeUndefined } from \"./util\";\n\n// TODO\n// - caching support?\n// - consider special \"limit\" handling for paged scans, maybe have \"scanLimit\" too\n// - consider \"sort\" shorthand for methods that return unpaginated collections\n// i.e. sort: { by: 'createdAt', dir: 'ASC' } or sort: (a,b) => a.createdAt - b.createdAt\n// - consider support for batchUpdates leveraging BatchExecute and PartiQL\n// - consider batchPut (batchPutOrThrow) and batchDelete that operate on a single table\n// - getGsi? throws if > 1 result, allows for assert, and filtering\n// - bug $in doesn't handle empty arrays, I imagine other operators are affected\n// - consider beforeCreate, beforePut, beforeUpdate, beforeDelete, after, etc.\n// - type out repo update data\n\nexport class Db {\n readonly client: Lib.DynamoDBDocumentClient;\n readonly config: DbConfig | undefined;\n\n //protected streamEventListeners: DbStreamEventListener[] = [];\n\n constructor(\n clientOrConfig: DynamoDBClient | DynamoDB | DynamoDBClientConfig,\n dbConfig?: DbConfig,\n ) {\n if (clientOrConfig instanceof DynamoDBClient || clientOrConfig instanceof DynamoDB) {\n this.client = Lib.DynamoDBDocumentClient.from(new DynamoDBClient(clientOrConfig));\n } else {\n const { endpoint, ...clientConfig } = clientOrConfig;\n // client doesn't interpret an empty string endpoint as falsy so normalize things\n // here so consumers don't have to worry about that quirk\n this.client = Lib.DynamoDBDocumentClient.from(\n new DynamoDBClient({\n endpoint: endpoint || undefined,\n ...clientConfig,\n }),\n );\n }\n\n this.config = dbConfig;\n }\n\n createRepo<T extends Table>(table: T): Repo<T> {\n return new Repo(this, table);\n }\n\n async createTable(table: Table): Promise<void> {\n await this.client.send(new CreateTableCommand(extractTableDesc(table)));\n }\n\n async deleteTable(tableName: string): Promise<void> {\n await this.client.send(new DeleteTableCommand({ TableName: tableName }));\n }\n\n async listTables(data?: DbListTables): Promise<string[]> {\n const tables: string[] = [];\n let lastEvaluatedTableName: string | undefined;\n do {\n const output = await this.client.send(\n new ListTablesCommand({\n Limit: data?.limit,\n ExclusiveStartTableName: lastEvaluatedTableName,\n }),\n );\n\n tables.push(...(output.TableNames ?? []));\n lastEvaluatedTableName = output.LastEvaluatedTableName;\n } while (lastEvaluatedTableName);\n return tables;\n }\n\n async get<R = Obj>(data: DbGet): Promise<R | undefined> {\n const exp = new ExpressionBuilder();\n\n const input = new Lib.GetCommand({\n TableName: data.table,\n Key: data.key,\n ConsistentRead: data.consistent,\n ProjectionExpression: exp.projection(data.projection),\n ExpressionAttributeNames: exp.attributeNames,\n });\n\n const output = await this.client.send(input);\n\n if (output.Item && data.filter && !data.filter(output.Item)) {\n return undefined;\n }\n\n return output.Item as R;\n }\n\n async getOrThrow<R = Obj>(data: DbGet): Promise<R> {\n const item = await this.get<R>(data);\n if (!item) {\n throw new Error(`Item not found in \"${data.table}\" table.`);\n }\n return item;\n }\n\n async put<R = Obj>(data: DbPut): Promise<R> {\n const exp = new ExpressionBuilder();\n\n const item = removeUndefined(data.item);\n\n const input = new Lib.PutCommand({\n TableName: data.table,\n Item: item,\n ReturnValues: data.returnOld ? \"ALL_OLD\" : \"NONE\",\n ReturnValuesOnConditionCheckFailure: \"ALL_OLD\",\n ConditionExpression: exp.condition(data.condition),\n ExpressionAttributeNames: exp.attributeNames,\n ExpressionAttributeValues: exp.attributeValues,\n });\n\n const output = await this.client.send(input);\n\n return (data.returnOld ? output.Attributes : item) as R;\n }\n\n async update<R = Obj>(data: DbUpdate): Promise<R> {\n const exp = new ExpressionBuilder();\n\n const condition = {\n $and: Object.keys(data.key).map((field) => ({\n [field]: { $exists: true },\n })),\n };\n\n if (data.condition) {\n condition.$and.push(data.condition);\n }\n\n const input = new Lib.UpdateCommand({\n TableName: data.table,\n Key: data.key,\n ReturnValues: \"ALL_NEW\",\n ReturnValuesOnConditionCheckFailure: \"ALL_OLD\",\n UpdateExpression: exp.update(data.update),\n ConditionExpression: exp.condition(condition),\n ExpressionAttributeNames: exp.attributeNames,\n ExpressionAttributeValues: exp.attributeValues,\n });\n\n const output = await this.client.send(input);\n\n return output.Attributes as R;\n }\n\n async delete<R = Obj>(data: DbDelete): Promise<R | undefined> {\n const exp = new ExpressionBuilder();\n\n const input = new Lib.DeleteCommand({\n TableName: data.table,\n Key: data.key,\n ReturnValues: \"ALL_OLD\",\n ConditionExpression: exp.condition(data.condition),\n ReturnValuesOnConditionCheckFailure: \"ALL_OLD\",\n ExpressionAttributeNames: exp.attributeNames,\n ExpressionAttributeValues: exp.attributeValues,\n });\n\n const output = await this.client.send(input);\n\n return output.Attributes as R | undefined;\n }\n\n async deleteOrThrow<R = Obj>(data: DbDelete): Promise<R> {\n const item = await this.delete<R>(data);\n if (!item) {\n throw new Error(`Item not found in \"${data.table}\" table.`);\n }\n return item;\n }\n\n async *queryPaged<R = Obj>(data: DbQuery): AsyncGenerator<R[]> {\n const exp = new ExpressionBuilder();\n\n let lastEvaluatedKey = data.startKey;\n do {\n const input = new Lib.QueryCommand({\n TableName: data.table,\n IndexName: data.index,\n ExclusiveStartKey: lastEvaluatedKey,\n Limit: data.limit,\n ScanIndexForward: data.sort !== \"DESC\",\n ConsistentRead: data.consistent,\n KeyConditionExpression: exp.condition(data.query),\n ProjectionExpression: exp.projection(data.projection),\n FilterExpression: exp.condition(data.filter),\n ExpressionAttributeNames: exp.attributeNames,\n ExpressionAttributeValues: exp.attributeValues,\n });\n\n const output = await this.client.send(input);\n\n if (output.Items?.length) {\n yield output.Items as R[];\n }\n lastEvaluatedKey = output.LastEvaluatedKey;\n } while (lastEvaluatedKey);\n }\n\n async query<R = Obj>(data: DbQuery): Promise<R[]> {\n const items: Obj[] = [];\n\n for await (const page of this.queryPaged(data)) {\n items.push(...page);\n }\n\n return items as R[];\n }\n\n async *scanPaged<R = Obj>(data: DbScan): AsyncGenerator<R[]> {\n const exp = new ExpressionBuilder();\n\n const totalSegments = data.parallel ?? 1;\n const segments = [...Array(totalSegments).keys()];\n\n // undefined: initial value when a start key isn't specified\n // null: scanning a particular segment is finished\n const lastEvaluatedKeys: (Obj | undefined | null)[] = segments.map(() => data.startKey);\n do {\n const results = await Promise.all(\n segments.map(async (segment) => {\n if (lastEvaluatedKeys[segment] === null) return [];\n\n const input = new Lib.ScanCommand({\n ExclusiveStartKey: lastEvaluatedKeys[segment],\n Segment: segment,\n TotalSegments: totalSegments,\n TableName: data.table,\n IndexName: data.index,\n Limit: data.limit,\n ConsistentRead: data.consistent,\n ProjectionExpression: exp.projection(data.projection),\n FilterExpression: exp.condition(data.filter),\n ExpressionAttributeNames: exp.attributeNames,\n ExpressionAttributeValues: exp.attributeValues,\n });\n\n const output = await this.client.send(input);\n lastEvaluatedKeys[segment] = output.LastEvaluatedKey ?? null;\n return output.Items ?? [];\n }),\n );\n\n const items = results.flat();\n\n if (items.length) {\n yield items as R[];\n }\n } while (lastEvaluatedKeys.some((key) => key !== null));\n }\n\n async scan<R = Obj>(data: DbScan): Promise<R[]> {\n const items: R[] = [];\n\n for await (const page of this.scanPaged(data)) {\n items.push(...(page as R[]));\n }\n\n return items;\n }\n\n async exists(data: DbExists): Promise<boolean> {\n const { query, ...otherOptions } = data;\n\n // we can't rely on the limit when a filter is being applied, since the filter is\n // applied after the scan/query page, so we only apply a limit of 1 when there is no filter.\n // otherwise, we page through the results and return true as soon as we see a single item\n const sharedOptions = {\n ...otherOptions,\n limit: data.filter ? undefined : 1,\n };\n\n const pagedItems = query\n ? this.queryPaged({ query, ...sharedOptions })\n : this.scanPaged(sharedOptions);\n\n for await (const items of pagedItems) {\n if (items.length) return true;\n }\n\n return false;\n }\n\n // TODO: test wildly different item sizes to make\n // sure retry algorithm works properly\n async batchGet(data: DbBatchGet): Promise<DbBatchGetResponse> {\n const result: DbBatchGetResponse = { items: {} };\n\n const tableData = Object.fromEntries(\n Object.entries(data).map(([table, request]) => {\n const exp = new ExpressionBuilder();\n\n result.items[table] = [];\n\n return [\n table,\n {\n request: {\n ConsistentRead: request?.consistent,\n ProjectionExpression: exp.projection(request?.projection),\n ExpressionAttributeNames: exp.attributeNames,\n },\n keyNames: Object.keys(request.keys.at(0) ?? {}),\n itemIndexMap: new Map<string, number>(),\n filter: request.filter,\n },\n ];\n }),\n );\n\n const flattenedBatches = Object.entries(data).flatMap(([table, request]) => {\n return request.keys.map((key, i) => {\n const itemIndexKey =\n tableData[table]?.keyNames.map((keyName) => key[keyName]).join(\"|\") ?? \"\";\n tableData[table]?.itemIndexMap.set(itemIndexKey, i);\n return [table, key] as const;\n });\n });\n\n let batchSize = 100;\n let retryCount = 0;\n\n while (flattenedBatches.length && retryCount < 5) {\n const batch = flattenedBatches.splice(0, batchSize || 1);\n\n const request: BatchGetItemInput[\"RequestItems\"] = {};\n for (const [table, key] of batch) {\n if (!request[table]) {\n request[table] = { ...tableData[table]?.request, Keys: [] };\n }\n\n request[table].Keys?.push(key);\n }\n\n const input = new Lib.BatchGetCommand({ RequestItems: request });\n const output = await this.client.send(input);\n\n for (const [table, items] of Object.entries(output.Responses ?? {})) {\n //just to appease typescript\n if (!result.items[table]) continue;\n\n const filteredItems = tableData[table]?.filter\n ? items.filter(tableData[table].filter)\n : items;\n\n result.items[table].push(...filteredItems);\n }\n\n // handle unprocessed requests\n let unprocessedKeyCount = 0;\n for (const [table, request] of Object.entries(output.UnprocessedKeys ?? {})) {\n const unprocessed = (request.Keys ?? []).map((key) => [table, key] as const);\n flattenedBatches.push(...unprocessed);\n unprocessedKeyCount += unprocessed.length;\n }\n\n //move immediately to next batch if all requests were processed\n if (!unprocessedKeyCount) {\n retryCount = 0;\n continue;\n }\n\n // reduce batch size so we don't continue to overfetch,\n // but do it gradually by only splitting the difference\n batchSize -= Math.floor(unprocessedKeyCount / 2);\n\n retryCount++;\n }\n\n // anything left in flattened batches needs to be returned in unprocessed\n if (flattenedBatches.length) {\n result.unprocessed = {};\n for (const [table, key] of flattenedBatches) {\n if (!result.unprocessed[table]) {\n result.unprocessed[table] = {\n ...tableData[table]?.request,\n keys: [],\n };\n }\n result.unprocessed[table].keys.push(key);\n }\n }\n\n // finally, sort any returned items by their original index to preserve order\n for (const [table, items] of Object.entries(result.items)) {\n const itemIndexMap = tableData[table]?.itemIndexMap;\n const keyNames = tableData[table]?.keyNames;\n\n if (!itemIndexMap || !keyNames) continue;\n\n items.sort((item1, item2) => {\n const item1IndexKey = keyNames.map((keyName) => item1[keyName]).join(\"|\");\n const item2IndexKey = keyNames.map((keyName) => item2[keyName]).join(\"|\");\n\n return (itemIndexMap.get(item1IndexKey) ?? 0) - (itemIndexMap.get(item2IndexKey) ?? 0);\n });\n }\n\n return result;\n }\n\n async batchGetOrThrow(data: DbBatchGet): Promise<DbBatchGetResponse[\"items\"]> {\n const { items, unprocessed } = await this.batchGet(data);\n\n for (const table of Object.keys(data)) {\n if (unprocessed?.[table]) {\n throw new Error(`One or more batch get requests were not processed in \"${table}\" table.`);\n }\n\n if (items[table]?.length !== data[table]?.keys?.length) {\n throw new Error(`One or more items were not found in \"${table}\" table.`);\n }\n }\n\n return items;\n }\n\n // TODO: test wildly different item sizes to make\n // sure retry algorithm works properly\n async batchWrite(data: DbBatchWrite): Promise<DbBatchWriteResponse> {\n const result: DbBatchWriteResponse = { items: {} };\n\n const flattenedBatches = Object.keys(data).flatMap((table) => {\n return (\n data[table]?.map((r) => {\n if (r.type === \"DELETE\") {\n return [table, { DeleteRequest: { Key: r.key } }] as [string, WriteRequest];\n } else {\n return [table, { PutRequest: { Item: r.item } }] as [string, WriteRequest];\n }\n }) ?? []\n );\n });\n\n let batchSize = 25;\n let retryCount = 0;\n\n while (flattenedBatches.length && retryCount < 5) {\n const batch = flattenedBatches.splice(0, batchSize || 1);\n\n const request: BatchWriteItemInput[\"RequestItems\"] = {};\n for (const [table, req] of batch) {\n if (!request[table]) {\n request[table] = [];\n }\n request[table].push(req);\n }\n\n const input = new Lib.BatchWriteCommand({ RequestItems: request });\n const output = await this.client.send(input);\n\n // handle unprocessed requests\n let unprocessedKeyCount = 0;\n for (const [table, requests] of Object.entries(output.UnprocessedItems ?? {})) {\n for (const request of requests) {\n flattenedBatches.push([table, request]);\n unprocessedKeyCount++;\n }\n }\n\n //move immediately to next batch if all requests were processed\n if (!unprocessedKeyCount) {\n retryCount = 0;\n continue;\n }\n\n // reduce batch size so we don't continue to overwrite,\n // but do it gradually by only splitting the difference\n batchSize -= Math.floor(unprocessedKeyCount / 2);\n\n retryCount++;\n }\n\n // anything left in flattened batches needs to be returned in unprocessed\n if (flattenedBatches.length) {\n result.unprocessed = {};\n for (const [table, request] of flattenedBatches) {\n if (!result.unprocessed[table]) {\n result.unprocessed[table] = [];\n }\n\n if (\"DeleteRequest\" in request && request.DeleteRequest?.Key) {\n result.unprocessed[table].push({\n type: \"DELETE\",\n key: request.DeleteRequest.Key,\n });\n } else if (\"PutRequest\" in request && request.PutRequest?.Item) {\n result.unprocessed[table].push({\n type: \"PUT\",\n item: request.PutRequest.Item,\n });\n }\n }\n }\n\n return result;\n }\n\n async trxGet<R extends DbTrxGetRequest[]>(...requests: R): Promise<DbTrxGetResult<R>> {\n const trxItems: TransactGetCommandInput[\"TransactItems\"] = requests.map((request) => {\n const exp = new ExpressionBuilder();\n return {\n Get: {\n Key: request.key,\n TableName: request.table,\n ProjectionExpression: exp.projection(request?.projection),\n ExpressionAttributeNames: exp.attributeNames,\n },\n };\n });\n\n const input = new Lib.TransactGetCommand({ TransactItems: trxItems });\n const output = await this.client.send(input);\n\n return (\n (output.Responses?.map((response, i) => {\n if (!response.Item) return;\n\n if (!requests[i]?.filter) return response.Item;\n\n return requests[i].filter(response.Item) ? response.Item : undefined;\n }) as DbTrxGetResult<R>) ?? []\n );\n }\n\n async trxGetOrThrow<R extends DbTrxGetRequest[]>(\n ...requests: R\n ): Promise<DbTrxGetOrThrowResult<R>> {\n const items = await this.trxGet(...requests);\n for (let i = 0; i < items.length; i++) {\n if (!items[i]) {\n throw new Error(`One or more items were not found in \"${requests[i]?.table}\" table.`);\n }\n }\n\n return items as DbTrxGetOrThrowResult<R>;\n }\n\n async trxWrite(...requests: DbTrxWriteRequest[]): Promise<void> {\n const trxItems: TransactWriteCommandInput[\"TransactItems\"] = requests.map((request) => {\n const exp = new ExpressionBuilder();\n\n if (request.type === \"CONDITION\" || request.type === \"DELETE\") {\n return {\n [request.type === \"CONDITION\" ? \"ConditionCheck\" : \"Delete\"]: {\n TableName: request.table,\n Key: request.key,\n ConditionExpression: exp.condition(request.condition),\n ExpressionAttributeNames: exp.attributeNames,\n ExpressionAttributeValues: exp.attributeValues,\n },\n };\n }\n\n if (request.type === \"PUT\") {\n return {\n Put: {\n TableName: request.table,\n Item: removeUndefined(request.item),\n ConditionExpression: exp.condition(request.condition),\n ExpressionAttributeNames: exp.attributeNames,\n ExpressionAttributeValues: exp.attributeValues,\n },\n };\n }\n\n return {\n Update: {\n Key: request.key,\n TableName: request.table,\n UpdateExpression: exp.update(request.update),\n ConditionExpression: exp.condition(request.condition),\n ExpressionAttributeNames: exp.attributeNames,\n ExpressionAttributeValues: exp.attributeValues,\n },\n };\n });\n\n const input = new Lib.TransactWriteCommand({ TransactItems: trxItems });\n await this.client.send(input);\n }\n\n /* Dynamodb Streams */\n\n /*\n\n\tasync enableStreamEvents(data?: DbEnableEventStreams): Promise<void> {\n\t\tconst tables = data?.tables ?? (await this.listTables());\n\n\t\tconst streamsClient = new DynamoDBStreams({\n\t\t\tendpoint: this.client.config.endpoint,\n\t\t\tcredentials: this.client.config.credentials,\n\t\t\tregion: this.client.config.region,\n\t\t});\n\n\t\tawait Promise.all(\n\t\t\ttables.map(async (table) => {\n\t\t\t\tconst tableDesc = await this.client.send(new DescribeTableCommand({ TableName: table }));\n\n\t\t\t\tconst latestStreamArn = tableDesc.Table?.LatestStreamArn;\n\n\t\t\t\tif (!latestStreamArn) {\n\t\t\t\t\tif (data?.tables) {\n\t\t\t\t\t\tthrow new Error(`Table \"${table}\" does not have streaming enabled.`);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst eventStreamer = new EventStreamer(streamsClient, latestStreamArn);\n\t\t\t\teventStreamer.startPolling();\n\t\t\t}),\n\t\t);\n\t}\n\n\tasync disableStreamEvents(): Promise<void> {}\n\n\tsubscribe(listener: DbStreamEventListener): void {\n\t\tthis.streamEventListeners.push(listener);\n\t}\n\n\tunsubscribe(listener: DbStreamEventListener): void {\n\t\tthis.streamEventListeners = this.streamEventListeners.filter((l) => l !== listener);\n\t}\n\n\tunsubscribeAll(): void {\n\t\tthis.streamEventListeners = [];\n\t}\n\t*/\n}\n\n// respondentRepo.onChange((respondent) => , { filter: (r1, r2) => r1.status !== r2.status } )\n/*\nconst time = new Date(record.dynamodb.ApproximateCreationDateTime).getTime();\nif (time >= startTime) {\n\tfor (const listener of this.streamEventListeners) {\n\t\tlistener({\n\t\t\ttable,\n\t\t\ttime,\n\t\t\tid: record.eventID,\n\t\t\ttype: record.eventName,\n\t\t\tkey: record.dynamodb.Keys,\n\t\t\toldItem: record.dynamodb.OldImage,\n\t\t\tnewItem: record.dynamodb.NewImage,\n\t\t});\n\t}\n}\n*/\n","import type { Static, TSchema } from \"typebox\";\nimport type { TableDef } from \"./types\";\n\ntype SchemaStatic<Schema extends TSchema> = unknown extends Static<Schema> ? any : Static<Schema>;\n\nexport class Table<\n Schema extends TSchema = TSchema,\n const Def extends TableDef<SchemaStatic<Schema>> = TableDef<SchemaStatic<Schema>>,\n> {\n readonly schema: Schema;\n readonly def: Def;\n\n constructor(schema: Schema, def: Def) {\n this.schema = schema;\n this.def = def;\n }\n}\n"],"mappings":";;;;AAEA,MAAM,YAAY;CAAC;CAAK;CAAM;CAAK;CAAM;CAAK;CAAM;CAAQ;CAAQ;CAAK;CAAI;AAC7E,MAAM,gBAA6B;CACjC,KAAK;CACL,KAAK;CACL,KAAK;CACL,MAAM;CACN,KAAK;CACL,MAAM;CACP;AAID,MAAa,eAAe,QAA6B;AACvD,KAAI,CAAC,OAAO,OAAO,QAAQ,YAAY,MAAM,QAAQ,IAAI,CAAE,QAAO;AAClE,QAAO,OAAO,KAAK,IAAI,CAAC,OAAO,OAAO,GAAG,WAAW,IAAI,CAAC;;AAG3D,IAAa,oBAAb,MAA+B;CAC7B,4BAA+B,IAAI,KAAqB;CACxD,6BAAgC,IAAI,KAAsB;CAE1D,IAAI,iBAA0C;AAC5C,SAAO,KAAK,UAAU,OAClB,OAAO,YACL,CAAC,GAAG,KAAK,UAAU,SAAS,CAAC,CAAC,KAAK,CAAC,MAAM,iBAAiB,CAAC,aAAa,KAAK,CAAC,CAChF,GACD,KAAA;;CAGN,IAAI,kBAAmC;AACrC,SAAO,KAAK,WAAW,OACnB,OAAO,YACL,CAAC,GAAG,KAAK,WAAW,SAAS,CAAC,CAAC,KAAK,CAAC,OAAO,iBAAiB,CAAC,aAAa,MAAM,CAAC,CACnF,GACD,KAAA;;CAGN,QAAc;AACZ,OAAK,UAAU,OAAO;AACtB,OAAK,WAAW,OAAO;;CAGzB,WAAW,MAAsB;EAC/B,MAAM,WAAW,KAAK,MAAM,IAAI;EAChC,MAAM,eAAyB,EAAE;AAEjC,OAA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AW;IAC5D,WAAW,QAAQ;IACnB,KAAK,QAAQ;IACb,qBAAqB,IAAI,UAAU,QAAQ,UAAU;IACrD,0BAA0B,IAAI;IAC9B,2BAA2B,IAAI;IAChC,EACF;AAGH,OAAI,QAAQ,SAAS,MACnB,QAAO,EACL,KAAK;IACH,WAAW,QAAQ;IACnB,MAAM,gBAAgB,QAAQ,KAAK;IACnC,qBAAqB,IAAI,UAAU,QAAQ,UAAU;IACrD,0BAA0B,IAAI;IAC9B,2BAA2B,IAAI;IAChC,EACF;AAGH,UAAO,EACL,QAAQ;IACN,KAAK,QAAQ;IACb,WAAW,QAAQ;IACnB,kBAAkB,IAAI,OAAO,QAAQ,OAAO;IAC5C,qBAAqB,IAAI,UAAU,QAAQ,UAAU;IACrD,0BAA0B,IAAI;IAC9B,2BAA2B,IAAI;IAChC,EACF;IACD;EAEF,MAAM,QAAQ,IAAI,IAAI,qBAAqB,EAAE,eAAe,UAAU,CAAC;AACvE,QAAM,KAAK,OAAO,KAAK,MAAM;;;;;ACrmBjC,IAAa,QAAb,MAGE;CACA;CACA;CAEA,YAAY,QAAgB,KAAU;AACpC,OAAK,SAAS;AACd,OAAK,MAAM"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/expression-builder.ts","../src/repo.ts","../src/db.ts","../src/table.ts"],"sourcesContent":["import type { Obj } from \"./types\";\n\nconst attrTypes = [\"S\", \"SS\", \"N\", \"NS\", \"B\", \"BS\", \"BOOL\", \"NULL\", \"L\", \"M\"] as const;\nconst comparatorOps: Obj<string> = {\n $eq: \"=\",\n $ne: \"<>\",\n $gt: \">\",\n $gte: \">=\",\n $lt: \"<\",\n $lte: \"<=\",\n};\n\n// TODO should { $eq: undefined } and { $ne: undefined } be converted into attribute_not_exists and attribute_exists ?\n\nexport const isOperation = (val: unknown): val is Obj => {\n if (!val || typeof val !== \"object\" || Array.isArray(val)) return false;\n return Object.keys(val).every((op) => op.startsWith(\"$\"));\n};\n\nexport class ExpressionBuilder {\n protected readonly attrNames = new Map<string, string>();\n protected readonly attrValues = new Map<unknown, string>();\n\n get attributeNames(): Obj<string> | undefined {\n return this.attrNames.size\n ? Object.fromEntries(\n [...this.attrNames.entries()].map(([name, placeholder]) => [placeholder, name]),\n )\n : undefined;\n }\n\n get attributeValues(): Obj | undefined {\n return this.attrValues.size\n ? Object.fromEntries(\n [...this.attrValues.entries()].map(([value, placeholder]) => [placeholder, value]),\n )\n : undefined;\n }\n\n reset(): void {\n this.attrNames.clear();\n this.attrValues.clear();\n }\n\n getPathSub(path: string): string {\n const segments = path.split(\".\");\n const placeholders: string[] = [];\n\n for (const segment of segments) {\n let placeholder = this.attrNames.get(segment);\n if (!placeholder) {\n placeholder = `#${this.attrNames.size}`;\n this.attrNames.set(segment, placeholder);\n }\n\n placeholders.push(placeholder);\n }\n\n return placeholders.join(\".\");\n }\n\n getValueSub(value: unknown): string {\n let placeholder = this.attrValues.get(value);\n if (!placeholder) {\n placeholder = `:${this.attrValues.size}`;\n this.attrValues.set(value, placeholder);\n }\n\n return placeholder;\n }\n\n getValueOrPathSub(pathOrValue: unknown): string {\n if (isOperation(pathOrValue)) {\n if (pathOrValue.$path) return this.getPathSub(pathOrValue.$path);\n throw new Error(\"Expected $path or operand.\");\n }\n\n return this.getValueSub(pathOrValue);\n }\n\n projection<T extends string[] | undefined>(paths: T): T extends undefined ? undefined : string {\n return paths?.map((path) => this.getPathSub(path)).join(\", \") as never;\n }\n\n condition<T extends Obj | undefined>(expression: T): T extends undefined ? undefined : string {\n if (!expression) return undefined as never;\n\n const expressions: string[] = [];\n for (const [key, val] of Object.entries(expression)) {\n if (key === \"$and\") {\n if (!Array.isArray(val)) throw new Error(\"$and expects an array operand.\");\n expressions.push(`(${val.map((v) => this.condition(v)).join(\" AND \")})`);\n } else if (key === \"$or\" && Array.isArray(val)) {\n if (!Array.isArray(val)) throw new Error(\"$or expects an array operand.\");\n expressions.push(`(${val.map((v) => this.condition(v)).join(\" OR \")})`);\n } else if (key === \"$not\") {\n if (!val || typeof val !== \"object\") throw new Error(\"$not expects an object operand.\");\n expressions.push(`NOT ${this.condition(val)}`);\n } else if (!key.startsWith(\"$\")) {\n expressions.push(this.resolveCondition(key, val));\n } else {\n throw new Error(\n `Unexpected operator \"${key}\". Expected attribute path or compound operator.`,\n );\n }\n }\n\n return expressions.join(\" AND \") as never;\n }\n\n update<T extends Obj | undefined>(expression: T): T extends undefined ? undefined : string {\n if (expression === undefined) return undefined as never;\n\n const setOperations: string[] = [];\n const removeOperations: string[] = [];\n const setAddOperations: string[] = [];\n const setDelOperations: string[] = [];\n\n for (const [path, valOrOperation] of Object.entries(expression)) {\n const placeholder = this.getPathSub(path);\n\n if (valOrOperation === undefined) {\n removeOperations.push(placeholder);\n } else if (isOperation(valOrOperation)) {\n if (valOrOperation.$remove === true) {\n removeOperations.push(placeholder);\n } else if (valOrOperation.$setAdd !== undefined || valOrOperation.$setDel !== undefined) {\n const operations = valOrOperation.$setAdd ? setAddOperations : setDelOperations;\n const operand = valOrOperation.$setAdd ?? valOrOperation.$setDel;\n operations.push(\n `${placeholder} ${this.getValueSub(operand instanceof Set ? operand : new Set([operand].flat()))}`,\n );\n } else {\n setOperations.push(`${placeholder} = ${this.resolveSetOperand(path, valOrOperation)}`);\n }\n } else {\n setOperations.push(`${placeholder} = ${this.getValueSub(valOrOperation)}`);\n }\n }\n\n let updateExpression = \"\";\n if (setOperations.length) {\n updateExpression += `SET ${setOperations.join(\", \")} `;\n }\n\n if (removeOperations.length) {\n updateExpression += `REMOVE ${removeOperations.join(\", \")} `;\n }\n\n if (setAddOperations.length) {\n updateExpression += `ADD ${setAddOperations.join(\", \")} `;\n }\n\n if (setDelOperations.length) {\n updateExpression += `DELETE ${setDelOperations.join(\", \")} `;\n }\n\n return updateExpression as never;\n }\n\n protected resolveCondition(path: string, exp: unknown): string {\n if (!exp || typeof exp !== \"object\" || !Object.keys(exp).at(0)?.startsWith(\"$\")) {\n return this.resolveCondition(path, { $eq: exp });\n }\n\n const placeholder = this.getPathSub(path);\n const [operator, operand] = Object.entries(exp).at(0) ?? [\"\"];\n\n if (comparatorOps[operator]) {\n if (isOperation(operand) && operand.$path) {\n return `${placeholder} ${comparatorOps[operator]} ${this.getPathSub(operand.$path)}`;\n }\n\n if (![\"string\", \"boolean\", \"number\"].includes(typeof operand)) {\n throw new Error(`${operator} expects a primitive/scalar operand.`);\n }\n return `${placeholder} ${comparatorOps[operator]} ${this.getValueSub(operand)}`;\n }\n\n switch (operator) {\n case \"$in\":\n if (!Array.isArray(operand)) {\n throw new Error(\"$in operator expects an array operand.\");\n }\n return `${placeholder} IN (${operand.map((op) => this.getValueSub(op)).join(\", \")})`;\n\n case \"$nin\":\n if (!Array.isArray(operand)) {\n throw new Error(\"$nin operator expects an array operand.\");\n }\n return `${placeholder} NOT IN (${operand.map((op) => this.getValueSub(op)).join(\", \")})`;\n\n case \"$prefix\":\n if (typeof operand !== \"string\") {\n throw new Error(\"$prefix operator expects a string operand.\");\n }\n return `begins_with(${placeholder}, ${this.getValueSub(operand)})`;\n\n case \"$includes\":\n return `contains(${placeholder}, ${this.getValueSub(operand)})`;\n\n case \"$between\":\n if (!Array.isArray(operand) || operand.length !== 2) {\n throw new Error(\"$between operator expects an array operand of exactly two values.\");\n }\n return `${placeholder} BETWEEN ${this.getValueSub(operand[0])} AND ${this.getValueSub(operand[1])}`;\n\n case \"$exists\":\n if (typeof operand !== \"boolean\") {\n throw new Error(\"$exists operator expects a boolean operand.\");\n }\n return operand\n ? `attribute_exists(${placeholder})`\n : `attribute_not_exists(${placeholder})`;\n\n case \"$type\":\n if (!attrTypes.includes(operand as any)) {\n throw new Error(`$type operator expects operand to be one of ${attrTypes.join(\",\")}`);\n }\n return `attribute_type(${placeholder})`;\n\n case \"$size\": {\n const sizeExp = typeof operand === \"number\" ? { $eq: operand } : operand;\n if (\n !sizeExp ||\n typeof sizeExp !== \"object\" ||\n !Object.keys(sizeExp).at(0)?.startsWith(\"$\")\n ) {\n throw new Error(\"$size operator expects a number operand or a comparator object.\");\n }\n const [sizeOperator, sizeOperand] = Object.entries(sizeExp).at(0) ?? [\"\"];\n\n if (!comparatorOps[sizeOperator]) {\n throw new Error(\"$size operator expects a number operand or a comparator object.\");\n }\n\n if (![\"string\", \"boolean\", \"number\"].includes(typeof sizeOperand)) {\n throw new Error(`${operator} expects a primitive/scalar operand.`);\n }\n\n return `size(${placeholder}) ${comparatorOps[sizeOperator]} ${this.getValueSub(sizeOperand)}`;\n }\n\n default:\n throw new Error(`Invalid operator \"${operator}\"`);\n }\n }\n\n protected resolveSetOperand(path: string, operand: unknown): string {\n if (isOperation(operand)) {\n if (operand.$ifNotExists) {\n const params = Array.isArray(operand.$ifNotExists)\n ? operand.$ifNotExists\n : [path, operand.$ifNotExists];\n return `if_not_exists(${this.getPathSub(params[0])}, ${this.resolveSetOperand(path, params[1])})`;\n }\n\n if (operand.$set) {\n return this.resolveSetOperand(path, operand.$set);\n }\n\n if (operand.$plus !== undefined || operand.$minus !== undefined) {\n const mathOperator = operand.$plus ? \"+\" : \"-\";\n const mathOperand = operand.$plus ?? operand.$minus;\n const params = Array.isArray(mathOperand) ? mathOperand : [{ $path: path }, mathOperand];\n return `${params.map((param) => this.resolveSetOperand(path, param)).join(` ${mathOperator} `)}`;\n }\n\n if (operand.$append !== undefined || operand.$prepend !== undefined) {\n const listOperand = operand.$append ?? operand.$prepend;\n const resolvedListOperand = isOperation(listOperand) ? listOperand : [listOperand].flat();\n const params = operand.$append\n ? [{ $path: path }, resolvedListOperand]\n : [resolvedListOperand, { $path: path }];\n return `list_append(${params.map((param) => this.resolveSetOperand(path, param)).join(\", \")})`;\n }\n }\n\n return this.getValueOrPathSub(operand);\n }\n}\n","import type { Db } from \"./db\";\nimport type { Table } from \"./table\";\nimport type { DbTrxGetRequest, DbTrxWriteRequest } from \"./db.types\";\nimport type {\n RepoBatchGetOptions,\n RepoBatchGetOrThrowResult,\n RepoBatchGetResult,\n RepoBatchWrite,\n RepoBatchWriteResult,\n RepoCreateOptions,\n RepoCreateItem,\n RepoCreateResult,\n RepoDeleteOptions,\n RepoDeleteOrThrowResult,\n RepoDeleteResult,\n RepoExistsOptions,\n RepoGetOptions,\n RepoGetOrThrowResult,\n RepoGetResult,\n RepoKey,\n RepoPutOptions,\n RepoPutItem,\n RepoPutResult,\n RepoQueryOptions,\n RepoQueryGsiOptions,\n RepoQueryGsiPagedResult,\n RepoQueryGsiResult,\n RepoQueryPagedResult,\n RepoQueryResult,\n RepoScanOptions,\n RepoScanGsiOptions,\n RepoScanGsiPagedResult,\n RepoScanGsiResult,\n RepoScanPagedResult,\n RepoScanResult,\n RepoTrxGetOptions,\n RepoTrxGetOrThrowResult,\n RepoTrxGetResult,\n RepoTrxWriteRequest,\n RepoUpdateOptions,\n RepoUpdateData,\n RepoUpdateResult,\n RepoQueryGsiQuery,\n RepoQueryQuery,\n TableGsiNames,\n} from \"./repo.types\";\nimport type { Condition, ExtractTableDef, ExtractTableSchema, Obj } from \"./types\";\n\n// TODO: query/queryGsi needs strongly typed \"key\" argument\n// allows =,>,>=,<,<=,begins_with, between on sort key\n// util -> extractExclusiveStartKey(item)\n\nexport abstract class AbstractRepo<T extends Table> {\n // these phantom properties are used to pre-compute types derived from T\n // which allows easy lookups using the \"this\" AbstractRepo type\n declare readonly $schema: ExtractTableSchema<T>;\n declare readonly $def: ExtractTableDef<T>;\n\n abstract readonly table: T;\n readonly db: Db;\n constructor(db: Db) {\n this.db = db;\n }\n\n get tableName(): string {\n return `${this.db.config?.tableNamePrefix ?? \"\"}${this.table.def.name}`;\n }\n\n get defaultPutData(): Partial<ExtractTableSchema<T>> {\n return {};\n }\n\n get defaultUpdateData(): Partial<ExtractTableSchema<T>> {\n return {};\n }\n\n transformItem(item: ExtractTableSchema<T>): ExtractTableSchema<T> {\n return item;\n }\n\n // TODO: should this throw if pk is missing?\n // should return type by narrower?\n extractKey(item: RepoKey<this>): RepoKey<this> {\n const { partitionKey, sortKey } = this.table.def;\n if (sortKey) {\n return {\n [partitionKey]: item[partitionKey as keyof RepoKey<this>],\n [sortKey]: item[sortKey as keyof RepoKey<this>],\n } as RepoKey<this>;\n }\n\n return { [partitionKey]: item[partitionKey as keyof RepoKey<this>] } as RepoKey<this>;\n }\n\n async get<O extends RepoGetOptions<this>>(\n key: RepoKey<this>,\n options?: O,\n ): Promise<RepoGetResult<this, O>> {\n const item = await this.db.get({\n table: this.tableName,\n key: this.extractKey(key),\n ...options,\n } as any);\n return item && this.applyTransformIfNeeded(item, options);\n }\n\n async getOrThrow<O extends RepoGetOptions<this>>(\n key: RepoKey<this>,\n options?: O,\n ): Promise<RepoGetOrThrowResult<this, O>> {\n const item = await this.db.getOrThrow({\n table: this.tableName,\n key: this.extractKey(key),\n ...options,\n } as any);\n return this.applyTransformIfNeeded(item, options);\n }\n\n async put(item: RepoPutItem<this>, options?: RepoPutOptions<this>): Promise<RepoPutResult<this>> {\n const itemWithDefaults = { ...this.defaultPutData, ...item };\n const result = await this.db.put({ table: this.tableName, item: itemWithDefaults, ...options });\n return this.applyTransformIfNeeded(result);\n }\n\n async update(\n key: RepoKey<this>,\n update: RepoUpdateData,\n options?: RepoUpdateOptions<this>,\n ): Promise<RepoUpdateResult<this>> {\n const updateWithDefaults = { ...this.defaultUpdateData, ...update };\n const result = await this.db.update({\n table: this.tableName,\n key: this.extractKey(key),\n update: updateWithDefaults,\n ...options,\n });\n return this.applyTransformIfNeeded(result);\n }\n\n async create(\n item: RepoPutItem<this>,\n options?: RepoCreateOptions<this>,\n ): Promise<RepoCreateResult<this>> {\n const { condition: otherCondition, ...otherOptions } = options ?? {};\n\n const condition = { $and: [{ [this.table.def.partitionKey]: { $exists: false } }] } as any;\n\n if (otherCondition) {\n condition.$and.push(otherCondition);\n }\n\n return this.put(item, { condition, ...otherOptions });\n }\n\n async delete(\n key: RepoKey<this>,\n options?: RepoDeleteOptions<this>,\n ): Promise<RepoDeleteResult<this>> {\n const item = await this.db.delete({\n table: this.tableName,\n key: this.extractKey(key),\n ...options,\n });\n return item && this.applyTransformIfNeeded(item);\n }\n\n async deleteOrThrow(\n key: RepoKey<this>,\n options?: Omit<RepoDeleteOptions<this>, \"return\">,\n ): Promise<RepoDeleteOrThrowResult<this>> {\n const item = await this.db.deleteOrThrow({\n table: this.tableName,\n key: this.extractKey(key),\n ...options,\n });\n return this.applyTransformIfNeeded(item);\n }\n\n async query<O extends RepoQueryOptions<this>>(\n query: RepoQueryQuery<this>,\n options?: O,\n ): Promise<RepoQueryResult<this, O>> {\n const items = await this.db.query({ table: this.tableName, query, ...options } as any);\n return this.applyTransformsIfNeeded(items, options);\n }\n\n async *queryPaged<O extends RepoQueryOptions<this>>(\n query: RepoQueryQuery<this>,\n options?: O,\n ): RepoQueryPagedResult<this, O> {\n for await (const page of this.db.queryPaged({\n table: this.tableName,\n query,\n ...options,\n } as any)) {\n yield this.applyTransformsIfNeeded(page, options);\n }\n }\n\n async queryGsi<G extends TableGsiNames<T>, O extends RepoQueryGsiOptions<this, T, G>>(\n gsi: G,\n query: RepoQueryGsiQuery<T, G>,\n options?: O,\n ): Promise<RepoQueryGsiResult<this, O, G>> {\n const items = await this.db.query({\n table: this.tableName,\n index: gsi,\n query,\n ...options,\n } as any);\n return this.applyTransformsIfNeeded(items, { ...options, gsi });\n }\n\n async *queryGsiPaged<G extends TableGsiNames<T>, O extends RepoQueryGsiOptions<this, T, G>>(\n gsi: G,\n query: RepoQueryGsiQuery<T, G>,\n options?: O,\n ): RepoQueryGsiPagedResult<this, O, G> {\n for await (const page of this.db.queryPaged({\n table: this.tableName,\n index: gsi,\n query,\n ...options,\n } as any)) {\n yield this.applyTransformsIfNeeded(page, { ...options, gsi });\n }\n }\n\n async scan<O extends RepoScanOptions<this>>(options?: O): Promise<RepoScanResult<this, O>> {\n const items = await this.db.scan({ table: this.tableName, ...options });\n return this.applyTransformsIfNeeded(items, options);\n }\n\n async *scanPaged<O extends RepoScanOptions<this>>(options?: O): RepoScanPagedResult<this, O> {\n for await (const page of this.db.scanPaged({ table: this.tableName, ...options })) {\n yield this.applyTransformsIfNeeded(page, options);\n }\n }\n\n async scanGsi<G extends TableGsiNames<T>, O extends RepoScanGsiOptions<this, T, G>>(\n gsi: G,\n options?: O,\n ): Promise<RepoScanGsiResult<this, O, G>> {\n const items = await this.db.scan({ table: this.tableName, index: gsi, ...options } as any);\n return this.applyTransformsIfNeeded(items, { ...options, gsi });\n }\n\n async *scanGsiPaged<G extends TableGsiNames<T>, O extends RepoScanGsiOptions<this, T, G>>(\n gsi: G,\n options?: O,\n ): RepoScanGsiPagedResult<this, O, G> {\n for await (const page of this.db.scanPaged({\n table: this.tableName,\n index: gsi,\n ...options,\n } as any)) {\n yield this.applyTransformsIfNeeded(page, { ...options, gsi });\n }\n }\n\n async exists(options?: RepoExistsOptions<this>): Promise<boolean> {\n return this.db.exists({\n table: this.tableName,\n projection: [this.table.def.partitionKey] as any,\n ...options,\n });\n }\n\n async existsGsi(gsi: TableGsiNames<T>, options?: RepoExistsOptions<this>): Promise<boolean> {\n return this.db.exists({\n table: this.tableName,\n index: gsi,\n projection: [this.table.def.partitionKey] as any,\n ...options,\n });\n }\n\n async batchGet<O extends RepoBatchGetOptions<this>>(\n keys: RepoKey<this>[],\n options?: O,\n ): Promise<RepoBatchGetResult<this, O>> {\n const { items, unprocessed } = await this.db.batchGet({\n [this.tableName]: { keys: keys.map((key) => this.extractKey(key)), ...options },\n } as any);\n const tableItems = items[this.tableName];\n return {\n items: tableItems && this.applyTransformsIfNeeded(tableItems, options),\n unprocessed: unprocessed?.[this.tableName]?.keys,\n } as RepoBatchGetResult<this, O>;\n }\n\n async batchGetOrThrow<O extends RepoBatchGetOptions<this>>(\n keys: RepoKey<this>[],\n options?: O,\n ): Promise<RepoBatchGetOrThrowResult<this, O>> {\n const result = await this.db.batchGetOrThrow({\n [this.tableName]: { keys: keys.map((key) => this.extractKey(key)), ...options },\n } as any);\n return this.applyTransformsIfNeeded(result[this.tableName] ?? [], options);\n }\n\n async batchWrite(requests: RepoBatchWrite<this>): Promise<RepoBatchWriteResult<this>> {\n const { items, unprocessed } = await this.db.batchWrite({\n [this.tableName]: requests.map((request) => {\n if (request.type === \"DELETE\") {\n return { type: \"DELETE\", key: this.extractKey(request.key) };\n } else {\n const itemWithDefaults = { ...this.defaultPutData, ...request.item };\n return { type: \"PUT\", item: itemWithDefaults };\n }\n }),\n });\n\n return {\n items: items[this.tableName],\n unprocessed: unprocessed?.[this.tableName],\n } as RepoBatchWriteResult<this>;\n }\n\n async trxGet<O extends RepoTrxGetOptions<this>>(\n keys: RepoKey<this>[],\n options?: O,\n ): Promise<RepoTrxGetResult<this, O>> {\n const items = await this.db.trxGet(\n ...keys.map(\n (key) =>\n ({\n table: this.tableName,\n key: this.extractKey(key),\n ...options,\n }) as any,\n ),\n );\n return items.map((item: any) => item && this.applyTransformIfNeeded(item, options)) as any;\n }\n\n async trxGetOrThrow<O extends RepoTrxGetOptions<this>>(\n keys: RepoKey<this>[],\n options?: O,\n ): Promise<RepoTrxGetOrThrowResult<this, O>> {\n const items = await this.db.trxGetOrThrow(\n ...keys.map(\n (key) =>\n ({\n table: this.tableName,\n key: this.extractKey(key),\n ...options,\n }) as any,\n ),\n );\n return this.applyTransformsIfNeeded(items, options);\n }\n\n async trxWrite(...requests: RepoTrxWriteRequest<this>[]): Promise<void> {\n await this.db.trxWrite(\n ...requests.map((request) => {\n switch (request.type) {\n case \"CONDITION\": {\n const { key, condition, ...options } = request;\n return this.trxConditionRequest(key, condition, options);\n }\n\n case \"DELETE\": {\n const { key, ...options } = request;\n return this.trxDeleteRequest(key, options);\n }\n\n case \"PUT\": {\n const { item, ...options } = request;\n return this.trxPutRequest(item, options);\n }\n\n case \"UPDATE\": {\n const { key, update, ...options } = request;\n return this.trxUpdateRequest(key, update, options);\n }\n\n default:\n throw new Error(\"Unexpected request type.\");\n }\n }),\n );\n }\n\n async trxDelete(\n keys: RepoKey<this>[],\n options?: Omit<RepoDeleteOptions<this>, \"return\">,\n ): Promise<void> {\n return this.db.trxWrite(...keys.map((key) => this.trxDeleteRequest(key, options)));\n }\n\n // todo: return items\n async trxPut(\n items: RepoPutItem<this>[],\n options?: Omit<RepoPutOptions<this>, \"return\">,\n ): Promise<void> {\n return this.db.trxWrite(...items.map((item) => this.trxPutRequest(item, options)));\n }\n\n async trxUpdate(\n keys: RepoKey<this>[],\n update: RepoUpdateData,\n options?: Omit<RepoUpdateOptions<this>, \"return\">,\n ): Promise<void> {\n return this.db.trxWrite(...keys.map((key) => this.trxUpdateRequest(key, update, options)));\n }\n\n // todo: return items\n async trxCreate(items: RepoCreateItem<this>[], options?: RepoCreateOptions<this>): Promise<void> {\n return this.db.trxWrite(...items.map((item) => this.trxCreateRequest(item, options)));\n }\n\n trxGetRequest<O extends RepoGetOptions<this>>(\n key: RepoKey<this>,\n options?: O,\n ): DbTrxGetRequest<RepoGetOrThrowResult<this, O>> {\n return { table: this.tableName, key: this.extractKey(key), ...options } as any;\n }\n\n trxDeleteRequest(\n key: RepoKey<this>,\n options?: Omit<RepoDeleteOptions<this>, \"return\">,\n ): DbTrxWriteRequest {\n return { table: this.tableName, type: \"DELETE\", key: this.extractKey(key), ...options };\n }\n\n trxConditionRequest(\n key: RepoKey<this>,\n condition: Condition<ExtractTableSchema<T>>,\n options?: Omit<RepoDeleteOptions<this>, \"return\" | \"condition\">,\n ): DbTrxWriteRequest {\n return {\n table: this.tableName,\n type: \"CONDITION\",\n key: this.extractKey(key),\n condition,\n ...options,\n };\n }\n\n trxPutRequest(\n item: RepoPutItem<this>,\n options?: Omit<RepoPutOptions<this>, \"return\">,\n ): DbTrxWriteRequest {\n const itemWithDefaults = { ...this.defaultPutData, ...item };\n return { table: this.tableName, type: \"PUT\", item: itemWithDefaults, ...options };\n }\n\n trxUpdateRequest(\n key: RepoKey<this>,\n update: RepoUpdateData,\n options?: Omit<RepoUpdateOptions<this>, \"return\">,\n ): DbTrxWriteRequest {\n const updateWithDefaults = { ...this.defaultUpdateData, ...update };\n return {\n table: this.tableName,\n type: \"UPDATE\",\n key: this.extractKey(key),\n update: updateWithDefaults,\n ...options,\n };\n }\n\n trxCreateRequest(\n item: RepoCreateItem<this>,\n options?: RepoCreateOptions<this>,\n ): DbTrxWriteRequest {\n const { condition: otherCondition, ...otherOptions } = options ?? {};\n\n const condition = { $and: [{ [this.table.def.partitionKey]: { $exists: false } }] } as any;\n\n if (otherCondition) {\n condition.$and.push(otherCondition);\n }\n\n const itemWithDefaults = { ...this.defaultPutData, ...item };\n\n return {\n table: this.tableName,\n type: \"PUT\",\n item: itemWithDefaults,\n condition,\n ...otherOptions,\n };\n }\n\n private applyTransformsIfNeeded(\n items: Obj[],\n options?: { projection?: any[]; gsi?: string },\n ): any[] {\n // transforms aren't applied when applying a projection\n if (options?.projection?.length) return items;\n if (options?.gsi) {\n // projections inherited to GSIs also prevent transformation\n const gsiProj = this.table.def.gsis?.[options.gsi]?.projection;\n if (gsiProj === \"KEYS_ONLY\" || Array.isArray(gsiProj)) return items;\n }\n\n return items.map((item) => this.transformItem(item as ExtractTableSchema<T>));\n }\n\n private applyTransformIfNeeded(item: Obj, options?: { projection?: any[]; gsi?: string }): any {\n const [transformedItem] = this.applyTransformsIfNeeded([item], options);\n return transformedItem;\n }\n}\n\nexport class Repo<T extends Table<any, any>> extends AbstractRepo<T> {\n readonly table: T;\n\n constructor(db: Db, table: T) {\n super(db);\n this.table = table;\n }\n}\n","import {\n type BatchGetItemInput,\n type BatchWriteItemInput,\n CreateTableCommand,\n DeleteTableCommand,\n DynamoDB,\n DynamoDBClient,\n type DynamoDBClientConfig,\n ListTablesCommand,\n type WriteRequest,\n} from \"@aws-sdk/client-dynamodb\";\n//import { DynamoDBStreams } from '@aws-sdk/client-dynamodb-streams';\nimport type { TransactGetCommandInput, TransactWriteCommandInput } from \"@aws-sdk/lib-dynamodb\";\nimport * as Lib from \"@aws-sdk/lib-dynamodb\";\nimport { ExpressionBuilder } from \"./expression-builder\";\nimport { Repo } from \"./repo\";\nimport type { Table } from \"./table\";\nimport type {\n DbBatchGet,\n DbBatchGetResponse,\n DbBatchWrite,\n DbBatchWriteResponse,\n DbConfig,\n DbDelete,\n DbExists,\n DbGet,\n DbListTables,\n DbPut,\n DbQuery,\n DbScan,\n DbTrxGetOrThrowResult,\n DbTrxGetRequest,\n DbTrxGetResult,\n DbTrxWriteRequest,\n DbUpdate,\n} from \"./db.types\";\nimport type { Obj } from \"./types\";\nimport { extractTableDesc, removeUndefined } from \"./util\";\n\n// TODO\n// - caching support?\n// - consider special \"limit\" handling for paged scans, maybe have \"scanLimit\" too\n// - consider \"sort\" shorthand for methods that return unpaginated collections\n// i.e. sort: { by: 'createdAt', dir: 'ASC' } or sort: (a,b) => a.createdAt - b.createdAt\n// - consider support for batchUpdates leveraging BatchExecute and PartiQL\n// - consider batchPut (batchPutOrThrow) and batchDelete that operate on a single table\n// - getGsi? throws if > 1 result, allows for assert, and filtering\n// - bug $in doesn't handle empty arrays, I imagine other operators are affected\n// - consider beforeCreate, beforePut, beforeUpdate, beforeDelete, after, etc.\n// - type out repo update data\n\nexport class Db {\n readonly client: Lib.DynamoDBDocumentClient;\n readonly config: DbConfig | undefined;\n\n //protected streamEventListeners: DbStreamEventListener[] = [];\n\n constructor(\n clientOrConfig: DynamoDBClient | DynamoDB | DynamoDBClientConfig,\n dbConfig?: DbConfig,\n ) {\n if (clientOrConfig instanceof DynamoDBClient || clientOrConfig instanceof DynamoDB) {\n this.client = Lib.DynamoDBDocumentClient.from(new DynamoDBClient(clientOrConfig));\n } else {\n const { endpoint, ...clientConfig } = clientOrConfig;\n // client doesn't interpret an empty string endpoint as falsy so normalize things\n // here so consumers don't have to worry about that quirk\n this.client = Lib.DynamoDBDocumentClient.from(\n new DynamoDBClient({\n endpoint: endpoint || undefined,\n ...clientConfig,\n }),\n );\n }\n\n this.config = dbConfig;\n }\n\n createRepo<T extends Table>(table: T): Repo<T> {\n return new Repo(this, table);\n }\n\n async createTable(table: Table): Promise<void> {\n await this.client.send(new CreateTableCommand(extractTableDesc(table)));\n }\n\n async deleteTable(tableName: string): Promise<void> {\n await this.client.send(new DeleteTableCommand({ TableName: tableName }));\n }\n\n async listTables(data?: DbListTables): Promise<string[]> {\n const tables: string[] = [];\n let lastEvaluatedTableName: string | undefined;\n do {\n const output = await this.client.send(\n new ListTablesCommand({\n Limit: data?.limit,\n ExclusiveStartTableName: lastEvaluatedTableName,\n }),\n );\n\n tables.push(...(output.TableNames ?? []));\n lastEvaluatedTableName = output.LastEvaluatedTableName;\n } while (lastEvaluatedTableName);\n return tables;\n }\n\n async get<T = Obj>(data: DbGet<T>): Promise<T | undefined> {\n const exp = new ExpressionBuilder();\n\n const input = new Lib.GetCommand({\n TableName: data.table,\n Key: data.key,\n ConsistentRead: data.consistent,\n ProjectionExpression: exp.projection(data.projection),\n ExpressionAttributeNames: exp.attributeNames,\n });\n\n const output = await this.client.send(input);\n\n if (output.Item && data.filter && !data.filter(output.Item as T)) {\n return undefined;\n }\n\n return output.Item as T;\n }\n\n async getOrThrow<T = Obj>(data: DbGet<T>): Promise<T> {\n const item = await this.get<T>(data);\n if (!item) {\n throw new Error(`Item not found in \"${data.table}\" table.`);\n }\n return item;\n }\n\n async put<T = Obj>(data: DbPut<T>): Promise<T> {\n const exp = new ExpressionBuilder();\n\n const item = removeUndefined(data.item as Obj);\n\n const input = new Lib.PutCommand({\n TableName: data.table,\n Item: item,\n ReturnValues: data.returnOld ? \"ALL_OLD\" : \"NONE\",\n ReturnValuesOnConditionCheckFailure: \"ALL_OLD\",\n ConditionExpression: exp.condition(data.condition),\n ExpressionAttributeNames: exp.attributeNames,\n ExpressionAttributeValues: exp.attributeValues,\n });\n\n const output = await this.client.send(input);\n\n return (data.returnOld ? output.Attributes : item) as T;\n }\n\n async update<T = Obj>(data: DbUpdate<T>): Promise<T> {\n const exp = new ExpressionBuilder();\n\n const condition: any = {\n $and: Object.keys(data.key).map((field) => ({\n [field]: { $exists: true },\n })),\n };\n\n if (data.condition) {\n condition.$and.push(data.condition);\n }\n\n const input = new Lib.UpdateCommand({\n TableName: data.table,\n Key: data.key,\n ReturnValues: \"ALL_NEW\",\n ReturnValuesOnConditionCheckFailure: \"ALL_OLD\",\n UpdateExpression: exp.update(data.update),\n ConditionExpression: exp.condition(condition),\n ExpressionAttributeNames: exp.attributeNames,\n ExpressionAttributeValues: exp.attributeValues,\n });\n\n const output = await this.client.send(input);\n\n return output.Attributes as T;\n }\n\n async delete<T = Obj>(data: DbDelete<T>): Promise<T | undefined> {\n const exp = new ExpressionBuilder();\n\n const input = new Lib.DeleteCommand({\n TableName: data.table,\n Key: data.key,\n ReturnValues: \"ALL_OLD\",\n ConditionExpression: exp.condition(data.condition),\n ReturnValuesOnConditionCheckFailure: \"ALL_OLD\",\n ExpressionAttributeNames: exp.attributeNames,\n ExpressionAttributeValues: exp.attributeValues,\n });\n\n const output = await this.client.send(input);\n\n return output.Attributes as T | undefined;\n }\n\n async deleteOrThrow<T = Obj>(data: DbDelete<T>): Promise<T> {\n const item = await this.delete<T>(data);\n if (!item) {\n throw new Error(`Item not found in \"${data.table}\" table.`);\n }\n return item;\n }\n\n async *queryPaged<T = Obj>(data: DbQuery<T>): AsyncGenerator<T[]> {\n const exp = new ExpressionBuilder();\n\n let lastEvaluatedKey: Obj | undefined = data.startKey as Obj | undefined;\n do {\n const input = new Lib.QueryCommand({\n TableName: data.table,\n IndexName: data.index,\n ExclusiveStartKey: lastEvaluatedKey,\n Limit: data.limit,\n ScanIndexForward: data.sort !== \"DESC\",\n ConsistentRead: data.consistent,\n KeyConditionExpression: exp.condition(data.query),\n ProjectionExpression: exp.projection(data.projection),\n FilterExpression: exp.condition(data.filter),\n ExpressionAttributeNames: exp.attributeNames,\n ExpressionAttributeValues: exp.attributeValues,\n });\n\n const output = await this.client.send(input);\n\n if (output.Items?.length) {\n yield output.Items as T[];\n }\n lastEvaluatedKey = output.LastEvaluatedKey;\n } while (lastEvaluatedKey);\n }\n\n async query<T = Obj>(data: DbQuery<T>): Promise<T[]> {\n const items: T[] = [];\n\n for await (const page of this.queryPaged(data)) {\n items.push(...page);\n }\n\n return items;\n }\n\n async *scanPaged<T = Obj>(data: DbScan<T>): AsyncGenerator<T[]> {\n const exp = new ExpressionBuilder();\n\n const totalSegments = data.parallel ?? 1;\n const segments = [...Array(totalSegments).keys()];\n\n // undefined: initial value when a start key isn't specified\n // null: scanning a particular segment is finished\n const lastEvaluatedKeys: (Obj | undefined | null)[] = segments.map(\n () => data.startKey as Obj | undefined,\n );\n do {\n const results = await Promise.all(\n segments.map(async (segment) => {\n if (lastEvaluatedKeys[segment] === null) return [];\n\n const input = new Lib.ScanCommand({\n ExclusiveStartKey: lastEvaluatedKeys[segment],\n Segment: segment,\n TotalSegments: totalSegments,\n TableName: data.table,\n IndexName: data.index,\n Limit: data.limit,\n ConsistentRead: data.consistent,\n ProjectionExpression: exp.projection(data.projection),\n FilterExpression: exp.condition(data.filter),\n ExpressionAttributeNames: exp.attributeNames,\n ExpressionAttributeValues: exp.attributeValues,\n });\n\n const output = await this.client.send(input);\n lastEvaluatedKeys[segment] = output.LastEvaluatedKey ?? null;\n return output.Items ?? [];\n }),\n );\n\n const items = results.flat();\n\n if (items.length) {\n yield items as T[];\n }\n } while (lastEvaluatedKeys.some((key) => key !== null));\n }\n\n async scan<T = Obj>(data: DbScan<T>): Promise<T[]> {\n const items: T[] = [];\n\n for await (const page of this.scanPaged(data)) {\n items.push(...(page as T[]));\n }\n\n return items;\n }\n\n async exists<T = Obj>(data: DbExists<T>): Promise<boolean> {\n const { query, ...otherOptions } = data;\n\n // we can't rely on the limit when a filter is being applied, since the filter is\n // applied after the scan/query page, so we only apply a limit of 1 when there is no filter.\n // otherwise, we page through the results and return true as soon as we see a single item\n const sharedOptions = {\n ...otherOptions,\n limit: data.filter ? undefined : 1,\n };\n\n const pagedItems = query\n ? this.queryPaged({ query, ...sharedOptions })\n : this.scanPaged(sharedOptions);\n\n for await (const items of pagedItems) {\n if (items.length) return true;\n }\n\n return false;\n }\n\n // TODO: test wildly different item sizes to make\n // sure retry algorithm works properly\n async batchGet(data: DbBatchGet): Promise<DbBatchGetResponse> {\n const result: DbBatchGetResponse = { items: {} };\n\n const tableData = Object.fromEntries(\n Object.entries(data).map(([table, request]) => {\n const exp = new ExpressionBuilder();\n\n result.items[table] = [];\n\n return [\n table,\n {\n request: {\n ConsistentRead: request?.consistent,\n ProjectionExpression: exp.projection(request?.projection),\n ExpressionAttributeNames: exp.attributeNames,\n },\n keyNames: Object.keys(request.keys.at(0) ?? {}),\n itemIndexMap: new Map<string, number>(),\n filter: request.filter,\n },\n ];\n }),\n );\n\n const flattenedBatches = Object.entries(data).flatMap(([table, request]) => {\n return request.keys.map((key, i) => {\n const itemIndexKey =\n tableData[table]?.keyNames.map((keyName) => key[keyName]).join(\"|\") ?? \"\";\n tableData[table]?.itemIndexMap.set(itemIndexKey, i);\n return [table, key] as const;\n });\n });\n\n let batchSize = 100;\n let retryCount = 0;\n\n while (flattenedBatches.length && retryCount < 5) {\n const batch = flattenedBatches.splice(0, batchSize || 1);\n\n const request: BatchGetItemInput[\"RequestItems\"] = {};\n for (const [table, key] of batch) {\n if (!request[table]) {\n request[table] = { ...tableData[table]?.request, Keys: [] };\n }\n\n request[table].Keys?.push(key);\n }\n\n const input = new Lib.BatchGetCommand({ RequestItems: request });\n const output = await this.client.send(input);\n\n for (const [table, items] of Object.entries(output.Responses ?? {})) {\n //just to appease typescript\n if (!result.items[table]) continue;\n\n const filteredItems = tableData[table]?.filter\n ? items.filter(tableData[table].filter)\n : items;\n\n result.items[table].push(...filteredItems);\n }\n\n // handle unprocessed requests\n let unprocessedKeyCount = 0;\n for (const [table, request] of Object.entries(output.UnprocessedKeys ?? {})) {\n const unprocessed = (request.Keys ?? []).map((key) => [table, key] as const);\n flattenedBatches.push(...unprocessed);\n unprocessedKeyCount += unprocessed.length;\n }\n\n //move immediately to next batch if all requests were processed\n if (!unprocessedKeyCount) {\n retryCount = 0;\n continue;\n }\n\n // reduce batch size so we don't continue to overfetch,\n // but do it gradually by only splitting the difference\n batchSize -= Math.floor(unprocessedKeyCount / 2);\n\n retryCount++;\n }\n\n // anything left in flattened batches needs to be returned in unprocessed\n if (flattenedBatches.length) {\n result.unprocessed = {};\n for (const [table, key] of flattenedBatches) {\n if (!result.unprocessed[table]) {\n result.unprocessed[table] = {\n ...tableData[table]?.request,\n keys: [],\n };\n }\n result.unprocessed[table].keys.push(key);\n }\n }\n\n // finally, sort any returned items by their original index to preserve order\n for (const [table, items] of Object.entries(result.items)) {\n const itemIndexMap = tableData[table]?.itemIndexMap;\n const keyNames = tableData[table]?.keyNames;\n\n if (!itemIndexMap || !keyNames) continue;\n\n items.sort((item1, item2) => {\n const item1IndexKey = keyNames.map((keyName) => item1[keyName]).join(\"|\");\n const item2IndexKey = keyNames.map((keyName) => item2[keyName]).join(\"|\");\n\n return (itemIndexMap.get(item1IndexKey) ?? 0) - (itemIndexMap.get(item2IndexKey) ?? 0);\n });\n }\n\n return result;\n }\n\n async batchGetOrThrow(data: DbBatchGet): Promise<DbBatchGetResponse[\"items\"]> {\n const { items, unprocessed } = await this.batchGet(data);\n\n for (const table of Object.keys(data)) {\n if (unprocessed?.[table]) {\n throw new Error(`One or more batch get requests were not processed in \"${table}\" table.`);\n }\n\n if (items[table]?.length !== data[table]?.keys?.length) {\n throw new Error(`One or more items were not found in \"${table}\" table.`);\n }\n }\n\n return items;\n }\n\n // TODO: test wildly different item sizes to make\n // sure retry algorithm works properly\n async batchWrite(data: DbBatchWrite): Promise<DbBatchWriteResponse> {\n const result: DbBatchWriteResponse = { items: {} };\n\n const flattenedBatches = Object.keys(data).flatMap((table) => {\n return (\n data[table]?.map((r) => {\n if (r.type === \"DELETE\") {\n return [table, { DeleteRequest: { Key: r.key } }] as [string, WriteRequest];\n } else {\n return [table, { PutRequest: { Item: r.item } }] as [string, WriteRequest];\n }\n }) ?? []\n );\n });\n\n let batchSize = 25;\n let retryCount = 0;\n\n while (flattenedBatches.length && retryCount < 5) {\n const batch = flattenedBatches.splice(0, batchSize || 1);\n\n const request: BatchWriteItemInput[\"RequestItems\"] = {};\n for (const [table, req] of batch) {\n if (!request[table]) {\n request[table] = [];\n }\n request[table].push(req);\n }\n\n const input = new Lib.BatchWriteCommand({ RequestItems: request });\n const output = await this.client.send(input);\n\n // handle unprocessed requests\n let unprocessedKeyCount = 0;\n for (const [table, requests] of Object.entries(output.UnprocessedItems ?? {})) {\n for (const request of requests) {\n flattenedBatches.push([table, request]);\n unprocessedKeyCount++;\n }\n }\n\n //move immediately to next batch if all requests were processed\n if (!unprocessedKeyCount) {\n retryCount = 0;\n continue;\n }\n\n // reduce batch size so we don't continue to overwrite,\n // but do it gradually by only splitting the difference\n batchSize -= Math.floor(unprocessedKeyCount / 2);\n\n retryCount++;\n }\n\n // anything left in flattened batches needs to be returned in unprocessed\n if (flattenedBatches.length) {\n result.unprocessed = {};\n for (const [table, request] of flattenedBatches) {\n if (!result.unprocessed[table]) {\n result.unprocessed[table] = [];\n }\n\n if (\"DeleteRequest\" in request && request.DeleteRequest?.Key) {\n result.unprocessed[table].push({\n type: \"DELETE\",\n key: request.DeleteRequest.Key,\n });\n } else if (\"PutRequest\" in request && request.PutRequest?.Item) {\n result.unprocessed[table].push({\n type: \"PUT\",\n item: request.PutRequest.Item,\n });\n }\n }\n }\n\n return result;\n }\n\n async trxGet<R extends DbTrxGetRequest[]>(...requests: R): Promise<DbTrxGetResult<R>> {\n const trxItems: TransactGetCommandInput[\"TransactItems\"] = requests.map((request) => {\n const exp = new ExpressionBuilder();\n return {\n Get: {\n Key: request.key,\n TableName: request.table,\n ProjectionExpression: exp.projection(request?.projection),\n ExpressionAttributeNames: exp.attributeNames,\n },\n };\n });\n\n const input = new Lib.TransactGetCommand({ TransactItems: trxItems });\n const output = await this.client.send(input);\n\n return (\n (output.Responses?.map((response, i) => {\n if (!response.Item) return;\n\n if (!requests[i]?.filter) return response.Item;\n\n return requests[i].filter(response.Item) ? response.Item : undefined;\n }) as DbTrxGetResult<R>) ?? []\n );\n }\n\n async trxGetOrThrow<R extends DbTrxGetRequest[]>(\n ...requests: R\n ): Promise<DbTrxGetOrThrowResult<R>> {\n const items = await this.trxGet(...requests);\n for (let i = 0; i < items.length; i++) {\n if (!items[i]) {\n throw new Error(`One or more items were not found in \"${requests[i]?.table}\" table.`);\n }\n }\n\n return items as DbTrxGetOrThrowResult<R>;\n }\n\n async trxWrite(...requests: DbTrxWriteRequest[]): Promise<void> {\n const trxItems: TransactWriteCommandInput[\"TransactItems\"] = requests.map((request) => {\n const exp = new ExpressionBuilder();\n\n if (request.type === \"CONDITION\" || request.type === \"DELETE\") {\n return {\n [request.type === \"CONDITION\" ? \"ConditionCheck\" : \"Delete\"]: {\n TableName: request.table,\n Key: request.key,\n ConditionExpression: exp.condition(request.condition),\n ExpressionAttributeNames: exp.attributeNames,\n ExpressionAttributeValues: exp.attributeValues,\n },\n };\n }\n\n if (request.type === \"PUT\") {\n return {\n Put: {\n TableName: request.table,\n Item: removeUndefined(request.item),\n ConditionExpression: exp.condition(request.condition),\n ExpressionAttributeNames: exp.attributeNames,\n ExpressionAttributeValues: exp.attributeValues,\n },\n };\n }\n\n return {\n Update: {\n Key: request.key,\n TableName: request.table,\n UpdateExpression: exp.update(request.update),\n ConditionExpression: exp.condition(request.condition),\n ExpressionAttributeNames: exp.attributeNames,\n ExpressionAttributeValues: exp.attributeValues,\n },\n };\n });\n\n const input = new Lib.TransactWriteCommand({ TransactItems: trxItems });\n await this.client.send(input);\n }\n\n /* Dynamodb Streams */\n\n /*\n\n\tasync enableStreamEvents(data?: DbEnableEventStreams): Promise<void> {\n\t\tconst tables = data?.tables ?? (await this.listTables());\n\n\t\tconst streamsClient = new DynamoDBStreams({\n\t\t\tendpoint: this.client.config.endpoint,\n\t\t\tcredentials: this.client.config.credentials,\n\t\t\tregion: this.client.config.region,\n\t\t});\n\n\t\tawait Promise.all(\n\t\t\ttables.map(async (table) => {\n\t\t\t\tconst tableDesc = await this.client.send(new DescribeTableCommand({ TableName: table }));\n\n\t\t\t\tconst latestStreamArn = tableDesc.Table?.LatestStreamArn;\n\n\t\t\t\tif (!latestStreamArn) {\n\t\t\t\t\tif (data?.tables) {\n\t\t\t\t\t\tthrow new Error(`Table \"${table}\" does not have streaming enabled.`);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst eventStreamer = new EventStreamer(streamsClient, latestStreamArn);\n\t\t\t\teventStreamer.startPolling();\n\t\t\t}),\n\t\t);\n\t}\n\n\tasync disableStreamEvents(): Promise<void> {}\n\n\tsubscribe(listener: DbStreamEventListener): void {\n\t\tthis.streamEventListeners.push(listener);\n\t}\n\n\tunsubscribe(listener: DbStreamEventListener): void {\n\t\tthis.streamEventListeners = this.streamEventListeners.filter((l) => l !== listener);\n\t}\n\n\tunsubscribeAll(): void {\n\t\tthis.streamEventListeners = [];\n\t}\n\t*/\n}\n\n// respondentRepo.onChange((respondent) => , { filter: (r1, r2) => r1.status !== r2.status } )\n/*\nconst time = new Date(record.dynamodb.ApproximateCreationDateTime).getTime();\nif (time >= startTime) {\n\tfor (const listener of this.streamEventListeners) {\n\t\tlistener({\n\t\t\ttable,\n\t\t\ttime,\n\t\t\tid: record.eventID,\n\t\t\ttype: record.eventName,\n\t\t\tkey: record.dynamodb.Keys,\n\t\t\toldItem: record.dynamodb.OldImage,\n\t\t\tnewItem: record.dynamodb.NewImage,\n\t\t});\n\t}\n}\n*/\n","import type { Static, TSchema } from \"typebox\";\nimport type { TableDef } from \"./types\";\n\ntype SchemaStatic<Schema extends TSchema> = unknown extends Static<Schema> ? any : Static<Schema>;\n\nexport class Table<\n Schema extends TSchema = TSchema,\n const Def extends TableDef<SchemaStatic<Schema>> = TableDef<SchemaStatic<Schema>>,\n> {\n readonly schema: Schema;\n readonly def: Def;\n\n constructor(schema: Schema, def: Def) {\n this.schema = schema;\n this.def = def;\n }\n}\n"],"mappings":";;;;AAEA,MAAM,YAAY;CAAC;CAAK;CAAM;CAAK;CAAM;CAAK;CAAM;CAAQ;CAAQ;CAAK;CAAI;AAC7E,MAAM,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B,IAAI,OAAO,QAAQ,OAAO;IAC5C,qBAAqB,IAAI,UAAU,QAAQ,UAAU;IACrD,0BAA0B,IAAI;IAC9B,2BAA2B,IAAI;IAChC,EACF;IACD;EAEF,MAAM,QAAQ,IAAI,IAAI,qBAAqB,EAAE,eAAe,UAAU,CAAC;AACvE,QAAM,KAAK,OAAO,KAAK,MAAM;;;;;ACvmBjC,IAAa,QAAb,MAGE;CACA;CACA;CAEA,YAAY,QAAgB,KAAU;AACpC,OAAK,SAAS;AACd,OAAK,MAAM"}
@@ -0,0 +1,128 @@
1
+ import { Static, TSchema } from "typebox";
2
+
3
+ //#region src/types.d.ts
4
+ type Obj<T = any> = Record<string, T>;
5
+ type AllKeys<T> = Extract<T extends any ? keyof T : never, string>;
6
+ type PartialSome<T, K extends string | number | symbol> = Omit<T, K> & Partial<Pick<T, Extract<K, keyof T>>>;
7
+ type DistPartialSome<T, K extends string | number | symbol> = T extends unknown ? PartialSome<T, K> : never;
8
+ type ExtractTableDef<T> = T extends Table<any, infer Def> ? Def : never;
9
+ type ExtractTableSchema<T> = T extends Table<infer Schema, any> ? unknown extends Static<Schema> ? any : Static<Schema> : never;
10
+ type ExtractKey<S, D> = D extends {
11
+ partitionKey: infer PK;
12
+ sortKey?: infer SK;
13
+ } ? PK extends keyof S ? SK extends keyof S ? Pick<S, PK | SK> : Pick<S, PK> : never : never;
14
+ type Func = (...args: any[]) => any;
15
+ type ExtractKeys<T, O> = { [K in AllKeys<T>]: PickTypeOf<T, K, O> extends never ? never : {
16
+ k: K;
17
+ v: PickTypeOf<T, K, O>;
18
+ } }[AllKeys<T>]["k"];
19
+ type PickTypeOf<T, K extends AllKeys<T>, O> = T extends { [k in K]?: O } ? T[K] : never;
20
+ type ToUnion<T> = T extends readonly (infer U)[] ? U : T;
21
+ type SortKeyQuery<Schema, SK> = SK extends readonly [infer A extends string & keyof Schema, infer B extends string & keyof Schema, infer C extends string & keyof Schema, infer D extends string & keyof Schema] ? {} | Pick<Schema, A> | Pick<Schema, A | B> | Pick<Schema, A | B | C> | Pick<Schema, A | B | C | D> : SK extends readonly [infer A extends string & keyof Schema, infer B extends string & keyof Schema, infer C extends string & keyof Schema] ? {} | Pick<Schema, A> | Pick<Schema, A | B> | Pick<Schema, A | B | C> : SK extends readonly [infer A extends string & keyof Schema, infer B extends string & keyof Schema] ? {} | Pick<Schema, A> | Pick<Schema, A | B> : SK extends readonly [infer A extends string & keyof Schema] ? {} | Pick<Schema, A> : SK extends string & keyof Schema ? Partial<Pick<Schema, SK>> : {};
22
+ type ValidPrimaryKeys<T> = { [K in keyof T]: T[K] extends string | number ? K : never }[keyof T];
23
+ type ValidTtlKeys<T> = ExtractKeys<T, number>;
24
+ type ValidGsiKeys<T> = ExtractKeys<T, string | number>;
25
+ /** Extract the type of field K across all members of union T */
26
+ type ValueOfUnion<T, K extends string> = T extends unknown ? K extends keyof T ? T[K] : never : never;
27
+ /** Comparison operators valid for ordered types (string, number) */
28
+ interface ComparatorOps<V> {
29
+ $eq?: V;
30
+ $ne?: V;
31
+ $gt?: V;
32
+ $gte?: V;
33
+ $lt?: V;
34
+ $lte?: V;
35
+ }
36
+ /** String-specific operators */
37
+ interface StringOps {
38
+ $prefix?: string;
39
+ $includes?: string;
40
+ $between?: [string, string];
41
+ }
42
+ /** Number-specific operators */
43
+ interface NumberOps {
44
+ $between?: [number, number];
45
+ }
46
+ /** Operators valid for any attribute type */
47
+ interface CommonOps<V> {
48
+ $eq?: V;
49
+ $ne?: V;
50
+ $exists?: boolean;
51
+ $type?: "S" | "SS" | "N" | "NS" | "B" | "BS" | "BOOL" | "NULL" | "L" | "M";
52
+ $in?: V[];
53
+ $nin?: V[];
54
+ }
55
+ /** Size operator — accepts a number or a comparator on number */
56
+ interface SizeOps {
57
+ $size?: number | ComparatorOps<number>;
58
+ }
59
+ /** Path reference for cross-attribute comparisons */
60
+ interface PathRef {
61
+ $path: string;
62
+ }
63
+ /**
64
+ * Map a field's value type to the set of valid operators.
65
+ * Uses `[V] extends [X]` (wrapped) to prevent distribution over unions.
66
+ */
67
+ type FieldOps<V> = [V] extends [string] ? CommonOps<V | PathRef> & ComparatorOps<V | PathRef> & StringOps & SizeOps : [V] extends [number] ? CommonOps<V | PathRef> & ComparatorOps<V | PathRef> & NumberOps & SizeOps : [V] extends [boolean] ? CommonOps<V | PathRef> : [V] extends [any[]] ? CommonOps<V | PathRef> & {
68
+ $includes?: V[number];
69
+ } & SizeOps : CommonOps<V | PathRef> & SizeOps;
70
+ /**
71
+ * A single field condition: either a direct value (shorthand for $eq)
72
+ * or an operator object.
73
+ */
74
+ type FieldCondition<T> = { [K in AllKeys<T>]?: ValueOfUnion<T, K> | FieldOps<ValueOfUnion<T, K>> };
75
+ /**
76
+ * Full condition expression with compound operators.
77
+ */
78
+ type Condition<T> = FieldCondition<T> & {
79
+ $and?: Condition<T>[];
80
+ $or?: Condition<T>[];
81
+ $not?: Condition<T>;
82
+ };
83
+ interface Gsi<T> {
84
+ readonly partitionKey: ValidGsiKeys<T> | readonly ValidGsiKeys<T>[];
85
+ readonly sortKey?: ValidGsiKeys<T> | readonly ValidGsiKeys<T>[];
86
+ readonly projection?: "ALL" | "KEYS_ONLY" | readonly AllKeys<T>[];
87
+ }
88
+ interface TableDef<T = any> {
89
+ readonly name: string;
90
+ readonly partitionKey: ValidPrimaryKeys<T>;
91
+ readonly sortKey?: ValidPrimaryKeys<T>;
92
+ readonly gsis?: Readonly<Record<string, Gsi<T>>>;
93
+ readonly ttlAttribute?: ValidTtlKeys<T>;
94
+ readonly billingMode?: "PAY_PER_REQUEST" | "PROVISIONED";
95
+ readonly stream?: "KEYS_ONLY" | "NEW_IMAGE" | "OLD_IMAGE" | "NEW_AND_OLD_IMAGES";
96
+ }
97
+ interface TableKey {
98
+ name: string;
99
+ type: "S" | "N";
100
+ }
101
+ interface TableGsi {
102
+ indexName: string;
103
+ projectionType: "KEYS_ONLY" | "ALL" | "INCLUDE";
104
+ partitionKey: TableKey;
105
+ sortKey?: TableKey;
106
+ nonKeyAttributes?: string[];
107
+ }
108
+ interface TableDesc {
109
+ tableName: string;
110
+ billingMode: "PAY_PER_REQUEST" | "PROVISIONED";
111
+ partitionKey: TableKey;
112
+ sortKey?: TableKey;
113
+ ttlAttribute?: string;
114
+ gsis?: TableGsi[];
115
+ stream?: "KEYS_ONLY" | "NEW_IMAGE" | "OLD_IMAGE" | "NEW_AND_OLD_IMAGES";
116
+ }
117
+ type ResolvedAttrType = ("S" | "N" | undefined)[];
118
+ //#endregion
119
+ //#region src/table.d.ts
120
+ type SchemaStatic<Schema extends TSchema> = unknown extends Static<Schema> ? any : Static<Schema>;
121
+ declare class Table<Schema extends TSchema = TSchema, const Def extends TableDef<SchemaStatic<Schema>> = TableDef<SchemaStatic<Schema>>> {
122
+ readonly schema: Schema;
123
+ readonly def: Def;
124
+ constructor(schema: Schema, def: Def);
125
+ }
126
+ //#endregion
127
+ export { ValidTtlKeys as C, ValidPrimaryKeys as S, TableDesc as _, ExtractKey as a, ToUnion as b, ExtractTableSchema as c, Obj as d, PartialSome as f, TableDef as g, SortKeyQuery as h, DistPartialSome as i, Func as l, ResolvedAttrType as m, AllKeys as n, ExtractKeys as o, PickTypeOf as p, Condition as r, ExtractTableDef as s, Table as t, Gsi as u, TableGsi as v, ValidGsiKeys as x, TableKey as y };
128
+ //# sourceMappingURL=table-BAEqBNk3.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"table-BAEqBNk3.d.mts","names":[],"sources":["../src/types.ts","../src/table.ts"],"mappings":";;;KAGY,GAAA,YAAe,MAAA,SAAe,CAAA;AAAA,KAM9B,OAAA,MAAa,OAAA,CAAQ,CAAA,qBAAsB,CAAA;AAAA,KAE3C,WAAA,0CAAqD,IAAA,CAAK,CAAA,EAAG,CAAA,IACvE,OAAA,CAAQ,IAAA,CAAK,CAAA,EAAG,OAAA,CAAQ,CAAA,QAAS,CAAA;AAAA,KAEvB,eAAA,0CAAyD,CAAA,mBACjE,WAAA,CAAY,CAAA,EAAG,CAA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GU,gBAAA;;;KCrNP,YAAA,gBAA4B,OAAA,oBAA2B,MAAA,CAAO,MAAA,UAAgB,MAAA,CAAO,MAAA;AAAA,cAE7E,KAAA,gBACI,OAAA,GAAU,OAAA,oBACP,QAAA,CAAS,YAAA,CAAa,MAAA,KAAW,QAAA,CAAS,YAAA,CAAa,MAAA;EAAA,SAEhE,MAAA,EAAQ,MAAA;EAAA,SACR,GAAA,EAAK,GAAA;EAEd,WAAA,CAAY,MAAA,EAAQ,MAAA,EAAQ,GAAA,EAAK,GAAA;AAAA"}
@@ -0,0 +1,128 @@
1
+ import { Static, TSchema } from "typebox";
2
+
3
+ //#region src/types.d.ts
4
+ type Obj<T = any> = Record<string, T>;
5
+ type AllKeys<T> = Extract<T extends any ? keyof T : never, string>;
6
+ type PartialSome<T, K extends string | number | symbol> = Omit<T, K> & Partial<Pick<T, Extract<K, keyof T>>>;
7
+ type DistPartialSome<T, K extends string | number | symbol> = T extends unknown ? PartialSome<T, K> : never;
8
+ type ExtractTableDef<T> = T extends Table<any, infer Def> ? Def : never;
9
+ type ExtractTableSchema<T> = T extends Table<infer Schema, any> ? unknown extends Static<Schema> ? any : Static<Schema> : never;
10
+ type ExtractKey<S, D> = D extends {
11
+ partitionKey: infer PK;
12
+ sortKey?: infer SK;
13
+ } ? PK extends keyof S ? SK extends keyof S ? Pick<S, PK | SK> : Pick<S, PK> : never : never;
14
+ type Func = (...args: any[]) => any;
15
+ type ExtractKeys<T, O> = { [K in AllKeys<T>]: PickTypeOf<T, K, O> extends never ? never : {
16
+ k: K;
17
+ v: PickTypeOf<T, K, O>;
18
+ } }[AllKeys<T>]["k"];
19
+ type PickTypeOf<T, K extends AllKeys<T>, O> = T extends { [k in K]?: O } ? T[K] : never;
20
+ type ToUnion<T> = T extends readonly (infer U)[] ? U : T;
21
+ type SortKeyQuery<Schema, SK> = SK extends readonly [infer A extends string & keyof Schema, infer B extends string & keyof Schema, infer C extends string & keyof Schema, infer D extends string & keyof Schema] ? {} | Pick<Schema, A> | Pick<Schema, A | B> | Pick<Schema, A | B | C> | Pick<Schema, A | B | C | D> : SK extends readonly [infer A extends string & keyof Schema, infer B extends string & keyof Schema, infer C extends string & keyof Schema] ? {} | Pick<Schema, A> | Pick<Schema, A | B> | Pick<Schema, A | B | C> : SK extends readonly [infer A extends string & keyof Schema, infer B extends string & keyof Schema] ? {} | Pick<Schema, A> | Pick<Schema, A | B> : SK extends readonly [infer A extends string & keyof Schema] ? {} | Pick<Schema, A> : SK extends string & keyof Schema ? Partial<Pick<Schema, SK>> : {};
22
+ type ValidPrimaryKeys<T> = { [K in keyof T]: T[K] extends string | number ? K : never }[keyof T];
23
+ type ValidTtlKeys<T> = ExtractKeys<T, number>;
24
+ type ValidGsiKeys<T> = ExtractKeys<T, string | number>;
25
+ /** Extract the type of field K across all members of union T */
26
+ type ValueOfUnion<T, K extends string> = T extends unknown ? K extends keyof T ? T[K] : never : never;
27
+ /** Comparison operators valid for ordered types (string, number) */
28
+ interface ComparatorOps<V> {
29
+ $eq?: V;
30
+ $ne?: V;
31
+ $gt?: V;
32
+ $gte?: V;
33
+ $lt?: V;
34
+ $lte?: V;
35
+ }
36
+ /** String-specific operators */
37
+ interface StringOps {
38
+ $prefix?: string;
39
+ $includes?: string;
40
+ $between?: [string, string];
41
+ }
42
+ /** Number-specific operators */
43
+ interface NumberOps {
44
+ $between?: [number, number];
45
+ }
46
+ /** Operators valid for any attribute type */
47
+ interface CommonOps<V> {
48
+ $eq?: V;
49
+ $ne?: V;
50
+ $exists?: boolean;
51
+ $type?: "S" | "SS" | "N" | "NS" | "B" | "BS" | "BOOL" | "NULL" | "L" | "M";
52
+ $in?: V[];
53
+ $nin?: V[];
54
+ }
55
+ /** Size operator — accepts a number or a comparator on number */
56
+ interface SizeOps {
57
+ $size?: number | ComparatorOps<number>;
58
+ }
59
+ /** Path reference for cross-attribute comparisons */
60
+ interface PathRef {
61
+ $path: string;
62
+ }
63
+ /**
64
+ * Map a field's value type to the set of valid operators.
65
+ * Uses `[V] extends [X]` (wrapped) to prevent distribution over unions.
66
+ */
67
+ type FieldOps<V> = [V] extends [string] ? CommonOps<V | PathRef> & ComparatorOps<V | PathRef> & StringOps & SizeOps : [V] extends [number] ? CommonOps<V | PathRef> & ComparatorOps<V | PathRef> & NumberOps & SizeOps : [V] extends [boolean] ? CommonOps<V | PathRef> : [V] extends [any[]] ? CommonOps<V | PathRef> & {
68
+ $includes?: V[number];
69
+ } & SizeOps : CommonOps<V | PathRef> & SizeOps;
70
+ /**
71
+ * A single field condition: either a direct value (shorthand for $eq)
72
+ * or an operator object.
73
+ */
74
+ type FieldCondition<T> = { [K in AllKeys<T>]?: ValueOfUnion<T, K> | FieldOps<ValueOfUnion<T, K>> };
75
+ /**
76
+ * Full condition expression with compound operators.
77
+ */
78
+ type Condition<T> = FieldCondition<T> & {
79
+ $and?: Condition<T>[];
80
+ $or?: Condition<T>[];
81
+ $not?: Condition<T>;
82
+ };
83
+ interface Gsi<T> {
84
+ readonly partitionKey: ValidGsiKeys<T> | readonly ValidGsiKeys<T>[];
85
+ readonly sortKey?: ValidGsiKeys<T> | readonly ValidGsiKeys<T>[];
86
+ readonly projection?: "ALL" | "KEYS_ONLY" | readonly AllKeys<T>[];
87
+ }
88
+ interface TableDef<T = any> {
89
+ readonly name: string;
90
+ readonly partitionKey: ValidPrimaryKeys<T>;
91
+ readonly sortKey?: ValidPrimaryKeys<T>;
92
+ readonly gsis?: Readonly<Record<string, Gsi<T>>>;
93
+ readonly ttlAttribute?: ValidTtlKeys<T>;
94
+ readonly billingMode?: "PAY_PER_REQUEST" | "PROVISIONED";
95
+ readonly stream?: "KEYS_ONLY" | "NEW_IMAGE" | "OLD_IMAGE" | "NEW_AND_OLD_IMAGES";
96
+ }
97
+ interface TableKey {
98
+ name: string;
99
+ type: "S" | "N";
100
+ }
101
+ interface TableGsi {
102
+ indexName: string;
103
+ projectionType: "KEYS_ONLY" | "ALL" | "INCLUDE";
104
+ partitionKey: TableKey;
105
+ sortKey?: TableKey;
106
+ nonKeyAttributes?: string[];
107
+ }
108
+ interface TableDesc {
109
+ tableName: string;
110
+ billingMode: "PAY_PER_REQUEST" | "PROVISIONED";
111
+ partitionKey: TableKey;
112
+ sortKey?: TableKey;
113
+ ttlAttribute?: string;
114
+ gsis?: TableGsi[];
115
+ stream?: "KEYS_ONLY" | "NEW_IMAGE" | "OLD_IMAGE" | "NEW_AND_OLD_IMAGES";
116
+ }
117
+ type ResolvedAttrType = ("S" | "N" | undefined)[];
118
+ //#endregion
119
+ //#region src/table.d.ts
120
+ type SchemaStatic<Schema extends TSchema> = unknown extends Static<Schema> ? any : Static<Schema>;
121
+ declare class Table<Schema extends TSchema = TSchema, const Def extends TableDef<SchemaStatic<Schema>> = TableDef<SchemaStatic<Schema>>> {
122
+ readonly schema: Schema;
123
+ readonly def: Def;
124
+ constructor(schema: Schema, def: Def);
125
+ }
126
+ //#endregion
127
+ export { ValidTtlKeys as C, ValidPrimaryKeys as S, TableDesc as _, ExtractKey as a, ToUnion as b, ExtractTableSchema as c, Obj as d, PartialSome as f, TableDef as g, SortKeyQuery as h, DistPartialSome as i, Func as l, ResolvedAttrType as m, AllKeys as n, ExtractKeys as o, PickTypeOf as p, Condition as r, ExtractTableDef as s, Table as t, Gsi as u, TableGsi as v, ValidGsiKeys as x, TableKey as y };
128
+ //# sourceMappingURL=table-Bx001Rxj.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"table-Bx001Rxj.d.cts","names":[],"sources":["../src/types.ts","../src/table.ts"],"mappings":";;;KAGY,GAAA,YAAe,MAAA,SAAe,CAAA;AAAA,KAM9B,OAAA,MAAa,OAAA,CAAQ,CAAA,qBAAsB,CAAA;AAAA,KAE3C,WAAA,0CAAqD,IAAA,CAAK,CAAA,EAAG,CAAA,IACvE,OAAA,CAAQ,IAAA,CAAK,CAAA,EAAG,OAAA,CAAQ,CAAA,QAAS,CAAA;AAAA,KAEvB,eAAA,0CAAyD,CAAA,mBACjE,WAAA,CAAY,CAAA,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