All files / utils entityBundleDiscovery.js

93% Statements 93/100
87.87% Branches 87/99
100% Functions 8/8
96.42% Lines 81/84

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 22213x 13x 13x   13x 13x         47x 4x 4x           42x                 111x 109x 106x 3x       125x     125x                         52x 52x     52x 54x                     54x 16x   38x   54x 54x     52x                                                                         70x 70x 70x 70x 70x 70x 38x   70x   70x 70x 70x 70x 70x     105x 105x   105x 105x 105x   105x 105x 105x 35x 35x 70x 15x   105x   105x 105x                 105x 103x 85x 40x 40x 39x   35x 2x 2x   33x         33x 33x 32x 32x   32x   31x 31x       105x     70x 74x                       70x 105x 87x 42x 42x 34x         70x     13x                
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, GetCommand, QueryCommand } = require('@aws-sdk/lib-dynamodb')
const { permissionChecker } = require('./PermissionChecker')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
// DynamoDB map key order isn't guaranteed, so `en` must be picked explicitly
// — taking Object.values(...)[0] can land on an empty (or absent) translation.
function pickTranslation(value, fallback) {
  if (typeof value === 'string') return value
  Eif (value && typeof value === 'object') {
    return value.en || value.fr || Object.values(value).find(Boolean) || fallback
  }
  return fallback
}
 
function getDisplayName(entity) {
  return pickTranslation(entity.name, entity.id)
}
 
/**
 * Whether the caller may bundle `entity`. A restricted entity additionally
 * needs explicit read access to the entity and its items (UC-ENTITY-007.2) —
 * `callerPermissions` being the caller's resolved permissions in their flow.
 */
function isAccessible(entity, callerFlowId, callerPermissions = []) {
  if (entity.visibility === 'public') return true
  if (entity.flowId !== callerFlowId) return false
  if (entity.visibility !== 'restricted') return true
  return permissionChecker.grantsEntityAndItemsRead(callerPermissions, entity)
}
 
async function fetchEntity(id) {
  const result = await docClient.send(
    new GetCommand({ TableName: process.env.TABLE_NAME, Key: { id } })
  )
  return result.Item || null
}
 
/**
 * Queries every item of `entityId` (paginated), or — with `countOnly` — just
 * the matching item count via DynamoDB's `Select: 'COUNT'`, avoiding the cost
 * of transferring full item payloads when only a preview count is needed
 * (the export-discover endpoint). With `max`, reading stops once more than
 * `max` items are found, so a caller that refuses past it (a pack, at most
 * 20 per entity) never reads a large entity whole: what it gets is at most a
 * page past `max`.
 */
async function queryAllItems(entityId, flowId, { countOnly = false, max } = {}) {
  const items = []
  let count = 0
  let lastEvaluatedKey
 
  do {
    const result = await docClient.send(
      new QueryCommand({
        TableName: process.env.ITEMS_TABLE_NAME,
        KeyConditionExpression: 'entityId = :entityId',
        FilterExpression: 'flowId = :flowId',
        ExpressionAttributeValues: { ':entityId': entityId, ':flowId': flowId },
        ExclusiveStartKey: lastEvaluatedKey,
        ...(countOnly && { Select: 'COUNT' }),
        ...(max !== undefined && { Limit: max + 1 })
      })
    )
    if (countOnly) {
      count += result.Count || 0
    } else {
      items.push(...(result.Items || []))
    }
    lastEvaluatedKey = result.LastEvaluatedKey
    if (max !== undefined && (countOnly ? count : items.length) > max) break
  } while (lastEvaluatedKey)
 
  return countOnly ? count : items
}
 
/**
 * Recursively bundles `startingEntities` and every private, same-flow entity
 * reachable through their `entity_ref` fields, privacy-scoped: recursion is
 * only allowed while walking entities owned by the caller's own flow. A
 * starting entity that's public-but-owned-by-another-flow is bundled itself
 * (the caller can read it) but treated as a leaf — its own entity_ref fields
 * are left untouched rather than chased, since the caller has no right to
 * pull a *different* flow's private dependency data just by exporting one of
 * its public entities.
 *
 * `options.excludeEntityIds` lets a caller prune specific dependencies the
 * user chose not to bundle — skipping one naturally cascades, since a
 * skipped entity is never recursed into, so anything reachable *only*
 * through it is never discovered either.
 *
 * `options.itemsMode` controls how items are fetched per bundled entity:
 * `'full'` (default) returns the actual items, `'count'` returns only
 * `itemCount` (cheap DynamoDB `Select: 'COUNT'`, no item payloads — used by
 * the discover-only preview), `'skip'` fetches nothing for every entity.
 * `options.excludeItemsEntityIds` is the per-entity equivalent, only
 * meaningful with `itemsMode: 'full'`: entities in the set are still
 * bundled, just with no items fetched for them (the export's per-entity
 * "include items" toggle). `options.includeItemsEntityIds` is the opposite
 * allowlist: when given, only those entities get their items (a pack's
 * publisher picks them). `options.maxItemsPerEntity` bounds what is read: an
 * entity with more is flagged `tooManyItems`, for the caller to refuse. There
 * is no limit by default: an export of everything (GDPR portability) reads
 * every item; the Store passes its own limit.
 *
 * Each returned entry also carries `dependsOn`: the ids of the other bundled
 * entities it references, so a caller (the export-discover preview) can
 * recompute which entities are still reachable after the user unchecks one.
 */
