{
  "version": 3,
  "sources": ["../../../../src/tables/templates/update-item.ts"],
  "sourcesContent": ["import type {Model} from '@code-like-a-carpenter/foundation-intermediate-representation';\n\nimport type {Config} from '../../config.ts';\nimport {filterNull} from '../../helpers.ts';\nimport {defineComputedInputFields, inputName} from '../computed-fields.ts';\n\nimport {ensureTableTemplate} from './ensure-table.ts';\nimport {handleCommonErrors, makeKeyForRead, objectToString} from './helpers.ts';\n\n/**\n * Generates the updateItem function for a table\n */\nexport function updateItemTemplate(config: Config, model: Model) {\n  const {\n    fields,\n    isPublic: hasPublicId,\n    primaryKey,\n    table: {tableName},\n    ttlConfig,\n    typeName,\n  } = model;\n  const key = makeKeyForRead(config, primaryKey);\n  const marshallPrimaryKey = objectToString(\n    Object.fromEntries(\n      (primaryKey.isComposite\n        ? [...primaryKey.partitionKeyFields, ...primaryKey.sortKeyFields]\n        : primaryKey.partitionKeyFields\n      )\n        .map(({fieldName}) => fieldName)\n        .sort()\n        .map((fieldName) => [fieldName, `input.${fieldName}`])\n    )\n  );\n  const primaryKeyFields = (\n    primaryKey.isComposite\n      ? [...primaryKey.partitionKeyFields, ...primaryKey.sortKeyFields]\n      : primaryKey.partitionKeyFields\n  ).map(({fieldName}) => fieldName);\n\n  const inputTypeName = `Update${typeName}Input`;\n  const omitInputFields = [\n    'id',\n    'createdAt',\n    'updatedAt',\n    hasPublicId && 'publicId',\n    ttlConfig?.fieldName,\n    ...fields\n      .filter(({computeFunction}) => !!computeFunction)\n      .map(({fieldName}) => fieldName),\n  ]\n    .filter(filterNull)\n    .filter((fieldName) => !primaryKeyFields.includes(fieldName as string))\n    .map((f) => `'${f}'`)\n    .sort();\n  const outputTypeName = `Update${typeName}Output`;\n\n  return `\nexport type ${inputTypeName} = Omit<${typeName}, ${omitInputFields.join(\n    '|'\n  )}> ${\n    ttlConfig ? ` & Partial<Pick<${typeName}, '${ttlConfig.fieldName}'>>` : ''\n  };\nexport type ${outputTypeName} = ResultType<${typeName}>\n\n/**  */\nexport async function update${typeName}(${inputName(\n    model\n  )}: Readonly<${inputTypeName}>): Promise<Readonly<${outputTypeName}>> {\n${ensureTableTemplate(tableName)}\n  ${defineComputedInputFields(fields, typeName)}\n  const {ExpressionAttributeNames, ExpressionAttributeValues, UpdateExpression} = marshall${typeName}(input);\n  try {\n    let previousVersionCE = '';\n    let previousVersionEAV = {};\n    if ('version' in input && typeof input.version !== 'undefined') {\n      previousVersionCE = '#version = :previousVersion AND ';\n      previousVersionEAV = {':previousVersion': input.version,}\n    }\n    const commandInput: UpdateCommandInput = {\n      ConditionExpression: \\`\\${previousVersionCE}#entity = :entity AND attribute_exists(#pk)\\`,\n      ExpressionAttributeNames,\n      ExpressionAttributeValues: {\n        ...ExpressionAttributeValues,\n        ...previousVersionEAV\n      },\n      Key: ${objectToString(key)},\n      ReturnConsumedCapacity: 'INDEXES',\n      ReturnItemCollectionMetrics: 'SIZE',\n      ReturnValues: 'ALL_NEW',\n      TableName: tableName,\n      UpdateExpression,\n    };\n\n    const {Attributes: item, ConsumedCapacity: capacity, ItemCollectionMetrics: metrics} = await ddbDocClient.send(new UpdateCommand(commandInput));\n\n    assert(capacity, 'Expected ConsumedCapacity to be returned. This is a bug in codegen.');\n\n    assert(item, 'Expected DynamoDB to return an Attributes prop.');\n    assert(item._et === '${typeName}', () => new DataIntegrityError(\\`Expected \\${JSON.stringify(${marshallPrimaryKey})} to update a ${typeName} but updated \\${item._et} instead\\`));\n\n    return {\n      capacity,\n      item: unmarshall${typeName}(item),\n      metrics,\n    }\n  }\n  catch (err) {\n    if (err instanceof ConditionalCheckFailedException) {\n      try {\n        await read${typeName}(input);\n      }\n      catch {\n        throw new NotFoundError('${typeName}', ${marshallPrimaryKey});\n      }\n      throw new OptimisticLockingError('${typeName}', ${marshallPrimaryKey});\n    }\n    ${handleCommonErrors()}\n  }\n}`;\n}\n"],
  "mappings": ";AAGA,SAAQ,kBAAiB;AACzB,SAAQ,2BAA2B,iBAAgB;AAEnD,SAAQ,2BAA0B;AAClC,SA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