All files / src/stores entities.ts

93.02% Statements 160/172
90% Branches 72/80
92.1% Functions 35/38
93.25% Lines 152/163

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  26x   26x 649x 649x 649x 649x 649x 649x 649x 649x 649x 649x 649x 649x     35x 2x   35x       35x     31x 31x     35x 2x     33x 33x 33x 33x 33x 33x 33x 2x   33x 33x   33x 2x     33x 18x     18x 2x       10x   3x 3x       3x 3x 3x     7x 5x   2x   7x 7x 7x   7x     9x     9x 9x 9x 9x 9x 9x   9x   21x 19x                         3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x       3x       649x               4x 4x 3x   2x   1x 1x   3x 3x         16x 1x               1x 1x     15x 15x   15x 15x                 2x     2x         4x 4x   3x 1x                   3x 3x   1x                                           6x 6x     6x   6x   6x                         1x 1x       1x 1x       30x     28x                                 3x 3x       2x 2x       29x 28x               4x       26x 25x           1x 1x       1x 1x       1x 1x                               1x 1x       1x       5x 5x 3x 3x         5x 5x 3x 3x               6x 6x 6x   6x 1x       6x 6x 2x       6x       6x       1x 1x       2x             2x     2x         649x                                                                                    
import { defineStore } from 'pinia'
import { ref } from 'vue'
import api from '@/services/api'
import { useFlowsStore } from '@/stores/flows'
import type { VisibilityLevel } from '@/utils/constants'
import type { RenamedField } from '@/utils/renamedFields'
import {
  ENTITY_SCHEMA,
  type EmailTemplate,
  type FormDefinition,
  type WorkflowDefinition
} from '@/schemas/entity-schema'
 
export interface EntityField {
  fieldId?: string // Stable internal identifier for the field (auto-generated if not provided)
  name: string | Record<string, string>
  type?:
    | 'text'
    | 'number'
    | 'email'
    | 'password'
    | 'select'
    | 'date'
    | 'boolean'
    | 'textarea'
    | 'image'
    | 'image_set'
    | 'file'
    | 'file_set'
    | 'geo_location'
    | 'workflow'
    | 'user'
    | 'entity_ref'
  length?: number
  maxLines?: number // For textarea: maximum number of lines allowed in the value
  min?: number // For number: minimum allowed value
  max?: number // For number: maximum allowed value
  step?: number // For number: input step increment
  mandatory?: boolean
  unique?: boolean
  disabled?: boolean
  options?: string[] | { value: string; label: string }[]
  placeholder?: string | Record<string, string>
  helpText?: string | Record<string, string>
  defaultValue?: any
  maxImages?: number // For image_set: maximum number of images
  minWidth?: number // For image/image_set: minimum width in pixels
  maxWidth?: number // For image/image_set: maximum width in pixels
  minHeight?: number // For image/image_set: minimum height in pixels
  maxHeight?: number // For image/image_set: maximum height in pixels
  aspectRatio?: string // For image/image_set: expected ratio (e.g. 1:1, 4:3, 16:9)
  resizeMaxWidth?: number // For image/image_set: auto-resize down to this max width
  resizeMaxHeight?: number // For image/image_set: auto-resize down to this max height
  cropEnabled?: boolean // For image/image_set: enable crop step before upload
  maxFiles?: number // For file_set: maximum number of files
  workflowDefinition?: WorkflowDefinition // For workflow type fields
  reference?: {
    kind: 'user' | 'entity'
    entityId?: string
    displayFormId?: string
    allowLinked?: boolean
    allowPublic?: boolean
    multiple?: boolean
    minValues?: number
    maxValues?: number
  }
}
 
// Stored for `file`/`file_set` item values. Unlike image/image_set (which
// store a bare S3 key), a generic file needs its original name for display —
// re-deriving it would mean an extra network round trip per render.
export interface FileValue {
  key: string
  name: string
  size: number
  type: string
}
 
export interface GeoLocationValue {
  lat: number
  lng: number
}
 
export interface EntityLinksInfo {
  entityId: string
  sameUserFlowsCount: number
  otherUserFlowsCount: number
  totalFlowsCount: number
}
 
export interface ImportBundleEntitySchema {
  name: string | Record<string, string>
  fields: EntityField[]
  forms?: FormDefinition[]
  description?: string | Record<string, string>
  picture?: string
  icon?: string
  defaultLanguage?: string
  enabledLanguages?: string[]
}
 
export interface ExportDiscoveredEntity {
  id: string
  name: string
  itemCount: number
  hasImages: boolean
  isRoot: boolean
  dependsOn: string[]
}
 
