All files / catalog list.js

92.94% Statements 145/156
72.04% Branches 67/93
96.29% Functions 26/27
93.05% Lines 134/144

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                                                                                  1x 1x 1x   1x 1x 1x 1x 1x   1x     13x       16x     1x 1x   1x 1x   1x 1x 1x     1x     34x 34x   16x 16x 16x 16x     17x       16x   16x             16x 16x   16x   1x   16x   16x 16x 21x 21x           16x       5x                         87x   87x 88x 83x 83x   82x       15x                   12x               18x             14x               13x             15x 15x       12x 12x 12x                 12x 12x 12x             12x 12x 39x         12x     3x 1x   2x 2x       1x 1x     1x               21x 21x 21x       21x 1x             20x 20x 20x 20x   20x 20x 2x               18x 18x 1x 1x 1x                                           17x   17x 17x 2x           2x 2x 2x 2x     15x 23x   14x 5x   14x       16x     16x 16x       16x 16x 16x 15x 15x 15x             1x       1x   15x 1x     15x 15x         15x                 16x 16x 16x         16x         16x 16x 16x 16x     21x                     16x 21x     16x 21x         21x                       16x   16x                         1x 1x               1x  
/**
 * GET /v1/catalog
 *
 * List all public entities from all flows, except those in the current flow
 * (which are already visible in GET /v1/entities). Needs a signed-in user but
 * no active flow: a user without one sees every public entity.
 *
 * Returns entities with additional metadata:
 * - forkedByCurrentFlow: boolean — true if current flow has forked this entity
 * - linkedByCurrentFlow: boolean — true if current flow has linked this entity
 * - subscribedByCurrentUser: boolean — true if the calling user (not flow)
 *   subscribes to this entity's recent-activity feed (GET /v1/feed)
 * - subscriberCount: number — total number of users subscribed to this entity
 * - ownerNickname: string | null — @nickname of the owning flow's owner
 * - flowSlug: string | null — the owning flow's slug, a human-readable
 *   disambiguator for when ownerNickname can't be resolved (deleted user) or
 *   several owners publish an identically-named entity
 *
 * The owning flow's name is never returned here — a flow's name is private,
 * so the catalog only ever exposes the opaque flowId (already present on the
 * entity itself), its slug, and the owner's public @nickname, never a
 * human-readable flow label.
 *
 * A `search` of MIN_QUERY_LENGTH (3, see utils/textSearchIndex.js) or more
 * normalized characters is resolved via the catalog-search index (see
 * utils/catalogSearchIndex.js) instead of scanning every public entity on
 * the platform — `total` then reflects the match count, not the platform
 * total (see the code for why), and `truncated: true` may appear if the
 * index's candidate cap was hit. A shorter search, or none at all, falls
 * back to the full scan as before.
 *
 * Query params:
 * - limit: page size (default 30, max 100)
 * - nextToken: pagination token (base64-encoded offset)
 * - search: optional full-text search on entity name
 * - sort: optional JSON `{"fieldId":"name"|"createdAt","direction":"asc"|"desc"}`
 *
 * @implements UC-CATALOG-001.1, UC-CATALOG-002.1, UC-CATALOG-003.1, UC-CATALOG-004.1, UC-CATALOG-005.1,
 *   UC-CATALOG-006.1
 */
 
const { getActiveFlowId } = require('../shared/activeFlow')
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, QueryCommand, BatchGetCommand } = require('@aws-sdk/lib-dynamodb')
 
const { getSubscriberCounts } = require('../utils/entitySubscriberCount')
const { parseSimpleSort, applySimpleSort } = require('../utils/simpleSort')
const { MIN_QUERY_LENGTH, normalizeForSearch } = require('../utils/textSearchIndex')
const { resolveCatalogSearchCandidates } = require('../utils/catalogSearchIndex')
const { MAX_CATALOG_SEARCH_INDEX_RESULTS } = require('../utils/constants')
 
const CATALOG_SORT_FIELDS = ['name', 'createdAt']
 
function getCatalogEntityName(entity) {
  return typeof entity.name === 'string' ? entity.name : entity.name?.en || ''
}
 
function getCatalogSortValue(entity, fieldId) {
  return fieldId === 'createdAt' ? entity.createdAt || '' : getCatalogEntityName(entity)
}
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
const ENTITIES_TABLE = process.env.ENTITIES_TABLE_NAME || 'EntitiesTable'
const ENTITY_LINKS_TABLE = process.env.ENTITY_LINKS_TABLE_NAME || 'EntityLinksTable'
const ENTITY_SUBSCRIPTIONS_TABLE =
  process.env.ENTITY_SUBSCRIPTIONS_TABLE_NAME || 'EntitySubscriptionsTable'
