All files / entities import-worker.js

95.38% Statements 413/433
84.19% Branches 261/310
100% Functions 58/58
96.42% Lines 378/392

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 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213                            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 1x 1x   1x 1x   1x     10x     10x       2x     1x     1x   1x 1x 1x     1x         1x 1x       2x     2x           58x   58x 53x 52x 52x     58x 69x   69x 11x 11x     58x 5x         5x 5x 1x 1x   4x 1x       1x     3x       3x 1x 1x     2x               2x         53x     53x     53x   53x 53x         53x 53x         53x 53x 2x 2x     51x                     58x                   58x     69x 53x     58x   4x 4x 4x 4x 4x     58x   58x 69x   51x           51x 1x 1x 1x     50x 50x   50x           50x           50x 50x 1x 1x 1x     49x         49x 1x 1x 1x 1x     48x               97x 97x     97x                       97x         58x   58x   58x 69x   48x             48x               48x 48x   48x                                                           48x   48x   269x             48x               58x 36x 36x                               18x 18x 2x     16x 16x 1x     15x 15x       15x                                         15x               15x               15x   9x           9x                           58x 58x 58x   58x 69x   16x 16x 16x 16x 16x 16x   16x 18x 18x   18x 18x 3x     3x     3x     15x   15x 15x 2x       2x     2x   13x   13x                     13x 13x           13x             13x 13x         13x     16x 16x   16x 8x       58x 69x 69x   13x 14x 3x 13x 14x 2x   13x 13x 13x 13x     2x       13x           13x 1x 1x               13x 13x     58x 1x                   58x 69x   69x 11x                   58x 8x                         50x                                       18x 18x 17x                                   9x       9x                             17x 15x 15x 15x                                                         8x 8x   8x   6x 1x 1x   5x   12x 12x 7x                           4x 4x 3x   1x 1x           25x 23x 25x 8x                 18x 18x 18x       18x 18x                           2x 1x                   11x 14x   15x 11x 11x     22x                 11x 11x     11x   10x     9x           9x   6x             6x     6x   6x               6x   6x 1x       5x                             14x 14x           14x 14x   1x             13x 1x 1x   13x 1x             12x   12x       12x 12x 12x 12x       12x   12x       12x 11x           11x     6x       4x               5x           6x 6x 6x 6x 6x                                         1x 1x       5x 10x             5x       5x                                   13x 13x   12x 12x 12x   12x   2x 21x 12x   11x 11x 11x 11x 11x   11x 11x 11x   11x   1x   15x 11x 11x 14x                       11x   11x                 65x                   65x 3x     62x 62x             62x           62x   62x 61x   61x 13x 11x 11x 11x 11x   48x   47x 47x 47x 47x 47x 47x 47x 47x   47x 47x     4x 4x 4x           58x 58x 58x     58x 58x 58x                                         1x     58x   58x 11x                 1x 65x 65x 65x      
/**
 * SQS-driven async worker for POST /v1/entities/import.
 *
 * Debits dynamodb_storage/dynamodb_throughput credits for what was actually
 * written, once the job completes — see
 * docs/architecture/USAGE_METERING.md "Gap found and closed: bulk import and
 * entity fork bypassed credits entirely".
 *
 * Also runs the upgrade of a flow's copies of a Store pack (store/upgrade.js),
 * which installs the version's new entities through the same phases.
 *
 * @implements UC-CREDITS-005.1, UC-STORE-005.1, UC-STORE-012.1, UC-STORE-013.1
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
  DynamoDBDocumentClient,
  GetCommand,
  PutCommand,
  UpdateCommand,
  TransactWriteCommand
} = require('@aws-sdk/lib-dynamodb')
const { randomUUID } = require('crypto')
const { checkPermissionDirect } = require('../utils/requirePermission')
const { readSnapshot, buildPackImportEntries } = require('../utils/packSnapshot')
const {
  validateMandatoryFields,
  validateFieldConstraints,
  validateFieldTypes
} = require('../items/field-validation')
const { buildItemIndexTransactItems, buildItemTextSearchRequests } = require('../items/createItem')
const { putEntityRecord } = require('./createEntityRecord')
const {
  getCatalogSearchTokens,
  buildCatalogSearchPutRequest
} = require('../utils/catalogSearchIndex')
const { sendTransactWriteWithUniqueCheck } = require('../utils/uniqueFieldValue')
const { batchWrite } = require('../utils/batchWrite')
const { getReferencedEntityIds, adjustCounters } = require('../utils/referenceCounters')
const { validateMandatoryCrossFlowReferences } = require('../utils/entityFieldCascadeValidation')
const { resolveForms } = require('../utils/resolveEntityForms')
const { findEntityNameConflict, normalizeName } = require('../utils/nameUniqueness')
const {
  computeFieldCompatibility,
  remapItemFieldIds
} = require('../utils/entityFieldCompatibility')
const { copyImageObject, copyImageFields, copyFileFields } = require('../utils/entityImageCopy')
const {
  validateEntitySchema,
  checkReservedName,
  getDisplayName
} = require('../utils/importValidation')
const {
  resolveEntityRefFields,
  remapEntityRefValues,
  resolveUserFieldValues
} = require('../utils/importReferenceResolution')
const { shortId } = require('../utils/deletedPlaceholder')
const {
  getJob,
  markJobProcessing,
  markJobCompleted,
  markJobFailed,
  createThrottledProgressReporter
} = require('../utils/jobsTable')
const { debitCredits } = require('../utils/creditsLedger')
const { getPricingConfig } = require('../utils/pricingConfig')
const { getConsumedCapacity } = require('../shared/usage-tracking')
const {
  loadPackCopies,
  planUpgrade,
  copyTargets,
  selectUpgrade,
  ownFieldsAfter,
  formsForCopy
} = require('../utils/packUpgrade')
const { validateFieldDefinitions } = require('../utils/validateFieldDefinitions')
const { renameDuplicateFieldNames } = require('../utils/fieldNameUniqueness')
const { baselineOf, nextBaseline } = require('../utils/packBaseline')
const { validateEmailTemplates } = require('../utils/emailTemplates')
const { validateWorkflowFields } = require('../utils/validateWorkflowFields')
const { validatePublicEntityFields } = require('../utils/validatePublicEntityFields')
const { loadLinkedEntities } = require('../utils/expressions/linkedItems')
const { MAX_ENTITY_SIZE_BYTES } = require('../utils/constants')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
const IMPORT_JOB_PHASE_COUNT = 4
 
async function fetchEntity(id) {
  const result = await docClient.send(
    new GetCommand({ TableName: process.env.TABLE_NAME, Key: { id } })
  )
  return result.Item || null
}
 
function isAccessible(entity, flowId) {
  return entity.visibility === 'public' || entity.flowId === flowId
}
 
const userLabelCache = new Map()
 
async function getUserLabel(userId) {
  Iif (userLabelCache.has(userId)) return userLabelCache.get(userId)
 
  let label = shortId(userId)
  try {
    const result = await docClient.send(
      new GetCommand({ TableName: process.env.USERS_TABLE_NAME, Key: { id: userId } })
    )
    Eif (result.Item) label = result.Item.name || result.Item.nickname || label
  } catch (error) {
    console.warn(`[import-worker] Could not resolve user label for ${userId}:`, error.message)
  }
 
  userLabelCache.set(userId, label)
  return label
}
 
async function isFlowMember(userId, flowId) {
  const result = await docClient.send(
    new GetCommand({ TableName: process.env.FLOW_MEMBERSHIPS_TABLE_NAME, Key: { userId, flowId } })
  )
  return !!result.Item
}
 
// ─── Phase 0: resolve each entry's outcome — id assignment for `create`,
// target validation for `merge`. No writes yet. ──────────────────────────
async function resolvePhase0(entries, flowId) {
  const state = new Map()
  let flowDefaultLanguage
  const defaultLanguageOf = async (entity) => {
    if (entity?.defaultLanguage) return entity.defaultLanguage
    flowDefaultLanguage ??= (await fetchFlowLanguages(flowId)).defaultLanguage
    return flowDefaultLanguage
  }
 
  for (const entry of entries) {
    const { tempId, mode } = entry
 
    if (mode === 'skip') {
      state.set(tempId, { status: 'skipped' })
      continue
    }
 
    if (mode === 'merge') {
      Iif (!entry.targetEntityId) {
        state.set(tempId, { status: 'failed', error: 'Missing targetEntityId for merge' })
        continue
      }
 
      const target = await fetchEntity(entry.targetEntityId)
      if (!target) {
        state.set(tempId, { status: 'failed', error: 'Target entity not found' })
        continue
      }
      if (target.flowId !== flowId) {
        state.set(tempId, {
          status: 'failed',
          error: 'Can only merge into an entity owned by the active flow'
        })
        continue
      }
 
      const { compatible, fieldIdMapping, missingFields } = computeFieldCompatibility(
        entry.entity?.fields,
        target.fields
      )
      if (!compatible) {
        state.set(tempId, { status: 'failed', error: 'FIELDS_INCOMPATIBLE', missingFields })
        continue
      }
 
      state.set(tempId, {
        status: 'pending',
        mode: 'merge',
        entry,
        finalEntityId: target.id,
        finalFields: target.fields,
        fieldIdMapping
      })
      continue
    }
 
    // mode === 'create'
    // The schema as the pack holds it, for the copy's baseline
    const sourceEntity = entry.entity
    // A schema written before field names became unique may hold duplicates:
    // the later field takes "Name (2)", and the result says so
    const { fields: renamed, renamedFields } = Array.isArray(entry.entity?.fields)
      ? renameDuplicateFieldNames(entry.entity.fields, await defaultLanguageOf(entry.entity))
      : { fields: entry.entity?.fields, renamedFields: [] }
    if (renamedFields.length > 0) entry.entity = { ...entry.entity, fields: renamed }
 
    const schemaValidation = validateEntitySchema(entry.entity)
    Iif (!schemaValidation.valid) {
      state.set(tempId, { status: 'failed', error: schemaValidation.error })
      continue
    }
 
    const name = entry.name || entry.entity.name
    Iif (!name) {
      state.set(tempId, { status: 'failed', error: 'Missing entity name' })
      continue
    }
 
    const reservedCheck = checkReservedName(name)
    if (!reservedCheck.valid) {
      state.set(tempId, { status: 'failed', error: reservedCheck.error })
      continue
    }
 
    state.set(tempId, {
      status: 'pending',
      mode: 'create',
      entry,
      name,
      finalEntityId: randomUUID(),
      sourceEntity,
      ...(renamedFields.length > 0 && { renamedFields })
    })
  }
 
  return state
}
 
// ─── Phase 1: for `create` entries, remap entity_ref fields onto the
// bundle's final ids / drop unresolvable external ones, then re-validate
// (mandatory cross-flow references, name uniqueness — both against the
// flow's existing entities and other entries in this same batch). ────────
// `knownTargets` maps tempIds to entities already in the flow: an upgrade's
// copies, which the new entities link to.
async function resolvePhase1(state, flowId, knownTargets = new Map()) {
  const tempIdToFinalEntityId = new Map([
    ...knownTargets,
    ...[...state.entries()]
      .filter(([, r]) => r.status === 'pending' && r.finalEntityId)
      .map(([tempId, r]) => [tempId, r.finalEntityId])
  ])
 
  const accessibilityCache = new Map()
  async function isAccessibleFromDestination(targetId) {
    Iif (accessibilityCache.has(targetId)) return accessibilityCache.get(targetId)
    const targetEntity = await fetchEntity(targetId)
    const accessible = !!targetEntity && isAccessible(targetEntity, flowId)
    accessibilityCache.set(targetId, accessible)
    return accessible
  }
 
  const usedNames = new Set()
 
  for (const r of state.values()) {
    if (r.status !== 'pending' || r.mode !== 'create') continue
 
    const { fields, droppedFieldsCount, droppedMandatoryField } = await resolveEntityRefFields(
      r.entry.entity.fields,
      tempIdToFinalEntityId,
      isAccessibleFromDestination
    )
 
    if (droppedMandatoryField) {
      r.status = 'failed'
      r.error = `Field "${getDisplayName(droppedMandatoryField.name, droppedMandatoryField.fieldId)}" is mandatory but its target entity is not accessible in the destination flow`
      continue
    }
 
    r.finalFields = fields
    r.droppedFieldsCount = droppedFieldsCount
 
    const crossFlowValidation = await validateMandatoryCrossFlowReferences(
      fields,
      docClient,
      process.env.TABLE_NAME,
      flowId
    )
    Iif (!crossFlowValidation.valid) {
      r.status = 'failed'
      r.error = JSON.parse(crossFlowValidation.errorResponse.body).error
      continue
    }
 
    const normalizedName = normalizeName(r.name)
    if (usedNames.has(normalizedName)) {
      r.status = 'failed'
      r.error = 'ENTITY_NAME_CONFLICT'
      continue
    }
 
    const nameConflict = await findEntityNameConflict(docClient, {
      tableName: process.env.TABLE_NAME,
      flowId,
      name: r.name
    })
    if (nameConflict) {
      r.status = 'failed'
      r.error = 'ENTITY_NAME_CONFLICT'
      r.conflictingEntityId = nameConflict.id
      continue
    }
 
    usedNames.add(normalizedName)
  }
}
 
// ─── Phase 2: write the `create` entities (merge never touches the target
// entity's own record — only its items, in phase 3). ─────────────────────
/** The flow's language defaults, `en` and `en`/`fr` when it cannot be read. */
async function fetchFlowLanguages(flowId) {
  try {
    const flowResult = await docClient.send(
      new GetCommand({ TableName: process.env.FLOWS_TABLE_NAME, Key: { id: flowId } })
    )
    Iif (flowResult.Item) {
      return {
        defaultLanguage: flowResult.Item.defaultLanguage || 'en',
        enabledLanguages: flowResult.Item.enabledLanguages || ['en', 'fr']
      }
    }
  } catch (error) {
    console.warn(
      '[import-worker] Could not fetch flow configuration, using defaults:',
      error.message
    )
  }
  return { defaultLanguage: 'en', enabledLanguages: ['en', 'fr'] }
}
 