async function discoverBundle(startingEntities, callerFlowId, options = {}) {
  const itemsMode = options.itemsMode || 'full'
  const excludeEntityIds = options.excludeEntityIds || new Set()
  const excludeItemsEntityIds = options.excludeItemsEntityIds || new Set()
  const includeItemsEntityIds = options.includeItemsEntityIds
  const maxItems = options.maxItemsPerEntity
  const wantsItems = (entityId) =>
    !excludeItemsEntityIds.has(entityId) &&
    (!includeItemsEntityIds || includeItemsEntityIds.has(entityId))
  const callerPermissions = options.callerPermissions || []
 
  const tempIdByEntityId = new Map()
  const entries = []
  const cyclesBroken = []
  const inProgress = new Set()
  let counter = 0
 
  async function processEntity(entity, allowRecursion) {
    Iif (tempIdByEntityId.has(entity.id)) return
    Iif (excludeEntityIds.has(entity.id)) return
 
    const tempId = `t${counter++}`
    tempIdByEntityId.set(entity.id, tempId)
    inProgress.add(entity.id)
 
    let items = []
    let itemCount = 0
    if (itemsMode === 'full' && wantsItems(entity.id)) {
      items = await queryAllItems(entity.id, entity.flowId, { max: maxItems })
      itemCount = items.length
    } else if (itemsMode === 'count') {
      itemCount = await queryAllItems(entity.id, entity.flowId, { countOnly: true })
    }
    const tooManyItems = maxItems !== undefined && items.length > maxItems
 
    const dependsOn = []
    entries.push({
      tempId,
      entity,
      items,
      itemCount,
      dependsOn,
      ...(tooManyItems && { tooManyItems })
    })
 
    if (allowRecursion) {
      for (const field of entity.fields || []) {
        if (field.type !== 'entity_ref') continue
        const targetId = field.reference?.entityId
        if (!targetId || targetId === entity.id) continue
        if (excludeEntityIds.has(targetId)) continue
 
        if (inProgress.has(targetId)) {
          cyclesBroken.push(`${getDisplayName(entity)} -> ${targetId}`)
          continue
        }
        Iif (tempIdByEntityId.has(targetId)) {
          dependsOn.push(targetId)
          continue
        }
 
        const targetEntity = await fetchEntity(targetId)
        if (!targetEntity) continue
        Iif (targetEntity.visibility === 'public') continue
        Iif (targetEntity.flowId !== callerFlowId) continue
        // An unreadable restricted dependency is left out, as if external.
        if (!isAccessible(targetEntity, callerFlowId, callerPermissions)) continue
 
        await processEntity(targetEntity, true)
        Eif (tempIdByEntityId.has(targetId)) dependsOn.push(targetId)
      }
    }
 
    inProgress.delete(entity.id)
  }
 
  for (const entity of startingEntities) {
    await processEntity(entity, entity.flowId === callerFlowId)
  }
 
  // Every bundled entity's entity_ref field DEFINITIONS still carry the
  // target's real entity id at this point. For the exported bundle, a target
  // that ended up in this same bundle must instead be expressed as that
  // target's tempId — that's the only signal import.js's field-remapping
  // (utils/importReferenceResolution.js) has to tell "this points inside the
  // bundle" apart from "this points at something external" (which it
  // resolves against the destination flow directly, using the real id). A
  // target not in `tempIdByEntityId` (excluded, or genuinely external) is
  // left as its real id unchanged.
  for (const entry of entries) {
    for (const field of entry.entity.fields || []) {
      if (field.type !== 'entity_ref' || !field.reference?.entityId) continue
      const targetTempId = tempIdByEntityId.get(field.reference.entityId)
      if (targetTempId) {
        field.reference = { ...field.reference, entityId: targetTempId }
      }
    }
  }
 
  return { entries, cyclesBroken }
}
 
module.exports = {
  pickTranslation,
  getDisplayName,
  isAccessible,
  fetchEntity,
  queryAllItems,
  discoverBundle
}