All files / entities update.js

94.3% Statements 265/281
87.78% Branches 194/221
92.3% Functions 12/13
94.79% Lines 255/269

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 8861x 1x 1x 1x 1x           1x 1x 1x 1x 1x           1x 1x 1x 1x 1x 1x 1x 1x           1x       1x             1x       1x 1x         1x 1x 1x 1x       1x   1x 1x 1x   1x 99x 99x 99x 99x 98x 98x   98x 1x                   97x 1x                     96x 3x                         93x             92x 1x                     91x 2x                               89x             89x 89x     89x 89x             89x 1x                         88x 88x     88x 29x     29x 2x                               86x 86x 86x   86x 15x             15x 1x                   14x 14x 14x           85x 85x           85x 85x 85x               85x 85x   85x           85x       34x             34x       34x     32x 32x       30x         30x       25x           25x   24x 24x 24x       24x 3x       3x       22x 22x 24x 22x 23x 23x     22x 22x 22x           22x 7x 2x           2x 1x                 1x       1x       21x 21x 21x           72x 25x 25x 1x 1x                   71x 3x     3x   70x 2x 1x   1x 1x   2x     70x 2x 1x                   1x 1x 1x                   68x       1x   68x       68x 13x 13x 13x       69x 18x 1x                           17x 5x           5x 5x           5x 1x                             4x           4x 1x                         15x 15x 15x           66x 66x       10x 10x         10x           63x         8x           8x   8x 8x 8x               8x 2x                           61x       2x 2x 2x     61x 7x   3x 3x   4x 4x 4x       61x 4x   3x 3x   1x 1x 1x       61x                           61x 3x 1x                 2x 2x 2x     60x 1x 1x 1x     60x 1x 1x 1x     60x 1x                   59x 59x 59x           59x 2x                         137x 59x 137x 8x 59x                               59x 59x                   59x 59x 59x 59x     59x                                         1x               59x 10x 2x                   10x 1x 1x   1x                           59x 9x 1x                         9x 2x               9x 2x 1x                       9x 1x                 9x 1x 1x                               59x 2x       2x 6x 5x   2x 1x 1x                     59x                 2x 2x                       1x      
const { getActiveFlowId } = require('../shared/activeFlow')
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, GetCommand, UpdateCommand } = require('@aws-sdk/lib-dynamodb')
const { requirePermission } = require('../utils/requirePermission')
const { ensureRestrictedEntityRoles } = require('../utils/restrictedEntityRoles')
const {
  RESERVED_ENTITY_IDS,
  VISIBILITY_LEVELS,
  MAX_ENTITY_FORMS,
  MAX_ENTITY_SIZE_BYTES
} = require('../utils/constants')
const { getCreditsBalance, debitCredits } = require('../utils/creditsLedger')
const { getPricingConfig } = require('../utils/pricingConfig')
const { getConsumedCapacity } = require('../shared/usage-tracking')
const { S3Client } = require('@aws-sdk/client-s3')
const {
  getBrandingKeys,
  getRemovedKeys,
  entityKeyGuard,
  deleteKeys
} = require('../utils/s3Cleanup')
const { validateWorkflowFields } = require('../utils/validateWorkflowFields')
const { loadLinkedEntities } = require('../utils/expressions/linkedItems')
const { validateEmailTemplates } = require('../utils/emailTemplates')
const { validateFieldNames } = require('../utils/validateFieldNames')
const { validateFieldDefinitions } = require('../utils/validateFieldDefinitions')
const { validateDescription } = require('../utils/validateDescription')
const { validatePublicEntityFields } = require('../utils/validatePublicEntityFields')
const {
  findRemovedSelectOptions,
  findRemovedWorkflowStates,
  validateWorkflowStateMigrations,
  validateMandatoryCrossFlowReferences
} = require('../utils/entityFieldCascadeValidation')
const {
  cascadeRemovedReferenceValue,
  cascadeWorkflowStateMigration
} = require('../utils/cascadeItemFieldValue')
const {
  diffUniqueFieldChanges,
  scanUniqueFieldValues,
  backfillUniqueFieldReservations,
  deleteAllReservationsForField,
  deleteUniqueReservationForField
} = require('../utils/uniqueFieldValue')
const {
  diffEqualityIndexFieldChanges,
  backfillEqualityIndexRows
} = require('../utils/equalityIndexValue')
const { batchWrite } = require('../utils/batchWrite')
const {
  diffCatalogSearchTokens,
  buildCatalogSearchPutRequest,
  buildCatalogSearchDeleteRequest
} = require('../utils/catalogSearchIndex')
const { getEntityLinkFlows } = require('../utils/entityLinks')
const { getPublicEntityRefUsers } = require('../utils/entityRefUsages')
const { resolveForms } = require('../utils/resolveEntityForms')
const {
  findEntityNameConflict,
  findPublicEntityNameConflictForOwner
} = require('../utils/nameUniqueness')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
const s3Client = new S3Client({ region: 'eu-central-1' })
 