async function resolvePhase2(state, flowId, userId, costTracker, pack) {
  const { defaultLanguage: flowDefaultLanguage, enabledLanguages: flowEnabledLanguages } =
    await fetchFlowLanguages(flowId)
 
  const catalogSearchRequests = []
 
  for (const r of state.values()) {
    if (r.status !== 'pending' || r.mode !== 'create') continue
 
    const importedPicture = r.entry.entity.picture
      ? await copyImageObject({
          sourceKey: r.entry.entity.picture,
          targetEntityId: r.finalEntityId,
          fieldId: 'entity-picture'
        })
      : undefined
    const importedIcon = r.entry.entity.icon
      ? await copyImageObject({
          sourceKey: r.entry.entity.icon,
          targetEntityId: r.finalEntityId,
          fieldId: 'entity-icon'
        })
      : undefined
 
    const forms = resolveForms({ fields: r.finalFields, forms: r.entry.entity.forms })
    const timestamp = new Date().toISOString()
 
    const newEntity = {
      id: r.finalEntityId,
      flowId,
      visibility: 'flow-members',
      name: r.name,
      fields: r.finalFields,
      commentsEnabled: r.entry.entity.commentsEnabled === true,
      defaultLanguage: r.entry.entity.defaultLanguage || flowDefaultLanguage,
      enabledLanguages: r.entry.entity.enabledLanguages || flowEnabledLanguages,
      ...(r.entry.entity.description && { description: r.entry.entity.description }),
      ...(importedPicture && { picture: importedPicture }),
      ...(importedIcon && { icon: importedIcon }),
      ...(forms && { forms }),
      ...(Array.isArray(r.entry.entity.emailTemplates) &&
        r.entry.entity.emailTemplates.length > 0 && {
          emailTemplates: r.entry.entity.emailTemplates
        }),
      ...(pack &&
        r.entry.packEntityKey && {
          packOrigin: packOriginOf(pack, r.entry.packEntityKey, r.finalFields, {
            packEntity: r.sourceEntity,
            forms,
            emailTemplates: r.entry.entity.emailTemplates
          })
        }),
      createdBy: userId,
      createdAt: timestamp,
      updatedAt: timestamp
    }
 
    await putEntityRecord(docClient, process.env.TABLE_NAME, newEntity)
 
    catalogSearchRequests.push(
      ...getCatalogSearchTokens(newEntity.name).map(({ kind, token }) =>
        buildCatalogSearchPutRequest(kind, token, newEntity.id)
      )
    )
 
    // Priced the same way as entities/create.js — schema size only (fields +
    // forms), not the entity record's own bookkeeping fields (id, flowId,
    // timestamps, ...).
    costTracker.storageBytes += Buffer.byteLength(
      JSON.stringify({ fields: r.finalFields, forms: forms || [] })
    )
  }
 
  // Catalog-search index rows are best-effort and non-transactional, same
  // reasoning as entities/create.js — flushed once for the whole batch
  // rather than per entity (batchWrite already chunks internally).
  if (process.env.FIELD_VALUE_INDEX_TABLE_NAME && catalogSearchRequests.length > 0) {
    try {
      await batchWrite(docClient, process.env.FIELD_VALUE_INDEX_TABLE_NAME, catalogSearchRequests)
    } catch (catalogSearchError) {
      console.error('Failed to write catalog-search index rows:', catalogSearchError)
    }
  }
}
 