const FLOWS_TABLE = process.env.FLOWS_TABLE_NAME || 'FlowsTable'
const USERS_TABLE = process.env.USERS_TABLE_NAME || 'UsersTable'
 
// DynamoDB BatchGetItem accepts at most 100 keys per table per request.
const BATCH_GET_LIMIT = 100
 
async function batchGetByIds(tableName, ids) {
  const uniqueIds = Array.from(new Set(ids)).filter(Boolean)
  if (uniqueIds.length === 0) return []
 
  const items = []
  for (let offset = 0; offset < uniqueIds.length; offset += BATCH_GET_LIMIT) {
    const chunk = uniqueIds.slice(offset, offset + BATCH_GET_LIMIT)
    const result = await docClient.send(
      new BatchGetCommand({
        RequestItems: {
          [tableName]: { Keys: chunk.map((id) => ({ id })) }
        }
      })
    )
    items.push(...(result.Responses?.[tableName] || []))
  }
  return items
}
 
// Resolves each entity's owning flow to its owner's @nickname and the flow's
// slug, best effort: a flow or user missing from its table (e.g. deleted)
// just yields nulls.
async function resolveFlowMetaByFlowId(flowIds) {
  const flows = await batchGetByIds(FLOWS_TABLE, flowIds)
  const flowById = new Map(flows.map((flow) => [flow.id, flow]))
 
  const users = await batchGetByIds(
    USERS_TABLE,
    flows.map((flow) => flow.ownerId)
  )
  const nicknameByUserId = new Map(users.map((user) => [user.id, user.nickname || null]))
 
  const metaByFlowId = new Map()
  for (const flowId of flowIds) {
    const flow = flowById.get(flowId)
    metaByFlowId.set(flowId, {
      ownerId: flow?.ownerId ?? null,
      ownerNickname: flow ? nicknameByUserId.get(flow.ownerId) || null : null,
      flowSlug: flow?.slug ?? null
    })
  }
  return metaByFlowId
}
 
function isMissingIndexError(error, indexName) {
  return (
    error?.name === 'ValidationException' &&
    typeof error?.message === 'string' &&
    error.message.includes(indexName)
  )
}
 
// Follows every page (via LastEvaluatedKey) rather than taking just the
// first one — a single capped-Limit Query would otherwise silently drop
// public entities once the platform-wide catalog grows past that cap, with
// no error or indication to the caller (e.g. search missing real matches,
// or a wrong `hasMore`/total since they'd be computed over a truncated set).
async function queryAllPages(queryParams) {
  const items = []
  let ExclusiveStartKey
  do {
    const result = await docClient.send(new QueryCommand({ ...queryParams, ExclusiveStartKey }))
    items.push(...(result.Items || []))
    ExclusiveStartKey = result.LastEvaluatedKey
  } while (ExclusiveStartKey)
  return items
}
 
async function queryPublicEntitiesByVisibility() {
  return queryAllPages({
    TableName: ENTITIES_TABLE,
    IndexName: 'visibilityIndex',
    KeyConditionExpression: '#visibility = :publicVisibility',
    ExpressionAttributeNames: { '#visibility': 'visibility' },
    ExpressionAttributeValues: { ':publicVisibility': 'public' }
  })
}
 
async function queryPublicEntitiesByLegacyVisibilityValue() {
  const items = await queryAllPages({
    TableName: ENTITIES_TABLE,
    IndexName: 'visibilityIndex',
    KeyConditionExpression: '#visibility = :legacyPublicVisibility',
    ExpressionAttributeNames: { '#visibility': 'visibility' },
    ExpressionAttributeValues: { ':legacyPublicVisibility': 'true' }
  })
 
  return items.map((entity) => ({
    ...entity,
    visibility: 'public'
  }))
}
 
async function queryPublicEntitiesLegacy() {
  const items = await queryAllPages({
    TableName: ENTITIES_TABLE,
    IndexName: 'publicIndex',
    KeyConditionExpression: '#isPublic = :isPublicTrue',
    ExpressionAttributeNames: { '#isPublic': 'isPublic' },
    ExpressionAttributeValues: { ':isPublicTrue': 'true' }
  })
 
  return items.map((entity) => ({
    ...entity,
    visibility: entity.visibility || 'public'
  }))
}
 