export interface ImportNameConflict {
  source: 'existing' | 'batch'
  conflictingEntityId?: string
  conflictingEntityName: string
  compatible: boolean
  missingFields: { name: string | Record<string, string>; type: string }[]
}
 
export interface ImportCheckResult {
  tempId: string
  valid: boolean
  error?: string
  nameConflict: ImportNameConflict | null
}
 
export interface ImportBundleEntry {
  tempId: string
  mode: 'create' | 'merge' | 'skip'
  targetEntityId?: string
  name?: string | Record<string, string>
  entity: ImportBundleEntitySchema
  items?: Record<string, unknown>[]
  includeItems?: boolean
}
 
export interface ImportItemIssue {
  itemIndex: number
  fieldId: string
  fieldName: string | Record<string, string>
  error: string
}
 
export interface ImportBundleResult {
  tempId: string
  status: 'created' | 'merged' | 'skipped' | 'failed'
  entityId?: string
  error?: string
  conflictingEntityId?: string
  missingFields?: { name: string | Record<string, string>; type: string }[]
  importedItemsCount: number
  droppedFieldsCount: number
  unresolvedReferenceCount: number
  invalidItemsCount: number
  itemIssues?: ImportItemIssue[]
  /** Fields renamed because an earlier field of the entity had their name in that language */
  renamedFields?: RenamedField[]
}
 
export interface JobProgress {
  done: number
  total: number
}
 
export interface ExportJobResult {
  downloadUrl: string
  entityCount: number
  cyclesBroken: string[]
}
 
export interface ExportJobStatus {
  status: 'pending' | 'processing' | 'completed' | 'failed'
  progress?: JobProgress
  result?: ExportJobResult
  error?: string
}
 
// Summary shape returned by the "Exports" list endpoint — same job as
// ExportJobStatus, plus the fields needed to render a list entry without a
// follow-up per-job request (id, when it was created, how many entities
// were requested).
export interface ExportJobSummary {
  id: string
  createdAt: string
  status: 'pending' | 'processing' | 'completed' | 'failed'
  requestedEntityCount: number
  progress?: JobProgress
  result?: ExportJobResult
  error?: string
}
 
export interface ImportJobResult {
  results: ImportBundleResult[]
}
 
export interface ForkJobStatus {
  status: 'pending' | 'processing' | 'completed' | 'failed'
  progress?: JobProgress
  result?: { entity: Entity }
  error?: string
}
 
export interface ImportJobStatus {
  status: 'pending' | 'processing' | 'completed' | 'failed'
  progress?: JobProgress
  result?: ImportJobResult
  error?: string
}
 
// Request-only: when a workflow status is removed from a workflow field, the
// editor must choose a fallback so existing items in that status can be
// migrated server-side (see entities/update.js). Not part of the Entity shape
// returned by the API.
export interface WorkflowStateMigration {
  fieldId: string
  removedStateId: string
  fallbackStateId: string
}
 
/**
 * The Store pack a copy was installed from, for display (UC-STORE-016.1):
 * `name` is the pack's current one, null once the pack is deleted.
 */
export interface EntityPackSource {
  packId: string
  version: number
  name: string | Record<string, string> | null
}
 
export interface Entity {
  id: string
  flowId: string
  visibility: VisibilityLevel
  commentsEnabled?: boolean
  isPublic: string // Deprecated, kept for backward compatibility
  name: string | Record<string, string>
  description?: string | Record<string, string>
  fields: EntityField[]
  defaultLanguage?: string
  enabledLanguages?: string[]
  picture?: string
  icon?: string
  publicPermissions?: string[]
  forms?: import('@/schemas/entity-schema').FormDefinition[]
  emailTemplates?: EmailTemplate[]
  forkedFromEntityId?: string
  forkedFromFlowId?: string
  forkedAt?: string
  forkedBy?: string
  forkedByCurrentFlow?: boolean
  linked?: boolean
  linkedByCurrentFlow?: boolean
  subscribedByCurrentUser?: boolean
  subscriberCount?: number
  sourceFlowId?: string
  linkedAt?: string
  archivedAt?: string | null
  sourceFlowName?: string
  ownerId?: string | null
  ownerNickname?: string | null
  flowSlug?: string | null
  sourceSnapshotVersion?: string
  copiedItemsCount?: number
  fromPack?: EntityPackSource
  createdBy: string
  createdAt: string
  updatedAt: string
}
 
export interface EntitySort {
  fieldId: 'name' | 'createdAt'
  direction: 'asc' | 'desc'
}
 