// Re-validates an imported item's data against the destination entity's
// CURRENT field constraints — mirrors items/create.js's mandatory/length/
// maxLines/type-shape checks exactly, because the entity may have gained a
// mandatory field, or a stricter length, since the bundle was exported (or
// the bundle simply never went through that validation at all, e.g. a
// hand-crafted or older export). Uniqueness is handled separately (see
// claimUniqueReservations below) since it needs a DynamoDB round trip, unlike
// these three which are pure/synchronous. Returns null when the item is valid.
function findInvalidItemIssue(fields, data) {
  const mandatoryCheck = validateMandatoryFields(fields, data)
  if (!mandatoryCheck.valid) {
    return { fieldId: mandatoryCheck.fieldId, error: 'MANDATORY_FIELD_MISSING' }
  }
 
  const constraintsCheck = validateFieldConstraints(fields, data)
  if (!constraintsCheck.valid) {
    return { fieldId: constraintsCheck.fieldId, error: constraintsCheck.error }
  }
 
  const typeCheck = validateFieldTypes(fields, data)
  Iif (!typeCheck.valid) {
    return { fieldId: typeCheck.fieldId, error: typeCheck.error }
  }
 
  return null
}
 
// Atomically claims every unique-field reservation an item's data needs, via
// a reservations-only TransactWriteCommand (offset: 0 — no primary item
// write action; the item itself isn't written until pass 3b, after
// entity_ref/user field remapping). Claiming this early, before pass 3a
// assigns the item's originalId -> new-id mapping used by *other* bundled
// items' entity_ref values, means a conflict here is indistinguishable from
// any other field-validation failure: the item is simply never assigned an
// id other items could dangle a reference to. Two items in the same bundle
// sharing a value are naturally caught too, since pass 3a processes items
// sequentially — the first item's reservation commits before the second
// item's claim attempt runs. Returns the conflicting fieldId, or null.
async function claimUniqueReservations(entityId, fields, data, itemId) {
  // Reservation/equality-index/item-count actions and trigram text-search
  // requests are built via the same shared logic items/createItem.js uses
  // for the single-request-response path — see items/createItem.js.
  // Trigram rows are best-effort/non-transactional (see items/create.js for
  // why) — accumulated here and flushed once per entity by the caller,
  // rather than per item, since a bundle can import many items at once.
  const { transactItems, reservationFieldIds } = buildItemIndexTransactItems({
    fieldValueIndexTableName: process.env.FIELD_VALUE_INDEX_TABLE_NAME,
    entityItemCountTableName: process.env.ENTITY_ITEM_COUNT_TABLE_NAME,
    entityId,
    fields,
    data,
    itemId
  })
  const textSearchRequests = buildItemTextSearchRequests({
    fieldValueIndexTableName: process.env.FIELD_VALUE_INDEX_TABLE_NAME,
    entityId,
    fields,
    data,
    itemId
  })
 
  if (transactItems.length === 0) return { conflictFieldId: null, textSearchRequests }
 
  const { conflictFieldId } = await sendTransactWriteWithUniqueCheck(
    docClient,
    transactItems,
    reservationFieldIds,
    { offset: 0 }
  )
  return { conflictFieldId, textSearchRequests: conflictFieldId ? [] : textSearchRequests }
}
 