const updateEntityHandler = async (event) => {
  try {
    const pricing = await getPricingConfig(docClient, process.env.PRICING_CONFIG_TABLE_NAME)
    const id = event.pathParameters?.entityId
    const body = JSON.parse(event.body || '{}')
    const flowId = await getActiveFlowId(event)
    const userId = event.requestContext?.authorizer?.claims?.sub
 
    if (!flowId) {
      return {
        statusCode: 401,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Missing flow context' })
      }
    }
 
    if (!id) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Missing id' })
      }
    }
 
    // Prevent modification of system entities
    if (RESERVED_ENTITY_IDS.includes(id)) {
      return {
        statusCode: 403,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({
          error: `Cannot modify system entity "${id}". System entities are read-only.`
        })
      }
    }
 
    // Verify entity exists and ownership
    const result = await docClient.send(
      new GetCommand({
        TableName: process.env.TABLE_NAME,
        Key: { id }
      })
    )
 
    if (!result.Item) {
      return {
        statusCode: 404,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Entity not found' })
      }
    }
 
    // Only owner flow can update
    if (result.Item.flowId !== flowId) {
      return {
        statusCode: 403,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Access denied - only owner can update' })
      }
    }
 
    // Storage-credit preflight — only the *growth* in fields+forms size is
    // charged, same delta model as items/update.js. Approximated from the
    // raw request body rather than replicating resolveForms()'s exact
    // derivation below — good enough for a credit estimate, not required to
    // be byte-exact (see docs/architecture/USAGE_METERING.md "Bounding
    // storage before it can be priced").
    const previousEntitySizeBytes = Buffer.byteLength(
      JSON.stringify({
        fields: result.Item.fields || [],
        forms: result.Item.forms || [],
        emailTemplates: result.Item.emailTemplates || []
      })
    )
    const nextFieldsForSizing = body.fields !== undefined ? body.fields : result.Item.fields || []
    const nextFormsForSizing = body.forms !== undefined ? body.forms : result.Item.forms || []
    // The email templates the entity will have (UC-WORKFLOW-010.1)
    const nextEmailTemplates =
      body.emailTemplates !== undefined ? body.emailTemplates : result.Item.emailTemplates
    const nextEntitySizeBytes = Buffer.byteLength(
      JSON.stringify({
        fields: nextFieldsForSizing,
        forms: nextFormsForSizing,
        emailTemplates: nextEmailTemplates || []
      })
    )
    if (nextEntitySizeBytes > MAX_ENTITY_SIZE_BYTES) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({
          error: 'ENTITY_TOO_LARGE',
          maxBytes: MAX_ENTITY_SIZE_BYTES,
          actualBytes: nextEntitySizeBytes
        })
      }
    }
    const entityGrowthBytes = Math.max(0, nextEntitySizeBytes - previousEntitySizeBytes)
    const storageCreditDelta = Math.ceil(
      (entityGrowthBytes / 1024) * pricing.dynamodb_storage_credits_per_kb
    )
    if (storageCreditDelta > 0) {
      const { balance: creditsBalance, isPlatformAdmin } = userId
        ? await getCreditsBalance(docClient, process.env.USERS_TABLE_NAME, userId)
        : { balance: 0, isPlatformAdmin: false }
      if (!userId || (!isPlatformAdmin && creditsBalance < storageCreditDelta)) {
        return {
          statusCode: 402,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
          },
          body: JSON.stringify({
            error: 'INSUFFICIENT_CREDITS',
            required: storageCreditDelta,
            balance: creditsBalance
          })
        }
      }
    }
 
    // Build update expression
    const updateExpressions = []
    const expressionAttributeNames = {}
    const expressionAttributeValues = {}
 
    if (body.name !== undefined) {
      const nameConflict = await findEntityNameConflict(docClient, {
        tableName: process.env.TABLE_NAME,
        flowId,
        name: body.name,
        excludeEntityId: id
      })
 
      if (nameConflict) {
        return {
          statusCode: 409,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
          },
          body: JSON.stringify({ error: 'An entity with this name already exists in this flow' })
        }
      }
 
      updateExpressions.push('#name = :name')
      expressionAttributeNames['#name'] = 'name'
      expressionAttributeValues[':name'] = body.name
    }
 
    // onDelete cascade bookkeeping for select-option and workflow-state removals,
    // populated below (if body.fields changes) and applied after the entity
    // UpdateCommand succeeds further down.
    let selectRemovals = []
    let workflowRemovals = []
    // Same idea for unique-field reservation bookkeeping: a field newly
    // marked unique:true is validated+scanned below (rejecting the update if
    // existing items already conflict) and backfilled after the entity write
    // succeeds; a field that lost unique:true (or was removed entirely) has
    // its now-orphaned reservation rows released at the same point.
    const uniqueFieldBackfills = []
    let noLongerUniqueFieldIds = []
    let fieldsRemovedEntirely = []
    // Equality-index eligibility (see utils/equalityIndexValue.js) is purely
    // a function of field type, which never changes once a field exists —
    // the ONE live post-creation transition is entity_ref/user's
    // reference.multiple flipping (multi-value fields aren't equality-
    // indexed). Text/textarea/email search indexing has no analogous
    // transition at all — it's always on, so entities/update.js never needs
    // to backfill or clean it up.
    let newlyEqualityIndexEligibleFields = []
    let noLongerEqualityIndexEligibleFieldIds = []
 
    Iif (body.description !== undefined) {
      // Validate description: cannot exceed the maximum number of line breaks
      const descriptionValidation = validateDescription(body.description)
      if (!descriptionValidation.valid) return descriptionValidation.errorResponse
    }
 
    if (body.fields !== undefined) {
      // Validate workflow fields: each workflow field must have a valid startStateId,
      // and each automatic transition a valid condition — rows on linked items
      // against their entity's fields (UC-WORKFLOW-008.1)
      const linkedEntities = await loadLinkedEntities({
        docClient,
        entitiesTableName: process.env.TABLE_NAME,
        fields: body.fields,
        entityId: id,
        flowId
      })
      const workflowValidation = validateWorkflowFields(body.fields, {
        linkedEntities,
        emailTemplates: nextEmailTemplates
      })
      if (!workflowValidation.valid) return workflowValidation.errorResponse
 
      // Validate field names: every field must have a non-empty name
      const fieldNameValidation = validateFieldNames(body.fields)
      if (!fieldNameValidation.valid) return fieldNameValidation.errorResponse
 
      // Validate field definitions: known type, well-formed select/multiselect
      // options, sound number min/max/step, positive length/maxLines
      const fieldDefinitionValidation = validateFieldDefinitions(body.fields, {
        previousFields: result.Item.fields || [],
        defaultLanguage: body.defaultLanguage ?? result.Item.defaultLanguage,
        previousDefaultLanguage: result.Item.defaultLanguage
      })
      if (!fieldDefinitionValidation.valid) return fieldDefinitionValidation.errorResponse
 
      // A mandatory Item Link field can't safely target a public entity owned by
      // another flow — see entityFieldCascadeValidation.js for why.
      const crossFlowValidation = await validateMandatoryCrossFlowReferences(
        body.fields,
        docClient,
        process.env.TABLE_NAME,
        flowId
      )
      if (!crossFlowValidation.valid) return crossFlowValidation.errorResponse
 
      const previousFields = result.Item.fields || []
      selectRemovals = findRemovedSelectOptions(previousFields, body.fields)
      workflowRemovals = findRemovedWorkflowStates(previousFields, body.fields)
 
      // Every removed workflow status requires an explicit fallback chosen by
      // the editor (see WorkflowEditor.vue) before the schema change is allowed.
      if (workflowRemovals.length > 0) {
        const migrationValidation = validateWorkflowStateMigrations(
          workflowRemovals,
          body.workflowStateMigrations
        )
        if (!migrationValidation.valid) return migrationValidation.errorResponse
      }
 
      const { newlyUniqueFields, noLongerUniqueFieldIds: removedUniqueFieldIds } =
        diffUniqueFieldChanges(previousFields, body.fields)
      noLongerUniqueFieldIds = removedUniqueFieldIds
      const nextFieldIds = new Set(body.fields.map((f) => f.fieldId))
      fieldsRemovedEntirely = previousFields
        .map((f) => f.fieldId)
        .filter((fieldId) => !nextFieldIds.has(fieldId))
 
      const { newlyEligibleFields: newlyEligible, noLongerEligibleFieldIds: removedEligible } =
        diffEqualityIndexFieldChanges(previousFields, body.fields)
      newlyEqualityIndexEligibleFields = newlyEligible
      noLongerEqualityIndexEligibleFieldIds = removedEligible
 
      // A field newly marked unique:true must not already be violated by the
      // entity's existing items — reject the whole update (no write at all)
      // if any duplicate is found, rather than silently accepting a schema
      // that's already broken by current data.
      if (process.env.FIELD_VALUE_INDEX_TABLE_NAME && process.env.ITEMS_TABLE_NAME) {
        for (const field of newlyUniqueFields) {
          const { valueEntries, conflicts } = await scanUniqueFieldValues(
            docClient,
            process.env.ITEMS_TABLE_NAME,
            id,
            field
          )
          if (conflicts.length > 0) {
            return {
              statusCode: 400,
              headers: {
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*'
              },
              body: JSON.stringify({
                error: 'UNIQUE_CONSTRAINT_VIOLATED_BY_EXISTING_ITEMS',
                fieldId: field.fieldId,
                conflicts: conflicts.map((c) => ({ itemIds: c.itemIds }))
              })
            }
          }
          uniqueFieldBackfills.push({ fieldId: field.fieldId, valueEntries })
        }
      }
 
      updateExpressions.push('#fields = :fields')
      expressionAttributeNames['#fields'] = 'fields'
      expressionAttributeValues[':fields'] = body.fields
    }
 
    // Email templates (UC-WORKFLOW-010.1): checked against the fields they insert
    // whenever either changes, and the transitions' Email actions against the
    // templates they use (a template still in use can't be deleted)
    if (body.fields !== undefined || body.emailTemplates !== undefined) {
      const templatesValidation = validateEmailTemplates(nextEmailTemplates, nextFieldsForSizing)
      if (!templatesValidation.valid) {
        const { valid, ...details } = templatesValidation // eslint-disable-line no-unused-vars
        return {
          statusCode: 400,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
          },
          body: JSON.stringify({ error: 'INVALID_EMAIL_TEMPLATE', ...details })
        }
      }
    }
    if (body.emailTemplates !== undefined && body.fields === undefined) {
      const actionsValidation = validateWorkflowFields(result.Item.fields || [], {
        emailTemplates: nextEmailTemplates
      })
      if (!actionsValidation.valid) return actionsValidation.errorResponse
    }
    if (body.emailTemplates !== undefined) {
      if (!Array.isArray(body.emailTemplates) || body.emailTemplates.length === 0) {
        updateExpressions.push('REMOVE #emailTemplates')
      } else {
        updateExpressions.push('#emailTemplates = :emailTemplates')
        expressionAttributeValues[':emailTemplates'] = body.emailTemplates
      }
      expressionAttributeNames['#emailTemplates'] = 'emailTemplates'
    }
 
    if (body.forms !== undefined) {
      if (Array.isArray(body.forms) && body.forms.length > MAX_ENTITY_FORMS) {
        return {
          statusCode: 400,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
          },
          body: JSON.stringify({ error: 'TOO_MANY_FORMS', max: MAX_ENTITY_FORMS })
        }
      }
 
      if (body.forms === null || (Array.isArray(body.forms) && body.forms.length === 0)) {
        updateExpressions.push('REMOVE #forms')
        expressionAttributeNames['#forms'] = 'forms'
      } else E{
        const forms = resolveForms({
          fields: body.fields !== undefined ? body.fields : result.Item.fields,
          forms: body.forms
        })
        updateExpressions.push('#forms = :forms')
        expressionAttributeNames['#forms'] = 'forms'
        expressionAttributeValues[':forms'] = forms || body.forms
      }
    } else Eif (
      body.fields !== undefined ||
      !Array.isArray(result.Item.forms) ||
      result.Item.forms.length === 0 ||
      !result.Item.forms.some((form) => form?.purpose === 'short')
    ) {
      const forms = resolveForms({
        fields: body.fields !== undefined ? body.fields : result.Item.fields,
        forms: result.Item.forms
      })
      if (forms) {
        updateExpressions.push('#forms = :forms')
        expressionAttributeNames['#forms'] = 'forms'
        expressionAttributeValues[':forms'] = forms
      }
    }
 
    if (body.visibility !== undefined) {
      if (!VISIBILITY_LEVELS.includes(body.visibility)) {
        return {
          statusCode: 400,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
          },
          body: JSON.stringify({
            error: `Invalid visibility level. Must be one of: ${VISIBILITY_LEVELS.join(', ')}`
          })
        }
      }
 
      // Demoting away from public would break flows owned by other users
      // that link this entity, since links only work while the entity is public.
      if (body.visibility !== 'public' && result.Item.visibility === 'public') {
        const ownerFlowResult = await docClient.send(
          new GetCommand({
            TableName: process.env.FLOWS_TABLE_NAME,
            Key: { id: flowId }
          })
        )
        const ownerUserId = ownerFlowResult.Item?.ownerId
        const { otherUserFlowIds } = await getEntityLinkFlows(docClient, {
          entityLinksTableName: process.env.ENTITY_LINKS_TABLE_NAME,
          flowsTableName: process.env.FLOWS_TABLE_NAME,
          entityId: id,
          ownerUserId
        })
        if (otherUserFlowIds.length > 0) {
          return {
            statusCode: 409,
            headers: {
              'Content-Type': 'application/json',
              'Access-Control-Allow-Origin': '*'
            },
            body: JSON.stringify({
              error: `Cannot change visibility: entity is linked into ${otherUserFlowIds.length} flow(s) owned by other users`
            })
          }
        }
 
        // Demoting away from public would also break the user's own public
        // entities that reference this one through an item link (entity_ref)
        // field, since validatePublicEntityFields requires such targets to stay public.
        const referencingEntities = await getPublicEntityRefUsers(docClient, {
          entitiesTableName: process.env.TABLE_NAME,
          flowsTableName: process.env.FLOWS_TABLE_NAME,
          entityId: id,
          ownerUserId
        })
        if (referencingEntities.length > 0) {
          return {
            statusCode: 409,
            headers: {
              'Content-Type': 'application/json',
              'Access-Control-Allow-Origin': '*'
            },
            body: JSON.stringify({
              error: `Cannot change visibility: entity is used by ${referencingEntities.length} of your public entit${referencingEntities.length > 1 ? 'ies' : 'y'} in an item link field`
            })
          }
        }
      }
 
      updateExpressions.push('#visibility = :visibility')
      expressionAttributeNames['#visibility'] = 'visibility'
      expressionAttributeValues[':visibility'] = body.visibility
    }
 
    // Public entities cannot expose user data or reference non-public entities.
    // Re-validate whenever the entity is (or becomes) public and fields or
    // visibility are part of this update.
    const nextVisibility = body.visibility !== undefined ? body.visibility : result.Item.visibility
    if (
      nextVisibility === 'public' &&
      (body.fields !== undefined || body.visibility !== undefined)
    ) {
      const nextFields = body.fields !== undefined ? body.fields : result.Item.fields
      const publicFieldsValidation = await validatePublicEntityFields(
        nextFields,
        docClient,
        process.env.TABLE_NAME
      )
      if (!publicFieldsValidation.valid) return publicFieldsValidation.errorResponse
    }
 
    // A user's public entity names must be unique across all of their own
    // flows, not just this one — re-check whenever the name changes while
    // public, or the entity is being promoted to public.
    if (
      nextVisibility === 'public' &&
      (body.name !== undefined ||
        (body.visibility === 'public' && result.Item.visibility !== 'public'))
    ) {
      const ownerFlowResult = await docClient.send(
        new GetCommand({
          TableName: process.env.FLOWS_TABLE_NAME,
          Key: { id: flowId }
        })
      )
      const flowOwnerId = ownerFlowResult.Item?.ownerId
 
      Eif (flowOwnerId) {
        const nextName = body.name !== undefined ? body.name : result.Item.name
        const publicNameConflict = await findPublicEntityNameConflictForOwner(docClient, {
          entitiesTableName: process.env.TABLE_NAME,
          flowsTableName: process.env.FLOWS_TABLE_NAME,
          ownerId: flowOwnerId,
          name: nextName,
          excludeEntityId: id
        })
 
        if (publicNameConflict) {
          return {
            statusCode: 409,
            headers: {
              'Content-Type': 'application/json',
              'Access-Control-Allow-Origin': '*'
            },
            body: JSON.stringify({
              error: 'A public entity with this name already exists in one of your other flows'
            })
          }
        }
      }
    }
 
    if (
      body.publicPermissions !== undefined &&
      (body.visibility === 'public' || result.Item.visibility === 'public')
    ) {
      updateExpressions.push('#publicPermissions = :publicPermissions')
      expressionAttributeNames['#publicPermissions'] = 'publicPermissions'
      expressionAttributeValues[':publicPermissions'] = body.publicPermissions
    }
 
    if (body.picture !== undefined) {
      if (body.picture === null || body.picture === '') {
        // Remove picture
        updateExpressions.push('REMOVE #picture')
        expressionAttributeNames['#picture'] = 'picture'
      } else {
        updateExpressions.push('#picture = :picture')
        expressionAttributeNames['#picture'] = 'picture'
        expressionAttributeValues[':picture'] = body.picture
      }
    }
 
    if (body.icon !== undefined) {
      if (body.icon === null || body.icon === '') {
        // Remove icon
        updateExpressions.push('REMOVE #icon')
        expressionAttributeNames['#icon'] = 'icon'
      } else {
        updateExpressions.push('#icon = :icon')
        expressionAttributeNames['#icon'] = 'icon'
        expressionAttributeValues[':icon'] = body.icon
      }
    }
 
    Iif (body.description !== undefined) {
      if (body.description === null || body.description === '') {
        // Remove description
        updateExpressions.push('REMOVE #description')
        expressionAttributeNames['#description'] = 'description'
      } else {
        updateExpressions.push('#description = :description')
        expressionAttributeNames['#description'] = 'description'
        expressionAttributeValues[':description'] = body.description
      }
    }
 
    // Turning comments off keeps the existing comments (they are just hidden),
    // so this is a plain flag flip with no cascade — see MODERATION.md.
    if (body.commentsEnabled !== undefined) {
      if (typeof body.commentsEnabled !== 'boolean') {
        return {
          statusCode: 400,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
          },
          body: JSON.stringify({ error: 'commentsEnabled must be a boolean' })
        }
      }
      updateExpressions.push('#commentsEnabled = :commentsEnabled')
      expressionAttributeNames['#commentsEnabled'] = 'commentsEnabled'
      expressionAttributeValues[':commentsEnabled'] = body.commentsEnabled
    }
 
    if (body.defaultLanguage !== undefined) {
      updateExpressions.push('#defaultLanguage = :defaultLanguage')
      expressionAttributeNames['#defaultLanguage'] = 'defaultLanguage'
      expressionAttributeValues[':defaultLanguage'] = body.defaultLanguage
    }
 
    if (body.enabledLanguages !== undefined) {
      updateExpressions.push('#enabledLanguages = :enabledLanguages')
      expressionAttributeNames['#enabledLanguages'] = 'enabledLanguages'
      expressionAttributeValues[':enabledLanguages'] = body.enabledLanguages
    }
 
    if (updateExpressions.length === 0) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'No fields to update' })
      }
    }
 
    updateExpressions.push('#updatedAt = :updatedAt')
    expressionAttributeNames['#updatedAt'] = 'updatedAt'
    expressionAttributeValues[':updatedAt'] = new Date().toISOString()
 
    // Switching to restricted: the entity's roles exist and the member making
    // the switch holds its Manager role before wildcards stop reaching it, so
    // they can't lock themselves out (UC-RBAC-008.1 AC-2). Kept even if the
    // update below fails — the roles are harmless on a non-restricted entity.
    if (body.visibility === 'restricted' && result.Item.visibility !== 'restricted' && userId) {
      await ensureRestrictedEntityRoles({
        docClient,
        rolesTableName: process.env.ROLES_TABLE_NAME,
        membershipsTableName: process.env.FLOW_MEMBERSHIPS_TABLE_NAME,
        flowId,
        entity: { id, name: body.name !== undefined ? body.name : result.Item.name },
        userId,
        now: expressionAttributeValues[':updatedAt']
      })
    }
 
    // `REMOVE …` entries were collected alongside the `SET` ones: DynamoDB
    // wants them in a clause of their own
    const setClauses = updateExpressions.filter((clause) => !clause.startsWith('REMOVE '))
    const removeClauses = updateExpressions
      .filter((clause) => clause.startsWith('REMOVE '))
      .map((clause) => clause.slice('REMOVE '.length))
    const updateResult = await docClient.send(
      new UpdateCommand({
        TableName: process.env.TABLE_NAME,
        Key: { id },
        UpdateExpression:
          `SET ${setClauses.join(', ')}` +
          (removeClauses.length > 0 ? ` REMOVE ${removeClauses.join(', ')}` : ''),
        ExpressionAttributeNames: expressionAttributeNames,
        ExpressionAttributeValues: expressionAttributeValues,
        ReturnValues: 'ALL_NEW'
      })
    )
 
    // A replaced or cleared picture/icon is now unreferenced: delete it. Only
    // when DynamoDB returned the new row, so an absent Attributes can never make
    // the current picture look "removed".
    Eif (updateResult.Attributes) {
      await deleteKeys(
        s3Client,
        process.env.ATTACHMENTS_BUCKET_NAME,
        getRemovedKeys(getBrandingKeys(result.Item), getBrandingKeys(updateResult.Attributes)),
        entityKeyGuard(id)
      )
    }
 
    // Best-effort from here: a failure doesn't unwind the write — see
    // items/update.js's identical reasoning.
    Eif (userId) {
      try {
        const { writeUnits } = getConsumedCapacity()
        const throughputCreditCost = Math.ceil(
          writeUnits * pricing.dynamodb_throughput_credits_per_wru
        )
        await debitCredits(docClient, {
          usersTableName: process.env.USERS_TABLE_NAME,
          creditsLedgerTableName: process.env.CREDITS_LEDGER_TABLE_NAME,
          userId,
          flowId,
          charges: [
            {
              pool: 'dynamodb_storage',
              operation: 'entity_update',
              costCredits: storageCreditDelta,
              referenceId: id
            },
            {
              pool: 'dynamodb_throughput',
              operation: 'entity_update',
              costCredits: throughputCreditCost,
              referenceId: id
            }
          ]
        })
      } catch (creditError) {
        console.error('Failed to debit credits for entity update:', creditError)
      }
    }
 
    // onDelete cascade: apply now that the schema change itself succeeded.
    // Existing items using a removed select option get SET_NULL (or a
    // placeholder if the field is mandatory); items in a removed workflow
    // state are migrated to the chosen fallback state.
    if (process.env.ITEMS_TABLE_NAME) {
      for (const removal of selectRemovals) {
        await cascadeRemovedReferenceValue({
          docClient,
          itemsTableName: process.env.ITEMS_TABLE_NAME,
          entityId: id,
          field: removal.field,
          matchValue: removal.removedValue,
          placeholderLabel: `Removed option (was "${removal.removedValue}")`
        })
      }
 
      for (const removal of workflowRemovals) {
        const migration = (body.workflowStateMigrations || []).find(
          (m) => m.fieldId === removal.field.fieldId && m.removedStateId === removal.removedStateId
        )
        await cascadeWorkflowStateMigration({
          docClient,
          itemsTableName: process.env.ITEMS_TABLE_NAME,
          entityId: id,
          field: removal.field,
          removedStateId: removal.removedStateId,
          fallbackStateId: migration.fallbackStateId
        })
      }
    }
 
    // Unique-field reservation bookkeeping: backfill for fields that just
    // became unique:true (their existing items were already scanned/verified
    // clean above), release for fields that lost unique:true or were removed.
    if (process.env.FIELD_VALUE_INDEX_TABLE_NAME) {
      for (const { fieldId, valueEntries } of uniqueFieldBackfills) {
        await backfillUniqueFieldReservations(
          docClient,
          process.env.FIELD_VALUE_INDEX_TABLE_NAME,
          id,
          fieldId,
          valueEntries
        )
      }
 
      // A field removed from the schema entirely has nothing left worth
      // keeping — release every row for it (reservation and/or index rows,
      // whatever shape it had) in one call, up front, so the loop below only
      // needs to handle fields that still exist but lost `unique`.
      for (const fieldId of fieldsRemovedEntirely) {
        await deleteAllReservationsForField(
          docClient,
          process.env.FIELD_VALUE_INDEX_TABLE_NAME,
          id,
          fieldId
        )
      }
 
      for (const fieldId of noLongerUniqueFieldIds) {
        if (fieldsRemovedEntirely.includes(fieldId)) continue
        await deleteUniqueReservationForField(
          docClient,
          process.env.FIELD_VALUE_INDEX_TABLE_NAME,
          id,
          fieldId
        )
      }
 
      // Equality-index eligibility only ever changes post-creation via
      // entity_ref/user's reference.multiple flipping — these fields are
      // never `unique`, so there's no coexisting row shape to preserve;
      // deleteAllReservationsForField is exactly right here too.
      for (const field of newlyEqualityIndexEligibleFields) {
        await backfillEqualityIndexRows(
          docClient,
          process.env.ITEMS_TABLE_NAME,
          process.env.FIELD_VALUE_INDEX_TABLE_NAME,
          id,
          field
        )
      }
 
      for (const fieldId of noLongerEqualityIndexEligibleFieldIds) {
        Iif (fieldsRemovedEntirely.includes(fieldId)) continue
        await deleteAllReservationsForField(
          docClient,
          process.env.FIELD_VALUE_INDEX_TABLE_NAME,
          id,
          fieldId
        )
      }
    }
 
    // Catalog-search index rows, kept in sync with the entity's own `name` —
    // a different, unrelated mechanism from the item-field search-index
    // eligibility bookkeeping above (which tracks the entity's *fields*
    // schema, not the entity's own name). Best-effort and non-transactional,
    // same reasoning as entities/create.js. Not gated on `visibility` at
    // all — see utils/catalogSearchIndex.js's own doc comments for why a
    // visibility change alone never needs an index write.
    if (process.env.FIELD_VALUE_INDEX_TABLE_NAME && body.name !== undefined) {
      const { toRelease, toClaim } = diffCatalogSearchTokens(
        result.Item.name,
        updateResult.Attributes.name
      )
      const catalogSearchRequests = [
        ...toRelease.map(({ kind, token }) => buildCatalogSearchDeleteRequest(kind, token, id)),
        ...toClaim.map(({ kind, token }) => buildCatalogSearchPutRequest(kind, token, id))
      ]
      if (catalogSearchRequests.length > 0) {
        try {
          await batchWrite(
            docClient,
            process.env.FIELD_VALUE_INDEX_TABLE_NAME,
            catalogSearchRequests
          )
        } catch (catalogSearchError) {
          console.error('Failed to update catalog-search index rows:', catalogSearchError)
        }
      }
    }
 
    return {
      statusCode: 200,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify(updateResult.Attributes)
    }
  } catch (error) {
    console.error('Error:', error)
    return {
      statusCode: 500,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify({ error: 'Failed to update entity' })
    }
  }
}
 
// Wrap with permission check: require 'entities-{id}:update' permission
exports.handler = requirePermission(updateEntityHandler, {
  permission: (event) => `entities-${event.pathParameters?.entityId}:update`
})