async function getPublicEntities() {
  try {
    const canonical = await queryPublicEntitiesByVisibility()
 
    // Compatibility for transitional records where visibility was set to
    // "true" instead of the canonical "public" value.
    let legacyVisibility = []
    try {
      legacyVisibility = await queryPublicEntitiesByLegacyVisibilityValue()
    } catch (legacyVisibilityError) {
      if (!isMissingIndexError(legacyVisibilityError, 'visibilityIndex')) {
        throw legacyVisibilityError
      }
    }
 
    // Best effort legacy merge for environments where some records still only
    // have isPublic populated.
    let legacy = []
    try {
      legacy = await queryPublicEntitiesLegacy()
    } catch (legacyError) {
      if (!isMissingIndexError(legacyError, 'publicIndex')) {
        throw legacyError
      }
    }
 
    const mergedById = new Map()
    for (const entity of [...canonical, ...legacyVisibility, ...legacy]) {
      mergedById.set(entity.id, {
        ...entity,
        visibility: entity.visibility || (entity.isPublic === 'true' ? 'public' : 'flow-members')
      })
    }
    return Array.from(mergedById.values())
  } catch (error) {
    // Backward compatibility for environments not yet migrated to visibilityIndex.
    if (!isMissingIndexError(error, 'visibilityIndex')) {
      throw error
    }
    try {
      return await queryPublicEntitiesLegacy()
    } catch (legacyError) {
      // Old local stacks may not have either index yet. Degrade gracefully
      // to an empty catalog instead of returning a 500.
      Eif (isMissingIndexError(legacyError, 'publicIndex')) {
        console.error(
          '[catalog/list] visibilityIndex and publicIndex missing - returning empty list'
        )
        return []
      }
      throw legacyError
    }
  }
}
 