// ─── Phase 3: create items for every resolved entry (create or merge).
// Split in two passes because an item's entity_ref VALUE may point at an
// item belonging to another entity in the *same* bundle — the new id for
// that other item is only known once every entity in the bundle has had its
// own items created (3a), so values are remapped and written afterward (3b).
// An item that fails field-constraint validation is skipped entirely here
// (never enters `created`/`originalItemIdToNewItemId`), so another item's
// entity_ref VALUE pointing at its originalId simply won't find a mapping in
// pass 3b — the same graceful "leave the value unresolved" fallback already
// used when a referenced entity/item was excluded from the bundle outright.
async function resolvePhase3(state, flowId, userId, costTracker) {
  const originalItemIdToNewItemId = new Map()
  const createdItemsByTempId = new Map()
  const referencedEntityCounts = new Map()
 
  for (const [tempId, r] of state) {
    if (r.status !== 'pending' || !r.entry.includeItems) continue
 
    const fields = r.finalFields || []
    const created = []
    const itemIssues = []
    const textSearchRequests = []
    const timestamp = new Date().toISOString()
    const rawItems = Array.isArray(r.entry.items) ? r.entry.items : []
 
    for (const [itemIndex, rawItem] of rawItems.entries()) {
      const { originalId, ...rest } = rawItem || {}
      const data = r.fieldIdMapping ? remapItemFieldIds(rest, r.fieldIdMapping) : { ...rest }
 
      const issue = findInvalidItemIssue(fields, data)
      if (issue) {
        itemIssues.push({
          itemIndex,
          fieldId: issue.fieldId,
          fieldName: fields.find((field) => field.fieldId === issue.fieldId)?.name ?? issue.fieldId,
          error: issue.error
        })
        continue
      }
 
      const itemId = randomUUID()
      const { conflictFieldId, textSearchRequests: itemTextSearchRequests } =
        await claimUniqueReservations(r.finalEntityId, fields, data, itemId)
      if (conflictFieldId) {
        itemIssues.push({
          itemIndex,
          fieldId: conflictFieldId,
          fieldName:
            fields.find((field) => field.fieldId === conflictFieldId)?.name ?? conflictFieldId,
          error: 'UNIQUE_FIELD_CONFLICT'
        })
        continue
      }
      textSearchRequests.push(...itemTextSearchRequests)
 
      const newItem = {
        ...data,
        id: itemId,
        entityId: r.finalEntityId,
        flowId,
        createdBy: userId,
        createdAt: timestamp,
        updatedAt: timestamp
      }
 
      // A pack's images and files are the publisher's: the installer pays for the copies
      const owner = r.entry.fromPack ? { userId, flowId } : undefined
      await copyImageFields({
        item: newItem,
        fields: r.finalFields,
        targetEntityId: r.finalEntityId,
        owner
      })
      await copyFileFields({
        item: newItem,
        fields: r.finalFields,
        targetEntityId: r.finalEntityId,
        owner
      })
 
      created.push(newItem)
      Eif (originalId) originalItemIdToNewItemId.set(originalId, newItem.id)
 
      // Priced the same way as items/create.js — the item's own data only,
      // computed before the envelope fields (id/entityId/flowId/timestamps)
      // are merged in above.
      costTracker.storageBytes += Buffer.byteLength(JSON.stringify(data))
    }
 
    createdItemsByTempId.set(tempId, created)
    r.itemIssues = itemIssues
 
    if (process.env.FIELD_VALUE_INDEX_TABLE_NAME && textSearchRequests.length > 0) {
      await batchWrite(docClient, process.env.FIELD_VALUE_INDEX_TABLE_NAME, textSearchRequests)
    }
  }
 
  for (const [tempId, r] of state) {
    const items = createdItemsByTempId.get(tempId)
    if (!items || items.length === 0) continue
 
    const entityRefFieldIds = (r.finalFields || [])
      .filter((f) => f.type === 'entity_ref')
      .map((f) => f.fieldId)
    const userFieldIds = (r.finalFields || [])
      .filter((f) => f.type === 'user')
      .map((f) => f.fieldId)
 
    let unresolvedReferenceCount = 0
    for (const item of items) {
      remapEntityRefValues(item, entityRefFieldIds, originalItemIdToNewItemId)
      unresolvedReferenceCount += await resolveUserFieldValues(
        item,
        userFieldIds,
        (candidateUserId) => isFlowMember(candidateUserId, flowId),
        getUserLabel
      )
 
      await docClient.send(new PutCommand({ TableName: process.env.ITEMS_TABLE_NAME, Item: item }))
 
      // Computed post-remap so counters reflect the item's final entity_ref
      // values, not the original bundle's — see utils/referenceCounters.js.
      // Accumulated across every entry and applied once below, same as the
      // text-search batching above.
      if (process.env.ENTITY_REFERENCE_COUNTERS_TABLE_NAME) {
        for (const refEntityId of getReferencedEntityIds(r.finalFields || [], item)) {
          referencedEntityCounts.set(
            refEntityId,
            (referencedEntityCounts.get(refEntityId) || 0) + 1
          )
        }
      }
    }
 
    r.importedItemsCount = items.length
    r.unresolvedReferenceCount = unresolvedReferenceCount
  }
 
  if (process.env.ENTITY_REFERENCE_COUNTERS_TABLE_NAME && referencedEntityCounts.size > 0) {
    await adjustCounters(
      docClient,
      process.env.ENTITY_REFERENCE_COUNTERS_TABLE_NAME,
      flowId,
      referencedEntityCounts
    )
  }
}
 
