@flexkit/studio 0.2.35 → 0.2.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/dist/{activity-nav-button-ZHQOZBCC.js → activity-nav-button-KOOMUTOW.js} +2 -2
  2. package/dist/{activity-nav-button-ZHQOZBCC.js.map → activity-nav-button-KOOMUTOW.js.map} +1 -1
  3. package/dist/chat-page-XYQOQPMW.js +4 -0
  4. package/dist/chat-page-XYQOQPMW.js.map +1 -0
  5. package/dist/{chunk-W7JDZHCV.js → chunk-337GX2BR.js} +2 -2
  6. package/dist/{chunk-W7JDZHCV.js.map → chunk-337GX2BR.js.map} +1 -1
  7. package/dist/{chunk-7N3LTSVX.js → chunk-36YXPN42.js} +2 -2
  8. package/dist/{chunk-7N3LTSVX.js.map → chunk-36YXPN42.js.map} +1 -1
  9. package/dist/{chunk-DEG7QP5C.js → chunk-6NRMVVU4.js} +3 -3
  10. package/dist/{chunk-DEG7QP5C.js.map → chunk-6NRMVVU4.js.map} +1 -1
  11. package/dist/{chunk-PMLDA2FF.js → chunk-AQSL5HBZ.js} +2 -2
  12. package/dist/{chunk-PMLDA2FF.js.map → chunk-AQSL5HBZ.js.map} +1 -1
  13. package/dist/{chunk-Q4CWQHBJ.js → chunk-BHHLWGZ4.js} +2 -2
  14. package/dist/{chunk-Q4CWQHBJ.js.map → chunk-BHHLWGZ4.js.map} +1 -1
  15. package/dist/{chunk-TI3EHLRE.js → chunk-CC2U7ASG.js} +3 -3
  16. package/dist/{chunk-TI3EHLRE.js.map → chunk-CC2U7ASG.js.map} +1 -1
  17. package/dist/{chunk-J6EGNRRT.js → chunk-CRTUZ22E.js} +3 -3
  18. package/dist/{chunk-J6EGNRRT.js.map → chunk-CRTUZ22E.js.map} +1 -1
  19. package/dist/{chunk-KEGJNZLW.js → chunk-DO32GATF.js} +3 -3
  20. package/dist/{chunk-KEGJNZLW.js.map → chunk-DO32GATF.js.map} +1 -1
  21. package/dist/{chunk-RAUQCO6W.js → chunk-KOM7G7WT.js} +2 -2
  22. package/dist/{chunk-RAUQCO6W.js.map → chunk-KOM7G7WT.js.map} +1 -1
  23. package/dist/{chunk-WU2KCXBC.js → chunk-L5Z56DDM.js} +2 -2
  24. package/dist/{chunk-WU2KCXBC.js.map → chunk-L5Z56DDM.js.map} +1 -1
  25. package/dist/{chunk-36DLIVZF.js → chunk-LVKBKU6Q.js} +2 -2
  26. package/dist/{chunk-36DLIVZF.js.map → chunk-LVKBKU6Q.js.map} +1 -1
  27. package/dist/{chunk-PWGLA33F.js → chunk-ND2RTUMM.js} +3 -3
  28. package/dist/{chunk-PWGLA33F.js.map → chunk-ND2RTUMM.js.map} +1 -1
  29. package/dist/{chunk-PZWEC6KD.js → chunk-OWY5BQER.js} +2 -2
  30. package/dist/{chunk-PZWEC6KD.js.map → chunk-OWY5BQER.js.map} +1 -1
  31. package/dist/chunk-PLCI2RJA.js +3 -0
  32. package/dist/chunk-PLCI2RJA.js.map +1 -0
  33. package/dist/{chunk-ZMONKGWJ.js → chunk-PNGPE7QM.js} +3 -3
  34. package/dist/{chunk-ZMONKGWJ.js.map → chunk-PNGPE7QM.js.map} +1 -1
  35. package/dist/{chunk-XYE6ZAUB.js → chunk-RGISZNQ2.js} +2 -2
  36. package/dist/{chunk-XYE6ZAUB.js.map → chunk-RGISZNQ2.js.map} +1 -1
  37. package/dist/{chunk-R6DPAMLC.js → chunk-RX6QUDLZ.js} +3 -3
  38. package/dist/{chunk-R6DPAMLC.js.map → chunk-RX6QUDLZ.js.map} +1 -1
  39. package/dist/{chunk-BTH7HU5Y.js → chunk-U4DUXPZV.js} +2 -2
  40. package/dist/{chunk-BTH7HU5Y.js.map → chunk-U4DUXPZV.js.map} +1 -1
  41. package/dist/{chunk-ZRTWLY77.js → chunk-UULPCFWK.js} +3 -3
  42. package/dist/{chunk-ZRTWLY77.js.map → chunk-UULPCFWK.js.map} +1 -1
  43. package/dist/{chunk-RFKMFD2O.js → chunk-XV4QJKOJ.js} +2 -2
  44. package/dist/{chunk-RFKMFD2O.js.map → chunk-XV4QJKOJ.js.map} +1 -1
  45. package/dist/chunk-ZV7I5RUM.js +10 -0
  46. package/dist/chunk-ZV7I5RUM.js.map +1 -0
  47. package/dist/{entry-NQRN7SWV.js → entry-6EWYXIS5.js} +2 -2
  48. package/dist/{entry-NQRN7SWV.js.map → entry-6EWYXIS5.js.map} +1 -1
  49. package/dist/index.js +2 -2
  50. package/dist/{list-RPIG75US.js → list-GBM53HFN.js} +2 -2
  51. package/dist/{list-RPIG75US.js.map → list-GBM53HFN.js.map} +1 -1
  52. package/dist/{list-7SCWJXUE.js → list-N5W7G3LD.js} +3 -3
  53. package/dist/{list-7SCWJXUE.js.map → list-N5W7G3LD.js.map} +1 -1
  54. package/dist/{pages-KXERA5Z6.js → pages-HPR3UHT7.js} +3 -3
  55. package/dist/{pages-KXERA5Z6.js.map → pages-HPR3UHT7.js.map} +1 -1
  56. package/dist/{plugin-pages-NXA4BT7Y.js → plugin-pages-VDRT7RLY.js} +2 -2
  57. package/dist/{plugin-pages-NXA4BT7Y.js.map → plugin-pages-VDRT7RLY.js.map} +1 -1
  58. package/dist/{project-selector-SA6UUVBK.js → project-selector-RRG52TSX.js} +2 -2
  59. package/dist/{project-selector-SA6UUVBK.js.map → project-selector-RRG52TSX.js.map} +1 -1
  60. package/dist/record-links-CI4OJPWW.js +2 -0
  61. package/dist/{record-links-RTMCYEPM.js.map → record-links-CI4OJPWW.js.map} +1 -1
  62. package/dist/{root-IBZPU2D4.js → root-DF2BNGOF.js} +3 -3
  63. package/dist/{root-IBZPU2D4.js.map → root-DF2BNGOF.js.map} +1 -1
  64. package/dist/{root-TSZ3CSJU.js → root-IXK2ESCS.js} +3 -3
  65. package/dist/{root-TSZ3CSJU.js.map → root-IXK2ESCS.js.map} +1 -1
  66. package/dist/{root-MBFQXX4E.js → root-JFYE2JRJ.js} +2 -2
  67. package/dist/{root-MBFQXX4E.js.map → root-JFYE2JRJ.js.map} +1 -1
  68. package/dist/{root-6H6K3YQF.js → root-KF6EFGM6.js} +3 -3
  69. package/dist/{root-6H6K3YQF.js.map → root-KF6EFGM6.js.map} +1 -1
  70. package/dist/{root-W5ZPSNQ2.js → root-LUWJS7SQ.js} +2 -2
  71. package/dist/{root-W5ZPSNQ2.js.map → root-LUWJS7SQ.js.map} +1 -1
  72. package/dist/{root-TZIXWEZO.js → root-RGAV2YAF.js} +2 -2
  73. package/dist/{root-TZIXWEZO.js.map → root-RGAV2YAF.js.map} +1 -1
  74. package/dist/{search-ZLEYFT3T.js → search-DQLC3XDJ.js} +2 -2
  75. package/dist/{search-ZLEYFT3T.js.map → search-DQLC3XDJ.js.map} +1 -1
  76. package/dist/{skills-pages-RPMWIBLS.js → skills-pages-Q4YUDTC2.js} +2 -2
  77. package/dist/{skills-pages-RPMWIBLS.js.map → skills-pages-Q4YUDTC2.js.map} +1 -1
  78. package/dist/{source-VYWE5EB5.js → source-J3ZCTEWZ.js} +2 -2
  79. package/dist/{source-VYWE5EB5.js.map → source-J3ZCTEWZ.js.map} +1 -1
  80. package/package.json +6 -6
  81. package/dist/chat-page-IR4RF46H.js +0 -4
  82. package/dist/chat-page-IR4RF46H.js.map +0 -1
  83. package/dist/chunk-FJRDLP7V.js +0 -10
  84. package/dist/chunk-FJRDLP7V.js.map +0 -1
  85. package/dist/chunk-U6VZY3V2.js +0 -3
  86. package/dist/chunk-U6VZY3V2.js.map +0 -1
  87. package/dist/record-links-RTMCYEPM.js +0 -2
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/graphql-client/refetch-entity-lists.ts","../src/graphql-client/use-entity-query.ts"],"names":["refetchTimer","pendingQueryNames","pendingResolvers","listeners","removalListeners","patchListeners","getEntityListQueryName","entityNameOrPlural","schema","getOperationEntityName","assetSchema","byPlural","entity","byName","plural","subscribeEntityListRefetch","listener","subscribeEntityListRemoval","subscribeEntityListPatch","scheduleEntityListRemoval","apolloClient","queryName","entityIds","ids","scheduleEntityListRefetch","scheduleEntityListPatch","patches","nextPatches","patch","_apolloClient","resolve","reject","names","resolvers","finish","error","fail","useEntityQuery","entityNamePlural","scope","variables","isForm","selection","includeCount","fetchPolicy","result","setResult","useState","isLoadingMore","setIsLoadingMore","isReloading","setIsReloading","unsupportedTotalCount","setUnsupportedTotalCount","isLoadingMoreRef","useRef","isReloadingRef","nextOffsetRef","syncedQueryKeyRef","pendingQueryKeyRef","defaultScope","useDefaultScope","totalCountField","entitySchema","getEntitySchema","countMode","queryDocument","useMemo","gql","getEntityQuery","fetchMoreDocument","schemaErrorMessage","setSchemaErrorMessage","useGraphQLError","isLoading","data","fetchNextPage","refetch","networkStatus","useQuery","fetchNextPageRef","refetchRef","fetchMoreDocumentRef","previousNetworkStatusRef","variablesRef","isMissingTotalCountField","isMissingGraphQLFieldError","shouldFallbackToAggregate","effectiveError","isTotalCountFallbackLoading","serverError","getServerError","schemaMismatchMessage","getGraphQLSchemaMismatchMessage","isProjectDisabled","isProjectReadOnly","responseBody","parseErrorBody","useEffect","fetchMore","useCallback","args","limit","offset","res","mappedFetchMoreResults","mapResults","pageLength","prevRows","merged","uniqBy","prop","fetchError","reload","options","preserve","queryKey","mapped","getVariablesOffset","previousStatus","NetworkStatus","listQueryName","unsubscribeRefetch","queryNames","unsubscribeRemoval","prev","nextResults","row","rowId","removedCount","unsubscribePatch","applyEntityListPatches","mapQueryResultForFormFields","mapQueryResult","sort","patchById","didPatch","sortEntityListResults","results","primarySort","primarySortEntry","sortField","sortDirection","direction","left","right","leftValue","rightValue","leftText","rightText"],"mappings":"wXAcA,IAAIA,CAAAA,CAAqD,KACnDC,CAAAA,CAAoB,IAAI,GAAA,CACxBC,EAAAA,CAAqF,EAAC,CACtFC,EAAY,IAAI,GAAA,CAChBC,EAAmB,IAAI,GAAA,CACvBC,EAAiB,IAAI,GAAA,CAEpB,SAASC,EAAAA,CAAuBC,CAAAA,CAA4BC,CAAAA,CAAwB,CACzF,GAAID,CAAAA,GAAuB,UAAYA,CAAAA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A,EAASA,CAAAA,GAAkB,OAC9D,OAAOJ,CAAAA,CAGT,IAAMK,CAAAA,CAAYD,CAAAA,GAAkB,MAAA,CAAS,EAAA,CAAK,CAAA,CAElD,OAAO,CAAC,GAAGJ,CAAO,EAAE,IAAA,CAAK,CAACM,EAAMC,CAAAA,GAAU,CACxC,IAAMC,CAAAA,CAAYF,CAAAA,CAAKH,CAAS,EAC1BM,CAAAA,CAAaF,CAAAA,CAAMJ,CAAS,CAAA,CAC5BO,CAAAA,CAAW,OAAOF,CAAAA,EAAc,QAAA,CAAWA,CAAAA,CAAY,EAAA,CACvDG,CAAAA,CAAY,OAAOF,GAAe,QAAA,CAAWA,CAAAA,CAAa,GAEhE,OAAOC,CAAAA,CAAS,cAAcC,CAAS,CAAA,CAAIN,CAC7C,CAAC,CACH","file":"chunk-W7JDZHCV.js","sourcesContent":["import type { ApolloClient } from '@apollo/client';\nimport type { Schema } from '../core/types';\nimport { assetSchema } from '../entities/assets-schema';\nimport { getOperationEntityName } from './queries';\n\ntype EntityListRefreshListener = (queryNames: ReadonlySet<string>) => void | Promise<void>;\ntype EntityListRemovalListener = (queryName: string, entityIds: ReadonlySet<string>) => void;\ntype EntityListPatchListener = (queryName: string, patches: EntityListRowPatch[]) => void;\n\nexport type EntityListRowPatch = {\n _id: string;\n attributes: { [key: string]: string };\n};\n\nlet refetchTimer: ReturnType<typeof setTimeout> | null = null;\nconst pendingQueryNames = new Set<string>();\nconst pendingResolvers: Array<{ resolve: () => void; reject: (error: unknown) => void }> = [];\nconst listeners = new Set<EntityListRefreshListener>();\nconst removalListeners = new Set<EntityListRemovalListener>();\nconst patchListeners = new Set<EntityListPatchListener>();\n\nexport function getEntityListQueryName(entityNameOrPlural: string, schema: Schema): string {\n if (entityNameOrPlural === '_asset' || entityNameOrPlural === '_assets') {\n return `Get${getOperationEntityName(assetSchema.plural)}`;\n }\n\n const byPlural = schema.find((entity) => entity.plural === entityNameOrPlural);\n const byName = schema.find((entity) => entity.name === entityNameOrPlural);\n const plural = byPlural?.plural ?? byName?.plural ?? entityNameOrPlural;\n\n return `Get${getOperationEntityName(plural)}`;\n}\n\n/**\n * Subscribe to soft list refreshes. Listeners should refetch their own query and\n * remap local paginated state (useEntityQuery ignores Apollo cache writes after sync).\n */\nexport function subscribeEntityListRefetch(listener: EntityListRefreshListener): () => void {\n listeners.add(listener);\n\n return () => {\n listeners.delete(listener);\n };\n}\n\n/**\n * Subscribe to optimistic row removals (e.g. after delete) before the soft-refetch lands.\n */\nexport function subscribeEntityListRemoval(listener: EntityListRemovalListener): () => void {\n removalListeners.add(listener);\n\n return () => {\n removalListeners.delete(listener);\n };\n}\n\n/**\n * Subscribe to in-place row patches (e.g. tag connect/disconnect) without a full list refetch.\n */\nexport function subscribeEntityListPatch(listener: EntityListPatchListener): () => void {\n patchListeners.add(listener);\n\n return () => {\n patchListeners.delete(listener);\n };\n}\n\n/**\n * Immediately drop rows from mounted lists, then soft-refetch to sync counts/pages.\n */\nexport function scheduleEntityListRemoval(\n apolloClient: ApolloClient,\n queryName: string,\n entityIds: string[]\n): Promise<void> {\n const ids = new Set(entityIds.filter(Boolean));\n\n if (ids.size > 0) {\n for (const listener of removalListeners) {\n listener(queryName, ids);\n }\n }\n\n return scheduleEntityListRefetch(apolloClient, queryName);\n}\n\n/**\n * Patch mounted list rows in place. Use when a mutation cannot change list cardinality\n * (e.g. tag connect/disconnect) so we avoid a full GetAssets soft-refetch.\n */\nexport function scheduleEntityListPatch(queryName: string, patches: EntityListRowPatch[]): void {\n const nextPatches = patches.filter((patch) => Boolean(patch._id));\n\n if (nextPatches.length === 0) {\n return;\n }\n\n for (const listener of patchListeners) {\n listener(queryName, nextPatches);\n }\n}\n\n/**\n * Ask mounted entity lists to soft-refresh. Debounced so batch deletes coalesce.\n */\nexport function scheduleEntityListRefetch(_apolloClient: ApolloClient, queryName: string): Promise<void> {\n pendingQueryNames.add(queryName);\n\n return new Promise<void>((resolve, reject) => {\n pendingResolvers.push({ resolve, reject });\n\n if (refetchTimer) {\n clearTimeout(refetchTimer);\n }\n\n refetchTimer = setTimeout(() => {\n const names = new Set(pendingQueryNames);\n const resolvers = pendingResolvers.splice(0);\n pendingQueryNames.clear();\n refetchTimer = null;\n\n void Promise.all([...listeners].map((listener) => Promise.resolve(listener(names))))\n .then(() => {\n for (const { resolve: finish } of resolvers) {\n finish();\n }\n })\n .catch((error: unknown) => {\n console.error('Error refreshing entity lists:', error);\n\n for (const { reject: fail } of resolvers) {\n fail(error);\n }\n });\n }, 50);\n });\n}\n","import { useDefaultScope } from '../core/default-scope';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { prop, uniqBy } from 'ramda';\nimport { gql, NetworkStatus } from '@apollo/client';\nimport type { OperationVariables } from '@apollo/client';\nimport { useQuery } from '@apollo/client/react';\nimport {\n getGraphQLSchemaMismatchMessage,\n getServerError,\n isMissingGraphQLFieldError,\n parseErrorBody,\n} from './error-utils';\nimport {\n getEntityQuery,\n getEntitySchema,\n getOperationEntityName,\n mapQueryResult,\n mapQueryResultForFormFields,\n} from './queries';\nimport {\n subscribeEntityListPatch,\n subscribeEntityListRefetch,\n subscribeEntityListRemoval,\n type EntityListRowPatch,\n} from './refetch-entity-lists';\nimport { useGraphQLError } from './graphql-context';\nimport type {\n EntityQueryAggregate,\n EntityQueryResults,\n FormEntityItem,\n MappedEntityQueryResults,\n MappedEntityItem,\n MappedFormEntityQueryResults,\n UseEntityQueryParams,\n ImageValue,\n} from './types';\n\ntype FetchMoreOptions = {\n // `offset` is accepted for call-site compatibility but overridden by nextOffsetRef.\n // `where`/`sort` are inherited from the active query unless overridden here.\n variables: OperationVariables & { offset: number; limit: number };\n};\ntype Results = (MappedEntityQueryResults | MappedFormEntityQueryResults) | { count: 0; results: [] };\n\nexport function useEntityQuery({\n entityNamePlural,\n schema,\n scope,\n variables,\n isForm,\n selection = 'full',\n includeCount = true,\n fetchPolicy,\n}: UseEntityQueryParams): {\n count: number;\n data: MappedEntityItem[] | FormEntityItem[] | ImageValue[] | undefined;\n fetchMore: (args: FetchMoreOptions) => void;\n isLoading: boolean;\n isLoadingMore: boolean;\n isProjectDisabled: boolean;\n isProjectReadOnly: boolean;\n reload: (options?: { preserve?: boolean }) => Promise<void>;\n schemaErrorMessage: string | null;\n} {\n const [result, setResult] = useState<Results>({\n count: 0,\n results: [],\n });\n const [isLoadingMore, setIsLoadingMore] = useState(false);\n const [isReloading, setIsReloading] = useState(false);\n const [unsupportedTotalCount, setUnsupportedTotalCount] = useState<{\n field: string;\n schema: UseEntityQueryParams['schema'];\n } | null>(null);\n const isLoadingMoreRef = useRef(false);\n const isReloadingRef = useRef(false);\n // Next offset for fetchMore — advanced by each requested page window, not by the\n // deduplicated row count. Using unique rows.length as offset collapses when pages\n // overlap (unstable sorts / tied timestamps) into irregular steps like 25→35→42.\n const nextOffsetRef = useRef(0);\n // Tracks the query identity we last synced into local result state.\n // fetchMore updates Apollo `data` without changing this identity; syncing those\n // updates would wipe accumulated pages and retrigger infinite load-more.\n // Must include entity/scope — variables alone collide across entity navigations.\n const syncedQueryKeyRef = useRef<string | null>(null);\n const pendingQueryKeyRef = useRef<string | null>(null);\n const defaultScope = useDefaultScope();\n const totalCountField = `${entityNamePlural}Total`;\n const entitySchema = getEntitySchema(schema, entityNamePlural);\n const canUseTotalCount =\n variables?.where === undefined &&\n (entitySchema?.spaces?.length ?? 0) === 0 &&\n (unsupportedTotalCount?.field !== totalCountField || unsupportedTotalCount.schema !== schema);\n const countMode = canUseTotalCount ? 'total' : 'aggregate';\n const queryDocument = useMemo(\n () =>\n gql(getEntityQuery(entityNamePlural, scope, schema, { selection, countMode, includeCount, defaultScope }).query),\n [entityNamePlural, scope, schema, selection, countMode, includeCount, defaultScope]\n );\n // fetchMore pages skip the top-level aggregate count (a filtered label scan\n // on the server); the total from the first page still stands.\n const fetchMoreDocument = useMemo(\n () => gql(getEntityQuery(entityNamePlural, scope, schema, { selection, includeCount: false, defaultScope }).query),\n [entityNamePlural, scope, schema, selection, defaultScope]\n );\n const { schemaErrorMessage, setSchemaErrorMessage } = useGraphQLError();\n const {\n loading: isLoading,\n data,\n fetchMore: fetchNextPage,\n refetch,\n error,\n networkStatus,\n } = useQuery<EntityQueryResults & EntityQueryAggregate>(queryDocument, {\n variables,\n notifyOnNetworkStatusChange: true,\n fetchPolicy,\n });\n const fetchNextPageRef = useRef(fetchNextPage);\n const refetchRef = useRef(refetch);\n const fetchMoreDocumentRef = useRef(fetchMoreDocument);\n const previousNetworkStatusRef = useRef(networkStatus);\n const variablesRef = useRef(variables);\n fetchNextPageRef.current = fetchNextPage;\n refetchRef.current = refetch;\n fetchMoreDocumentRef.current = fetchMoreDocument;\n variablesRef.current = variables;\n\n // Parse 403 error response to determine the specific error code\n const isMissingTotalCountField = includeCount && isMissingGraphQLFieldError(error, totalCountField);\n const shouldFallbackToAggregate = countMode === 'total' && isMissingTotalCountField;\n const effectiveError = isMissingTotalCountField ? undefined : error;\n const isTotalCountFallbackLoading = isMissingTotalCountField && !data?.[entityNamePlural];\n const serverError = getServerError(effectiveError);\n const schemaMismatchMessage = getGraphQLSchemaMismatchMessage(effectiveError);\n\n const { isProjectDisabled, isProjectReadOnly } = (() => {\n if (serverError?.statusCode === 403) {\n const responseBody = parseErrorBody<{ code?: string }>(serverError.bodyText);\n\n if (responseBody && typeof responseBody.code === 'string') {\n if (responseBody.code === 'PROJECT_PAUSED') {\n return {\n isProjectDisabled: true,\n isProjectReadOnly: false,\n };\n }\n\n if (responseBody.code === 'READ_ONLY_MODE') {\n return {\n isProjectDisabled: false,\n isProjectReadOnly: true,\n };\n }\n }\n\n return {\n isProjectDisabled: true,\n isProjectReadOnly: false,\n };\n }\n\n return {\n isProjectDisabled: false,\n isProjectReadOnly: false,\n };\n })();\n\n useEffect(() => {\n if (!shouldFallbackToAggregate) {\n return;\n }\n\n setUnsupportedTotalCount({ field: totalCountField, schema });\n }, [schema, shouldFallbackToAggregate, totalCountField]);\n\n const fetchMore = useCallback(\n (args: FetchMoreOptions): void => {\n if (isLoadingMoreRef.current || isReloadingRef.current) {\n return;\n }\n\n isLoadingMoreRef.current = true;\n setIsLoadingMore(true);\n\n const { limit } = args.variables;\n const offset = nextOffsetRef.current;\n\n fetchNextPageRef\n .current({\n ...args,\n query: fetchMoreDocumentRef.current,\n variables: {\n // fetchMore uses a count-free document, so Apollo will not inherit\n // the original operation's where/sort unless we pass them again.\n ...variablesRef.current,\n ...args.variables,\n offset,\n limit,\n },\n })\n .then(({ data: res }) => {\n const mappedFetchMoreResults = mapResults({\n data: res,\n entityNamePlural,\n isForm,\n schema,\n scope,\n defaultScope,\n });\n // Advance by the fetched page window (capped at limit), not by how many unique\n // rows survived client-side merge. Cap protects against Apollo returning a\n // merged cache blob larger than the requested page.\n const pageLength = mappedFetchMoreResults.results.length;\n nextOffsetRef.current = offset + (pageLength === 0 ? 0 : Math.min(pageLength, limit));\n\n setResult((prevRows) => {\n const merged = uniqBy(prop('_id'), [\n ...prevRows.results,\n ...mappedFetchMoreResults.results,\n ]) as Results['results'];\n\n // Empty/duplicate pages must end pagination, otherwise load-more loops forever\n // when aggregate count is ahead of rows that the where-clause can actually return.\n if (merged.length === prevRows.results.length) {\n return {\n count: prevRows.results.length,\n results: prevRows.results,\n } as Results;\n }\n\n // Count-free pagination pages report 0; the first page's total stands.\n return {\n count: mappedFetchMoreResults.count || prevRows.count,\n results: merged,\n } as Results;\n });\n })\n .catch((fetchError: unknown) => {\n console.error('Error fetching more data:', fetchError);\n })\n .finally(() => {\n isLoadingMoreRef.current = false;\n setIsLoadingMore(false);\n });\n },\n [defaultScope, entityNamePlural, isForm, schema, scope]\n );\n\n const reload = useCallback(\n (options?: { preserve?: boolean }): Promise<void> => {\n if (isReloadingRef.current) {\n return Promise.resolve();\n }\n\n const preserve = options?.preserve === true;\n\n isReloadingRef.current = true;\n isLoadingMoreRef.current = false;\n setIsLoadingMore(false);\n\n if (!preserve) {\n syncedQueryKeyRef.current = null;\n pendingQueryKeyRef.current = null;\n nextOffsetRef.current = 0;\n setIsReloading(true);\n setResult({ count: 0, results: [] });\n }\n\n return refetchRef\n .current()\n .then(({ data: res }) => {\n const queryKey = JSON.stringify({ entityNamePlural, scope, selection, includeCount, variables });\n const mapped = mapResults({ data: res, entityNamePlural, isForm, schema, scope, defaultScope });\n\n syncedQueryKeyRef.current = queryKey;\n pendingQueryKeyRef.current = null;\n nextOffsetRef.current = getVariablesOffset(variables) + mapped.results.length;\n setResult(mapped);\n })\n .catch((fetchError: unknown) => {\n console.error('Error reloading data:', fetchError);\n })\n .finally(() => {\n isReloadingRef.current = false;\n setIsReloading(false);\n });\n },\n [defaultScope, entityNamePlural, isForm, schema, scope, selection, includeCount, variables]\n );\n\n useEffect(() => {\n if (schemaMismatchMessage) {\n setSchemaErrorMessage(schemaMismatchMessage);\n\n return;\n }\n\n if (data && schemaErrorMessage && !effectiveError) {\n setSchemaErrorMessage(null);\n }\n }, [data, effectiveError, schemaErrorMessage, schemaMismatchMessage, setSchemaErrorMessage]);\n\n useEffect(() => {\n if (effectiveError || schemaMismatchMessage || isTotalCountFallbackLoading) {\n return;\n }\n\n const queryKey = JSON.stringify({ entityNamePlural, scope, selection, includeCount, variables });\n\n // Already synced for this query identity — ignore Apollo `data` updates from fetchMore.\n if (syncedQueryKeyRef.current === queryKey) {\n return;\n }\n\n if (isLoading && pendingQueryKeyRef.current !== queryKey) {\n pendingQueryKeyRef.current = queryKey;\n nextOffsetRef.current = 0;\n setResult({ count: 0, results: [] });\n\n return;\n }\n\n if (isLoading) {\n return;\n }\n\n const mapped = mapResults({ data, entityNamePlural, isForm, schema, scope, defaultScope });\n syncedQueryKeyRef.current = queryKey;\n pendingQueryKeyRef.current = null;\n nextOffsetRef.current = getVariablesOffset(variables) + mapped.results.length;\n setResult(mapped);\n }, [\n defaultScope,\n data,\n effectiveError,\n entityNamePlural,\n isForm,\n isLoading,\n isTotalCountFallbackLoading,\n schema,\n schemaMismatchMessage,\n scope,\n selection,\n includeCount,\n variables,\n ]);\n\n // After an Apollo refetch (delete/upload), replace accumulated pages with the\n // fresh first page. fetchMore uses NetworkStatus.fetchMore and is ignored.\n useEffect(() => {\n const previousStatus = previousNetworkStatusRef.current;\n previousNetworkStatusRef.current = networkStatus;\n\n if (effectiveError || schemaMismatchMessage || isReloadingRef.current || isTotalCountFallbackLoading) {\n return;\n }\n\n if (previousStatus !== NetworkStatus.refetch || networkStatus !== NetworkStatus.ready || !data) {\n return;\n }\n\n const queryKey = JSON.stringify({ entityNamePlural, scope, selection, includeCount, variables });\n const mapped = mapResults({ data, entityNamePlural, isForm, schema, scope, defaultScope });\n syncedQueryKeyRef.current = queryKey;\n pendingQueryKeyRef.current = null;\n nextOffsetRef.current = getVariablesOffset(variables) + mapped.results.length;\n setResult(mapped);\n }, [\n defaultScope,\n data,\n effectiveError,\n entityNamePlural,\n isForm,\n isTotalCountFallbackLoading,\n networkStatus,\n schema,\n schemaMismatchMessage,\n scope,\n selection,\n includeCount,\n variables,\n ]);\n\n // Soft-refresh after mutations (tags, deletes, uploads). Local paginated state\n // ignores Apollo cache writes, so we must refetch and remap explicitly.\n useEffect(() => {\n if (isForm) {\n return;\n }\n\n const listQueryName = `Get${getOperationEntityName(entityNamePlural)}`;\n\n const unsubscribeRefetch = subscribeEntityListRefetch((queryNames) => {\n if (!queryNames.has(listQueryName) || isLoadingMoreRef.current || isReloadingRef.current) {\n return;\n }\n\n return refetchRef\n .current()\n .then(({ data: res }) => {\n const queryKey = JSON.stringify({ entityNamePlural, scope, selection, includeCount, variables });\n const mapped = mapResults({ data: res, entityNamePlural, isForm, schema, scope, defaultScope });\n syncedQueryKeyRef.current = queryKey;\n pendingQueryKeyRef.current = null;\n nextOffsetRef.current = getVariablesOffset(variables) + mapped.results.length;\n setResult(mapped);\n })\n .catch((fetchError: unknown) => {\n console.error('Error soft-refreshing entity list:', fetchError);\n });\n });\n\n const unsubscribeRemoval = subscribeEntityListRemoval((queryName, entityIds) => {\n if (queryName !== listQueryName) {\n return;\n }\n\n setResult((prev) => {\n const nextResults = prev.results.filter((row) => {\n const rowId = typeof row._id === 'string' ? row._id : undefined;\n\n return !rowId || !entityIds.has(rowId);\n });\n const removedCount = prev.results.length - nextResults.length;\n\n if (removedCount === 0) {\n return prev;\n }\n\n return {\n count: Math.max(0, prev.count - removedCount),\n results: nextResults,\n } as Results;\n });\n });\n\n const unsubscribePatch = subscribeEntityListPatch((queryName, patches) => {\n if (queryName !== listQueryName) {\n return;\n }\n\n setResult((prev) => applyEntityListPatches(prev, patches, variables?.sort));\n });\n\n return () => {\n unsubscribeRefetch();\n unsubscribeRemoval();\n unsubscribePatch();\n };\n }, [defaultScope, entityNamePlural, isForm, schema, scope, selection, includeCount, variables]);\n\n return {\n // Refetch keeps existing rows visible; only initial load / explicit reload show as loading.\n isLoading:\n (isLoading && networkStatus !== NetworkStatus.refetch) || isReloading || isTotalCountFallbackLoading,\n isLoadingMore,\n fetchMore,\n reload,\n count: result.count,\n data: result.results,\n isProjectDisabled,\n isProjectReadOnly,\n schemaErrorMessage,\n };\n}\n\nfunction getVariablesOffset(variables: OperationVariables | undefined): number {\n const offset = variables?.offset;\n\n return typeof offset === 'number' && Number.isFinite(offset) ? offset : 0;\n}\n\nfunction mapResults(\n args: {\n data: (EntityQueryResults & EntityQueryAggregate) | undefined;\n defaultScope: string;\n } & UseEntityQueryParams\n): MappedEntityQueryResults | MappedFormEntityQueryResults {\n const entityNamePlural = args.entityNamePlural as keyof FormEntityItem;\n\n if (!args.data?.[entityNamePlural]) {\n return { count: 0, results: [] };\n }\n\n return args.isForm\n ? mapQueryResultForFormFields(args.entityNamePlural, args.scope, args.data, args.schema, args.defaultScope)\n : mapQueryResult(args.entityNamePlural, args.scope, args.data, args.schema);\n}\n\nfunction applyEntityListPatches(\n prev: Results,\n patches: EntityListRowPatch[],\n sort: unknown\n): Results {\n const patchById = new Map(patches.map((patch) => [patch._id, patch]));\n let didPatch = false;\n const nextResults = prev.results.map((row) => {\n const rowId = typeof row._id === 'string' ? row._id : undefined;\n\n if (!rowId) {\n return row;\n }\n\n const patch = patchById.get(rowId);\n\n if (!patch) {\n return row;\n }\n\n didPatch = true;\n\n return {\n ...row,\n ...patch.attributes,\n };\n });\n\n if (!didPatch) {\n return prev;\n }\n\n return {\n count: prev.count,\n results: sortEntityListResults(nextResults, sort),\n } as Results;\n}\n\nfunction sortEntityListResults<T extends { [key: string]: unknown }>(results: T[], sort: unknown): T[] {\n if (!Array.isArray(sort) || sort.length === 0) {\n return results;\n }\n\n const [primarySort] = sort;\n\n if (!primarySort || typeof primarySort !== 'object') {\n return results;\n }\n\n const [primarySortEntry] = Object.entries(primarySort as { [key: string]: unknown });\n const [sortField, sortDirection] = primarySortEntry ?? [];\n\n if (!sortField || (sortDirection !== 'ASC' && sortDirection !== 'DESC')) {\n return results;\n }\n\n const direction = sortDirection === 'DESC' ? -1 : 1;\n\n return [...results].sort((left, right) => {\n const leftValue = left[sortField];\n const rightValue = right[sortField];\n const leftText = typeof leftValue === 'string' ? leftValue : '';\n const rightText = typeof rightValue === 'string' ? rightValue : '';\n\n return leftText.localeCompare(rightText) * direction;\n });\n}\n"]}
1
+ {"version":3,"sources":["../src/graphql-client/refetch-entity-lists.ts","../src/graphql-client/use-entity-query.ts"],"names":["refetchTimer","pendingQueryNames","pendingResolvers","listeners","removalListeners","patchListeners","getEntityListQueryName","entityNameOrPlural","schema","getOperationEntityName","assetSchema","byPlural","entity","byName","plural","subscribeEntityListRefetch","listener","subscribeEntityListRemoval","subscribeEntityListPatch","scheduleEntityListRemoval","apolloClient","queryName","entityIds","ids","scheduleEntityListRefetch","scheduleEntityListPatch","patches","nextPatches","patch","_apolloClient","resolve","reject","names","resolvers","finish","error","fail","useEntityQuery","entityNamePlural","scope","variables","isForm","selection","includeCount","fetchPolicy","result","setResult","useState","isLoadingMore","setIsLoadingMore","isReloading","setIsReloading","unsupportedTotalCount","setUnsupportedTotalCount","isLoadingMoreRef","useRef","isReloadingRef","nextOffsetRef","syncedQueryKeyRef","pendingQueryKeyRef","defaultScope","useDefaultScope","totalCountField","entitySchema","getEntitySchema","countMode","queryDocument","useMemo","gql","getEntityQuery","fetchMoreDocument","schemaErrorMessage","setSchemaErrorMessage","useGraphQLError","isLoading","data","fetchNextPage","refetch","networkStatus","useQuery","fetchNextPageRef","refetchRef","fetchMoreDocumentRef","previousNetworkStatusRef","variablesRef","isMissingTotalCountField","isMissingGraphQLFieldError","shouldFallbackToAggregate","effectiveError","isTotalCountFallbackLoading","serverError","getServerError","schemaMismatchMessage","getGraphQLSchemaMismatchMessage","isProjectDisabled","isProjectReadOnly","responseBody","parseErrorBody","useEffect","fetchMore","useCallback","args","limit","offset","res","mappedFetchMoreResults","mapResults","pageLength","prevRows","merged","uniqBy","prop","fetchError","reload","options","preserve","queryKey","mapped","getVariablesOffset","previousStatus","NetworkStatus","listQueryName","unsubscribeRefetch","queryNames","unsubscribeRemoval","prev","nextResults","row","rowId","removedCount","unsubscribePatch","applyEntityListPatches","mapQueryResultForFormFields","mapQueryResult","sort","patchById","didPatch","sortEntityListResults","results","primarySort","primarySortEntry","sortField","sortDirection","direction","left","right","leftValue","rightValue","leftText","rightText"],"mappings":"wXAcA,IAAIA,CAAAA,CAAqD,KACnDC,CAAAA,CAAoB,IAAI,GAAA,CACxBC,EAAAA,CAAqF,EAAC,CACtFC,EAAY,IAAI,GAAA,CAChBC,EAAmB,IAAI,GAAA,CACvBC,EAAiB,IAAI,GAAA,CAEpB,SAASC,EAAAA,CAAuBC,CAAAA,CAA4BC,CAAAA,CAAwB,CACzF,GAAID,CAAAA,GAAuB,UAAYA,CAAAA,GAAuB,SAAA,CAC5D,OAAO,CAAA,GAAA,EAAME,CAAAA,CAAuBC,CAAAA,CAAY,MAAM,CAAC,CAAA,CAAA,CAGzD,IAAMC,GAAAA,CAAWH,CAAAA,CAAO,KAAMI,CAAAA,EAAWA,CAAAA,CAAO,SAAWL,CAAkB,CAAA,CACvEM,CAAAA,CAASL,CAAAA,CAAO,IAAA,CAAMI,CAAAA,EAAWA,EAAO,IAAA,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AA,CAAMJ,CAAS,CAAA,CAC5BO,CAAAA,CAAW,OAAOF,CAAAA,EAAc,QAAA,CAAWA,CAAAA,CAAY,EAAA,CACvDG,CAAAA,CAAY,OAAOF,GAAe,QAAA,CAAWA,CAAAA,CAAa,GAEhE,OAAOC,CAAAA,CAAS,cAAcC,CAAS,CAAA,CAAIN,CAC7C,CAAC,CACH","file":"chunk-337GX2BR.js","sourcesContent":["import type { ApolloClient } from '@apollo/client';\nimport type { Schema } from '../core/types';\nimport { assetSchema } from '../entities/assets-schema';\nimport { getOperationEntityName } from './queries';\n\ntype EntityListRefreshListener = (queryNames: ReadonlySet<string>) => void | Promise<void>;\ntype EntityListRemovalListener = (queryName: string, entityIds: ReadonlySet<string>) => void;\ntype EntityListPatchListener = (queryName: string, patches: EntityListRowPatch[]) => void;\n\nexport type EntityListRowPatch = {\n _id: string;\n attributes: { [key: string]: string };\n};\n\nlet refetchTimer: ReturnType<typeof setTimeout> | null = null;\nconst pendingQueryNames = new Set<string>();\nconst pendingResolvers: Array<{ resolve: () => void; reject: (error: unknown) => void }> = [];\nconst listeners = new Set<EntityListRefreshListener>();\nconst removalListeners = new Set<EntityListRemovalListener>();\nconst patchListeners = new Set<EntityListPatchListener>();\n\nexport function getEntityListQueryName(entityNameOrPlural: string, schema: Schema): string {\n if (entityNameOrPlural === '_asset' || entityNameOrPlural === '_assets') {\n return `Get${getOperationEntityName(assetSchema.plural)}`;\n }\n\n const byPlural = schema.find((entity) => entity.plural === entityNameOrPlural);\n const byName = schema.find((entity) => entity.name === entityNameOrPlural);\n const plural = byPlural?.plural ?? byName?.plural ?? entityNameOrPlural;\n\n return `Get${getOperationEntityName(plural)}`;\n}\n\n/**\n * Subscribe to soft list refreshes. Listeners should refetch their own query and\n * remap local paginated state (useEntityQuery ignores Apollo cache writes after sync).\n */\nexport function subscribeEntityListRefetch(listener: EntityListRefreshListener): () => void {\n listeners.add(listener);\n\n return () => {\n listeners.delete(listener);\n };\n}\n\n/**\n * Subscribe to optimistic row removals (e.g. after delete) before the soft-refetch lands.\n */\nexport function subscribeEntityListRemoval(listener: EntityListRemovalListener): () => void {\n removalListeners.add(listener);\n\n return () => {\n removalListeners.delete(listener);\n };\n}\n\n/**\n * Subscribe to in-place row patches (e.g. tag connect/disconnect) without a full list refetch.\n */\nexport function subscribeEntityListPatch(listener: EntityListPatchListener): () => void {\n patchListeners.add(listener);\n\n return () => {\n patchListeners.delete(listener);\n };\n}\n\n/**\n * Immediately drop rows from mounted lists, then soft-refetch to sync counts/pages.\n */\nexport function scheduleEntityListRemoval(\n apolloClient: ApolloClient,\n queryName: string,\n entityIds: string[]\n): Promise<void> {\n const ids = new Set(entityIds.filter(Boolean));\n\n if (ids.size > 0) {\n for (const listener of removalListeners) {\n listener(queryName, ids);\n }\n }\n\n return scheduleEntityListRefetch(apolloClient, queryName);\n}\n\n/**\n * Patch mounted list rows in place. Use when a mutation cannot change list cardinality\n * (e.g. tag connect/disconnect) so we avoid a full GetAssets soft-refetch.\n */\nexport function scheduleEntityListPatch(queryName: string, patches: EntityListRowPatch[]): void {\n const nextPatches = patches.filter((patch) => Boolean(patch._id));\n\n if (nextPatches.length === 0) {\n return;\n }\n\n for (const listener of patchListeners) {\n listener(queryName, nextPatches);\n }\n}\n\n/**\n * Ask mounted entity lists to soft-refresh. Debounced so batch deletes coalesce.\n */\nexport function scheduleEntityListRefetch(_apolloClient: ApolloClient, queryName: string): Promise<void> {\n pendingQueryNames.add(queryName);\n\n return new Promise<void>((resolve, reject) => {\n pendingResolvers.push({ resolve, reject });\n\n if (refetchTimer) {\n clearTimeout(refetchTimer);\n }\n\n refetchTimer = setTimeout(() => {\n const names = new Set(pendingQueryNames);\n const resolvers = pendingResolvers.splice(0);\n pendingQueryNames.clear();\n refetchTimer = null;\n\n void Promise.all([...listeners].map((listener) => Promise.resolve(listener(names))))\n .then(() => {\n for (const { resolve: finish } of resolvers) {\n finish();\n }\n })\n .catch((error: unknown) => {\n console.error('Error refreshing entity lists:', error);\n\n for (const { reject: fail } of resolvers) {\n fail(error);\n }\n });\n }, 50);\n });\n}\n","import { useDefaultScope } from '../core/default-scope';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { prop, uniqBy } from 'ramda';\nimport { gql, NetworkStatus } from '@apollo/client';\nimport type { OperationVariables } from '@apollo/client';\nimport { useQuery } from '@apollo/client/react';\nimport {\n getGraphQLSchemaMismatchMessage,\n getServerError,\n isMissingGraphQLFieldError,\n parseErrorBody,\n} from './error-utils';\nimport {\n getEntityQuery,\n getEntitySchema,\n getOperationEntityName,\n mapQueryResult,\n mapQueryResultForFormFields,\n} from './queries';\nimport {\n subscribeEntityListPatch,\n subscribeEntityListRefetch,\n subscribeEntityListRemoval,\n type EntityListRowPatch,\n} from './refetch-entity-lists';\nimport { useGraphQLError } from './graphql-context';\nimport type {\n EntityQueryAggregate,\n EntityQueryResults,\n FormEntityItem,\n MappedEntityQueryResults,\n MappedEntityItem,\n MappedFormEntityQueryResults,\n UseEntityQueryParams,\n ImageValue,\n} from './types';\n\ntype FetchMoreOptions = {\n // `offset` is accepted for call-site compatibility but overridden by nextOffsetRef.\n // `where`/`sort` are inherited from the active query unless overridden here.\n variables: OperationVariables & { offset: number; limit: number };\n};\ntype Results = (MappedEntityQueryResults | MappedFormEntityQueryResults) | { count: 0; results: [] };\n\nexport function useEntityQuery({\n entityNamePlural,\n schema,\n scope,\n variables,\n isForm,\n selection = 'full',\n includeCount = true,\n fetchPolicy,\n}: UseEntityQueryParams): {\n count: number;\n data: MappedEntityItem[] | FormEntityItem[] | ImageValue[] | undefined;\n fetchMore: (args: FetchMoreOptions) => void;\n isLoading: boolean;\n isLoadingMore: boolean;\n isProjectDisabled: boolean;\n isProjectReadOnly: boolean;\n reload: (options?: { preserve?: boolean }) => Promise<void>;\n schemaErrorMessage: string | null;\n} {\n const [result, setResult] = useState<Results>({\n count: 0,\n results: [],\n });\n const [isLoadingMore, setIsLoadingMore] = useState(false);\n const [isReloading, setIsReloading] = useState(false);\n const [unsupportedTotalCount, setUnsupportedTotalCount] = useState<{\n field: string;\n schema: UseEntityQueryParams['schema'];\n } | null>(null);\n const isLoadingMoreRef = useRef(false);\n const isReloadingRef = useRef(false);\n // Next offset for fetchMore — advanced by each requested page window, not by the\n // deduplicated row count. Using unique rows.length as offset collapses when pages\n // overlap (unstable sorts / tied timestamps) into irregular steps like 25→35→42.\n const nextOffsetRef = useRef(0);\n // Tracks the query identity we last synced into local result state.\n // fetchMore updates Apollo `data` without changing this identity; syncing those\n // updates would wipe accumulated pages and retrigger infinite load-more.\n // Must include entity/scope — variables alone collide across entity navigations.\n const syncedQueryKeyRef = useRef<string | null>(null);\n const pendingQueryKeyRef = useRef<string | null>(null);\n const defaultScope = useDefaultScope();\n const totalCountField = `${entityNamePlural}Total`;\n const entitySchema = getEntitySchema(schema, entityNamePlural);\n const canUseTotalCount =\n variables?.where === undefined &&\n (entitySchema?.spaces?.length ?? 0) === 0 &&\n (unsupportedTotalCount?.field !== totalCountField || unsupportedTotalCount.schema !== schema);\n const countMode = canUseTotalCount ? 'total' : 'aggregate';\n const queryDocument = useMemo(\n () =>\n gql(getEntityQuery(entityNamePlural, scope, schema, { selection, countMode, includeCount, defaultScope }).query),\n [entityNamePlural, scope, schema, selection, countMode, includeCount, defaultScope]\n );\n // fetchMore pages skip the top-level aggregate count (a filtered label scan\n // on the server); the total from the first page still stands.\n const fetchMoreDocument = useMemo(\n () => gql(getEntityQuery(entityNamePlural, scope, schema, { selection, includeCount: false, defaultScope }).query),\n [entityNamePlural, scope, schema, selection, defaultScope]\n );\n const { schemaErrorMessage, setSchemaErrorMessage } = useGraphQLError();\n const {\n loading: isLoading,\n data,\n fetchMore: fetchNextPage,\n refetch,\n error,\n networkStatus,\n } = useQuery<EntityQueryResults & EntityQueryAggregate>(queryDocument, {\n variables,\n notifyOnNetworkStatusChange: true,\n fetchPolicy,\n });\n const fetchNextPageRef = useRef(fetchNextPage);\n const refetchRef = useRef(refetch);\n const fetchMoreDocumentRef = useRef(fetchMoreDocument);\n const previousNetworkStatusRef = useRef(networkStatus);\n const variablesRef = useRef(variables);\n fetchNextPageRef.current = fetchNextPage;\n refetchRef.current = refetch;\n fetchMoreDocumentRef.current = fetchMoreDocument;\n variablesRef.current = variables;\n\n // Parse 403 error response to determine the specific error code\n const isMissingTotalCountField = includeCount && isMissingGraphQLFieldError(error, totalCountField);\n const shouldFallbackToAggregate = countMode === 'total' && isMissingTotalCountField;\n const effectiveError = isMissingTotalCountField ? undefined : error;\n const isTotalCountFallbackLoading = isMissingTotalCountField && !data?.[entityNamePlural];\n const serverError = getServerError(effectiveError);\n const schemaMismatchMessage = getGraphQLSchemaMismatchMessage(effectiveError);\n\n const { isProjectDisabled, isProjectReadOnly } = (() => {\n if (serverError?.statusCode === 403) {\n const responseBody = parseErrorBody<{ code?: string }>(serverError.bodyText);\n\n if (responseBody && typeof responseBody.code === 'string') {\n if (responseBody.code === 'PROJECT_PAUSED') {\n return {\n isProjectDisabled: true,\n isProjectReadOnly: false,\n };\n }\n\n if (responseBody.code === 'READ_ONLY_MODE') {\n return {\n isProjectDisabled: false,\n isProjectReadOnly: true,\n };\n }\n }\n\n return {\n isProjectDisabled: true,\n isProjectReadOnly: false,\n };\n }\n\n return {\n isProjectDisabled: false,\n isProjectReadOnly: false,\n };\n })();\n\n useEffect(() => {\n if (!shouldFallbackToAggregate) {\n return;\n }\n\n setUnsupportedTotalCount({ field: totalCountField, schema });\n }, [schema, shouldFallbackToAggregate, totalCountField]);\n\n const fetchMore = useCallback(\n (args: FetchMoreOptions): void => {\n if (isLoadingMoreRef.current || isReloadingRef.current) {\n return;\n }\n\n isLoadingMoreRef.current = true;\n setIsLoadingMore(true);\n\n const { limit } = args.variables;\n const offset = nextOffsetRef.current;\n\n fetchNextPageRef\n .current({\n ...args,\n query: fetchMoreDocumentRef.current,\n variables: {\n // fetchMore uses a count-free document, so Apollo will not inherit\n // the original operation's where/sort unless we pass them again.\n ...variablesRef.current,\n ...args.variables,\n offset,\n limit,\n },\n })\n .then(({ data: res }) => {\n const mappedFetchMoreResults = mapResults({\n data: res,\n entityNamePlural,\n isForm,\n schema,\n scope,\n defaultScope,\n });\n // Advance by the fetched page window (capped at limit), not by how many unique\n // rows survived client-side merge. Cap protects against Apollo returning a\n // merged cache blob larger than the requested page.\n const pageLength = mappedFetchMoreResults.results.length;\n nextOffsetRef.current = offset + (pageLength === 0 ? 0 : Math.min(pageLength, limit));\n\n setResult((prevRows) => {\n const merged = uniqBy(prop('_id'), [\n ...prevRows.results,\n ...mappedFetchMoreResults.results,\n ]) as Results['results'];\n\n // Empty/duplicate pages must end pagination, otherwise load-more loops forever\n // when aggregate count is ahead of rows that the where-clause can actually return.\n if (merged.length === prevRows.results.length) {\n return {\n count: prevRows.results.length,\n results: prevRows.results,\n } as Results;\n }\n\n // Count-free pagination pages report 0; the first page's total stands.\n return {\n count: mappedFetchMoreResults.count || prevRows.count,\n results: merged,\n } as Results;\n });\n })\n .catch((fetchError: unknown) => {\n console.error('Error fetching more data:', fetchError);\n })\n .finally(() => {\n isLoadingMoreRef.current = false;\n setIsLoadingMore(false);\n });\n },\n [defaultScope, entityNamePlural, isForm, schema, scope]\n );\n\n const reload = useCallback(\n (options?: { preserve?: boolean }): Promise<void> => {\n if (isReloadingRef.current) {\n return Promise.resolve();\n }\n\n const preserve = options?.preserve === true;\n\n isReloadingRef.current = true;\n isLoadingMoreRef.current = false;\n setIsLoadingMore(false);\n\n if (!preserve) {\n syncedQueryKeyRef.current = null;\n pendingQueryKeyRef.current = null;\n nextOffsetRef.current = 0;\n setIsReloading(true);\n setResult({ count: 0, results: [] });\n }\n\n return refetchRef\n .current()\n .then(({ data: res }) => {\n const queryKey = JSON.stringify({ entityNamePlural, scope, selection, includeCount, variables });\n const mapped = mapResults({ data: res, entityNamePlural, isForm, schema, scope, defaultScope });\n\n syncedQueryKeyRef.current = queryKey;\n pendingQueryKeyRef.current = null;\n nextOffsetRef.current = getVariablesOffset(variables) + mapped.results.length;\n setResult(mapped);\n })\n .catch((fetchError: unknown) => {\n console.error('Error reloading data:', fetchError);\n })\n .finally(() => {\n isReloadingRef.current = false;\n setIsReloading(false);\n });\n },\n [defaultScope, entityNamePlural, isForm, schema, scope, selection, includeCount, variables]\n );\n\n useEffect(() => {\n if (schemaMismatchMessage) {\n setSchemaErrorMessage(schemaMismatchMessage);\n\n return;\n }\n\n if (data && schemaErrorMessage && !effectiveError) {\n setSchemaErrorMessage(null);\n }\n }, [data, effectiveError, schemaErrorMessage, schemaMismatchMessage, setSchemaErrorMessage]);\n\n useEffect(() => {\n if (effectiveError || schemaMismatchMessage || isTotalCountFallbackLoading) {\n return;\n }\n\n const queryKey = JSON.stringify({ entityNamePlural, scope, selection, includeCount, variables });\n\n // Already synced for this query identity — ignore Apollo `data` updates from fetchMore.\n if (syncedQueryKeyRef.current === queryKey) {\n return;\n }\n\n if (isLoading && pendingQueryKeyRef.current !== queryKey) {\n pendingQueryKeyRef.current = queryKey;\n nextOffsetRef.current = 0;\n setResult({ count: 0, results: [] });\n\n return;\n }\n\n if (isLoading) {\n return;\n }\n\n const mapped = mapResults({ data, entityNamePlural, isForm, schema, scope, defaultScope });\n syncedQueryKeyRef.current = queryKey;\n pendingQueryKeyRef.current = null;\n nextOffsetRef.current = getVariablesOffset(variables) + mapped.results.length;\n setResult(mapped);\n }, [\n defaultScope,\n data,\n effectiveError,\n entityNamePlural,\n isForm,\n isLoading,\n isTotalCountFallbackLoading,\n schema,\n schemaMismatchMessage,\n scope,\n selection,\n includeCount,\n variables,\n ]);\n\n // After an Apollo refetch (delete/upload), replace accumulated pages with the\n // fresh first page. fetchMore uses NetworkStatus.fetchMore and is ignored.\n useEffect(() => {\n const previousStatus = previousNetworkStatusRef.current;\n previousNetworkStatusRef.current = networkStatus;\n\n if (effectiveError || schemaMismatchMessage || isReloadingRef.current || isTotalCountFallbackLoading) {\n return;\n }\n\n if (previousStatus !== NetworkStatus.refetch || networkStatus !== NetworkStatus.ready || !data) {\n return;\n }\n\n const queryKey = JSON.stringify({ entityNamePlural, scope, selection, includeCount, variables });\n const mapped = mapResults({ data, entityNamePlural, isForm, schema, scope, defaultScope });\n syncedQueryKeyRef.current = queryKey;\n pendingQueryKeyRef.current = null;\n nextOffsetRef.current = getVariablesOffset(variables) + mapped.results.length;\n setResult(mapped);\n }, [\n defaultScope,\n data,\n effectiveError,\n entityNamePlural,\n isForm,\n isTotalCountFallbackLoading,\n networkStatus,\n schema,\n schemaMismatchMessage,\n scope,\n selection,\n includeCount,\n variables,\n ]);\n\n // Soft-refresh after mutations (tags, deletes, uploads). Local paginated state\n // ignores Apollo cache writes, so we must refetch and remap explicitly.\n useEffect(() => {\n if (isForm) {\n return;\n }\n\n const listQueryName = `Get${getOperationEntityName(entityNamePlural)}`;\n\n const unsubscribeRefetch = subscribeEntityListRefetch((queryNames) => {\n if (!queryNames.has(listQueryName) || isLoadingMoreRef.current || isReloadingRef.current) {\n return;\n }\n\n return refetchRef\n .current()\n .then(({ data: res }) => {\n const queryKey = JSON.stringify({ entityNamePlural, scope, selection, includeCount, variables });\n const mapped = mapResults({ data: res, entityNamePlural, isForm, schema, scope, defaultScope });\n syncedQueryKeyRef.current = queryKey;\n pendingQueryKeyRef.current = null;\n nextOffsetRef.current = getVariablesOffset(variables) + mapped.results.length;\n setResult(mapped);\n })\n .catch((fetchError: unknown) => {\n console.error('Error soft-refreshing entity list:', fetchError);\n });\n });\n\n const unsubscribeRemoval = subscribeEntityListRemoval((queryName, entityIds) => {\n if (queryName !== listQueryName) {\n return;\n }\n\n setResult((prev) => {\n const nextResults = prev.results.filter((row) => {\n const rowId = typeof row._id === 'string' ? row._id : undefined;\n\n return !rowId || !entityIds.has(rowId);\n });\n const removedCount = prev.results.length - nextResults.length;\n\n if (removedCount === 0) {\n return prev;\n }\n\n return {\n count: Math.max(0, prev.count - removedCount),\n results: nextResults,\n } as Results;\n });\n });\n\n const unsubscribePatch = subscribeEntityListPatch((queryName, patches) => {\n if (queryName !== listQueryName) {\n return;\n }\n\n setResult((prev) => applyEntityListPatches(prev, patches, variables?.sort));\n });\n\n return () => {\n unsubscribeRefetch();\n unsubscribeRemoval();\n unsubscribePatch();\n };\n }, [defaultScope, entityNamePlural, isForm, schema, scope, selection, includeCount, variables]);\n\n return {\n // Refetch keeps existing rows visible; only initial load / explicit reload show as loading.\n isLoading:\n (isLoading && networkStatus !== NetworkStatus.refetch) || isReloading || isTotalCountFallbackLoading,\n isLoadingMore,\n fetchMore,\n reload,\n count: result.count,\n data: result.results,\n isProjectDisabled,\n isProjectReadOnly,\n schemaErrorMessage,\n };\n}\n\nfunction getVariablesOffset(variables: OperationVariables | undefined): number {\n const offset = variables?.offset;\n\n return typeof offset === 'number' && Number.isFinite(offset) ? offset : 0;\n}\n\nfunction mapResults(\n args: {\n data: (EntityQueryResults & EntityQueryAggregate) | undefined;\n defaultScope: string;\n } & UseEntityQueryParams\n): MappedEntityQueryResults | MappedFormEntityQueryResults {\n const entityNamePlural = args.entityNamePlural as keyof FormEntityItem;\n\n if (!args.data?.[entityNamePlural]) {\n return { count: 0, results: [] };\n }\n\n return args.isForm\n ? mapQueryResultForFormFields(args.entityNamePlural, args.scope, args.data, args.schema, args.defaultScope)\n : mapQueryResult(args.entityNamePlural, args.scope, args.data, args.schema);\n}\n\nfunction applyEntityListPatches(\n prev: Results,\n patches: EntityListRowPatch[],\n sort: unknown\n): Results {\n const patchById = new Map(patches.map((patch) => [patch._id, patch]));\n let didPatch = false;\n const nextResults = prev.results.map((row) => {\n const rowId = typeof row._id === 'string' ? row._id : undefined;\n\n if (!rowId) {\n return row;\n }\n\n const patch = patchById.get(rowId);\n\n if (!patch) {\n return row;\n }\n\n didPatch = true;\n\n return {\n ...row,\n ...patch.attributes,\n };\n });\n\n if (!didPatch) {\n return prev;\n }\n\n return {\n count: prev.count,\n results: sortEntityListResults(nextResults, sort),\n } as Results;\n}\n\nfunction sortEntityListResults<T extends { [key: string]: unknown }>(results: T[], sort: unknown): T[] {\n if (!Array.isArray(sort) || sort.length === 0) {\n return results;\n }\n\n const [primarySort] = sort;\n\n if (!primarySort || typeof primarySort !== 'object') {\n return results;\n }\n\n const [primarySortEntry] = Object.entries(primarySort as { [key: string]: unknown });\n const [sortField, sortDirection] = primarySortEntry ?? [];\n\n if (!sortField || (sortDirection !== 'ASC' && sortDirection !== 'DESC')) {\n return results;\n }\n\n const direction = sortDirection === 'DESC' ? -1 : 1;\n\n return [...results].sort((left, right) => {\n const leftValue = left[sortField];\n const rightValue = right[sortField];\n const leftText = typeof leftValue === 'string' ? leftValue : '';\n const rightText = typeof rightValue === 'string' ? rightValue : '';\n\n return leftText.localeCompare(rightText) * direction;\n });\n}\n"]}
@@ -1,2 +1,2 @@
1
- import'./index.css';import {a,c as c$1,d,f as f$1,g as g$1,e as e$1,i,h as h$2}from'./chunk-4ZWQ44NZ.js';import {b as b$1}from'./chunk-DSLPTDZX.js';import {h}from'./chunk-7KLXWCDS.js';import {f}from'./chunk-TI3EHLRE.js';import {ma}from'./chunk-RULCANNM.js';import {e,g,h as h$1,j as j$1,o,n}from'./chunk-A4DPLZZF.js';import {b}from'./chunk-5JUG4BEF.js';import {c}from'./chunk-X3SHNHHM.js';import {put}from'@vercel/blob/client';import {useMemo,useRef,useEffect,useState}from'react';import {LoaderCircle,EllipsisVerticalIcon,DownloadIcon,ExternalLinkIcon,Trash2Icon}from'lucide-react';import {mutate}from'swr';import {Document}from'@untitledui/file-icons/dist/solid/document.mjs';import {Docx}from'@untitledui/file-icons/dist/solid/docx.mjs';import {Html}from'@untitledui/file-icons/dist/solid/html.mjs';import {Pdf}from'@untitledui/file-icons/dist/solid/pdf.mjs';import {Pptx}from'@untitledui/file-icons/dist/solid/pptx.mjs';import {Txt}from'@untitledui/file-icons/dist/solid/txt.mjs';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var u=class extends Error{code;status;constructor(n,t,r=null){super(t),this.name="KnowledgeApiError",this.code=r,this.status=n;}},k=class extends Error{status;constructor(n,t="Request failed"){super(t),this.name="FetcherError",this.status=n;}},fe=async e=>{let n=await fetch(e,{credentials:"include"});if(!n.ok)throw new k(n.status);return await n.json()};function j(e){let n=`/api/flexkit/${e}/knowledge`;return {entitySources:t=>`${n}/entities/${encodeURIComponent(t)}/sources`,file:t=>`${n}/sources/${encodeURIComponent(t)}/file`,job:t=>`${n}/jobs/${encodeURIComponent(t)}`,links:t=>`${n}/sources/${encodeURIComponent(t)}/links`,passages:(t,{from:r,to:o})=>`${n}/sources/${encodeURIComponent(t)}/passages?from=${String(r)}&to=${String(o)}`,recordSources:({entity:t,recordId:r})=>`${n}/records/${encodeURIComponent(t)}/${encodeURIComponent(r)}/sources`,source:t=>`${n}/sources/${encodeURIComponent(t)}`,sources:(t={})=>{let{limit:r=25,offset:o=0,search:i,status:a}=t,l=new URLSearchParams({limit:r.toString(),offset:o.toString()}),c=i?.trim();return c&&l.set("q",c),a&&l.set("status",a),`${n}/sources?${l.toString()}`},spaces:`/api/flexkit/${e}/spaces`}}function N(e){return typeof e=="string"&&e.includes("/knowledge/sources?")}function J(e){return typeof e=="string"&&(e.includes("/knowledge/records/")||e.includes("/knowledge/entities/")||e.includes("/knowledge/sources/")&&e.endsWith("/links"))}async function L(e,n){let t={};try{t=await e.json();}catch{}return new u(e.status,t.error?String(t.error):n,t.code??null)}function O(e){let n=`/api/flexkit/${e}/knowledge`;async function t(o,i){let{fallback:a,...l}=i,c=await fetch(o,{credentials:"include",headers:{"Content-Type":"application/json",...l.headers??{}},...l});if(!c.ok)throw await L(c,a);return await c.json()}function r(o){return t(`${n}/sources`,{body:JSON.stringify(o),fallback:"The document could not be added.",method:"POST"})}return {addFile:async(o,i)=>{let a=await fetch(`${n}/uploads`,{body:JSON.stringify({filename:o.name,mediaType:o.type||null,sizeBytes:o.size}),credentials:"include",headers:{"Content-Type":"application/json"},method:"POST",signal:i?.signal});if(!a.ok)throw await L(a,"The file could not be uploaded.");let l=await a.json();if(!l.pathname||!l.token||!l.mediaType)throw new u(a.status,"The file could not be uploaded.");return await put(l.pathname,o,{abortSignal:i?.signal,access:"public",contentType:l.mediaType,token:l.token}),r({kind:"upload",pathname:l.pathname})},addUrl:({title:o,url:i})=>r({kind:"url",url:i,...o?{title:o}:{}}),addChatAttachment:({filename:o,url:i})=>r({filename:o,kind:"chat-attachment",url:i}),deleteSource:o=>t(`${n}/sources/${encodeURIComponent(o)}`,{fallback:"The document could not be removed.",method:"DELETE"}),linkSource:(o,i)=>t(`${n}/sources/${encodeURIComponent(o)}/links`,{body:JSON.stringify(i),fallback:"The document could not be attached.",method:"POST"}),reingestSource:o=>t(`${n}/sources/${encodeURIComponent(o)}/reingest`,{fallback:"The document could not be re-indexed.",method:"POST"}),unlinkSource:(o,{entity:i,recordId:a})=>t(`${n}/sources/${encodeURIComponent(o)}/links/${encodeURIComponent(i)}${a===void 0?"":`/${encodeURIComponent(a)}`}`,{fallback:"The document could not be detached.",method:"DELETE"}),updateSource:(o,i)=>t(`${n}/sources/${encodeURIComponent(o)}`,{body:JSON.stringify(i),fallback:"The document could not be updated.",method:"PATCH"})}}var ae={busy:"fk:bg-amber-500/15 fk:text-amber-700 fk:dark:text-amber-400",error:"fk:bg-destructive/15 fk:text-destructive",muted:"fk:bg-muted fk:text-muted-foreground",ready:"fk:bg-emerald-500/15 fk:text-emerald-700 fk:dark:text-emerald-400"};function le(){let{currentProjectId:e}=f();return {api:useMemo(()=>e?O(e):null,[e]),projectId:e}}function de(){return mutate(N,void 0,{revalidate:true})}function Pe(){return mutate(J,void 0,{revalidate:true})}function ce(e,n){return e instanceof u||e instanceof Error?e.message:n}function Ee(e,n){if(e.duplicate){ma.info(`"${e.source.title}" is already in Knowledge.`);return}ma.success(`Added ${n}. Indexing starts now.`);}function _e({children:e}){return jsx("div",{className:"fk:rounded-md fk:border fk:border-dashed fk:p-8 fk:text-center fk:text-sm fk:text-muted-foreground fk:corner-squircle",children:e})}function Me({label:e,tone:n}){return jsxs(b,{className:`fk:border-none fk:corner-squircle ${ae[n]}`,variant:"outline",children:[n==="busy"?jsx(LoaderCircle,{className:"fk:size-3 fk:animate-spin"}):null,e]})}var ue={document:Document,docx:Docx,html:Html,pdf:Pdf,pptx:Pptx,txt:Txt};function ge({className:e="",size:n=24,source:t}){let r=h(t),o=ue[r.icon];return jsx("span",{"aria-label":r.label,className:`fk:flex fk:shrink-0 fk:items-center fk:justify-center ${e}`,"data-knowledge-type":r.icon,role:"img",children:jsx(o,{size:n})})}function Ue({source:e}){return jsx(ge,{size:40,source:e})}function Le({onVisible:e}){let n=useRef(null),t=useRef(e);return t.current=e,useEffect(()=>{let r=n.current;if(!r)return;let o=new IntersectionObserver(i=>{i.some(a=>a.isIntersecting)&&t.current();});return o.observe(r),()=>{o.disconnect();}},[]),jsx("div",{"aria-hidden":true,className:"fk:h-px",ref:n})}function je({isBusy:e$2=false,onOpen:n$1,onRemoved:t,source:r,trigger:o$1="row"}){let{api:i$1,projectId:a$1}=le(),l=b$1(),[c$2,p]=useState(false),[f,b]=useState(false);if(!i$1||!a$1)return null;let X=i$1;async function H(){b(true);try{await X.deleteSource(r.id),ma.success(`Removed "${r.title}".`),p(!1),t(),de();}catch(w){ma.error(ce(w,"The document could not be removed."));}finally{b(false);}}return jsxs(Fragment,{children:[jsxs(e,{children:[jsx(g,{asChild:true,children:jsx(c,{"aria-label":`Actions for ${r.title}`,className:o$1==="row"?"fk:size-8 fk:shrink-0 fk:text-muted-foreground":void 0,"data-knowledge-menu":true,size:"icon-sm",variant:o$1==="row"?"ghost":"outline",children:jsx(EllipsisVerticalIcon,{className:"fk:size-4"})})}),jsxs(h$1,{align:"end",children:[n$1?jsx(j$1,{onSelect:n$1,children:"Open"}):null,r.path?jsx(j$1,{asChild:true,children:jsxs("a",{href:j(a$1).file(r.id),children:[jsx(DownloadIcon,{}),"Download"]})}):null,r.originUrl?jsx(j$1,{asChild:true,children:jsxs("a",{href:r.originUrl,rel:"noreferrer",target:"_blank",children:[jsx(ExternalLinkIcon,{}),"Open page"]})}):null,n$1||r.path||r.originUrl?jsx(o,{}):null,jsxs(j$1,{disabled:!l||e$2,variant:"destructive",onSelect:()=>p(true),children:[jsx(Trash2Icon,{}),"Remove"]}),l?null:jsx(n,{className:"fk:max-w-56 fk:whitespace-normal fk:text-xs fk:font-normal fk:text-muted-foreground",children:"Your member role cannot remove documents."})]})]}),jsx(a,{open:c$2,onOpenChange:p,children:jsxs(c$1,{children:[jsxs(d,{children:[jsx(f$1,{children:"Remove this document?"}),jsxs(g$1,{children:['"',r.title,'" and its indexed passages are deleted for everyone. Answers the agent gave earlier keep their citations, but the document can no longer be opened.']})]}),jsxs(e$1,{children:[jsx(i,{disabled:f,children:"Cancel"}),jsxs(h$2,{disabled:f,onClick:w=>{w.preventDefault(),H();},children:[f?jsx(LoaderCircle,{className:"fk:animate-spin"}):null,"Remove document"]})]})]})})]})}export{k as a,fe as b,j as c,O as d,le as e,de as f,Pe as g,ce as h,Ee as i,_e as j,Me as k,ge as l,Ue as m,Le as n,je as o};//# sourceMappingURL=chunk-7N3LTSVX.js.map
2
- //# sourceMappingURL=chunk-7N3LTSVX.js.map
1
+ import'./index.css';import {a,c as c$1,d,f as f$1,g as g$1,e as e$1,i,h as h$2}from'./chunk-4ZWQ44NZ.js';import {b as b$1}from'./chunk-DSLPTDZX.js';import {h}from'./chunk-7KLXWCDS.js';import {f}from'./chunk-CC2U7ASG.js';import {ma}from'./chunk-RULCANNM.js';import {e,g,h as h$1,j as j$1,o,n}from'./chunk-A4DPLZZF.js';import {b}from'./chunk-5JUG4BEF.js';import {c}from'./chunk-X3SHNHHM.js';import {put}from'@vercel/blob/client';import {useMemo,useRef,useEffect,useState}from'react';import {LoaderCircle,EllipsisVerticalIcon,DownloadIcon,ExternalLinkIcon,Trash2Icon}from'lucide-react';import {mutate}from'swr';import {Document}from'@untitledui/file-icons/dist/solid/document.mjs';import {Docx}from'@untitledui/file-icons/dist/solid/docx.mjs';import {Html}from'@untitledui/file-icons/dist/solid/html.mjs';import {Pdf}from'@untitledui/file-icons/dist/solid/pdf.mjs';import {Pptx}from'@untitledui/file-icons/dist/solid/pptx.mjs';import {Txt}from'@untitledui/file-icons/dist/solid/txt.mjs';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var u=class extends Error{code;status;constructor(n,t,r=null){super(t),this.name="KnowledgeApiError",this.code=r,this.status=n;}},k=class extends Error{status;constructor(n,t="Request failed"){super(t),this.name="FetcherError",this.status=n;}},fe=async e=>{let n=await fetch(e,{credentials:"include"});if(!n.ok)throw new k(n.status);return await n.json()};function j(e){let n=`/api/flexkit/${e}/knowledge`;return {entitySources:t=>`${n}/entities/${encodeURIComponent(t)}/sources`,file:t=>`${n}/sources/${encodeURIComponent(t)}/file`,job:t=>`${n}/jobs/${encodeURIComponent(t)}`,links:t=>`${n}/sources/${encodeURIComponent(t)}/links`,passages:(t,{from:r,to:o})=>`${n}/sources/${encodeURIComponent(t)}/passages?from=${String(r)}&to=${String(o)}`,recordSources:({entity:t,recordId:r})=>`${n}/records/${encodeURIComponent(t)}/${encodeURIComponent(r)}/sources`,source:t=>`${n}/sources/${encodeURIComponent(t)}`,sources:(t={})=>{let{limit:r=25,offset:o=0,search:i,status:a}=t,l=new URLSearchParams({limit:r.toString(),offset:o.toString()}),c=i?.trim();return c&&l.set("q",c),a&&l.set("status",a),`${n}/sources?${l.toString()}`},spaces:`/api/flexkit/${e}/spaces`}}function N(e){return typeof e=="string"&&e.includes("/knowledge/sources?")}function J(e){return typeof e=="string"&&(e.includes("/knowledge/records/")||e.includes("/knowledge/entities/")||e.includes("/knowledge/sources/")&&e.endsWith("/links"))}async function L(e,n){let t={};try{t=await e.json();}catch{}return new u(e.status,t.error?String(t.error):n,t.code??null)}function O(e){let n=`/api/flexkit/${e}/knowledge`;async function t(o,i){let{fallback:a,...l}=i,c=await fetch(o,{credentials:"include",headers:{"Content-Type":"application/json",...l.headers??{}},...l});if(!c.ok)throw await L(c,a);return await c.json()}function r(o){return t(`${n}/sources`,{body:JSON.stringify(o),fallback:"The document could not be added.",method:"POST"})}return {addFile:async(o,i)=>{let a=await fetch(`${n}/uploads`,{body:JSON.stringify({filename:o.name,mediaType:o.type||null,sizeBytes:o.size}),credentials:"include",headers:{"Content-Type":"application/json"},method:"POST",signal:i?.signal});if(!a.ok)throw await L(a,"The file could not be uploaded.");let l=await a.json();if(!l.pathname||!l.token||!l.mediaType)throw new u(a.status,"The file could not be uploaded.");return await put(l.pathname,o,{abortSignal:i?.signal,access:"public",contentType:l.mediaType,token:l.token}),r({kind:"upload",pathname:l.pathname})},addUrl:({title:o,url:i})=>r({kind:"url",url:i,...o?{title:o}:{}}),addChatAttachment:({filename:o,url:i})=>r({filename:o,kind:"chat-attachment",url:i}),deleteSource:o=>t(`${n}/sources/${encodeURIComponent(o)}`,{fallback:"The document could not be removed.",method:"DELETE"}),linkSource:(o,i)=>t(`${n}/sources/${encodeURIComponent(o)}/links`,{body:JSON.stringify(i),fallback:"The document could not be attached.",method:"POST"}),reingestSource:o=>t(`${n}/sources/${encodeURIComponent(o)}/reingest`,{fallback:"The document could not be re-indexed.",method:"POST"}),unlinkSource:(o,{entity:i,recordId:a})=>t(`${n}/sources/${encodeURIComponent(o)}/links/${encodeURIComponent(i)}${a===void 0?"":`/${encodeURIComponent(a)}`}`,{fallback:"The document could not be detached.",method:"DELETE"}),updateSource:(o,i)=>t(`${n}/sources/${encodeURIComponent(o)}`,{body:JSON.stringify(i),fallback:"The document could not be updated.",method:"PATCH"})}}var ae={busy:"fk:bg-amber-500/15 fk:text-amber-700 fk:dark:text-amber-400",error:"fk:bg-destructive/15 fk:text-destructive",muted:"fk:bg-muted fk:text-muted-foreground",ready:"fk:bg-emerald-500/15 fk:text-emerald-700 fk:dark:text-emerald-400"};function le(){let{currentProjectId:e}=f();return {api:useMemo(()=>e?O(e):null,[e]),projectId:e}}function de(){return mutate(N,void 0,{revalidate:true})}function Pe(){return mutate(J,void 0,{revalidate:true})}function ce(e,n){return e instanceof u||e instanceof Error?e.message:n}function Ee(e,n){if(e.duplicate){ma.info(`"${e.source.title}" is already in Knowledge.`);return}ma.success(`Added ${n}. Indexing starts now.`);}function _e({children:e}){return jsx("div",{className:"fk:rounded-md fk:border fk:border-dashed fk:p-8 fk:text-center fk:text-sm fk:text-muted-foreground fk:corner-squircle",children:e})}function Me({label:e,tone:n}){return jsxs(b,{className:`fk:border-none fk:corner-squircle ${ae[n]}`,variant:"outline",children:[n==="busy"?jsx(LoaderCircle,{className:"fk:size-3 fk:animate-spin"}):null,e]})}var ue={document:Document,docx:Docx,html:Html,pdf:Pdf,pptx:Pptx,txt:Txt};function ge({className:e="",size:n=24,source:t}){let r=h(t),o=ue[r.icon];return jsx("span",{"aria-label":r.label,className:`fk:flex fk:shrink-0 fk:items-center fk:justify-center ${e}`,"data-knowledge-type":r.icon,role:"img",children:jsx(o,{size:n})})}function Ue({source:e}){return jsx(ge,{size:40,source:e})}function Le({onVisible:e}){let n=useRef(null),t=useRef(e);return t.current=e,useEffect(()=>{let r=n.current;if(!r)return;let o=new IntersectionObserver(i=>{i.some(a=>a.isIntersecting)&&t.current();});return o.observe(r),()=>{o.disconnect();}},[]),jsx("div",{"aria-hidden":true,className:"fk:h-px",ref:n})}function je({isBusy:e$2=false,onOpen:n$1,onRemoved:t,source:r,trigger:o$1="row"}){let{api:i$1,projectId:a$1}=le(),l=b$1(),[c$2,p]=useState(false),[f,b]=useState(false);if(!i$1||!a$1)return null;let X=i$1;async function H(){b(true);try{await X.deleteSource(r.id),ma.success(`Removed "${r.title}".`),p(!1),t(),de();}catch(w){ma.error(ce(w,"The document could not be removed."));}finally{b(false);}}return jsxs(Fragment,{children:[jsxs(e,{children:[jsx(g,{asChild:true,children:jsx(c,{"aria-label":`Actions for ${r.title}`,className:o$1==="row"?"fk:size-8 fk:shrink-0 fk:text-muted-foreground":void 0,"data-knowledge-menu":true,size:"icon-sm",variant:o$1==="row"?"ghost":"outline",children:jsx(EllipsisVerticalIcon,{className:"fk:size-4"})})}),jsxs(h$1,{align:"end",children:[n$1?jsx(j$1,{onSelect:n$1,children:"Open"}):null,r.path?jsx(j$1,{asChild:true,children:jsxs("a",{href:j(a$1).file(r.id),children:[jsx(DownloadIcon,{}),"Download"]})}):null,r.originUrl?jsx(j$1,{asChild:true,children:jsxs("a",{href:r.originUrl,rel:"noreferrer",target:"_blank",children:[jsx(ExternalLinkIcon,{}),"Open page"]})}):null,n$1||r.path||r.originUrl?jsx(o,{}):null,jsxs(j$1,{disabled:!l||e$2,variant:"destructive",onSelect:()=>p(true),children:[jsx(Trash2Icon,{}),"Remove"]}),l?null:jsx(n,{className:"fk:max-w-56 fk:whitespace-normal fk:text-xs fk:font-normal fk:text-muted-foreground",children:"Your member role cannot remove documents."})]})]}),jsx(a,{open:c$2,onOpenChange:p,children:jsxs(c$1,{children:[jsxs(d,{children:[jsx(f$1,{children:"Remove this document?"}),jsxs(g$1,{children:['"',r.title,'" and its indexed passages are deleted for everyone. Answers the agent gave earlier keep their citations, but the document can no longer be opened.']})]}),jsxs(e$1,{children:[jsx(i,{disabled:f,children:"Cancel"}),jsxs(h$2,{disabled:f,onClick:w=>{w.preventDefault(),H();},children:[f?jsx(LoaderCircle,{className:"fk:animate-spin"}):null,"Remove document"]})]})]})})]})}export{k as a,fe as b,j as c,O as d,le as e,de as f,Pe as g,ce as h,Ee as i,_e as j,Me as k,ge as l,Ue as m,Le as n,je as o};//# sourceMappingURL=chunk-36YXPN42.js.map
2
+ //# sourceMappingURL=chunk-36YXPN42.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/apps/knowledge/api.ts","../src/apps/knowledge/shared.tsx"],"names":["KnowledgeApiError","status","message","code","FetcherError","fetcher","url","response","knowledgePaths","projectId","basePath","entity","sourceId","jobId","from","to","recordId","options","limit","offset","search","params","trimmedSearch","isKnowledgeListKey","key","isKnowledgeLinkKey","readError","fallback","data","createKnowledgeApi","request","init","requestInit","register","body","file","tokenResponse","tokenData","put","title","filename","target","patch","STATUS_TONE_CLASSES","useProjectKnowledge","currentProjectId","useConfig","useMemo","invalidateKnowledgeLists","mutateGlobal","invalidateKnowledgeLinks","describeApiError","error","announceRegistered","result","name","toast","PageMessage","children","jsx","StatusBadge","label","tone","jsxs","Badge","LoaderCircle","FILE_ICONS","Document","Docx","Html","Pdf","Pptx","Txt","KnowledgeTypeIcon","className","size","source","format","getKnowledgeFormat","Icon","SourceIcon","InfiniteScrollSentinel","onVisible","sentinelRef","useRef","onVisibleRef","useEffect","node","observer","entries","entry","SourceActionsMenu","isBusy","onOpen","onRemoved","trigger","api","canMutate","useCanMutate","isConfirmingRemoval","setIsConfirmingRemoval","useState","isRemoving","setIsRemoving","knowledgeApi","remove","removeError","Fragment","DropdownMenu","DropdownMenuTrigger","Button","EllipsisVerticalIcon","DropdownMenuContent","DropdownMenuItem","DownloadIcon","ExternalLinkIcon","DropdownMenuSeparator","Trash2Icon","DropdownMenuLabel","AlertDialog","AlertDialogContent","AlertDialogHeader","AlertDialogTitle","AlertDialogDescription","AlertDialogFooter","AlertDialogCancel","AlertDialogAction","event"],"mappings":"0gCAYO,IAAMA,CAAAA,CAAN,cAAgC,KAAM,CAC3C,IAAA,CACA,MAAA,CAEA,YAAYC,CAAAA,CAAgBC,CAAAA,CAAiBC,EAAsB,IAAA,CAAM,CACvE,MAAMD,CAAO,CAAA,CACb,IAAA,CAAK,IAAA,CAAO,oBACZ,IAAA,CAAK,IAAA,CAAOC,CAAAA,CACZ,IAAA,CAAK,OAASF,EAChB,CACF,CAAA,CAsBaG,CAAAA,CAAN,cAA2B,KAAM,CACtC,OAEA,WAAA,CAAYH,CAAAA,CAAgBC,EAAU,gBAAA,CAAkB,CACtD,KAAA,CAAMA,CAAO,EACb,IAAA,CAAK,IAAA,CAAO,cAAA,CACZ,IAAA,CAAK,OAASD,EAChB,CACF,CAAA,CAEaI,EAAAA,CAAU,MAAUC,CAAAA,EAA4B,CAC3D,IAAMC,CAAAA,CAAW,MAAM,MAAMD,CAAAA,CAAK,CAAE,WAAA,CAAa,SAAU,CAAC,CAAA,CAE5D,GAAI,CAACC,CAAAA,CAAS,EAAA,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CAAA,CAAa,SAAA,CAAU,iBAAA,CAAkB,EAAK,IAAA,CAAK,iBAAA,CAAA,CAEpE,GACF,CAAA,CAAA,CACF,CAAA,CACF,GACF,CAEJ","file":"chunk-7N3LTSVX.js","sourcesContent":["import { put } from '@vercel/blob/client';\nimport type {\n KnowledgeJob,\n KnowledgeLinkTarget,\n KnowledgeRecordRef,\n KnowledgeSource,\n KnowledgeSourcePatch,\n KnowledgeSourceStatus,\n RegisterKnowledgeSourceResult,\n} from './knowledge';\n\n/** The platform refused a knowledge request; `code` lets the UI tailor the message. */\nexport class KnowledgeApiError extends Error {\n code: string | null;\n status: number;\n\n constructor(status: number, message: string, code: string | null = null) {\n super(message);\n this.name = 'KnowledgeApiError';\n this.code = code;\n this.status = status;\n }\n}\n\nexport interface ProjectSpace {\n code: string;\n id: string;\n label: string;\n}\n\nexport interface KnowledgeApi {\n /** Uploads a document to the file store, then registers it; resolves once indexing is queued or the file was already there. */\n addFile: (_file: File, _options?: { signal?: AbortSignal }) => Promise<RegisterKnowledgeSourceResult>;\n addUrl: (_input: { title?: string; url: string }) => Promise<RegisterKnowledgeSourceResult>;\n /** Promotes a file the caller attached to a chat: the platform copies it into the knowledge folder. */\n addChatAttachment: (_input: { filename: string; url: string }) => Promise<RegisterKnowledgeSourceResult>;\n deleteSource: (_sourceId: string) => Promise<{ deleted: true }>;\n /** Attaches the document to a record, or to every record of an entity type; `linked` is false when it already was. */\n linkSource: (_sourceId: string, _target: KnowledgeLinkTarget) => Promise<{ linked: boolean }>;\n reingestSource: (_sourceId: string) => Promise<{ job: KnowledgeJob }>;\n unlinkSource: (_sourceId: string, _target: KnowledgeLinkTarget) => Promise<{ unlinked: boolean }>;\n updateSource: (_sourceId: string, _patch: KnowledgeSourcePatch) => Promise<{ source: KnowledgeSource }>;\n}\n\nexport class FetcherError extends Error {\n status: number;\n\n constructor(status: number, message = 'Request failed') {\n super(message);\n this.name = 'FetcherError';\n this.status = status;\n }\n}\n\nexport const fetcher = async <T>(url: string): Promise<T> => {\n const response = await fetch(url, { credentials: 'include' });\n\n if (!response.ok) {\n throw new FetcherError(response.status);\n }\n\n return (await response.json()) as T;\n};\n\nexport function knowledgePaths(projectId: string): {\n /** The documents attached to every record of an entity type. */\n entitySources: (_entity: string) => string;\n /** The original file of an uploaded document, served under its name. */\n file: (_sourceId: string) => string;\n job: (_jobId: string) => string;\n /** The records a document is attached to, and the entity types it applies to. */\n links: (_sourceId: string) => string;\n passages: (_sourceId: string, _options: { from: number; to: number }) => string;\n /** The documents attached to a record. */\n recordSources: (_record: KnowledgeRecordRef) => string;\n source: (_sourceId: string) => string;\n sources: (_options?: { limit?: number; offset?: number; search?: string; status?: KnowledgeSourceStatus }) => string;\n spaces: string;\n} {\n const basePath = `/api/flexkit/${projectId}/knowledge`;\n\n return {\n entitySources: (entity) => `${basePath}/entities/${encodeURIComponent(entity)}/sources`,\n file: (sourceId) => `${basePath}/sources/${encodeURIComponent(sourceId)}/file`,\n job: (jobId) => `${basePath}/jobs/${encodeURIComponent(jobId)}`,\n links: (sourceId) => `${basePath}/sources/${encodeURIComponent(sourceId)}/links`,\n passages: (sourceId, { from, to }) =>\n `${basePath}/sources/${encodeURIComponent(sourceId)}/passages?from=${String(from)}&to=${String(to)}`,\n recordSources: ({ entity, recordId }) =>\n `${basePath}/records/${encodeURIComponent(entity)}/${encodeURIComponent(recordId)}/sources`,\n source: (sourceId) => `${basePath}/sources/${encodeURIComponent(sourceId)}`,\n sources: (options = {}) => {\n const { limit = 25, offset = 0, search, status } = options;\n const params = new URLSearchParams({ limit: limit.toString(), offset: offset.toString() });\n const trimmedSearch = search?.trim();\n\n if (trimmedSearch) {\n params.set('q', trimmedSearch);\n }\n\n if (status) {\n params.set('status', status);\n }\n\n return `${basePath}/sources?${params.toString()}`;\n },\n spaces: `/api/flexkit/${projectId}/spaces`,\n };\n}\n\n/** Whether an SWR key is a page of the document list, whatever its filters. */\nexport function isKnowledgeListKey(key: unknown): boolean {\n return typeof key === 'string' && key.includes('/knowledge/sources?');\n}\n\n/** Whether an SWR key lists the documents of a record or an entity type, or the links of a document. */\nexport function isKnowledgeLinkKey(key: unknown): boolean {\n return (\n typeof key === 'string' &&\n (key.includes('/knowledge/records/') ||\n key.includes('/knowledge/entities/') ||\n (key.includes('/knowledge/sources/') && key.endsWith('/links')))\n );\n}\n\nasync function readError(response: Response, fallback: string): Promise<KnowledgeApiError> {\n let data: { code?: string; error?: string } = {};\n\n try {\n data = (await response.json()) as { code?: string; error?: string };\n } catch {\n // Non-JSON error bodies keep the fallback message.\n }\n\n return new KnowledgeApiError(response.status, data.error ? String(data.error) : fallback, data.code ?? null);\n}\n\nexport function createKnowledgeApi(projectId: string): KnowledgeApi {\n const basePath = `/api/flexkit/${projectId}/knowledge`;\n\n async function request<T>(url: string, init: RequestInit & { fallback: string }): Promise<T> {\n const { fallback, ...requestInit } = init;\n const response = await fetch(url, {\n credentials: 'include',\n headers: { 'Content-Type': 'application/json', ...(requestInit.headers ?? {}) },\n ...requestInit,\n });\n\n if (!response.ok) {\n throw await readError(response, fallback);\n }\n\n return (await response.json()) as T;\n }\n\n function register(body: Record<string, unknown>): Promise<RegisterKnowledgeSourceResult> {\n return request<RegisterKnowledgeSourceResult>(`${basePath}/sources`, {\n body: JSON.stringify(body),\n fallback: 'The document could not be added.',\n method: 'POST',\n });\n }\n\n return {\n addFile: async (file, options) => {\n // The platform issues a token pinned to one pathname, type and size; the\n // browser writes the bytes to the store itself, so a 20 MB document never\n // crosses the API function body limit. Registration then hashes the blob.\n const tokenResponse = await fetch(`${basePath}/uploads`, {\n body: JSON.stringify({ filename: file.name, mediaType: file.type || null, sizeBytes: file.size }),\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n method: 'POST',\n signal: options?.signal,\n });\n\n if (!tokenResponse.ok) {\n throw await readError(tokenResponse, 'The file could not be uploaded.');\n }\n\n const tokenData = (await tokenResponse.json()) as { mediaType?: string; pathname?: string; token?: string };\n\n if (!tokenData.pathname || !tokenData.token || !tokenData.mediaType) {\n throw new KnowledgeApiError(tokenResponse.status, 'The file could not be uploaded.');\n }\n\n await put(tokenData.pathname, file, {\n abortSignal: options?.signal,\n access: 'public',\n contentType: tokenData.mediaType,\n token: tokenData.token,\n });\n\n return register({ kind: 'upload', pathname: tokenData.pathname });\n },\n addUrl: ({ title, url }) => register({ kind: 'url', url, ...(title ? { title } : {}) }),\n addChatAttachment: ({ filename, url }) => register({ filename, kind: 'chat-attachment', url }),\n deleteSource: (sourceId) =>\n request<{ deleted: true }>(`${basePath}/sources/${encodeURIComponent(sourceId)}`, {\n fallback: 'The document could not be removed.',\n method: 'DELETE',\n }),\n linkSource: (sourceId, target) =>\n request<{ linked: boolean }>(`${basePath}/sources/${encodeURIComponent(sourceId)}/links`, {\n body: JSON.stringify(target),\n fallback: 'The document could not be attached.',\n method: 'POST',\n }),\n reingestSource: (sourceId) =>\n request<{ job: KnowledgeJob }>(`${basePath}/sources/${encodeURIComponent(sourceId)}/reingest`, {\n fallback: 'The document could not be re-indexed.',\n method: 'POST',\n }),\n unlinkSource: (sourceId, { entity, recordId }) =>\n request<{ unlinked: boolean }>(\n `${basePath}/sources/${encodeURIComponent(sourceId)}/links/${encodeURIComponent(entity)}${\n recordId === undefined ? '' : `/${encodeURIComponent(recordId)}`\n }`,\n { fallback: 'The document could not be detached.', method: 'DELETE' }\n ),\n updateSource: (sourceId, patch) =>\n request<{ source: KnowledgeSource }>(`${basePath}/sources/${encodeURIComponent(sourceId)}`, {\n body: JSON.stringify(patch),\n fallback: 'The document could not be updated.',\n method: 'PATCH',\n }),\n };\n}\n","import type { JSX, MouseEvent } from 'react';\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport { DownloadIcon, EllipsisVerticalIcon, ExternalLinkIcon, LoaderCircle, Trash2Icon } from 'lucide-react';\nimport { mutate as mutateGlobal } from 'swr';\n// File type icons: Untitled UI's free file icons, Solid variant. The set is\n// published as the MIT package `@untitledui/file-icons`; the page below shows\n// every icon and offers each as SVG or JSX should another format need one.\n// https://www.untitledui.com/resources/file-icons\nimport { Document } from '@untitledui/file-icons/dist/solid/document.mjs';\nimport { Docx } from '@untitledui/file-icons/dist/solid/docx.mjs';\nimport { Html } from '@untitledui/file-icons/dist/solid/html.mjs';\nimport { Pdf } from '@untitledui/file-icons/dist/solid/pdf.mjs';\nimport { Pptx } from '@untitledui/file-icons/dist/solid/pptx.mjs';\nimport { Txt } from '@untitledui/file-icons/dist/solid/txt.mjs';\nimport { useConfig } from '../../core/config/config-context';\nimport { useCanMutate } from '../../core/permissions';\nimport {\n Badge,\n Button,\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuLabel,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n toast,\n} from '../../ui';\nimport {\n AlertDialog,\n AlertDialogAction,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogTitle,\n} from '../../ui/primitives/alert-dialog';\nimport {\n createKnowledgeApi,\n isKnowledgeLinkKey,\n isKnowledgeListKey,\n KnowledgeApiError,\n knowledgePaths,\n type KnowledgeApi,\n} from './api';\nimport {\n getKnowledgeFormat,\n type KnowledgeFileIcon,\n type KnowledgeSource,\n type KnowledgeStatusTone,\n type RegisterKnowledgeSourceResult,\n} from './knowledge';\n\nconst STATUS_TONE_CLASSES: { [tone in KnowledgeStatusTone]: string } = {\n busy: 'fk:bg-amber-500/15 fk:text-amber-700 fk:dark:text-amber-400',\n error: 'fk:bg-destructive/15 fk:text-destructive',\n muted: 'fk:bg-muted fk:text-muted-foreground',\n ready: 'fk:bg-emerald-500/15 fk:text-emerald-700 fk:dark:text-emerald-400',\n};\n\nexport function useProjectKnowledge(): { api: KnowledgeApi | null; projectId: string | undefined } {\n const { currentProjectId } = useConfig();\n const api = useMemo(() => (currentProjectId ? createKnowledgeApi(currentProjectId) : null), [currentProjectId]);\n\n return { api, projectId: currentProjectId };\n}\n\n/** Drops every cached page of the document list, so the next visit fetches it afresh. */\nexport function invalidateKnowledgeLists(): Promise<unknown> {\n return mutateGlobal(isKnowledgeListKey, undefined, { revalidate: true });\n}\n\n/** Drops every cached link listing (a record's documents, a document's records) after a link changed. */\nexport function invalidateKnowledgeLinks(): Promise<unknown> {\n return mutateGlobal(isKnowledgeLinkKey, undefined, { revalidate: true });\n}\n\nexport function describeApiError(error: unknown, fallback: string): string {\n if (error instanceof KnowledgeApiError) {\n return error.message;\n }\n\n return error instanceof Error ? error.message : fallback;\n}\n\n/** What the user hears once a document was registered. */\nexport function announceRegistered(result: RegisterKnowledgeSourceResult, name: string): void {\n if (result.duplicate) {\n toast.info(`\"${result.source.title}\" is already in Knowledge.`);\n\n return;\n }\n\n toast.success(`Added ${name}. Indexing starts now.`);\n}\n\nexport function PageMessage({ children }: { children: string }): JSX.Element {\n return (\n <div className=\"fk:rounded-md fk:border fk:border-dashed fk:p-8 fk:text-center fk:text-sm fk:text-muted-foreground fk:corner-squircle\">\n {children}\n </div>\n );\n}\n\nexport function StatusBadge({ label, tone }: { label: string; tone: KnowledgeStatusTone }): JSX.Element {\n return (\n <Badge className={`fk:border-none fk:corner-squircle ${STATUS_TONE_CLASSES[tone]}`} variant=\"outline\">\n {tone === 'busy' ? <LoaderCircle className=\"fk:size-3 fk:animate-spin\" /> : null}\n {label}\n </Badge>\n );\n}\n\nconst FILE_ICONS: { [icon in KnowledgeFileIcon]: typeof Pdf } = {\n document: Document,\n docx: Docx,\n html: Html,\n pdf: Pdf,\n pptx: Pptx,\n txt: Txt,\n};\n\n/** The document's format as its file icon; the format's name is what a screen reader hears. */\nexport function KnowledgeTypeIcon({\n className = '',\n size = 24,\n source,\n}: {\n className?: string;\n size?: number;\n source: Pick<KnowledgeSource, 'kind' | 'mimeType'>;\n}): JSX.Element {\n const format = getKnowledgeFormat(source);\n const Icon = FILE_ICONS[format.icon];\n\n return (\n <span\n aria-label={format.label}\n className={`fk:flex fk:shrink-0 fk:items-center fk:justify-center ${className}`}\n data-knowledge-type={format.icon}\n role=\"img\"\n >\n <Icon size={size} />\n </span>\n );\n}\n\n/** The larger file icon of the document page and the record panel: the same icon as the list, at 40px. */\nexport function SourceIcon({ source }: { source: Pick<KnowledgeSource, 'kind' | 'mimeType'> }): JSX.Element {\n return <KnowledgeTypeIcon size={40} source={source} />;\n}\n\nexport function InfiniteScrollSentinel({ onVisible }: { onVisible: () => void }): JSX.Element {\n const sentinelRef = useRef<HTMLDivElement>(null);\n const onVisibleRef = useRef(onVisible);\n\n onVisibleRef.current = onVisible;\n\n useEffect(() => {\n const node = sentinelRef.current;\n\n if (!node) {\n return;\n }\n\n const observer = new IntersectionObserver((entries) => {\n if (entries.some((entry) => entry.isIntersecting)) {\n onVisibleRef.current();\n }\n });\n\n observer.observe(node);\n\n return () => {\n observer.disconnect();\n };\n }, []);\n\n return <div aria-hidden className=\"fk:h-px\" ref={sentinelRef} />;\n}\n\n/**\n * The actions of one document, behind a three-dots button: open (lists\n * only), download the original file (web pages open their address instead)\n * and remove, behind one confirmation. The list and the document page share\n * it so the copy, the download link and the busy rules stay the same.\n */\nexport function SourceActionsMenu({\n isBusy = false,\n onOpen,\n onRemoved,\n source,\n trigger = 'row',\n}: {\n /** Another action on the document is in flight; removing waits for it. */\n isBusy?: boolean;\n /** Offered as the first item when given (the document page is already open). */\n onOpen?: () => void;\n /** The document is gone: drop it from the list, or leave its page. The list invalidation is done here. */\n onRemoved: () => void;\n source: KnowledgeSource;\n /** How the button looks: a quiet icon in a row or card, an outlined one next to page actions. */\n trigger?: 'row' | 'page';\n}): JSX.Element | null {\n const { api, projectId } = useProjectKnowledge();\n const canMutate = useCanMutate();\n const [isConfirmingRemoval, setIsConfirmingRemoval] = useState(false);\n const [isRemoving, setIsRemoving] = useState(false);\n\n if (!api || !projectId) {\n return null;\n }\n\n const knowledgeApi = api;\n\n async function remove(): Promise<void> {\n setIsRemoving(true);\n\n try {\n await knowledgeApi.deleteSource(source.id);\n toast.success(`Removed \"${source.title}\".`);\n setIsConfirmingRemoval(false);\n onRemoved();\n void invalidateKnowledgeLists();\n } catch (removeError) {\n toast.error(describeApiError(removeError, 'The document could not be removed.'));\n } finally {\n setIsRemoving(false);\n }\n }\n\n return (\n <>\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n aria-label={`Actions for ${source.title}`}\n className={trigger === 'row' ? 'fk:size-8 fk:shrink-0 fk:text-muted-foreground' : undefined}\n data-knowledge-menu\n size=\"icon-sm\"\n variant={trigger === 'row' ? 'ghost' : 'outline'}\n >\n <EllipsisVerticalIcon className=\"fk:size-4\" />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n {onOpen ? <DropdownMenuItem onSelect={onOpen}>Open</DropdownMenuItem> : null}\n {source.path ? (\n <DropdownMenuItem asChild>\n <a href={knowledgePaths(projectId).file(source.id)}>\n <DownloadIcon />\n Download\n </a>\n </DropdownMenuItem>\n ) : null}\n {source.originUrl ? (\n <DropdownMenuItem asChild>\n <a href={source.originUrl} rel=\"noreferrer\" target=\"_blank\">\n <ExternalLinkIcon />\n Open page\n </a>\n </DropdownMenuItem>\n ) : null}\n {onOpen || source.path || source.originUrl ? <DropdownMenuSeparator /> : null}\n <DropdownMenuItem\n disabled={!canMutate || isBusy}\n variant=\"destructive\"\n onSelect={() => setIsConfirmingRemoval(true)}\n >\n <Trash2Icon />\n Remove\n </DropdownMenuItem>\n {canMutate ? null : (\n <DropdownMenuLabel className=\"fk:max-w-56 fk:whitespace-normal fk:text-xs fk:font-normal fk:text-muted-foreground\">\n Your member role cannot remove documents.\n </DropdownMenuLabel>\n )}\n </DropdownMenuContent>\n </DropdownMenu>\n <AlertDialog open={isConfirmingRemoval} onOpenChange={setIsConfirmingRemoval}>\n <AlertDialogContent>\n <AlertDialogHeader>\n <AlertDialogTitle>Remove this document?</AlertDialogTitle>\n <AlertDialogDescription>\n \"{source.title}\" and its indexed passages are deleted for everyone. Answers the agent gave earlier keep\n their citations, but the document can no longer be opened.\n </AlertDialogDescription>\n </AlertDialogHeader>\n <AlertDialogFooter>\n <AlertDialogCancel disabled={isRemoving}>Cancel</AlertDialogCancel>\n <AlertDialogAction\n disabled={isRemoving}\n onClick={(event: MouseEvent) => {\n event.preventDefault();\n void remove();\n }}\n >\n {isRemoving ? <LoaderCircle className=\"fk:animate-spin\" /> : null}\n Remove document\n </AlertDialogAction>\n </AlertDialogFooter>\n </AlertDialogContent>\n </AlertDialog>\n </>\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/apps/knowledge/api.ts","../src/apps/knowledge/shared.tsx"],"names":["KnowledgeApiError","status","message","code","FetcherError","fetcher","url","response","knowledgePaths","projectId","basePath","entity","sourceId","jobId","from","to","recordId","options","limit","offset","search","params","trimmedSearch","isKnowledgeListKey","key","isKnowledgeLinkKey","readError","fallback","data","createKnowledgeApi","request","init","requestInit","register","body","file","tokenResponse","tokenData","put","title","filename","target","patch","STATUS_TONE_CLASSES","useProjectKnowledge","currentProjectId","useConfig","useMemo","invalidateKnowledgeLists","mutateGlobal","invalidateKnowledgeLinks","describeApiError","error","announceRegistered","result","name","toast","PageMessage","children","jsx","StatusBadge","label","tone","jsxs","Badge","LoaderCircle","FILE_ICONS","Document","Docx","Html","Pdf","Pptx","Txt","KnowledgeTypeIcon","className","size","source","format","getKnowledgeFormat","Icon","SourceIcon","InfiniteScrollSentinel","onVisible","sentinelRef","useRef","onVisibleRef","useEffect","node","observer","entries","entry","SourceActionsMenu","isBusy","onOpen","onRemoved","trigger","api","canMutate","useCanMutate","isConfirmingRemoval","setIsConfirmingRemoval","useState","isRemoving","setIsRemoving","knowledgeApi","remove","removeError","Fragment","DropdownMenu","DropdownMenuTrigger","Button","EllipsisVerticalIcon","DropdownMenuContent","DropdownMenuItem","DownloadIcon","ExternalLinkIcon","DropdownMenuSeparator","Trash2Icon","DropdownMenuLabel","AlertDialog","AlertDialogContent","AlertDialogHeader","AlertDialogTitle","AlertDialogDescription","AlertDialogFooter","AlertDialogCancel","AlertDialogAction","event"],"mappings":"0gCAYO,IAA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AAAA,CACpD,QAAA,CAAArC,KAACyD,GAAAA,CAAA,CACC,UAAAzD,IAAAA,CAAC0D,CAAAA,CAAA,CACC,QAAA,CAAA,CAAA9D,GAAAA,CAAC+D,GAAAA,CAAA,CAAiB,iCAAqB,CAAA,CACvC3D,IAAAA,CAAC4D,IAAA,CAAuB,QAAA,CAAA,CAAA,GAAA,CACpB/C,EAAO,KAAA,CAAM,qJAAA,CAAA,CAEjB,CAAA,CAAA,CACF,CAAA,CACAb,KAAC6D,GAAAA,CAAA,CACC,QAAA,CAAA,CAAAjE,GAAAA,CAACkE,EAAA,CAAkB,QAAA,CAAUvB,CAAAA,CAAY,QAAA,CAAA,QAAA,CAAM,EAC/CvC,IAAAA,CAAC+D,GAAAA,CAAA,CACC,QAAA,CAAUxB,CAAAA,CACV,QAAUyB,CAAAA,EAAsB,CAC9BA,CAAAA,CAAM,cAAA,GACDtB,CAAAA,GACP,EAEC,QAAA,CAAA,CAAAH,CAAAA,CAAa3C,IAACM,YAAAA,CAAA,CAAa,SAAA,CAAU,iBAAA,CAAkB,EAAK,IAAA,CAAK,iBAAA,CAAA,CAEpE,GACF,CAAA,CAAA,CACF,CAAA,CACF,GACF,CAEJ","file":"chunk-36YXPN42.js","sourcesContent":["import { put } from '@vercel/blob/client';\nimport type {\n KnowledgeJob,\n KnowledgeLinkTarget,\n KnowledgeRecordRef,\n KnowledgeSource,\n KnowledgeSourcePatch,\n KnowledgeSourceStatus,\n RegisterKnowledgeSourceResult,\n} from './knowledge';\n\n/** The platform refused a knowledge request; `code` lets the UI tailor the message. */\nexport class KnowledgeApiError extends Error {\n code: string | null;\n status: number;\n\n constructor(status: number, message: string, code: string | null = null) {\n super(message);\n this.name = 'KnowledgeApiError';\n this.code = code;\n this.status = status;\n }\n}\n\nexport interface ProjectSpace {\n code: string;\n id: string;\n label: string;\n}\n\nexport interface KnowledgeApi {\n /** Uploads a document to the file store, then registers it; resolves once indexing is queued or the file was already there. */\n addFile: (_file: File, _options?: { signal?: AbortSignal }) => Promise<RegisterKnowledgeSourceResult>;\n addUrl: (_input: { title?: string; url: string }) => Promise<RegisterKnowledgeSourceResult>;\n /** Promotes a file the caller attached to a chat: the platform copies it into the knowledge folder. */\n addChatAttachment: (_input: { filename: string; url: string }) => Promise<RegisterKnowledgeSourceResult>;\n deleteSource: (_sourceId: string) => Promise<{ deleted: true }>;\n /** Attaches the document to a record, or to every record of an entity type; `linked` is false when it already was. */\n linkSource: (_sourceId: string, _target: KnowledgeLinkTarget) => Promise<{ linked: boolean }>;\n reingestSource: (_sourceId: string) => Promise<{ job: KnowledgeJob }>;\n unlinkSource: (_sourceId: string, _target: KnowledgeLinkTarget) => Promise<{ unlinked: boolean }>;\n updateSource: (_sourceId: string, _patch: KnowledgeSourcePatch) => Promise<{ source: KnowledgeSource }>;\n}\n\nexport class FetcherError extends Error {\n status: number;\n\n constructor(status: number, message = 'Request failed') {\n super(message);\n this.name = 'FetcherError';\n this.status = status;\n }\n}\n\nexport const fetcher = async <T>(url: string): Promise<T> => {\n const response = await fetch(url, { credentials: 'include' });\n\n if (!response.ok) {\n throw new FetcherError(response.status);\n }\n\n return (await response.json()) as T;\n};\n\nexport function knowledgePaths(projectId: string): {\n /** The documents attached to every record of an entity type. */\n entitySources: (_entity: string) => string;\n /** The original file of an uploaded document, served under its name. */\n file: (_sourceId: string) => string;\n job: (_jobId: string) => string;\n /** The records a document is attached to, and the entity types it applies to. */\n links: (_sourceId: string) => string;\n passages: (_sourceId: string, _options: { from: number; to: number }) => string;\n /** The documents attached to a record. */\n recordSources: (_record: KnowledgeRecordRef) => string;\n source: (_sourceId: string) => string;\n sources: (_options?: { limit?: number; offset?: number; search?: string; status?: KnowledgeSourceStatus }) => string;\n spaces: string;\n} {\n const basePath = `/api/flexkit/${projectId}/knowledge`;\n\n return {\n entitySources: (entity) => `${basePath}/entities/${encodeURIComponent(entity)}/sources`,\n file: (sourceId) => `${basePath}/sources/${encodeURIComponent(sourceId)}/file`,\n job: (jobId) => `${basePath}/jobs/${encodeURIComponent(jobId)}`,\n links: (sourceId) => `${basePath}/sources/${encodeURIComponent(sourceId)}/links`,\n passages: (sourceId, { from, to }) =>\n `${basePath}/sources/${encodeURIComponent(sourceId)}/passages?from=${String(from)}&to=${String(to)}`,\n recordSources: ({ entity, recordId }) =>\n `${basePath}/records/${encodeURIComponent(entity)}/${encodeURIComponent(recordId)}/sources`,\n source: (sourceId) => `${basePath}/sources/${encodeURIComponent(sourceId)}`,\n sources: (options = {}) => {\n const { limit = 25, offset = 0, search, status } = options;\n const params = new URLSearchParams({ limit: limit.toString(), offset: offset.toString() });\n const trimmedSearch = search?.trim();\n\n if (trimmedSearch) {\n params.set('q', trimmedSearch);\n }\n\n if (status) {\n params.set('status', status);\n }\n\n return `${basePath}/sources?${params.toString()}`;\n },\n spaces: `/api/flexkit/${projectId}/spaces`,\n };\n}\n\n/** Whether an SWR key is a page of the document list, whatever its filters. */\nexport function isKnowledgeListKey(key: unknown): boolean {\n return typeof key === 'string' && key.includes('/knowledge/sources?');\n}\n\n/** Whether an SWR key lists the documents of a record or an entity type, or the links of a document. */\nexport function isKnowledgeLinkKey(key: unknown): boolean {\n return (\n typeof key === 'string' &&\n (key.includes('/knowledge/records/') ||\n key.includes('/knowledge/entities/') ||\n (key.includes('/knowledge/sources/') && key.endsWith('/links')))\n );\n}\n\nasync function readError(response: Response, fallback: string): Promise<KnowledgeApiError> {\n let data: { code?: string; error?: string } = {};\n\n try {\n data = (await response.json()) as { code?: string; error?: string };\n } catch {\n // Non-JSON error bodies keep the fallback message.\n }\n\n return new KnowledgeApiError(response.status, data.error ? String(data.error) : fallback, data.code ?? null);\n}\n\nexport function createKnowledgeApi(projectId: string): KnowledgeApi {\n const basePath = `/api/flexkit/${projectId}/knowledge`;\n\n async function request<T>(url: string, init: RequestInit & { fallback: string }): Promise<T> {\n const { fallback, ...requestInit } = init;\n const response = await fetch(url, {\n credentials: 'include',\n headers: { 'Content-Type': 'application/json', ...(requestInit.headers ?? {}) },\n ...requestInit,\n });\n\n if (!response.ok) {\n throw await readError(response, fallback);\n }\n\n return (await response.json()) as T;\n }\n\n function register(body: Record<string, unknown>): Promise<RegisterKnowledgeSourceResult> {\n return request<RegisterKnowledgeSourceResult>(`${basePath}/sources`, {\n body: JSON.stringify(body),\n fallback: 'The document could not be added.',\n method: 'POST',\n });\n }\n\n return {\n addFile: async (file, options) => {\n // The platform issues a token pinned to one pathname, type and size; the\n // browser writes the bytes to the store itself, so a 20 MB document never\n // crosses the API function body limit. Registration then hashes the blob.\n const tokenResponse = await fetch(`${basePath}/uploads`, {\n body: JSON.stringify({ filename: file.name, mediaType: file.type || null, sizeBytes: file.size }),\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n method: 'POST',\n signal: options?.signal,\n });\n\n if (!tokenResponse.ok) {\n throw await readError(tokenResponse, 'The file could not be uploaded.');\n }\n\n const tokenData = (await tokenResponse.json()) as { mediaType?: string; pathname?: string; token?: string };\n\n if (!tokenData.pathname || !tokenData.token || !tokenData.mediaType) {\n throw new KnowledgeApiError(tokenResponse.status, 'The file could not be uploaded.');\n }\n\n await put(tokenData.pathname, file, {\n abortSignal: options?.signal,\n access: 'public',\n contentType: tokenData.mediaType,\n token: tokenData.token,\n });\n\n return register({ kind: 'upload', pathname: tokenData.pathname });\n },\n addUrl: ({ title, url }) => register({ kind: 'url', url, ...(title ? { title } : {}) }),\n addChatAttachment: ({ filename, url }) => register({ filename, kind: 'chat-attachment', url }),\n deleteSource: (sourceId) =>\n request<{ deleted: true }>(`${basePath}/sources/${encodeURIComponent(sourceId)}`, {\n fallback: 'The document could not be removed.',\n method: 'DELETE',\n }),\n linkSource: (sourceId, target) =>\n request<{ linked: boolean }>(`${basePath}/sources/${encodeURIComponent(sourceId)}/links`, {\n body: JSON.stringify(target),\n fallback: 'The document could not be attached.',\n method: 'POST',\n }),\n reingestSource: (sourceId) =>\n request<{ job: KnowledgeJob }>(`${basePath}/sources/${encodeURIComponent(sourceId)}/reingest`, {\n fallback: 'The document could not be re-indexed.',\n method: 'POST',\n }),\n unlinkSource: (sourceId, { entity, recordId }) =>\n request<{ unlinked: boolean }>(\n `${basePath}/sources/${encodeURIComponent(sourceId)}/links/${encodeURIComponent(entity)}${\n recordId === undefined ? '' : `/${encodeURIComponent(recordId)}`\n }`,\n { fallback: 'The document could not be detached.', method: 'DELETE' }\n ),\n updateSource: (sourceId, patch) =>\n request<{ source: KnowledgeSource }>(`${basePath}/sources/${encodeURIComponent(sourceId)}`, {\n body: JSON.stringify(patch),\n fallback: 'The document could not be updated.',\n method: 'PATCH',\n }),\n };\n}\n","import type { JSX, MouseEvent } from 'react';\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport { DownloadIcon, EllipsisVerticalIcon, ExternalLinkIcon, LoaderCircle, Trash2Icon } from 'lucide-react';\nimport { mutate as mutateGlobal } from 'swr';\n// File type icons: Untitled UI's free file icons, Solid variant. The set is\n// published as the MIT package `@untitledui/file-icons`; the page below shows\n// every icon and offers each as SVG or JSX should another format need one.\n// https://www.untitledui.com/resources/file-icons\nimport { Document } from '@untitledui/file-icons/dist/solid/document.mjs';\nimport { Docx } from '@untitledui/file-icons/dist/solid/docx.mjs';\nimport { Html } from '@untitledui/file-icons/dist/solid/html.mjs';\nimport { Pdf } from '@untitledui/file-icons/dist/solid/pdf.mjs';\nimport { Pptx } from '@untitledui/file-icons/dist/solid/pptx.mjs';\nimport { Txt } from '@untitledui/file-icons/dist/solid/txt.mjs';\nimport { useConfig } from '../../core/config/config-context';\nimport { useCanMutate } from '../../core/permissions';\nimport {\n Badge,\n Button,\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuLabel,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n toast,\n} from '../../ui';\nimport {\n AlertDialog,\n AlertDialogAction,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogTitle,\n} from '../../ui/primitives/alert-dialog';\nimport {\n createKnowledgeApi,\n isKnowledgeLinkKey,\n isKnowledgeListKey,\n KnowledgeApiError,\n knowledgePaths,\n type KnowledgeApi,\n} from './api';\nimport {\n getKnowledgeFormat,\n type KnowledgeFileIcon,\n type KnowledgeSource,\n type KnowledgeStatusTone,\n type RegisterKnowledgeSourceResult,\n} from './knowledge';\n\nconst STATUS_TONE_CLASSES: { [tone in KnowledgeStatusTone]: string } = {\n busy: 'fk:bg-amber-500/15 fk:text-amber-700 fk:dark:text-amber-400',\n error: 'fk:bg-destructive/15 fk:text-destructive',\n muted: 'fk:bg-muted fk:text-muted-foreground',\n ready: 'fk:bg-emerald-500/15 fk:text-emerald-700 fk:dark:text-emerald-400',\n};\n\nexport function useProjectKnowledge(): { api: KnowledgeApi | null; projectId: string | undefined } {\n const { currentProjectId } = useConfig();\n const api = useMemo(() => (currentProjectId ? createKnowledgeApi(currentProjectId) : null), [currentProjectId]);\n\n return { api, projectId: currentProjectId };\n}\n\n/** Drops every cached page of the document list, so the next visit fetches it afresh. */\nexport function invalidateKnowledgeLists(): Promise<unknown> {\n return mutateGlobal(isKnowledgeListKey, undefined, { revalidate: true });\n}\n\n/** Drops every cached link listing (a record's documents, a document's records) after a link changed. */\nexport function invalidateKnowledgeLinks(): Promise<unknown> {\n return mutateGlobal(isKnowledgeLinkKey, undefined, { revalidate: true });\n}\n\nexport function describeApiError(error: unknown, fallback: string): string {\n if (error instanceof KnowledgeApiError) {\n return error.message;\n }\n\n return error instanceof Error ? error.message : fallback;\n}\n\n/** What the user hears once a document was registered. */\nexport function announceRegistered(result: RegisterKnowledgeSourceResult, name: string): void {\n if (result.duplicate) {\n toast.info(`\"${result.source.title}\" is already in Knowledge.`);\n\n return;\n }\n\n toast.success(`Added ${name}. Indexing starts now.`);\n}\n\nexport function PageMessage({ children }: { children: string }): JSX.Element {\n return (\n <div className=\"fk:rounded-md fk:border fk:border-dashed fk:p-8 fk:text-center fk:text-sm fk:text-muted-foreground fk:corner-squircle\">\n {children}\n </div>\n );\n}\n\nexport function StatusBadge({ label, tone }: { label: string; tone: KnowledgeStatusTone }): JSX.Element {\n return (\n <Badge className={`fk:border-none fk:corner-squircle ${STATUS_TONE_CLASSES[tone]}`} variant=\"outline\">\n {tone === 'busy' ? <LoaderCircle className=\"fk:size-3 fk:animate-spin\" /> : null}\n {label}\n </Badge>\n );\n}\n\nconst FILE_ICONS: { [icon in KnowledgeFileIcon]: typeof Pdf } = {\n document: Document,\n docx: Docx,\n html: Html,\n pdf: Pdf,\n pptx: Pptx,\n txt: Txt,\n};\n\n/** The document's format as its file icon; the format's name is what a screen reader hears. */\nexport function KnowledgeTypeIcon({\n className = '',\n size = 24,\n source,\n}: {\n className?: string;\n size?: number;\n source: Pick<KnowledgeSource, 'kind' | 'mimeType'>;\n}): JSX.Element {\n const format = getKnowledgeFormat(source);\n const Icon = FILE_ICONS[format.icon];\n\n return (\n <span\n aria-label={format.label}\n className={`fk:flex fk:shrink-0 fk:items-center fk:justify-center ${className}`}\n data-knowledge-type={format.icon}\n role=\"img\"\n >\n <Icon size={size} />\n </span>\n );\n}\n\n/** The larger file icon of the document page and the record panel: the same icon as the list, at 40px. */\nexport function SourceIcon({ source }: { source: Pick<KnowledgeSource, 'kind' | 'mimeType'> }): JSX.Element {\n return <KnowledgeTypeIcon size={40} source={source} />;\n}\n\nexport function InfiniteScrollSentinel({ onVisible }: { onVisible: () => void }): JSX.Element {\n const sentinelRef = useRef<HTMLDivElement>(null);\n const onVisibleRef = useRef(onVisible);\n\n onVisibleRef.current = onVisible;\n\n useEffect(() => {\n const node = sentinelRef.current;\n\n if (!node) {\n return;\n }\n\n const observer = new IntersectionObserver((entries) => {\n if (entries.some((entry) => entry.isIntersecting)) {\n onVisibleRef.current();\n }\n });\n\n observer.observe(node);\n\n return () => {\n observer.disconnect();\n };\n }, []);\n\n return <div aria-hidden className=\"fk:h-px\" ref={sentinelRef} />;\n}\n\n/**\n * The actions of one document, behind a three-dots button: open (lists\n * only), download the original file (web pages open their address instead)\n * and remove, behind one confirmation. The list and the document page share\n * it so the copy, the download link and the busy rules stay the same.\n */\nexport function SourceActionsMenu({\n isBusy = false,\n onOpen,\n onRemoved,\n source,\n trigger = 'row',\n}: {\n /** Another action on the document is in flight; removing waits for it. */\n isBusy?: boolean;\n /** Offered as the first item when given (the document page is already open). */\n onOpen?: () => void;\n /** The document is gone: drop it from the list, or leave its page. The list invalidation is done here. */\n onRemoved: () => void;\n source: KnowledgeSource;\n /** How the button looks: a quiet icon in a row or card, an outlined one next to page actions. */\n trigger?: 'row' | 'page';\n}): JSX.Element | null {\n const { api, projectId } = useProjectKnowledge();\n const canMutate = useCanMutate();\n const [isConfirmingRemoval, setIsConfirmingRemoval] = useState(false);\n const [isRemoving, setIsRemoving] = useState(false);\n\n if (!api || !projectId) {\n return null;\n }\n\n const knowledgeApi = api;\n\n async function remove(): Promise<void> {\n setIsRemoving(true);\n\n try {\n await knowledgeApi.deleteSource(source.id);\n toast.success(`Removed \"${source.title}\".`);\n setIsConfirmingRemoval(false);\n onRemoved();\n void invalidateKnowledgeLists();\n } catch (removeError) {\n toast.error(describeApiError(removeError, 'The document could not be removed.'));\n } finally {\n setIsRemoving(false);\n }\n }\n\n return (\n <>\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n aria-label={`Actions for ${source.title}`}\n className={trigger === 'row' ? 'fk:size-8 fk:shrink-0 fk:text-muted-foreground' : undefined}\n data-knowledge-menu\n size=\"icon-sm\"\n variant={trigger === 'row' ? 'ghost' : 'outline'}\n >\n <EllipsisVerticalIcon className=\"fk:size-4\" />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n {onOpen ? <DropdownMenuItem onSelect={onOpen}>Open</DropdownMenuItem> : null}\n {source.path ? (\n <DropdownMenuItem asChild>\n <a href={knowledgePaths(projectId).file(source.id)}>\n <DownloadIcon />\n Download\n </a>\n </DropdownMenuItem>\n ) : null}\n {source.originUrl ? (\n <DropdownMenuItem asChild>\n <a href={source.originUrl} rel=\"noreferrer\" target=\"_blank\">\n <ExternalLinkIcon />\n Open page\n </a>\n </DropdownMenuItem>\n ) : null}\n {onOpen || source.path || source.originUrl ? <DropdownMenuSeparator /> : null}\n <DropdownMenuItem\n disabled={!canMutate || isBusy}\n variant=\"destructive\"\n onSelect={() => setIsConfirmingRemoval(true)}\n >\n <Trash2Icon />\n Remove\n </DropdownMenuItem>\n {canMutate ? null : (\n <DropdownMenuLabel className=\"fk:max-w-56 fk:whitespace-normal fk:text-xs fk:font-normal fk:text-muted-foreground\">\n Your member role cannot remove documents.\n </DropdownMenuLabel>\n )}\n </DropdownMenuContent>\n </DropdownMenu>\n <AlertDialog open={isConfirmingRemoval} onOpenChange={setIsConfirmingRemoval}>\n <AlertDialogContent>\n <AlertDialogHeader>\n <AlertDialogTitle>Remove this document?</AlertDialogTitle>\n <AlertDialogDescription>\n \"{source.title}\" and its indexed passages are deleted for everyone. Answers the agent gave earlier keep\n their citations, but the document can no longer be opened.\n </AlertDialogDescription>\n </AlertDialogHeader>\n <AlertDialogFooter>\n <AlertDialogCancel disabled={isRemoving}>Cancel</AlertDialogCancel>\n <AlertDialogAction\n disabled={isRemoving}\n onClick={(event: MouseEvent) => {\n event.preventDefault();\n void remove();\n }}\n >\n {isRemoving ? <LoaderCircle className=\"fk:animate-spin\" /> : null}\n Remove document\n </AlertDialogAction>\n </AlertDialogFooter>\n </AlertDialogContent>\n </AlertDialog>\n </>\n );\n}\n"]}
@@ -1,4 +1,4 @@
1
- import'./index.css';import {f,a,b,g}from'./chunk-KEGJNZLW.js';import {find,propEq}from'ramda';var I=25,K=25,B=2e3,N=12,x=new Set(["_asset"]),P={light:["#2a78d6","#eb6834","#1baf7a","#eda100","#e87ba4","#008300","#6250d6","#e34948","#0e9aa7","#6b8e23","#9c27b0","#a05a2c"],dark:["#3987e5","#d95926","#199e70","#c98500","#d55181","#008300","#9085e9","#e66767","#1a9fb0","#6f8a28","#c058d6","#a35226"]};function $(t,n){return `${t}:${n}`}function l(t){return t.attributes.filter(n=>a(n)==="relationship"&&n.relationship!==void 0&&!x.has(n.relationship.entity))}function V(t){return t.filter(n=>!x.has(n.name)&&l(n).length>0)}function _(t,n){return find(propEq(n,"name"))(t)}function J(t){return t.menu?.label??t.plural}function W(t,n){let e=P[n];return Object.fromEntries(t.filter(r=>!x.has(r.name)).map((r,i)=>[r.name,e[i%e.length]]))}function S(t,n,e=f){let r=b(t);if(!r)return "";let i=a(r);return i==="global"?r.name:i==="local"?`${r.name} { ${D(n,e)} }`:""}function D(t,n=f){let e=g(n);return t===n?e:`${e} ${t}`}function T(t,n,e,r,i){let o=_(n,t.relationship?.entity??"");return `${t.name}${r} { _id ${S(o,e,i)} }`}function q(t){return `${t.name}Connection { aggregate { count { nodes } } }`}var Y=5;function z({defaultScope:t,entity:n,schema:e,scope:r,expand:i}){let o=i?l(n).map(s=>T(s,e,r,`(limit: ${I})`,t)):[];return `query GraphRecords($where: ${n.name}Where, $limit: Int) {
1
+ import'./index.css';import {f,a,b,g}from'./chunk-DO32GATF.js';import {find,propEq}from'ramda';var I=25,K=25,B=2e3,N=12,x=new Set(["_asset"]),P={light:["#2a78d6","#eb6834","#1baf7a","#eda100","#e87ba4","#008300","#6250d6","#e34948","#0e9aa7","#6b8e23","#9c27b0","#a05a2c"],dark:["#3987e5","#d95926","#199e70","#c98500","#d55181","#008300","#9085e9","#e66767","#1a9fb0","#6f8a28","#c058d6","#a35226"]};function $(t,n){return `${t}:${n}`}function l(t){return t.attributes.filter(n=>a(n)==="relationship"&&n.relationship!==void 0&&!x.has(n.relationship.entity))}function V(t){return t.filter(n=>!x.has(n.name)&&l(n).length>0)}function _(t,n){return find(propEq(n,"name"))(t)}function J(t){return t.menu?.label??t.plural}function W(t,n){let e=P[n];return Object.fromEntries(t.filter(r=>!x.has(r.name)).map((r,i)=>[r.name,e[i%e.length]]))}function S(t,n,e=f){let r=b(t);if(!r)return "";let i=a(r);return i==="global"?r.name:i==="local"?`${r.name} { ${D(n,e)} }`:""}function D(t,n=f){let e=g(n);return t===n?e:`${e} ${t}`}function T(t,n,e,r,i){let o=_(n,t.relationship?.entity??"");return `${t.name}${r} { _id ${S(o,e,i)} }`}function q(t){return `${t.name}Connection { aggregate { count { nodes } } }`}var Y=5;function z({defaultScope:t,entity:n,schema:e,scope:r,expand:i}){let o=i?l(n).map(s=>T(s,e,r,`(limit: ${I})`,t)):[];return `query GraphRecords($where: ${n.name}Where, $limit: Int) {
2
2
  ${n.plural}(where: $where, limit: $limit) {
3
3
  _id
4
4
  ${S(n,r,t)}
@@ -26,5 +26,5 @@ import'./index.css';import {f,a,b,g}from'./chunk-KEGJNZLW.js';import {find,propE
26
26
  }`}function O(t){return t.filter(n=>(n.spaces?.length??0)===0)}function nt(t){return `query GraphTotals {
27
27
  ${O(t).map(n=>`${n.plural}Total`).join(`
28
28
  `)}
29
- }`}function j(t,n){if(t==null)return "";if(Array.isArray(t)){let[e]=t;return j(e?.[n]??e?.default,n)}return typeof t=="object"?JSON.stringify(t):String(t)}function G(t,n,e){let r=b(n),i=r?t[r.name]:void 0;if(typeof i=="string"||typeof i=="number")return String(i);if(Array.isArray(i)){let[o]=i,s=o?.[e]??o?.default;if(typeof s=="string"||typeof s=="number")return String(s)}return t._id}function M(t,n,e){let r=e.name,i=e.relationship?.field??e.name,[o]=[t.key,n.key].sort(),s=o===t.key?r:i,d=o===t.key?n.key:t.key;return {key:`${o}|${d}|${s}`,source:t.key,target:n.key,sourceAttribute:r,targetAttribute:i}}function et({records:t,entity:n,schema:e,scope:r}){let i=new Map,o=new Map,s={},d=l(n);return t.forEach(p=>{let a={key:$(n.name,p._id),entity:n.name,id:p._id,label:G(p,n,r)};i.set(a.key,a),d.forEach(u=>{let y=u.relationship?.entity??"",C=_(e,y),A=p[u.name],k=p[`${u.name}Connection`]?.aggregate?.count?.nodes;typeof k=="number"&&(s[a.key]={...s[a.key],[u.name]:k}),Array.isArray(A)&&A.forEach(f=>{let c={key:$(y,f._id),entity:y,id:f._id,label:G(f,C,r)};if(i.has(c.key)||i.set(c.key,c),c.key!==a.key){let h=M(a,c,u);o.has(h.key)||o.set(h.key,h);}});});}),{nodes:[...i.values()],edges:[...o.values()],counts:s}}function rt(t,n){let e={};return t.forEach(r=>{l(n).forEach(i=>{let o=r[i.name];if(Array.isArray(o)){let s=$(n.name,r._id);e[s]={...e[s],[i.name]:o.length};}});}),e}function it(t,{entity:n,ids:e}){let r=new URLSearchParams({entity:n});return e&&e.length>0&&r.set("ids",e.join(",")),`/${t}/graph?${r.toString()}`}function ot(t){let n=new URLSearchParams(t),e=n.get("entity");if(!e)return null;let r=(n.get("ids")??"").split(",").map(i=>i.trim()).filter(Boolean);return {entity:e,ids:r}}export{I as a,K as b,B as c,$ as d,l as e,V as f,_ as g,J as h,W as i,S as j,Y as k,z as l,Z as m,v as n,L as o,tt as p,O as q,nt as r,j as s,G as t,M as u,et as v,rt as w,it as x,ot as y};//# sourceMappingURL=chunk-DEG7QP5C.js.map
30
- //# sourceMappingURL=chunk-DEG7QP5C.js.map
29
+ }`}function j(t,n){if(t==null)return "";if(Array.isArray(t)){let[e]=t;return j(e?.[n]??e?.default,n)}return typeof t=="object"?JSON.stringify(t):String(t)}function G(t,n,e){let r=b(n),i=r?t[r.name]:void 0;if(typeof i=="string"||typeof i=="number")return String(i);if(Array.isArray(i)){let[o]=i,s=o?.[e]??o?.default;if(typeof s=="string"||typeof s=="number")return String(s)}return t._id}function M(t,n,e){let r=e.name,i=e.relationship?.field??e.name,[o]=[t.key,n.key].sort(),s=o===t.key?r:i,d=o===t.key?n.key:t.key;return {key:`${o}|${d}|${s}`,source:t.key,target:n.key,sourceAttribute:r,targetAttribute:i}}function et({records:t,entity:n,schema:e,scope:r}){let i=new Map,o=new Map,s={},d=l(n);return t.forEach(p=>{let a={key:$(n.name,p._id),entity:n.name,id:p._id,label:G(p,n,r)};i.set(a.key,a),d.forEach(u=>{let y=u.relationship?.entity??"",C=_(e,y),A=p[u.name],k=p[`${u.name}Connection`]?.aggregate?.count?.nodes;typeof k=="number"&&(s[a.key]={...s[a.key],[u.name]:k}),Array.isArray(A)&&A.forEach(f=>{let c={key:$(y,f._id),entity:y,id:f._id,label:G(f,C,r)};if(i.has(c.key)||i.set(c.key,c),c.key!==a.key){let h=M(a,c,u);o.has(h.key)||o.set(h.key,h);}});});}),{nodes:[...i.values()],edges:[...o.values()],counts:s}}function rt(t,n){let e={};return t.forEach(r=>{l(n).forEach(i=>{let o=r[i.name];if(Array.isArray(o)){let s=$(n.name,r._id);e[s]={...e[s],[i.name]:o.length};}});}),e}function it(t,{entity:n,ids:e}){let r=new URLSearchParams({entity:n});return e&&e.length>0&&r.set("ids",e.join(",")),`/${t}/graph?${r.toString()}`}function ot(t){let n=new URLSearchParams(t),e=n.get("entity");if(!e)return null;let r=(n.get("ids")??"").split(",").map(i=>i.trim()).filter(Boolean);return {entity:e,ids:r}}export{I as a,K as b,B as c,$ as d,l as e,V as f,_ as g,J as h,W as i,S as j,Y as k,z as l,Z as m,v as n,L as o,tt as p,O as q,nt as r,j as s,G as t,M as u,et as v,rt as w,it as x,ot as y};//# sourceMappingURL=chunk-6NRMVVU4.js.map
30
+ //# sourceMappingURL=chunk-6NRMVVU4.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/apps/graph/graph.ts"],"names":["EXPAND_PAGE","SAMPLE_LIMIT","MAX_NODES","DETAIL_ATTRIBUTE_LIMIT","HIDDEN_ENTITIES","GRAPH_PALETTE","nodeKey","entity","id","getRelationshipAttributes","attribute","getAttributeScope","getGraphEntities","schema","getEntity","name","find","propEq","getEntityLabel","getEntityColors","theme","palette","index","getDisplaySelection","scope","defaultScope","DEFAULT_SCOPE_KEY","display","getDisplayAttribute","scopeType","getScopeFields","fallback","defaultValueSelection","getRelatedSelection","args","relatedEntity","getCountSelection","EXPAND_HOP_MAX_RECORDS","buildRecordsQuery","expand","relationships","buildExpandQuery","buildCountsQuery","getDetailAttributes","buildDetailsQuery","fields","getTotalEntities","entities","buildTotalsQuery","formatDetailValue","value","first","captionOf","record","scoped","edgeOf","source","target","sourceAttribute","targetAttribute","left","leftAttribute","right","graphFromRecords","records","nodes","edges","counts","relatedEntityName","relatedRecords","total","relatedRecord","edge","fetchedFromRecords","fetched","related","key","graphPath","projectId","ids","params","parseGraphParams","search"],"mappings":"kGAaaA,CAAAA,CAAc,EAAA,CAEdC,CAAAA,CAAe,EAAA,CAEfC,EAAY,GAAA,CAEZC,CAAAA,CAAyB,EAAA,CAGhCC,CAAAA,CAAkB,IAAI,GAAA,CAAI,CAAC,QAAQ,CAAC,EAU7BC,CAAAA,CAAgB,CAC3B,KAAA,CAAO,CACL,UACA,SAAA,CACA,SAAA,CACA,SAAA,CACA,SAAA,CACA,UACA,SAAA,CACA,SAAA,CACA,SAAA,CACA,SAAA,CACA,UACA,SACF,CAAA,CACA,IAAA,CAAM,CACJ,UACA,SAAA,CACA,SAAA,CACA,SAAA,CACA,SAAA,CACA,UACA,SAAA,CACA,SAAA,CACA,SAAA,CACA,SAAA,CACA,UACA,SACF,CACF,EAgCO,SAASC,EAAQC,CAAAA,CAAgBC,CAAAA,CAAoB,CAC1D,OAAO,GAAGD,CAAM,CAAA,CAAA,EAAIC,CAAE,CAAA,CACxB,CAGO,SAASC,CAAAA,CAA0BF,CAAAA,CAA6B,CACrE,OAAOA,CAAAA,CAAO,UAAA,CAAW,OACtBG,CAAAA,EACCC,CAAAA,CAAkBD,CAAS,CAAA,GAAM,cAAA,EACjCA,CAAAA,CAAU,YAAA,GAAiB,QAC3B,CAACN,CAAAA,CAAgB,GAAA,CAAIM,CAAAA,CAAU,aAAa,MAAM,CACtD,CACF,CAGO,SAASE,CAAAA,CAAiBC,CAAAA,CAA4B,CAC3D,OAAOA,EAAO,MAAA,CAAQN,CAAAA,EAAW,CAACH,CAAAA,CAAgB,IAAIG,CAAAA,CAAO,IAAI,CAAA,EAAKE,CAAAA,CAA0BF,CAAM,CAAA,CAAE,MAAA,CAAS,CAAC,CACpH,CAEO,SAASO,CAAAA,CAAUD,CAAAA,C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CAAE,MAAA,CAAAD,CAAAA,CAAQ,GAAA,CAAAwE,CAAI,CACvB","file":"chunk-DEG7QP5C.js","sourcesContent":["import { find, propEq } from 'ramda';\nimport { DEFAULT_SCOPE_KEY, defaultValueSelection } from '../../graphql-client/queries';\nimport { getAttributeScope } from '../../core/attribute-scope';\nimport { getDisplayAttribute } from '../../core/get-display-attribute';\nimport type { Attribute, Entity } from '../../core/types';\n\n/**\n * Pure helpers of the Graph app: the GraphQL queries that fetch records with\n * their relationships, and the mapping of their results to the nodes and\n * edges the canvas draws. No React, no sigma, so the rules are unit-testable.\n */\n\n/** Related records fetched per relationship attribute in one go. */\nexport const EXPAND_PAGE = 25;\n/** Records loaded when starting from an entity. */\nexport const SAMPLE_LIMIT = 25;\n/** Nodes a canvas holds at most; later additions are dropped with a notice. */\nexport const MAX_NODES = 2000;\n/** Attributes shown in the inspector at most. */\nexport const DETAIL_ATTRIBUTE_LIMIT = 12;\n\n/** Entities whose nodes are never drawn: assets are media, not records. */\nconst HIDDEN_ENTITIES = new Set(['_asset']);\n\n/**\n * Categorical palette, one hue per entity in schema order (light and dark\n * surfaces step the same hues). The first eight are the validated dataviz\n * palette; the next four were checked with its script so adjacent pairs\n * stay apart under colour-blindness simulation and no pair on either\n * surface comes closer than the reference palette's own closest pair.\n * Projects with more entities than hues reuse them.\n */\nexport const GRAPH_PALETTE = {\n light: [\n '#2a78d6',\n '#eb6834',\n '#1baf7a',\n '#eda100',\n '#e87ba4',\n '#008300',\n '#6250d6',\n '#e34948',\n '#0e9aa7',\n '#6b8e23',\n '#9c27b0',\n '#a05a2c',\n ],\n dark: [\n '#3987e5',\n '#d95926',\n '#199e70',\n '#c98500',\n '#d55181',\n '#008300',\n '#9085e9',\n '#e66767',\n '#1a9fb0',\n '#6f8a28',\n '#c058d6',\n '#a35226',\n ],\n} as const;\n\nexport interface GraphNode {\n key: string;\n entity: string;\n id: string;\n label: string;\n}\n\nexport interface GraphEdge {\n key: string;\n source: string;\n target: string;\n /** The relationship attribute on the source node's entity. */\n sourceAttribute: string;\n /** The mirror attribute on the target node's entity. */\n targetAttribute: string;\n}\n\n/** Related records per relationship attribute, keyed by node, as the API counted them. */\nexport type GraphCounts = { [nodeKey: string]: { [attribute: string]: number } };\n\nexport interface GraphData {\n nodes: GraphNode[];\n edges: GraphEdge[];\n counts: GraphCounts;\n}\n\nexport type GraphRecord = { _id: string; [key: string]: unknown };\n\ntype ConnectionCount = { aggregate?: { count?: { nodes?: number } } };\n\nexport function nodeKey(entity: string, id: string): string {\n return `${entity}:${id}`;\n}\n\n/** Relationship attributes of an entity that point at drawable entities. */\nexport function getRelationshipAttributes(entity: Entity): Attribute[] {\n return entity.attributes.filter(\n (attribute) =>\n getAttributeScope(attribute) === 'relationship' &&\n attribute.relationship !== undefined &&\n !HIDDEN_ENTITIES.has(attribute.relationship.entity)\n );\n}\n\n/** Entities worth starting from: at least one drawable relationship. */\nexport function getGraphEntities(schema: Entity[]): Entity[] {\n return schema.filter((entity) => !HIDDEN_ENTITIES.has(entity.name) && getRelationshipAttributes(entity).length > 0);\n}\n\nexport function getEntity(schema: Entity[], name: string): Entity | undefined {\n return find<Entity>(propEq(name, 'name'))(schema);\n}\n\nexport function getEntityLabel(entity: Entity): string {\n return entity.menu?.label ?? entity.plural;\n}\n\n/** Colour per entity name, assigned in schema order and never re-cycled on filter. */\nexport function getEntityColors(schema: Entity[], theme: 'light' | 'dark'): { [entity: string]: string } {\n const palette = GRAPH_PALETTE[theme];\n\n return Object.fromEntries(\n schema.filter((entity) => !HIDDEN_ENTITIES.has(entity.name)).map((entity, index) => [entity.name, palette[index % palette.length]])\n );\n}\n\n/**\n * Selection of the display attribute: a scalar for global attributes, the\n * current scope's value for local ones. Relationship display attributes fall\n * back to the id.\n */\nexport function getDisplaySelection(\n entity: Entity | undefined,\n scope: string,\n defaultScope = DEFAULT_SCOPE_KEY\n): string {\n const display = getDisplayAttribute(entity);\n\n if (!display) {\n return '';\n }\n\n const scopeType = getAttributeScope(display);\n\n if (scopeType === 'global') {\n return display.name;\n }\n\n if (scopeType === 'local') {\n return `${display.name} { ${getScopeFields(scope, defaultScope)} }`;\n }\n\n return '';\n}\n\n/**\n * The scope value and the default one to fall back on, as the Desk queries\n * select them: the default scope's value always comes back as `default`,\n * whatever the project named that scope.\n */\nexport function getScopeFields(scope: string, defaultScope = DEFAULT_SCOPE_KEY): string {\n const fallback = defaultValueSelection(defaultScope);\n\n return scope === defaultScope ? fallback : `${fallback} ${scope}`;\n}\n\nfunction getRelatedSelection(\n attribute: Attribute,\n schema: Entity[],\n scope: string,\n args: string,\n defaultScope?: string\n): string {\n const relatedEntity = getEntity(schema, attribute.relationship?.entity ?? '');\n\n return `${attribute.name}${args} { _id ${getDisplaySelection(relatedEntity, scope, defaultScope)} }`;\n}\n\nfunction getCountSelection(attribute: Attribute): string {\n return `${attribute.name}Connection { aggregate { count { nodes } } }`;\n}\n\n/** Records a one-hop load covers at most; more records come without their relationships. */\nexport const EXPAND_HOP_MAX_RECORDS = 5;\n\n/**\n * Records by id or a sample of them; with `expand`, each comes with the first\n * page of every drawable relationship. Totals are left to the inspector:\n * counting every relationship of every record is what makes a load slow.\n */\nexport function buildRecordsQuery({\n defaultScope,\n entity,\n schema,\n scope,\n expand,\n}: {\n defaultScope?: string;\n entity: Entity;\n schema: Entity[];\n scope: string;\n expand: boolean;\n}): string {\n const relationships = expand\n ? getRelationshipAttributes(entity).map((attribute) =>\n getRelatedSelection(attribute, schema, scope, `(limit: ${EXPAND_PAGE})`, defaultScope)\n )\n : [];\n\n return `query GraphRecords($where: ${entity.name}Where, $limit: Int) {\n ${entity.plural}(where: $where, limit: $limit) {\n _id\n ${getDisplaySelection(entity, scope, defaultScope)}\n ${relationships.join('\\n ')}\n }\n}`;\n}\n\n/** One more page of a single relationship of one record. */\nexport function buildExpandQuery({\n defaultScope,\n entity,\n schema,\n scope,\n attribute,\n}: {\n defaultScope?: string;\n entity: Entity;\n schema: Entity[];\n scope: string;\n attribute: Attribute;\n}): string {\n return `query GraphExpand($id: ID!, $offset: Int, $limit: Int) {\n ${entity.plural}(where: { _id: { eq: $id } }) {\n _id\n ${getRelatedSelection(attribute, schema, scope, '(limit: $limit, offset: $offset)', defaultScope)}\n }\n}`;\n}\n\n/** The total per drawable relationship of one record. */\nexport function buildCountsQuery({ entity }: { entity: Entity }): string {\n return `query GraphCounts($id: ID!) {\n ${entity.plural}(where: { _id: { eq: $id } }) {\n _id\n ${getRelationshipAttributes(entity).map(getCountSelection).join('\\n ')}\n }\n}`;\n}\n\n/** Attributes the inspector lists: visible scalars, global or in the current scope; rich text is skipped. */\nexport function getDetailAttributes(entity: Entity): Attribute[] {\n return entity.attributes\n .filter((attribute) => {\n const scopeType = getAttributeScope(attribute);\n\n return (\n !attribute.hidden &&\n attribute.dataType !== 'asset' &&\n attribute.inputType !== 'editor' &&\n (scopeType === 'global' || scopeType === 'local')\n );\n })\n .slice(0, DETAIL_ATTRIBUTE_LIMIT);\n}\n\n/** The scalar values of one record for the inspector. */\nexport function buildDetailsQuery({\n defaultScope,\n entity,\n scope,\n}: {\n defaultScope?: string;\n entity: Entity;\n scope: string;\n}): string {\n const fields = getDetailAttributes(entity).map((attribute) =>\n getAttributeScope(attribute) === 'local'\n ? `${attribute.name} { ${getScopeFields(scope, defaultScope)} }`\n : attribute.name\n );\n\n return `query GraphDetails($id: ID!) {\n ${entity.plural}(where: { _id: { eq: $id } }) {\n _id\n _updatedAt\n ${fields.join('\\n ')}\n }\n}`;\n}\n\n/** Entities whose count-store total the API exposes (not space-bound). */\nexport function getTotalEntities(entities: Entity[]): Entity[] {\n return entities.filter((entity) => (entity.spaces?.length ?? 0) === 0);\n}\n\nexport function buildTotalsQuery(entities: Entity[]): string {\n return `query GraphTotals {\\n ${getTotalEntities(entities)\n .map((entity) => `${entity.plural}Total`)\n .join('\\n ')}\\n}`;\n}\n\n/** A scalar as the inspector shows it: the scope value of a local attribute, else the value itself. */\nexport function formatDetailValue(value: unknown, scope: string): string {\n if (value === null || value === undefined) {\n return '';\n }\n\n if (Array.isArray(value)) {\n const [first] = value as { [key: string]: unknown }[];\n\n return formatDetailValue(first?.[scope] ?? first?.default, scope);\n }\n\n if (typeof value === 'object') {\n return JSON.stringify(value);\n }\n\n return String(value);\n}\n\n/** The caption of a record: its display value in the scope, else in the default scope, else its id. */\nexport function captionOf(record: GraphRecord, entity: Entity | undefined, scope: string): string {\n const display = getDisplayAttribute(entity);\n const value = display ? record[display.name] : undefined;\n\n if (typeof value === 'string' || typeof value === 'number') {\n return String(value);\n }\n\n if (Array.isArray(value)) {\n const [first] = value as { [key: string]: unknown }[];\n const scoped = first?.[scope] ?? first?.default;\n\n if (typeof scoped === 'string' || typeof scoped === 'number') {\n return String(scoped);\n }\n }\n\n return record._id;\n}\n\n/**\n * The edge between two nodes for a relationship: one Neo4j relationship per\n * entity pair, so the key is the same whichever side it was fetched from.\n */\nexport function edgeOf(source: GraphNode, target: GraphNode, attribute: Attribute): GraphEdge {\n const sourceAttribute = attribute.name;\n const targetAttribute = attribute.relationship?.field ?? attribute.name;\n const [left] = [source.key, target.key].sort();\n const leftAttribute = left === source.key ? sourceAttribute : targetAttribute;\n const right = left === source.key ? target.key : source.key;\n\n return { key: `${left}|${right}|${leftAttribute}`, source: source.key, target: target.key, sourceAttribute, targetAttribute };\n}\n\n/**\n * Nodes and edges from records of an entity; the related records under each\n * relationship attribute become nodes too, and `xConnection` aggregates\n * become counts.\n */\nexport function graphFromRecords({\n records,\n entity,\n schema,\n scope,\n}: {\n records: GraphRecord[];\n entity: Entity;\n schema: Entity[];\n scope: string;\n}): GraphData {\n const nodes = new Map<string, GraphNode>();\n const edges = new Map<string, GraphEdge>();\n const counts: GraphCounts = {};\n const relationships = getRelationshipAttributes(entity);\n\n records.forEach((record) => {\n const source: GraphNode = {\n key: nodeKey(entity.name, record._id),\n entity: entity.name,\n id: record._id,\n label: captionOf(record, entity, scope),\n };\n nodes.set(source.key, source);\n\n relationships.forEach((attribute) => {\n const relatedEntityName = attribute.relationship?.entity ?? '';\n const relatedEntity = getEntity(schema, relatedEntityName);\n const relatedRecords = record[attribute.name];\n const connection = record[`${attribute.name}Connection`] as ConnectionCount | undefined;\n const total = connection?.aggregate?.count?.nodes;\n\n if (typeof total === 'number') {\n counts[source.key] = { ...counts[source.key], [attribute.name]: total };\n }\n\n if (!Array.isArray(relatedRecords)) {\n return;\n }\n\n (relatedRecords as GraphRecord[]).forEach((relatedRecord) => {\n const target: GraphNode = {\n key: nodeKey(relatedEntityName, relatedRecord._id),\n entity: relatedEntityName,\n id: relatedRecord._id,\n label: captionOf(relatedRecord, relatedEntity, scope),\n };\n\n if (!nodes.has(target.key)) {\n nodes.set(target.key, target);\n }\n\n if (target.key !== source.key) {\n const edge = edgeOf(source, target, attribute);\n\n if (!edges.has(edge.key)) {\n edges.set(edge.key, edge);\n }\n }\n });\n });\n });\n\n return { nodes: [...nodes.values()], edges: [...edges.values()], counts };\n}\n\n/** How many related records each record carries per relationship, to continue paging from. */\nexport function fetchedFromRecords(records: GraphRecord[], entity: Entity): GraphCounts {\n const fetched: GraphCounts = {};\n\n records.forEach((record) => {\n getRelationshipAttributes(entity).forEach((attribute) => {\n const related = record[attribute.name];\n\n if (Array.isArray(related)) {\n const key = nodeKey(entity.name, record._id);\n fetched[key] = { ...fetched[key], [attribute.name]: related.length };\n }\n });\n });\n\n return fetched;\n}\n\n/** The Graph app route for an entity, optionally for given records. */\nexport function graphPath(projectId: string, { entity, ids }: { entity: string; ids?: string[] }): string {\n const params = new URLSearchParams({ entity });\n\n if (ids && ids.length > 0) {\n params.set('ids', ids.join(','));\n }\n\n return `/${projectId}/graph?${params.toString()}`;\n}\n\nexport function parseGraphParams(search: string): { entity: string; ids: string[] } | null {\n const params = new URLSearchParams(search);\n const entity = params.get('entity');\n\n if (!entity) {\n return null;\n }\n\n const ids = (params.get('ids') ?? '')\n .split(',')\n .map((id) => id.trim())\n .filter(Boolean);\n\n return { entity, ids };\n}\n"]}
1
+ {"version":3,"sources":["../src/apps/graph/graph.ts"],"names":["EXPAND_PAGE","SAMPLE_LIMIT","MAX_NODES","DETAIL_ATTRIBUTE_LIMIT","HIDDEN_ENTITIES","GRAPH_PALETTE","nodeKey","entity","id","getRelationshipAttributes","attribute","getAttributeScope","getGraphEntities","schema","getEntity","name","find","propEq","getEntityLabel","getEntityColors","theme","palette","index","getDisplaySelection","scope","defaultScope","DEFAULT_SCOPE_KEY","display","getDisplayAttribute","scopeType","getScopeFields","fallback","defaultValueSelection","getRelatedSelection","args","relatedEntity","getCountSelection","EXPAND_HOP_MAX_RECORDS","buildRecordsQuery","expand","relationships","buildExpandQuery","buildCountsQuery","getDetailAttributes","buildDetailsQuery","fields","getTotalEntities","entities","buildTotalsQuery","formatDetailValue","value","first","captionOf","record","scoped","edgeOf","source","target","sourceAttribute","targetAttribute","left","leftAttribute","right","graphFromRecords","records","nodes","edges","counts","relatedEntityName","relatedRecords","total","relatedRecord","edge","fetchedFromRecords","fetched","related","key","graphPath","projectId","ids","params","parseGraphParams","search"],"mappings":"kGAaaA,CAAAA,CAAc,EAAA,CAEdC,CAAAA,CAAe,EAAA,CAEfC,EAAY,GAAA,CAEZC,CAAAA,CAAyB,EAAA,CAGhCC,CAAAA,CAAkB,IAAI,GAAA,CAAI,CAAC,QAAQ,CAAC,EAU7BC,CAAAA,CAAgB,CAC3B,KAAA,CAAO,CACL,UACA,SAAA,CACA,SAAA,CACA,SAAA,CACA,SAAA,CACA,UACA,SAAA,CACA,SAAA,CACA,SAAA,CACA,SAAA,CACA,UACA,SACF,CAAA,CACA,IAAA,CAAM,CACJ,UACA,SAAA,CACA,SAAA,CACA,SAAA,CACA,SAAA,CACA,UACA,SAAA,CACA,SAAA,CACA,SAAA,CACA,SAAA,CACA,UACA,SACF,CACF,EAgCO,SAASC,EAAQC,CAAAA,CAAgBC,CAAAA,CAAoB,CAC1D,OAAO,GAAGD,CAAM,CAAA,CAAA,EAAIC,CAAE,CAAA,CACxB,CAGO,SAASC,CAAAA,CAA0BF,CAAAA,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AO,QAAA,EAAU,CAAA,CACjD,CAEO,SAASC,EAAAA,CAAiBC,CAAAA,CAA0D,CACzF,IAAMF,CAAAA,CAAS,IAAI,eAAA,CAAgBE,CAAM,CAAA,CACnC3E,CAAAA,CAASyE,CAAAA,CAAO,GAAA,CAAI,QAAQ,CAAA,CAElC,GAAI,CAACzE,CAAAA,CACH,OAAO,IAAA,CAGT,IAAMwE,CAAAA,CAAAA,CAAOC,CAAAA,CAAO,GAAA,CAAI,KAAK,CAAA,EAAK,EAAA,EAC/B,KAAA,CAAM,GAAG,CAAA,CACT,GAAA,CAAKxE,CAAAA,EAAOA,CAAAA,CAAG,IAAA,EAAM,CAAA,CACrB,MAAA,CAAO,OAAO,CAAA,CAEjB,OAAO,CAAE,MAAA,CAAAD,CAAAA,CAAQ,GAAA,CAAAwE,CAAI,CACvB","file":"chunk-6NRMVVU4.js","sourcesContent":["import { find, propEq } from 'ramda';\nimport { DEFAULT_SCOPE_KEY, defaultValueSelection } from '../../graphql-client/queries';\nimport { getAttributeScope } from '../../core/attribute-scope';\nimport { getDisplayAttribute } from '../../core/get-display-attribute';\nimport type { Attribute, Entity } from '../../core/types';\n\n/**\n * Pure helpers of the Graph app: the GraphQL queries that fetch records with\n * their relationships, and the mapping of their results to the nodes and\n * edges the canvas draws. No React, no sigma, so the rules are unit-testable.\n */\n\n/** Related records fetched per relationship attribute in one go. */\nexport const EXPAND_PAGE = 25;\n/** Records loaded when starting from an entity. */\nexport const SAMPLE_LIMIT = 25;\n/** Nodes a canvas holds at most; later additions are dropped with a notice. */\nexport const MAX_NODES = 2000;\n/** Attributes shown in the inspector at most. */\nexport const DETAIL_ATTRIBUTE_LIMIT = 12;\n\n/** Entities whose nodes are never drawn: assets are media, not records. */\nconst HIDDEN_ENTITIES = new Set(['_asset']);\n\n/**\n * Categorical palette, one hue per entity in schema order (light and dark\n * surfaces step the same hues). The first eight are the validated dataviz\n * palette; the next four were checked with its script so adjacent pairs\n * stay apart under colour-blindness simulation and no pair on either\n * surface comes closer than the reference palette's own closest pair.\n * Projects with more entities than hues reuse them.\n */\nexport const GRAPH_PALETTE = {\n light: [\n '#2a78d6',\n '#eb6834',\n '#1baf7a',\n '#eda100',\n '#e87ba4',\n '#008300',\n '#6250d6',\n '#e34948',\n '#0e9aa7',\n '#6b8e23',\n '#9c27b0',\n '#a05a2c',\n ],\n dark: [\n '#3987e5',\n '#d95926',\n '#199e70',\n '#c98500',\n '#d55181',\n '#008300',\n '#9085e9',\n '#e66767',\n '#1a9fb0',\n '#6f8a28',\n '#c058d6',\n '#a35226',\n ],\n} as const;\n\nexport interface GraphNode {\n key: string;\n entity: string;\n id: string;\n label: string;\n}\n\nexport interface GraphEdge {\n key: string;\n source: string;\n target: string;\n /** The relationship attribute on the source node's entity. */\n sourceAttribute: string;\n /** The mirror attribute on the target node's entity. */\n targetAttribute: string;\n}\n\n/** Related records per relationship attribute, keyed by node, as the API counted them. */\nexport type GraphCounts = { [nodeKey: string]: { [attribute: string]: number } };\n\nexport interface GraphData {\n nodes: GraphNode[];\n edges: GraphEdge[];\n counts: GraphCounts;\n}\n\nexport type GraphRecord = { _id: string; [key: string]: unknown };\n\ntype ConnectionCount = { aggregate?: { count?: { nodes?: number } } };\n\nexport function nodeKey(entity: string, id: string): string {\n return `${entity}:${id}`;\n}\n\n/** Relationship attributes of an entity that point at drawable entities. */\nexport function getRelationshipAttributes(entity: Entity): Attribute[] {\n return entity.attributes.filter(\n (attribute) =>\n getAttributeScope(attribute) === 'relationship' &&\n attribute.relationship !== undefined &&\n !HIDDEN_ENTITIES.has(attribute.relationship.entity)\n );\n}\n\n/** Entities worth starting from: at least one drawable relationship. */\nexport function getGraphEntities(schema: Entity[]): Entity[] {\n return schema.filter((entity) => !HIDDEN_ENTITIES.has(entity.name) && getRelationshipAttributes(entity).length > 0);\n}\n\nexport function getEntity(schema: Entity[], name: string): Entity | undefined {\n return find<Entity>(propEq(name, 'name'))(schema);\n}\n\nexport function getEntityLabel(entity: Entity): string {\n return entity.menu?.label ?? entity.plural;\n}\n\n/** Colour per entity name, assigned in schema order and never re-cycled on filter. */\nexport function getEntityColors(schema: Entity[], theme: 'light' | 'dark'): { [entity: string]: string } {\n const palette = GRAPH_PALETTE[theme];\n\n return Object.fromEntries(\n schema.filter((entity) => !HIDDEN_ENTITIES.has(entity.name)).map((entity, index) => [entity.name, palette[index % palette.length]])\n );\n}\n\n/**\n * Selection of the display attribute: a scalar for global attributes, the\n * current scope's value for local ones. Relationship display attributes fall\n * back to the id.\n */\nexport function getDisplaySelection(\n entity: Entity | undefined,\n scope: string,\n defaultScope = DEFAULT_SCOPE_KEY\n): string {\n const display = getDisplayAttribute(entity);\n\n if (!display) {\n return '';\n }\n\n const scopeType = getAttributeScope(display);\n\n if (scopeType === 'global') {\n return display.name;\n }\n\n if (scopeType === 'local') {\n return `${display.name} { ${getScopeFields(scope, defaultScope)} }`;\n }\n\n return '';\n}\n\n/**\n * The scope value and the default one to fall back on, as the Desk queries\n * select them: the default scope's value always comes back as `default`,\n * whatever the project named that scope.\n */\nexport function getScopeFields(scope: string, defaultScope = DEFAULT_SCOPE_KEY): string {\n const fallback = defaultValueSelection(defaultScope);\n\n return scope === defaultScope ? fallback : `${fallback} ${scope}`;\n}\n\nfunction getRelatedSelection(\n attribute: Attribute,\n schema: Entity[],\n scope: string,\n args: string,\n defaultScope?: string\n): string {\n const relatedEntity = getEntity(schema, attribute.relationship?.entity ?? '');\n\n return `${attribute.name}${args} { _id ${getDisplaySelection(relatedEntity, scope, defaultScope)} }`;\n}\n\nfunction getCountSelection(attribute: Attribute): string {\n return `${attribute.name}Connection { aggregate { count { nodes } } }`;\n}\n\n/** Records a one-hop load covers at most; more records come without their relationships. */\nexport const EXPAND_HOP_MAX_RECORDS = 5;\n\n/**\n * Records by id or a sample of them; with `expand`, each comes with the first\n * page of every drawable relationship. Totals are left to the inspector:\n * counting every relationship of every record is what makes a load slow.\n */\nexport function buildRecordsQuery({\n defaultScope,\n entity,\n schema,\n scope,\n expand,\n}: {\n defaultScope?: string;\n entity: Entity;\n schema: Entity[];\n scope: string;\n expand: boolean;\n}): string {\n const relationships = expand\n ? getRelationshipAttributes(entity).map((attribute) =>\n getRelatedSelection(attribute, schema, scope, `(limit: ${EXPAND_PAGE})`, defaultScope)\n )\n : [];\n\n return `query GraphRecords($where: ${entity.name}Where, $limit: Int) {\n ${entity.plural}(where: $where, limit: $limit) {\n _id\n ${getDisplaySelection(entity, scope, defaultScope)}\n ${relationships.join('\\n ')}\n }\n}`;\n}\n\n/** One more page of a single relationship of one record. */\nexport function buildExpandQuery({\n defaultScope,\n entity,\n schema,\n scope,\n attribute,\n}: {\n defaultScope?: string;\n entity: Entity;\n schema: Entity[];\n scope: string;\n attribute: Attribute;\n}): string {\n return `query GraphExpand($id: ID!, $offset: Int, $limit: Int) {\n ${entity.plural}(where: { _id: { eq: $id } }) {\n _id\n ${getRelatedSelection(attribute, schema, scope, '(limit: $limit, offset: $offset)', defaultScope)}\n }\n}`;\n}\n\n/** The total per drawable relationship of one record. */\nexport function buildCountsQuery({ entity }: { entity: Entity }): string {\n return `query GraphCounts($id: ID!) {\n ${entity.plural}(where: { _id: { eq: $id } }) {\n _id\n ${getRelationshipAttributes(entity).map(getCountSelection).join('\\n ')}\n }\n}`;\n}\n\n/** Attributes the inspector lists: visible scalars, global or in the current scope; rich text is skipped. */\nexport function getDetailAttributes(entity: Entity): Attribute[] {\n return entity.attributes\n .filter((attribute) => {\n const scopeType = getAttributeScope(attribute);\n\n return (\n !attribute.hidden &&\n attribute.dataType !== 'asset' &&\n attribute.inputType !== 'editor' &&\n (scopeType === 'global' || scopeType === 'local')\n );\n })\n .slice(0, DETAIL_ATTRIBUTE_LIMIT);\n}\n\n/** The scalar values of one record for the inspector. */\nexport function buildDetailsQuery({\n defaultScope,\n entity,\n scope,\n}: {\n defaultScope?: string;\n entity: Entity;\n scope: string;\n}): string {\n const fields = getDetailAttributes(entity).map((attribute) =>\n getAttributeScope(attribute) === 'local'\n ? `${attribute.name} { ${getScopeFields(scope, defaultScope)} }`\n : attribute.name\n );\n\n return `query GraphDetails($id: ID!) {\n ${entity.plural}(where: { _id: { eq: $id } }) {\n _id\n _updatedAt\n ${fields.join('\\n ')}\n }\n}`;\n}\n\n/** Entities whose count-store total the API exposes (not space-bound). */\nexport function getTotalEntities(entities: Entity[]): Entity[] {\n return entities.filter((entity) => (entity.spaces?.length ?? 0) === 0);\n}\n\nexport function buildTotalsQuery(entities: Entity[]): string {\n return `query GraphTotals {\\n ${getTotalEntities(entities)\n .map((entity) => `${entity.plural}Total`)\n .join('\\n ')}\\n}`;\n}\n\n/** A scalar as the inspector shows it: the scope value of a local attribute, else the value itself. */\nexport function formatDetailValue(value: unknown, scope: string): string {\n if (value === null || value === undefined) {\n return '';\n }\n\n if (Array.isArray(value)) {\n const [first] = value as { [key: string]: unknown }[];\n\n return formatDetailValue(first?.[scope] ?? first?.default, scope);\n }\n\n if (typeof value === 'object') {\n return JSON.stringify(value);\n }\n\n return String(value);\n}\n\n/** The caption of a record: its display value in the scope, else in the default scope, else its id. */\nexport function captionOf(record: GraphRecord, entity: Entity | undefined, scope: string): string {\n const display = getDisplayAttribute(entity);\n const value = display ? record[display.name] : undefined;\n\n if (typeof value === 'string' || typeof value === 'number') {\n return String(value);\n }\n\n if (Array.isArray(value)) {\n const [first] = value as { [key: string]: unknown }[];\n const scoped = first?.[scope] ?? first?.default;\n\n if (typeof scoped === 'string' || typeof scoped === 'number') {\n return String(scoped);\n }\n }\n\n return record._id;\n}\n\n/**\n * The edge between two nodes for a relationship: one Neo4j relationship per\n * entity pair, so the key is the same whichever side it was fetched from.\n */\nexport function edgeOf(source: GraphNode, target: GraphNode, attribute: Attribute): GraphEdge {\n const sourceAttribute = attribute.name;\n const targetAttribute = attribute.relationship?.field ?? attribute.name;\n const [left] = [source.key, target.key].sort();\n const leftAttribute = left === source.key ? sourceAttribute : targetAttribute;\n const right = left === source.key ? target.key : source.key;\n\n return { key: `${left}|${right}|${leftAttribute}`, source: source.key, target: target.key, sourceAttribute, targetAttribute };\n}\n\n/**\n * Nodes and edges from records of an entity; the related records under each\n * relationship attribute become nodes too, and `xConnection` aggregates\n * become counts.\n */\nexport function graphFromRecords({\n records,\n entity,\n schema,\n scope,\n}: {\n records: GraphRecord[];\n entity: Entity;\n schema: Entity[];\n scope: string;\n}): GraphData {\n const nodes = new Map<string, GraphNode>();\n const edges = new Map<string, GraphEdge>();\n const counts: GraphCounts = {};\n const relationships = getRelationshipAttributes(entity);\n\n records.forEach((record) => {\n const source: GraphNode = {\n key: nodeKey(entity.name, record._id),\n entity: entity.name,\n id: record._id,\n label: captionOf(record, entity, scope),\n };\n nodes.set(source.key, source);\n\n relationships.forEach((attribute) => {\n const relatedEntityName = attribute.relationship?.entity ?? '';\n const relatedEntity = getEntity(schema, relatedEntityName);\n const relatedRecords = record[attribute.name];\n const connection = record[`${attribute.name}Connection`] as ConnectionCount | undefined;\n const total = connection?.aggregate?.count?.nodes;\n\n if (typeof total === 'number') {\n counts[source.key] = { ...counts[source.key], [attribute.name]: total };\n }\n\n if (!Array.isArray(relatedRecords)) {\n return;\n }\n\n (relatedRecords as GraphRecord[]).forEach((relatedRecord) => {\n const target: GraphNode = {\n key: nodeKey(relatedEntityName, relatedRecord._id),\n entity: relatedEntityName,\n id: relatedRecord._id,\n label: captionOf(relatedRecord, relatedEntity, scope),\n };\n\n if (!nodes.has(target.key)) {\n nodes.set(target.key, target);\n }\n\n if (target.key !== source.key) {\n const edge = edgeOf(source, target, attribute);\n\n if (!edges.has(edge.key)) {\n edges.set(edge.key, edge);\n }\n }\n });\n });\n });\n\n return { nodes: [...nodes.values()], edges: [...edges.values()], counts };\n}\n\n/** How many related records each record carries per relationship, to continue paging from. */\nexport function fetchedFromRecords(records: GraphRecord[], entity: Entity): GraphCounts {\n const fetched: GraphCounts = {};\n\n records.forEach((record) => {\n getRelationshipAttributes(entity).forEach((attribute) => {\n const related = record[attribute.name];\n\n if (Array.isArray(related)) {\n const key = nodeKey(entity.name, record._id);\n fetched[key] = { ...fetched[key], [attribute.name]: related.length };\n }\n });\n });\n\n return fetched;\n}\n\n/** The Graph app route for an entity, optionally for given records. */\nexport function graphPath(projectId: string, { entity, ids }: { entity: string; ids?: string[] }): string {\n const params = new URLSearchParams({ entity });\n\n if (ids && ids.length > 0) {\n params.set('ids', ids.join(','));\n }\n\n return `/${projectId}/graph?${params.toString()}`;\n}\n\nexport function parseGraphParams(search: string): { entity: string; ids: string[] } | null {\n const params = new URLSearchParams(search);\n const entity = params.get('entity');\n\n if (!entity) {\n return null;\n }\n\n const ids = (params.get('ids') ?? '')\n .split(',')\n .map((id) => id.trim())\n .filter(Boolean);\n\n return { entity, ids };\n}\n"]}