async function getCatalogHandler(event) {
  try {
    const currentFlowId = await getActiveFlowId(event)
    const currentUserId = event.requestContext?.authorizer?.claims?.sub
    // No active flow is fine (e.g. a new user who hasn't created or joined
    // one yet): nothing is excluded and nothing is forked/linked, while
    // subscriptions are per user anyway.
    if (!currentUserId) {
      return {
        statusCode: 401,
        headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },
        body: JSON.stringify({ error: 'Unauthorized' })
      }
    }
 
    const requestedLimit = parseInt(event.queryStringParameters?.limit || 30, 10)
    const limit = Number.isNaN(requestedLimit) ? 30 : Math.min(Math.max(requestedLimit, 1), 100)
    const nextToken = event.queryStringParameters?.nextToken
    const search = event.queryStringParameters?.search?.toLowerCase()
 
    const sort = parseSimpleSort(event.queryStringParameters?.sort, CATALOG_SORT_FIELDS)
    if (sort?.error) {
      return {
        statusCode: 400,
        headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },
        body: JSON.stringify({ error: sort.error, ...(sort.fieldId && { fieldId: sort.fieldId }) })
      }
    }
 
    // Pagination
    let offset = 0
    if (nextToken) {
      const parsedOffset = parseInt(Buffer.from(nextToken, 'base64').toString(), 10)
      Eif (Number.isNaN(parsedOffset) || parsedOffset < 0) {
        return {
          statusCode: 400,
          headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },
          body: JSON.stringify({ error: 'Invalid nextToken' })
        }
      }
      offset = parsedOffset
    }
 
    // Resolving `filtered`/`total` has two paths. The indexed-search path
    // (search term >= MIN_QUERY_LENGTH) never calls getPublicEntities() at
    // all — that's the whole point: a platform-wide scan is exactly what
    // the search index exists to avoid. The other path (no search term, or
    // a term too short to seed a trigram query) still needs it, same as
    // before. `total` intentionally tracks whichever set `filtered` came
    // from rather than always being the platform-wide public-entity count:
    // during an indexed search it becomes the match count, since "3 results
    // out of 15,000 total public entities" was never a meaningful number to
    // show next to search results anyway, and computing the real platform
    // total here would reintroduce the same scan this path exists to avoid.
    let filtered
    let total
    let searchTruncated = false
 
    const normalizedSearch = search ? normalizeForSearch(search) : ''
    if (search && normalizedSearch.length >= MIN_QUERY_LENGTH) {
      const { entityIds, truncated } = await resolveCatalogSearchCandidates(docClient, {
        fieldValueIndexTableName: process.env.FIELD_VALUE_INDEX_TABLE_NAME,
        entitiesTableName: ENTITIES_TABLE,
        searchValue: search,
        maxResults: MAX_CATALOG_SEARCH_INDEX_RESULTS
      })
      searchTruncated = truncated
      const candidates = await batchGetByIds(ENTITIES_TABLE, [...entityIds])
      filtered = candidates.filter((e) => e.visibility === 'public' && e.flowId !== currentFlowId)
      total = filtered.length
    } else {
      // Query public entities with compatibility fallback for legacy environments.
      const publicEntities = await getPublicEntities()
      const otherFlowEntities = publicEntities.filter((e) => e.flowId !== currentFlowId)
 
      filtered = search
        ? otherFlowEntities.filter((e) => getCatalogEntityName(e).toLowerCase().includes(search))
        : otherFlowEntities
      total = otherFlowEntities.length
    }
 
    // Apply sort (defaults to whatever order the candidates arrived in, i.e. unsorted)
    if (sort) applySimpleSort(filtered, sort, getCatalogSortValue)
 
    // Paginate
    const paginatedItems = filtered.slice(offset, offset + limit)
    const hasMore = offset + limit < filtered.length
 
    // Fetch forked and linked entities in current flow to mark them. Without
    // an active flow there is nothing to mark.
    let forkedEntityIds = new Set()
    let linkedEntityIds = new Set()
    if (currentFlowId) {
      let currentFlowEntities = []
      try {
        currentFlowEntities = await queryAllPages({
          TableName: ENTITIES_TABLE,
          IndexName: 'flowIndex',
          KeyConditionExpression: 'flowId = :flowId',
          ExpressionAttributeValues: { ':flowId': currentFlowId }
        })
      } catch (flowIndexError) {
        Iif (!isMissingIndexError(flowIndexError, 'flowIndex')) {
          throw flowIndexError
        }
        // Older local environments might not have flowIndex yet.
        console.error('[catalog/list] flowIndex missing - fork status disabled')
      }
      forkedEntityIds = new Set(
        currentFlowEntities.filter((e) => e.forkedFromEntityId).map((e) => e.forkedFromEntityId)
      )
 
      try {
        const links = await queryAllPages({
          TableName: ENTITY_LINKS_TABLE,
          KeyConditionExpression: 'flowId = :flowId',
          ExpressionAttributeValues: { ':flowId': currentFlowId }
        })
        linkedEntityIds = new Set(links.map((l) => l.entityId))
      } catch (linkErr) {
        console.error('[catalog/list] Error fetching links:', linkErr)
      }
    }
 
    // Fetch the current user's subscriptions to mark them. Personal, keyed by
    // userId rather than flowId — unlike forks/links, subscriptions aren't
    // tied to the active flow.
    let subscribedEntityIds = new Set()
    try {
      const subscriptions = await queryAllPages({
        TableName: ENTITY_SUBSCRIPTIONS_TABLE,
        KeyConditionExpression: 'userId = :userId',
        ExpressionAttributeValues: { ':userId': currentUserId }
      })
      subscribedEntityIds = new Set(subscriptions.map((s) => s.entityId))
    } catch (subscriptionErr) {
      console.error('[catalog/list] Error fetching subscriptions:', subscriptionErr)
    }
 
    let subscriberCounts = new Map()
    Eif (process.env.ENTITY_SUBSCRIBER_COUNT_TABLE_NAME) {
      try {
        subscriberCounts = await getSubscriberCounts(
          docClient,
          process.env.ENTITY_SUBSCRIBER_COUNT_TABLE_NAME,
          paginatedItems.map((entity) => entity.id)
        )
      } catch (subscriberCountErr) {
        console.error('[catalog/list] Error fetching subscriber counts:', subscriberCountErr)
      }
    }
 
    // Resolve each entity's owning flow to its owner's @nickname and slug.
    // Deliberately no flow name here: a public entity's owner flow is
    // private, and the catalog must not leak it — only the opaque flowId,
    // its slug, and the owner's already-public @nickname are exposed.
    const flowMetaByFlowId = await resolveFlowMetaByFlowId(
      paginatedItems.map((entity) => entity.flowId)
    )
 
    const enrichedItems = paginatedItems.map((entity) => {
      const meta = flowMetaByFlowId.get(entity.flowId) ?? {
        ownerId: null,
        ownerNickname: null,
        flowSlug: null
      }
      return {
        ...entity,
        forkedByCurrentFlow: forkedEntityIds.has(entity.id),
        linkedByCurrentFlow: linkedEntityIds.has(entity.id),
        subscribedByCurrentUser: subscribedEntityIds.has(entity.id),
        subscriberCount: subscriberCounts.get(entity.id) ?? 0,
        ownerId: meta.ownerId,
        ownerNickname: meta.ownerNickname,
        flowSlug: meta.flowSlug
      }
    })
 
    const newNextToken = hasMore ? Buffer.from(String(offset + limit)).toString('base64') : null
 
    return {
      statusCode: 200,
      headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },
      body: JSON.stringify({
        items: enrichedItems,
        nextToken: newNextToken,
        hasMore,
        filteredTotal: filtered.length,
        total,
        ...(searchTruncated && { truncated: true })
      })
    }
  } catch (error) {
    console.error('[catalog/list] Error:', error)
    return {
      statusCode: 500,
      headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },
      body: JSON.stringify({ error: 'Failed to list catalog' })
    }
  }
}
 
module.exports = { getCatalogHandler }