function buildResults(entries, state) {
  return entries.map((entry) => {
    const r = state.get(entry.tempId)
 
    if (r.status === 'skipped') {
      return {
        tempId: entry.tempId,
        status: 'skipped',
        importedItemsCount: 0,
        droppedFieldsCount: 0,
        unresolvedReferenceCount: 0,
        invalidItemsCount: 0
      }
    }
 
    if (r.status === 'failed') {
      return {
        tempId: entry.tempId,
        status: 'failed',
        error: r.error,
        ...(r.missingFields && { missingFields: r.missingFields }),
        ...(r.conflictingEntityId && { conflictingEntityId: r.conflictingEntityId }),
        importedItemsCount: 0,
        droppedFieldsCount: 0,
        unresolvedReferenceCount: 0,
        invalidItemsCount: 0
      }
    }
 
    return {
      tempId: entry.tempId,
      status: r.mode === 'merge' ? 'merged' : 'created',
      entityId: r.finalEntityId,
      importedItemsCount: r.importedItemsCount || 0,
      droppedFieldsCount: r.droppedFieldsCount || 0,
      unresolvedReferenceCount: r.unresolvedReferenceCount || 0,
      invalidItemsCount: r.itemIssues?.length || 0,
      ...(r.itemIssues?.length > 0 && { itemIssues: r.itemIssues }),
      ...(r.renamedFields && { renamedFields: r.renamedFields })
    }
  })
}
 
/**
 * The entries of a Store installation (store/import.js): the stored schema, with
 * the installer's choices. The snapshot of a version replaced since then may be
 * gone (utils/packCleanup.js's removeStaleSnapshots): the installer starts again.
 */
async function loadPackEntries({ snapshotKey, choices }) {
  const bundle = await readSnapshot(snapshotKey)
  if (!bundle) throw new Error('PACK_VERSION_REPLACED')
  return buildPackImportEntries(bundle, choices)
}
 
/**
 * What a copy installed from a pack remembers (UC-STORE-005.1): the pack, the
 * version, which entity of the pack it is, and the fields it got, so that a
 * later version can tell its additions from fields the installer removed.
 */
/**
 * Where a copy comes from, with its baseline: what it took from the version,
 * for the next one to tell Alice's changes from Bob's (utils/packBaseline.js).
 */
function packOriginOf(
  { packId, version },
  entityKey,
  fields,
  { packEntity, forms, emailTemplates }
) {
  return {
    packId,
    version,
    entityKey,
    fieldIds: (fields || []).map((field) => field.fieldId),
    baseline: baselineOf(packEntity, { fields, forms, emailTemplates })
  }
}
 
/**
 * A pack's import count follows the flows that installed it with something
 * created, other than its own: a flow installing it again is not counted again
 * (UC-STORE-012.1). The flow's row, a check that the pack still exists (its
 * counter is not recreated once deleted) and the counter go in one
 * transaction. The row then gathers the copies the flow got, for a later
 * version to find them (UC-STORE-005.1). Best-effort: a failure must not fail
 * a finished job.
 */