export const DEFAULT_ENTITY_SORT: EntitySort = { fieldId: 'name', direction: 'asc' }
 
export const useEntitiesStore = defineStore('entities', () => {
  const entities = ref<Entity[]>([])
  const currentEntity = ref<Entity | null>(null)
  const loading = ref(false)
  const error = ref<string | null>(null)
  const errorStatus = ref<number | null>(null)
  const nextToken = ref<string | null>(null)
  const hasMore = ref(true)
  const total = ref(0)
  const filteredTotal = ref(0)
  const searchQuery = ref('')
  const sort = ref<EntitySort | null>(DEFAULT_ENTITY_SORT)
  let latestFetchRequestId = 0
 
  async function fetchEntities(reset = true, search?: string, newSort?: EntitySort | null) {
    if (search !== undefined) {
      searchQuery.value = search
    }
    Iif (newSort !== undefined) {
      sort.value = newSort
    }
 
    if (reset) {
      // Do NOT clear entities.value eagerly — it causes a visible flash.
      // Entities are replaced atomically when the response arrives below.
      nextToken.value = null
      hasMore.value = true
    }
 
    if ((!reset && loading.value) || (!reset && !hasMore.value)) {
      return
    }
 
    const requestId = ++latestFetchRequestId
    loading.value = true
    error.value = null
    errorStatus.value = null
    try {
      const params: any = { limit: 30 }
      if (searchQuery.value.trim()) {
        params.search = searchQuery.value.trim()
      }
      Eif (sort.value) {
        params.sort = JSON.stringify(sort.value)
      }
      if (!reset && nextToken.value) {
        params.nextToken = nextToken.value
      }
 
      const response = await api.get('/v1/entities', { params })
      const data = response.data
 
      // A newer request has started: ignore stale response.
      if (requestId !== latestFetchRequestId) {
        return
      }
 
      // Handle both old format (array) and new format (object with items)
      if (Array.isArray(data)) {
        // Old format - no pagination
        if (reset) {
          entities.value = data
        } else E{
          entities.value = [...entities.value, ...data]
        }
        hasMore.value = false
        filteredTotal.value = data.length
        total.value = data.length
      } else {
        // New format with pagination
        if (reset) {
          entities.value = data.items
        } else {
          entities.value = [...entities.value, ...data.items]
        }
        nextToken.value = data.nextToken
        hasMore.value = data.hasMore
        filteredTotal.value =
          typeof data.filteredTotal === 'number' ? data.filteredTotal : entities.value.length
        total.value = typeof data.total === 'number' ? data.total : filteredTotal.value
      }
    } catch (err: any) {
      Iif (requestId !== latestFetchRequestId) {
        return
      }
      error.value = err.response?.data?.error || err.message || 'Failed to fetch entities'
      errorStatus.value = err.response?.status ?? null
      Eif (reset) {
        entities.value = []
        filteredTotal.value = 0
        total.value = 0
      }
      throw err
    } finally {
      if (requestId === latestFetchRequestId) {
        loading.value = false
      }
    }
  }
 
  /**
   * Drops everything listed for the previous active flow. Called on a flow
   * switch so no view (page or sidebar badge) keeps showing the old flow's
   * entities — notably when the new flow does not grant entities:list and
   * therefore never refetches. Bumping the request id discards any response
   * still in flight for the old flow.
   */
  function reset() {
    latestFetchRequestId++
    entities.value = []
    currentEntity.value = null
    loading.value = false
    error.value = null
    errorStatus.value = null
    nextToken.value = null
    hasMore.value = true
    total.value = 0
    filteredTotal.value = 0
    searchQuery.value = ''
  }
 
  async function loadMore() {
    await fetchEntities(false)
  }
 
  // Entity definitions read for conditions on linked items, by id
  const entityDefinitions = new Map<string, Promise<Entity | null>>()
 
  /**
   * An entity's definition (name, fields), without touching `currentEntity`:
   * the targets of item link fields, for conditions on linked items
   * (UC-WORKFLOW-008.1). Cached for the session; null when it can't be read.
   */
  function fetchEntityDefinition(id: string): Promise<Entity | null> {
    const cached = entityDefinitions.get(id)
    if (cached) return cached
    const request = api
      .get(`/v1/entities/${id}`)
      .then((response) => response.data as Entity)
      .catch(() => {
        entityDefinitions.delete(id)
        return null
      })
    entityDefinitions.set(id, request)
    return request
  }
 
  async function fetchEntity(id: string) {
    // Check if requesting system entity schema
    if (id === 'entity') {
      const systemEntity = {
        ...ENTITY_SCHEMA,
        flowId: 'SYSTEM',
        isPublic: 'false', // Backward compatibility
        createdBy: 'SYSTEM',
        createdAt: '2026-01-01T00:00:00Z',
        updatedAt: '2026-01-01T00:00:00Z'
      } as any as Entity // Cast to Entity type (system schema has extended field types)
      currentEntity.value = systemEntity
      return systemEntity
    }
 
    const response = await api.get(`/v1/entities/${id}`)
    const entity = response.data
 
    currentEntity.value = entity
    return entity
  }
 
  /**
   * One page of the active flow's entities, without touching the list the
   * Entities page shows: for a panel that lists them elsewhere (the Store's
   * publish panel).
   */
  async function fetchEntitiesPage(pageToken?: string) {
    const response = await api.get<{ items: Entity[]; nextToken: string | null }>('/v1/entities', {
      params: { limit: 100, ...(pageToken && { nextToken: pageToken }) }
    })
    return { items: response.data.items, nextToken: response.data.nextToken ?? null }
  }
 
  /** An entity, or null when it is gone, without making it the current one. */
  async function findEntity(id: string): Promise<Entity | null> {
    try {
      return (await api.get<Entity>(`/v1/entities/${id}`)).data
    } catch (err: any) {
      if (err.response?.status === 404 || err.response?.status === 403) return null
      throw err
    }
  }
 
  /**
   * Making an entity restricted hands its Manager role to the current user
   * (UC-RBAC-008.1 AC-2) — reload the membership's resolved permissions so the
   * UI reflects that role right away.
   */
  async function refreshOwnPermissions() {
    try {
      await useFlowsStore().fetchMyFlows()
    } catch (error) {
      console.error('Failed to refresh permissions:', error)
    }
  }
 
  async function createEntity(data: {
    // Generated client-side so picture/icon uploads during creation can be
    // keyed by the real id from the start (see EntitiesPage.vue's newEntityId).
    id?: string
    name: string | Record<string, string>
    fields: any[]
    visibility?: VisibilityLevel
    commentsEnabled?: boolean
    isPublic?: boolean // Deprecated, kept for backward compatibility
    description?: string | Record<string, string>
    forms?: FormDefinition[]
    emailTemplates?: EmailTemplate[]
    picture?: string
    icon?: string
    publicPermissions?: string[]
    defaultLanguage?: string
    enabledLanguages?: string[]
  }) {
    const response = await api.post('/v1/entities', data)
    const newEntity = response.data
 
    // Add new entity to the beginning of the list
    entities.value.unshift(newEntity)
 
    if (newEntity.visibility === 'restricted') await refreshOwnPermissions()
 
    return newEntity
  }
 
  async function forkEntity(
    entityId: string,
    data?: {
      name?: string | Record<string, string>
      visibility?: 'flow-members' | 'public'
      copyItems?: boolean
    }
  ) {
    // Async, like import: this only enqueues the job — poll getForkJobStatus
    // (see composables/useForkJob.ts) for progress and the forked entity.
    const response = await api.post(`/v1/entities/${entityId}/fork`, data ?? {})
    return response.data as { jobId: string }
  }
 
  async function getForkJobStatus(jobId: string) {
    const response = await api.get(`/v1/entities/fork/jobs/${jobId}`)
    return response.data as ForkJobStatus
  }
 
  async function forkPreview(entityId: string, copyItems: boolean) {
    const response = await api.get(`/v1/entities/${entityId}/fork-preview`, {
      params: { copyItems }
    })
    return response.data as {
      itemCount: number
      estimatedCredits: number
      balance: number
      insufficientCredits: boolean
    }
  }
 
  async function exportEntities(
    entityIds: string[],
    options?: {
      format?: 'json' | 'csv'
      excludeEntityIds?: string[]
      excludeItemsEntityIds?: string[]
      excludeImagesEntityIds?: string[]
    }
  ) {
    const response = await api.post('/v1/entities/export', { entityIds, ...options })
    return response.data as { jobId: string }
  }
 
  async function getExportJobStatus(jobId: string) {
    const response = await api.get(`/v1/entities/export/jobs/${jobId}`)
    return response.data as ExportJobStatus
  }
 
  async function fetchExportJobs(params?: { limit?: number; nextToken?: string }) {
    const response = await api.get('/v1/entities/export/jobs', { params })
    return response.data as {
      items: ExportJobSummary[]
      nextToken: string | null
      hasMore: boolean
    }
  }
 
  async function deleteExportJob(jobId: string) {
    await api.delete(`/v1/entities/export/jobs/${jobId}`)
  }
 
  async function discoverExportBundle(entityIds: string[]) {
    const response = await api.post('/v1/entities/export/discover', { entityIds })
    return response.data as { entities: ExportDiscoveredEntity[]; cyclesBroken: string[] }
  }
 
  async function checkImportBundle(
    entities: { tempId: string; entity: ImportBundleEntitySchema }[]
  ) {
    const response = await api.post('/v1/entities/import/check', { entities })
    return response.data.results as ImportCheckResult[]
  }
 
  async function importBundle(entries: ImportBundleEntry[]) {
    const response = await api.post('/v1/entities/import', { entities: entries })
    return response.data as { jobId: string }
  }
 
  async function getImportJobStatus(jobId: string) {
    const response = await api.get(`/v1/entities/import/jobs/${jobId}`)
    return response.data as ImportJobStatus
  }
 
  async function linkEntity(entityId: string) {
    const response = await api.post(`/v1/entities/${entityId}/link`)
    const linkedEntity = response.data
    entities.value.unshift(linkedEntity)
    return linkedEntity
  }
 
  async function unlinkEntity(entityId: string) {
    await api.delete(`/v1/entities/${entityId}/link`)
    entities.value = entities.value.filter((e) => e.id !== entityId)
  }
 
  async function subscribeToEntity(entityId: string) {
    const response = await api.post(`/v1/entities/${entityId}/subscription`)
    return response.data
  }
 
  async function unsubscribeFromEntity(entityId: string) {
    await api.delete(`/v1/entities/${entityId}/subscription`)
  }
 
  function markAsSubscribed(entityId: string) {
    const entity = entities.value.find((e) => e.id === entityId)
    if (entity) {
      entity.subscribedByCurrentUser = true
      entity.subscriberCount = (entity.subscriberCount ?? 0) + 1
    }
  }
 
  function markAsUnsubscribed(entityId: string) {
    const entity = entities.value.find((e) => e.id === entityId)
    if (entity) {
      entity.subscribedByCurrentUser = false
      entity.subscriberCount = Math.max(0, (entity.subscriberCount ?? 0) - 1)
    }
  }
 
  async function updateEntity(
    id: string,
    data: Partial<Entity> & { workflowStateMigrations?: WorkflowStateMigration[] }
  ) {
    const previousVisibility = entities.value.find((e) => e.id === id)?.visibility
    const response = await api.put(`/v1/entities/${id}`, data)
    const updatedEntity = response.data
 
    if (updatedEntity.visibility === 'restricted' && previousVisibility !== 'restricted') {
      await refreshOwnPermissions()
    }
 
    // Replace the entity in the array
    const index = entities.value.findIndex((e) => e.id === id)
    if (index !== -1) {
      entities.value[index] = updatedEntity
    }
 
    // Update currentEntity if it's the one being updated
    Iif (currentEntity.value?.id === id) {
      currentEntity.value = updatedEntity
    }
 
    return updatedEntity
  }
 
  async function fetchEntityLinks(id: string): Promise<EntityLinksInfo> {
    const response = await api.get(`/v1/entities/${id}/links`)
    return response.data
  }
 
  async function deleteEntity(id: string, options?: { confirmTransfer?: boolean }) {
    await api.delete(`/v1/entities/${id}`, {
      params: options?.confirmTransfer ? { confirmTransfer: true } : undefined
    })
 
    // Whether the entity was actually deleted or its ownership transferred
    // away to another flow (see docs/architecture/PUBLIC_ENTITIES.md), it no
    // longer belongs to the current flow either way — remove it locally.
    entities.value = entities.value.filter((e) => e.id !== id)
 
    // Clear currentEntity if it's the one being deleted
    Iif (currentEntity.value?.id === id) {
      currentEntity.value = null
    }
  }
 
  return {
    entities,
    currentEntity,
    loading,
    error,
    errorStatus,
    nextToken,
    hasMore,
    total,
    filteredTotal,
    searchQuery,
    sort,
    fetchEntities,
    reset,
    loadMore,
    fetchEntity,
    fetchEntityDefinition,
    createEntity,
    forkEntity,
    getForkJobStatus,
    forkPreview,
    exportEntities,
    getExportJobStatus,
    fetchExportJobs,
    deleteExportJob,
    discoverExportBundle,
    fetchEntitiesPage,
    findEntity,
    checkImportBundle,
    importBundle,
    getImportJobStatus,
    linkEntity,
    unlinkEntity,
    subscribeToEntity,
    unsubscribeFromEntity,
    markAsSubscribed,
    markAsUnsubscribed,
    updateEntity,
    fetchEntityLinks,
    deleteEntity
  }
})