async function countPackImport({ packId, ownerFlowId, version }, flowId, results, entries) {
  if (ownerFlowId === flowId || !results.some((result) => result.status === 'created')) return
  let counted = true
  try {
    await docClient.send(
      new TransactWriteCommand({
        TransactItems: [
          {
            Put: {
              TableName: process.env.PACK_IMPORTS_TABLE_NAME,
              Item: { packId, flowId, importedAt: new Date().toISOString() },
              ConditionExpression: 'attribute_not_exists(packId)'
            }
          },
          {
            ConditionCheck: {
              TableName: process.env.PACKS_TABLE_NAME,
              Key: { id: packId },
              ConditionExpression: 'attribute_exists(id)'
            }
          },
          {
            Update: {
              TableName: process.env.PACK_STATS_TABLE_NAME,
              Key: { packId },
              UpdateExpression: 'ADD importsCount :one',
              ExpressionAttributeValues: { ':one': 1 }
            }
          }
        ]
      })
    )
  } catch (error) {
    const reasons = error.CancellationReasons || []
    const canceled = error.name === 'TransactionCanceledException'
    // The pack is gone: nothing to count, nor to remember
    if (canceled && reasons[1]?.Code === 'ConditionalCheckFailed') return
    // Already counted for this flow: its copies are still remembered
    if (!(canceled && reasons[0]?.Code === 'ConditionalCheckFailed')) {
      console.error('[import-worker] Could not count pack import:', packId, error.message)
      return
    }
    counted = false
  }
  const copies = createdCopies(results, entries)
  if (copies.length === 0) return
  await rememberPackCopies(
    packId,
    flowId,
    copies,
    counted ? version : await lowestVersionWith(packId, flowId, version)
  )
}
 
/**
 * Installing again: the row's other copies may be behind, or deleted since,
 * so the lowest version is read from those left (at most `MAX_PACK_COPIES`).
 * Unknown when they cannot be read: the row keeps the version it has.
 */
async function lowestVersionWith(packId, flowId, version) {
  try {
    const copies = await loadPackCopies(docClient, packId, flowId)
    return Math.min(version, ...copies.map((copy) => copy.packOrigin.version))
  } catch (error) {
    console.error('[import-worker] Could not read the pack copies:', packId, error.message)
    return undefined
  }
}
 
/** The entities an import created from the pack's entities: the copies to remember. */
function createdCopies(results, entries) {
  const keyed = new Set(entries.filter((entry) => entry.packEntityKey).map((entry) => entry.tempId))
  return results
    .filter((result) => result.status === 'created' && keyed.has(result.tempId))
    .map((result) => result.entityId)
}
 
/**
 * The flow's row gathers the copies it got (UC-STORE-005.1), and `version`,
 * the lowest version among them, for the Store's Installed tab to tell that an
 * update is available without reading the copies (UC-STORE-015.1).
 */
async function rememberPackCopies(packId, flowId, copies, lowestVersion) {
  const setsVersion = typeof lowestVersion === 'number' && Number.isFinite(lowestVersion)
  Iif (copies.length === 0 && !setsVersion) return
  const clauses = [
    ...(setsVersion ? ['SET version = :version'] : []),
    ...(copies.length > 0 ? ['ADD copyEntityIds :copies'] : [])
  ]
  try {
    await docClient.send(
      new UpdateCommand({
        TableName: process.env.PACK_IMPORTS_TABLE_NAME,
        Key: { packId, flowId },
        UpdateExpression: clauses.join(' '),
        // Not recreated once the pack's cleanup removed it
        ConditionExpression: 'attribute_exists(packId)',
        ExpressionAttributeValues: {
          ...(copies.length > 0 && { ':copies': new Set(copies) }),
          ...(setsVersion && { ':version': lowestVersion })
        }
      })
    )
  } catch (error) {
    if (error.name === 'ConditionalCheckFailedException') return
    console.error('[import-worker] Could not remember pack copies:', packId, error.message)
  }
}
 
/**
 * The lowest version among the flow's copies once an upgrade ran: a copy
 * upgraded, and every new entity, are at the upgrade's version; the others
 * (refused, edited meanwhile, or not behind) keep theirs. None left: unknown.
 */
function lowestCopyVersion(copies, upgraded, results, version) {
  const moved = new Set(
    upgraded.filter((outcome) => outcome.status === 'upgraded').map((o) => o.entityId)
  )
  const versions = copies.map((copy) => (moved.has(copy.id) ? version : copy.packOrigin.version))
  if (results.some((result) => result.status === 'created')) versions.push(version)
  return versions.length > 0 ? Math.min(...versions) : undefined
}
 
const refusalOf = (check) => (check.valid ? null : JSON.parse(check.errorResponse.body).error)
 
/**
 * Why a copy cannot take the fields an upgrade adds: the checks
 * entities/update.js makes on a schema, for the copy as it would become.
 * Existing items need nothing: they have no value for a new field, so no
 * unique or equality index row to write.
 */
async function refuseUpgradedFields(entity, next, writtenFields, flowId) {
  const { fields: nextFields, forms, emailTemplates } = next
  const size = Buffer.byteLength(
    JSON.stringify({ fields: nextFields, forms: forms || [], emailTemplates: emailTemplates || [] })
  )
  if (size > MAX_ENTITY_SIZE_BYTES) return 'ENTITY_TOO_LARGE'
 
  if (!validateEmailTemplates(emailTemplates, nextFields).valid) return 'INVALID_EMAIL_TEMPLATE'
 
  // Only a name an added field takes is refused: duplicates the copy holds already stay
  const definitions = refusalOf(
    validateFieldDefinitions(nextFields, {
      previousFields: entity.fields || [],
      defaultLanguage: entity.defaultLanguage
    })
  )
  if (definitions) return definitions
 
  const linkedEntities = await loadLinkedEntities({
    docClient,
    entitiesTableName: process.env.TABLE_NAME,
    fields: nextFields,
    entityId: entity.id,
    flowId
  })
  const workflows = refusalOf(
    validateWorkflowFields(nextFields, { linkedEntities, emailTemplates })
  )
  Iif (workflows) return workflows
 
  const crossFlow = refusalOf(
    await validateMandatoryCrossFlowReferences(
      writtenFields,
      docClient,
      process.env.TABLE_NAME,
      flowId
    )
  )
  Iif (crossFlow) return crossFlow
 
  if (entity.visibility === 'public') {
    return refusalOf(
      await validatePublicEntityFields(nextFields, docClient, process.env.TABLE_NAME)
    )
  }
  return null
}
 
/**
 * Moves one copy to the upgrade's version, appending the fields chosen and
 * taking the version's definition of the fields and sections chosen among
 * those only Alice changed; none possibly, which still moves it, so that what
 * was declined is offered again only by the next version. Added fields'
 * references to the pack's entities point at the flow's copies, else are
 * dropped as at installation; a changed field's were remapped by the plan.
 * The result goes through the checks of an edit, and the baseline moves with
 * what was taken. Conditional on the copy being unchanged since it was read:
 * an edit made meanwhile wins, and the copy is reported as changed.
 */
async function upgradeCopy(entity, selected, targets, upgrade, flowId, userId, costTracker) {
  const { copy: planned, fields: addedFields, renames, changes, sections } = selected
  const outcome = {
    entityId: entity.id,
    addedFieldsCount: 0,
    changedFieldsCount: 0,
    droppedFieldsCount: 0
  }
  try {
    await checkPermissionDirect(userId, flowId, `entities-${entity.id}:update`)
  } catch {
    return { ...outcome, status: 'failed', error: 'Permission denied' }
  }
 
  const {
    fields: resolved,
    droppedFieldsCount,
    droppedMandatoryField
  } = await resolveEntityRefFields(addedFields, targets, async (targetId) => {
    const target = await fetchEntity(targetId)
    return !!target && isAccessible(target, flowId)
  })
  if (droppedMandatoryField) {
    return {
      ...outcome,
      status: 'failed',
      error: `Field "${getDisplayName(droppedMandatoryField.name, droppedMandatoryField.fieldId)}" is mandatory but its target entity is not accessible in the destination flow`
    }
  }
 
  const previousFields = entity.fields || []
  // A field the version removed may be renamed, freeing its name for an added one
  const nextFields = [
    ...ownFieldsAfter(previousFields, { renames, changes }, entity.defaultLanguage),
    ...resolved
  ]
  const packEntity = planned.packEntity || {}
  const takesForms = sections.includes('forms')
  const takesTemplates = sections.includes('emailTemplates')
  const forms = resolveForms({
    fields: nextFields,
    forms: takesForms ? formsForCopy(packEntity.forms, nextFields) : entity.forms
  })
  const emailTemplates = takesTemplates ? packEntity.emailTemplates || [] : entity.emailTemplates
  const edited =
    resolved.length > 0 ||
    changes.length > 0 ||
    sections.length > 0 ||
    Object.keys(renames || {}).length > 0
  if (edited) {
    const refusal = await refuseUpgradedFields(
      entity,
      { fields: nextFields, forms, emailTemplates },
      [...resolved, ...changes],
      flowId
    )
    if (refusal) return { ...outcome, status: 'failed', error: refusal }
  }
 
  const origin = {
    ...entity.packOrigin,
    version: upgrade.version,
    fieldIds: [
      ...new Set([...(entity.packOrigin.fieldIds || []), ...resolved.map((f) => f.fieldId)])
    ],
    baseline: nextBaseline(
      entity.packOrigin.baseline,
      packEntity,
      entity,
      { fields: nextFields, forms, emailTemplates },
      {
        fieldIds: [...resolved, ...changes].map((field) => field.fieldId),
        sections
      }
    )
  }
 
  const sets = ['#fields = :fields', 'packOrigin = :origin', 'updatedAt = :now']
  Eif (forms) sets.push('#forms = :forms')
  if (takesTemplates) sets.push('emailTemplates = :templates')
  try {
    await docClient.send(
      new UpdateCommand({
        TableName: process.env.TABLE_NAME,
        Key: { id: entity.id },
        UpdateExpression: `SET ${sets.join(', ')}`,
        ConditionExpression: entity.updatedAt
          ? 'flowId = :flowId AND updatedAt = :previous'
          : 'flowId = :flowId AND attribute_not_exists(updatedAt)',
        ExpressionAttributeNames: { '#fields': 'fields', ...(forms && { '#forms': 'forms' }) },
        ExpressionAttributeValues: {
          ':fields': nextFields,
          ':origin': origin,
          ':now': new Date().toISOString(),
          ':flowId': flowId,
          ...(forms && { ':forms': forms }),
          ...(takesTemplates && { ':templates': emailTemplates }),
          ...(entity.updatedAt && { ':previous': entity.updatedAt })
        }
      })
    )
  } catch (error) {
    Iif (error.name !== 'ConditionalCheckFailedException') throw error
    return { ...outcome, status: 'failed', error: 'ENTITY_CHANGED' }
  }
 
  // Priced as entities/update.js does: the growth of the schema
  const schemaBytes = (schema) =>
    Buffer.byteLength(
      JSON.stringify({
        fields: schema.fields || [],
        forms: schema.forms || [],
        emailTemplates: schema.emailTemplates || []
      })
    )
  costTracker.storageBytes += Math.max(
    0,
    schemaBytes({ fields: nextFields, forms, emailTemplates }) - schemaBytes(entity)
  )
  return {
    ...outcome,
    status: 'upgraded',
    addedFieldsCount: resolved.length,
    changedFieldsCount: changes.length,
    ...(sections.length > 0 && { changedSections: sections }),
    droppedFieldsCount
  }
}
 
/**
 * An upgrade of the flow's copies of a pack (store/upgrade.js): what it
 * offers is computed again from the stored snapshot and the copies as they
 * are now, and only what the installer chose among it is applied. The new
 * entities go through the import's phases, linked to the copies; then each
 * copy takes its fields, which may point at the new entities.
 */
async function runPackUpgrade(upgrade, flowId, userId, costTracker, report) {
  const bundle = await readSnapshot(upgrade.snapshotKey)
  if (!bundle) throw new Error('PACK_VERSION_REPLACED')
 
  const copies = await loadPackCopies(docClient, upgrade.packId, flowId)
  const selection = selectUpgrade(planUpgrade(bundle, copies, upgrade.version), upgrade)
  const knownTargets = copyTargets(bundle, copies)
 
  const entries = buildPackImportEntries(
    bundle,
    selection.entities.map((choice) => ({ ...choice, mode: 'create' }))
  ).filter((entry) => entry.mode === 'create')
  if (entries.length > 0) await checkPermissionDirect(userId, flowId, 'entities:create')
 
  const state = await resolvePhase0(entries, flowId)
  await report(1, IMPORT_JOB_PHASE_COUNT)
  await resolvePhase1(state, flowId, knownTargets)
  await report(2, IMPORT_JOB_PHASE_COUNT)
  await resolvePhase2(state, flowId, userId, costTracker, upgrade)
  // New entities come with the version's items for them, as at installation
  await resolvePhase3(state, flowId, userId, costTracker)
  await report(3, IMPORT_JOB_PHASE_COUNT)
  const results = buildResults(entries, state)
 
  const targets = new Map([
    ...knownTargets,
    ...results.filter((r) => r.status === 'created').map((r) => [r.tempId, r.entityId])
  ])
  const copyById = new Map(copies.map((copy) => [copy.id, copy]))
  const upgraded = []
  for (const selected of selection.copies) {
    upgraded.push(
      await upgradeCopy(
        copyById.get(selected.copy.entityId),
        selected,
        targets,
        upgrade,
        flowId,
        userId,
        costTracker
      )
    )
  }
  await report(4, IMPORT_JOB_PHASE_COUNT)
 
  return {
    entries,
    results,
    upgraded,
    lowestVersion: lowestCopyVersion(copies, upgraded, results, upgrade.version)
  }
}
 
async function processImportJob(jobId) {
  const job = await getJob(jobId)
  // Only ever run a job from `pending` — if status is anything else (already
  // `completed`/`failed`, or `processing` because a previous attempt got far
  // enough to mark it so before crashing), skip rather than redo the work.
  // Re-running resolvePhase0 on a redelivered message would assign brand new
  // randomUUID() entity ids and could create duplicate entities alongside
  // whatever the crashed attempt already committed — unlike export-worker.js,
  // where a re-run is merely wasteful (a second harmless zip upload), here
  // it would corrupt data, so a job stuck at `processing` is left for the
  // DLQ alarm to surface rather than auto-retried.
  if (!job || job.status !== 'pending') {
    return
  }
 
  const { flowId, userId, request } = job
  const report = createThrottledProgressReporter(jobId)
  // Accumulated in place by resolvePhase2/resolvePhase3 as entities/items are
  // actually written — see the credits debit below. Only what's actually
  // written is charged: entries that end up skipped/failed (name conflicts,
  // per-item validation, unique-field conflicts, ...) never touch this, so
  // the real debit can come in lower than import.js's submit-time estimate,
  // never higher.
  const costTracker = { storageBytes: 0 }
  let entries
  let results
  // An upgrade's: the lowest version among the flow's copies once it ran
  let lowestVersion
 
  try {
    // An upgrade checks each right it uses: one may only add fields
    if (!request.upgrade) await checkPermissionDirect(userId, flowId, 'entities:create')
    await markJobProcessing(jobId)
 
    if (request.upgrade) {
      const run = await runPackUpgrade(request.upgrade, flowId, userId, costTracker, report)
      entries = run.entries
      results = run.results
      lowestVersion = run.lowestVersion
      await markJobCompleted(jobId, { results, upgraded: run.upgraded })
    } else {
      entries = request.pack ? await loadPackEntries(request.pack) : request.entries
 
      const state = await resolvePhase0(entries, flowId)
      await report(1, IMPORT_JOB_PHASE_COUNT)
      await resolvePhase1(state, flowId)
      await report(2, IMPORT_JOB_PHASE_COUNT)
      await resolvePhase2(state, flowId, userId, costTracker, request.pack)
      await report(3, IMPORT_JOB_PHASE_COUNT)
      await resolvePhase3(state, flowId, userId, costTracker)
      await report(4, IMPORT_JOB_PHASE_COUNT)
 
      results = buildResults(entries, state)
      await markJobCompleted(jobId, { results })
    }
  } catch (error) {
    console.error('[import-worker] Job failed:', jobId, error.message, error.stack)
    await markJobFailed(jobId, error.message || 'Failed to import entities')
    return
  }
 
  // Best-effort from here: a failure doesn't unwind the writes, nor does it
  // retroactively mark an already-completed job as failed — see
  // items/create.js's identical reasoning.
  try {
    const pricing = await getPricingConfig(docClient, process.env.PRICING_CONFIG_TABLE_NAME)
    const storageCreditCost = Math.ceil(
      (costTracker.storageBytes / 1024) * pricing.dynamodb_storage_credits_per_kb
    )
    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_import',
          costCredits: storageCreditCost,
          referenceId: jobId
        },
        {
          pool: 'dynamodb_throughput',
          operation: 'entity_import',
          costCredits: throughputCreditCost,
          referenceId: jobId
        }
      ]
    })
  } catch (creditError) {
    console.error('Failed to debit credits for entity import:', jobId, creditError)
  }
 
  if (request.pack) await countPackImport(request.pack, flowId, results, entries)
  // The flow already counts: its new copies join the ones it has
  if (request.upgrade) {
    await rememberPackCopies(
      request.upgrade.packId,
      flowId,
      createdCopies(results, entries),
      lowestVersion
    )
  }
}
 
exports.handler = async (event) => {
  for (const record of event.Records) {
    const { jobId } = JSON.parse(record.body)
    await processImportJob(jobId)
  }
}