@flexkit/studio 0.2.19 → 0.2.21

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 (101) hide show
  1. package/dist/activity-nav-button-7RLCHOFV.js +2 -0
  2. package/dist/{activity-nav-button-V5DFHADL.js.map → activity-nav-button-7RLCHOFV.js.map} +1 -1
  3. package/dist/chat-page-QKSMDM7A.js +4 -0
  4. package/dist/chat-page-QKSMDM7A.js.map +1 -0
  5. package/dist/chunk-3TAYSYYW.js +7 -0
  6. package/dist/{chunk-XNHSHVG2.js.map → chunk-3TAYSYYW.js.map} +1 -1
  7. package/dist/{chunk-ME55YNBF.js → chunk-4PUMSUJL.js} +2 -2
  8. package/dist/{chunk-ME55YNBF.js.map → chunk-4PUMSUJL.js.map} +1 -1
  9. package/dist/{chunk-BMX4URYN.js → chunk-7ERLYAPR.js} +2 -2
  10. package/dist/{chunk-BMX4URYN.js.map → chunk-7ERLYAPR.js.map} +1 -1
  11. package/dist/chunk-7KLXWCDS.js +3 -0
  12. package/dist/chunk-7KLXWCDS.js.map +1 -0
  13. package/dist/{chunk-4IEOAKKK.js → chunk-7KRDPQXX.js} +2 -2
  14. package/dist/{chunk-4IEOAKKK.js.map → chunk-7KRDPQXX.js.map} +1 -1
  15. package/dist/{chunk-HCJAM5LG.js → chunk-AFLZA2R5.js} +2 -2
  16. package/dist/{chunk-HCJAM5LG.js.map → chunk-AFLZA2R5.js.map} +1 -1
  17. package/dist/chunk-AHR2EZGG.js +4 -0
  18. package/dist/{chunk-VMWUMFUL.js.map → chunk-AHR2EZGG.js.map} +1 -1
  19. package/dist/chunk-BXUW6OXZ.js +2 -0
  20. package/dist/{chunk-ZKA2HKNI.js.map → chunk-BXUW6OXZ.js.map} +1 -1
  21. package/dist/chunk-DZS344SD.js +378 -0
  22. package/dist/chunk-DZS344SD.js.map +1 -0
  23. package/dist/chunk-ELOJGLAR.js +2 -0
  24. package/dist/chunk-ELOJGLAR.js.map +1 -0
  25. package/dist/chunk-HKN6BX5U.js +2 -0
  26. package/dist/chunk-HKN6BX5U.js.map +1 -0
  27. package/dist/{chunk-DFLAX7EE.js → chunk-I4INIJFN.js} +2 -2
  28. package/dist/{chunk-DFLAX7EE.js.map → chunk-I4INIJFN.js.map} +1 -1
  29. package/dist/{chunk-QWQHXMXW.js → chunk-MJICM7YP.js} +2 -2
  30. package/dist/{chunk-QWQHXMXW.js.map → chunk-MJICM7YP.js.map} +1 -1
  31. package/dist/chunk-MLHXPTBT.js +2 -0
  32. package/dist/chunk-MLHXPTBT.js.map +1 -0
  33. package/dist/{chunk-H2RWSC56.js → chunk-PLZUH56T.js} +3 -3
  34. package/dist/{chunk-H2RWSC56.js.map → chunk-PLZUH56T.js.map} +1 -1
  35. package/dist/{chunk-UOR437J2.js → chunk-QCVQJN5O.js} +2 -2
  36. package/dist/{chunk-UOR437J2.js.map → chunk-QCVQJN5O.js.map} +1 -1
  37. package/dist/{chunk-DHVKE36X.js → chunk-SY67F62K.js} +3 -3
  38. package/dist/{chunk-DHVKE36X.js.map → chunk-SY67F62K.js.map} +1 -1
  39. package/dist/chunk-T2DOW23R.js +3 -0
  40. package/dist/chunk-T2DOW23R.js.map +1 -0
  41. package/dist/{chunk-6RRB47OZ.js → chunk-YBLY77TV.js} +5 -5
  42. package/dist/{chunk-6RRB47OZ.js.map → chunk-YBLY77TV.js.map} +1 -1
  43. package/dist/{chunk-V6RB45UU.js → chunk-YJM2RPTA.js} +2 -2
  44. package/dist/{chunk-V6RB45UU.js.map → chunk-YJM2RPTA.js.map} +1 -1
  45. package/dist/{entry-3JSFO4OU.js → entry-BKWT63OH.js} +2 -2
  46. package/dist/{entry-3JSFO4OU.js.map → entry-BKWT63OH.js.map} +1 -1
  47. package/dist/index.css +24 -0
  48. package/dist/index.js +6 -6
  49. package/dist/index.js.map +1 -1
  50. package/dist/list-F2MN4VI4.js +3 -0
  51. package/dist/{list-SY3L2ACH.js.map → list-F2MN4VI4.js.map} +1 -1
  52. package/dist/list-RFIARR7J.js +2 -0
  53. package/dist/{list-Z2C74QDN.js.map → list-RFIARR7J.js.map} +1 -1
  54. package/dist/{pages-INCA54HE.js → pages-6YG37BSV.js} +3 -3
  55. package/dist/{pages-INCA54HE.js.map → pages-6YG37BSV.js.map} +1 -1
  56. package/dist/plugin-pages-R5QCB5GZ.js +2 -0
  57. package/dist/{plugin-pages-WO3MCJKC.js.map → plugin-pages-R5QCB5GZ.js.map} +1 -1
  58. package/dist/record-links-BACU2DWS.js +2 -0
  59. package/dist/{record-links-CTB4SC4J.js.map → record-links-BACU2DWS.js.map} +1 -1
  60. package/dist/root-6FML7PJC.js +23 -0
  61. package/dist/{root-DOOWSYWY.js.map → root-6FML7PJC.js.map} +1 -1
  62. package/dist/{root-XHXX3SZG.js → root-FCO3MQTE.js} +3 -3
  63. package/dist/{root-XHXX3SZG.js.map → root-FCO3MQTE.js.map} +1 -1
  64. package/dist/{root-JA2LFGNX.js → root-MQ5FZRMQ.js} +2 -2
  65. package/dist/{root-JA2LFGNX.js.map → root-MQ5FZRMQ.js.map} +1 -1
  66. package/dist/root-MTJAYVPT.js +14 -0
  67. package/dist/root-MTJAYVPT.js.map +1 -0
  68. package/dist/{root-6MSWGFZX.js → root-U4QMDA3Q.js} +2 -2
  69. package/dist/{root-6MSWGFZX.js.map → root-U4QMDA3Q.js.map} +1 -1
  70. package/dist/root-UCQDMHDV.js +2 -0
  71. package/dist/{root-OGX4DUTM.js.map → root-UCQDMHDV.js.map} +1 -1
  72. package/dist/{search-Z4M4R4NJ.js → search-7DVZZIZ6.js} +2 -2
  73. package/dist/{search-Z4M4R4NJ.js.map → search-7DVZZIZ6.js.map} +1 -1
  74. package/dist/skills-pages-EPIBHZVO.js +2 -0
  75. package/dist/skills-pages-EPIBHZVO.js.map +1 -0
  76. package/dist/source-F6B2UBWX.js +2 -0
  77. package/dist/{source-5J56KIFA.js.map → source-F6B2UBWX.js.map} +1 -1
  78. package/package.json +4 -1
  79. package/dist/activity-nav-button-V5DFHADL.js +0 -2
  80. package/dist/chat-page-LAK4TFN4.js +0 -4
  81. package/dist/chat-page-LAK4TFN4.js.map +0 -1
  82. package/dist/chunk-A7XHA2P6.js +0 -3
  83. package/dist/chunk-A7XHA2P6.js.map +0 -1
  84. package/dist/chunk-BMO7JFAX.js +0 -2
  85. package/dist/chunk-BMO7JFAX.js.map +0 -1
  86. package/dist/chunk-OOYCTZ3C.js +0 -379
  87. package/dist/chunk-OOYCTZ3C.js.map +0 -1
  88. package/dist/chunk-VMWUMFUL.js +0 -4
  89. package/dist/chunk-XNHSHVG2.js +0 -7
  90. package/dist/chunk-ZKA2HKNI.js +0 -2
  91. package/dist/list-SY3L2ACH.js +0 -3
  92. package/dist/list-Z2C74QDN.js +0 -2
  93. package/dist/plugin-pages-WO3MCJKC.js +0 -2
  94. package/dist/record-links-CTB4SC4J.js +0 -2
  95. package/dist/root-B4D3C37Q.js +0 -2
  96. package/dist/root-B4D3C37Q.js.map +0 -1
  97. package/dist/root-DOOWSYWY.js +0 -23
  98. package/dist/root-OGX4DUTM.js +0 -2
  99. package/dist/skills-pages-TP2XQPCQ.js +0 -2
  100. package/dist/skills-pages-TP2XQPCQ.js.map +0 -1
  101. package/dist/source-5J56KIFA.js +0 -2
@@ -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","display","getDisplayAttribute","scopeType","getScopeFields","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":"mIAYO,IAAMA,CAAAA,CAAc,EAAA,CAEdC,CAAAA,CAAe,GAEfC,CAAAA,CAAY,GAAA,CAEZC,CAAAA,CAAyB,EAAA,CAGhCC,EAAkB,IAAI,GAAA,CAAI,CAAC,QAAQ,CAAC,CAAA,CAU7BC,CAAAA,CAAgB,CAC3B,MAAO,CACL,SAAA,CACA,SAAA,CACA,SAAA,CACA,UACA,SAAA,CACA,SAAA,CACA,SAAA,CACA,SAAA,CACA,UACA,SAAA,CACA,SAAA,CACA,SACF,CAAA,CACA,IAAA,CAAM,CACJ,SAAA,CACA,SAAA,CACA,UACA,SAAA,CACA,SAAA,CACA,SAAA,CACA,SAAA,CACA,UACA,SAAA,CACA,SAAA,CACA,SAAA,CACA,SACF,CACF,EAgCO,SAASC,CAAAA,CAAQC,CAAAA,CAAgBC,CAAAA,CAAoB,CAC1D,OAAO,CAAA,EAAGD,CAAM,CAAA,CAAA,EAAIC,CAAE,CAAA,CACxB,CAGO,SAASC,CAAAA,CAA0BF,CAAAA,CAA6B,CACrE,OAAOA,EAAO,UAAA,CAAW,MAAA,CACtBG,CAAAA,EACCC,CAAAA,CAAkBD,CAAS,CAAA,GAAM,cAAA,EACjCA,CAAAA,CAAU,eAAiB,MAAA,EAC3B,CAACN,CAAAA,CAAgB,GAAA,CAAIM,EAAU,YAAA,CAAa,MAAM,CACtD,CACF,CAGO,SAASE,CAAAA,CAAiBC,CAAAA,CAA4B,CAC3D,OAAOA,CAAAA,CAAO,MAAA,CAAQN,CAAAA,EAAW,CAACH,CAAAA,CAAgB,GAAA,CAAIG,CAAAA,CAAO,IAAI,GAAKE,CAAAA,CAA0BF,CAAM,CAAA,CAAE,MAAA,CAAS,CAAC,CACpH,CAEO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,CAAG,CAAC9D,CAAAA,CAAU,IAAI,EAAG6D,CAAAA,CAAQ,MAAO,EACrE,CACF,CAAC,EACH,CAAC,CAAA,CAEMD,CACT,CAGO,SAASG,EAAAA,CAAUC,CAAAA,CAAmB,CAAE,MAAA,CAAAnE,CAAAA,CAAQ,GAAA,CAAAoE,CAAI,CAAA,CAA+C,CACxG,IAAMC,CAAAA,CAAS,IAAI,eAAA,CAAgB,CAAE,MAAA,CAAArE,CAAO,CAAC,CAAA,CAE7C,OAAIoE,CAAAA,EAAOA,CAAAA,CAAI,MAAA,CAAS,CAAA,EACtBC,CAAAA,CAAO,GAAA,CAAI,KAAA,CAAOD,CAAAA,CAAI,IAAA,CAAK,GAAG,CAAC,CAAA,CAG1B,CAAA,CAAA,EAAID,CAAS,CAAA,OAAA,EAAUE,CAAAA,CAAO,QAAA,EAAU,CAAA,CACjD,CAEO,SAASC,EAAAA,CAAiBC,CAAAA,CAA0D,CACzF,IAAMF,CAAAA,CAAS,IAAI,eAAA,CAAgBE,CAAM,CAAA,CACnCvE,CAAAA,CAASqE,CAAAA,CAAO,GAAA,CAAI,QAAQ,CAAA,CAElC,GAAI,CAACrE,CAAAA,CACH,OAAO,IAAA,CAGT,IAAMoE,CAAAA,CAAAA,CAAOC,CAAAA,CAAO,GAAA,CAAI,KAAK,CAAA,EAAK,EAAA,EAC/B,KAAA,CAAM,GAAG,CAAA,CACT,GAAA,CAAKpE,CAAAA,EAAOA,CAAAA,CAAG,IAAA,EAAM,CAAA,CACrB,MAAA,CAAO,OAAO,CAAA,CAEjB,OAAO,CAAE,MAAA,CAAAD,CAAAA,CAAQ,GAAA,CAAAoE,CAAI,CACvB","file":"chunk-ME55YNBF.js","sourcesContent":["import { find, propEq } from 'ramda';\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(entity: Entity | undefined, scope: string): 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)} }`;\n }\n\n return '';\n}\n\n/** The scope value and the default one to fall back on, as the Desk queries select them. */\nexport function getScopeFields(scope: string): string {\n return scope === 'default' ? 'default' : `default ${scope}`;\n}\n\nfunction getRelatedSelection(attribute: Attribute, schema: Entity[], scope: string, args: string): string {\n const relatedEntity = getEntity(schema, attribute.relationship?.entity ?? '');\n\n return `${attribute.name}${args} { _id ${getDisplaySelection(relatedEntity, scope)} }`;\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 entity,\n schema,\n scope,\n expand,\n}: {\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})`)\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)}\n ${relationships.join('\\n ')}\n }\n}`;\n}\n\n/** One more page of a single relationship of one record. */\nexport function buildExpandQuery({\n entity,\n schema,\n scope,\n attribute,\n}: {\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)')}\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({ entity, scope }: { entity: Entity; scope: string }): string {\n const fields = getDetailAttributes(entity).map((attribute) =>\n getAttributeScope(attribute) === 'local' ? `${attribute.name} { ${getScopeFields(scope)} }` : 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","display","getDisplayAttribute","scopeType","getScopeFields","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":"mIAYO,IAAMA,CAAAA,CAAc,E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CAAI,CAAA,CAA+C,CACxG,IAAMC,CAAAA,CAAS,IAAI,eAAA,CAAgB,CAAE,MAAA,CAAArE,CAAO,CAAC,CAAA,CAE7C,OAAIoE,CAAAA,EAAOA,CAAAA,CAAI,MAAA,CAAS,CAAA,EACtBC,CAAAA,CAAO,GAAA,CAAI,KAAA,CAAOD,CAAAA,CAAI,IAAA,CAAK,GAAG,CAAC,CAAA,CAG1B,CAAA,CAAA,EAAID,CAAS,CAAA,OAAA,EAAUE,CAAAA,CAAO,QAAA,EAAU,CAAA,CACjD,CAEO,SAASC,EAAAA,CAAiBC,CAAAA,CAA0D,CACzF,IAAMF,CAAAA,CAAS,IAAI,eAAA,CAAgBE,CAAM,CAAA,CACnCvE,CAAAA,CAASqE,CAAAA,CAAO,GAAA,CAAI,QAAQ,CAAA,CAElC,GAAI,CAACrE,CAAAA,CACH,OAAO,IAAA,CAGT,IAAMoE,CAAAA,CAAAA,CAAOC,CAAAA,CAAO,GAAA,CAAI,KAAK,CAAA,EAAK,EAAA,EAC/B,KAAA,CAAM,GAAG,CAAA,CACT,GAAA,CAAKpE,CAAAA,EAAOA,CAAAA,CAAG,IAAA,EAAM,CAAA,CACrB,MAAA,CAAO,OAAO,CAAA,CAEjB,OAAO,CAAE,MAAA,CAAAD,CAAAA,CAAQ,GAAA,CAAAoE,CAAI,CACvB","file":"chunk-4PUMSUJL.js","sourcesContent":["import { find, propEq } from 'ramda';\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(entity: Entity | undefined, scope: string): 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)} }`;\n }\n\n return '';\n}\n\n/** The scope value and the default one to fall back on, as the Desk queries select them. */\nexport function getScopeFields(scope: string): string {\n return scope === 'default' ? 'default' : `default ${scope}`;\n}\n\nfunction getRelatedSelection(attribute: Attribute, schema: Entity[], scope: string, args: string): string {\n const relatedEntity = getEntity(schema, attribute.relationship?.entity ?? '');\n\n return `${attribute.name}${args} { _id ${getDisplaySelection(relatedEntity, scope)} }`;\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 entity,\n schema,\n scope,\n expand,\n}: {\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})`)\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)}\n ${relationships.join('\\n ')}\n }\n}`;\n}\n\n/** One more page of a single relationship of one record. */\nexport function buildExpandQuery({\n entity,\n schema,\n scope,\n attribute,\n}: {\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)')}\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({ entity, scope }: { entity: Entity; scope: string }): string {\n const fields = getDetailAttributes(entity).map((attribute) =>\n getAttributeScope(attribute) === 'local' ? `${attribute.name} { ${getScopeFields(scope)} }` : 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,2 +1,2 @@
1
- import'./index.css';import {g,f as f$1}from'./chunk-DHVKE36X.js';import {b}from'./chunk-5CVDMZUI.js';import {a,b as b$1,c,e}from'./chunk-USNXQOMJ.js';import {b as b$2}from'./chunk-6NRQMG26.js';import {useEffect}from'react';import {BellIcon}from'lucide-react';import {Link}from'react-router-dom';import A from'swr';import {jsx,jsxs}from'react/jsx-runtime';function T(t){let{data:i}=A(t?g(t).activitySummary():null,f$1,{refreshInterval:3e4});return i}function f(t){return t>99?"99+":t.toString()}function $({projectId:t}){let i=T(t),e$1=i?.needsActionCount??0,r=i?.unreadCount??0;useEffect(()=>{let n=b();if(n)return n.setBadgeCount(e$1),()=>{n.setBadgeCount(0);}},[e$1]);let s=e$1>0?`Activity: ${f(e$1)} waiting for you`:r>0?`Activity: ${f(r)} unread`:"Activity";return jsx(a,{children:jsxs(b$1,{children:[jsx(c,{asChild:true,children:jsx(b$2,{asChild:true,"aria-label":s,className:"fk:relative fk:h-8 fk:w-8 fk:rounded-full",size:"icon",variant:"ghost",children:jsxs(Link,{to:`/${t}/ai/activity`,children:[jsx(BellIcon,{className:"fk:size-4"}),e$1>0?jsx("span",{className:"fk:absolute fk:-right-1 fk:-top-1 fk:flex fk:h-4 fk:min-w-4 fk:items-center fk:justify-center fk:rounded-full fk:bg-amber-500 fk:px-1 fk:text-[0.625rem] fk:font-semibold fk:leading-none fk:text-white",children:f(e$1)}):r>0?jsx("span",{className:"fk:absolute fk:right-1 fk:top-1 fk:size-2 fk:rounded-full fk:bg-success"}):null]})})}),jsx(e,{children:s})]})})}export{T as a,$ as b};//# sourceMappingURL=chunk-BMX4URYN.js.map
2
- //# sourceMappingURL=chunk-BMX4URYN.js.map
1
+ import'./index.css';import {g,f as f$1}from'./chunk-SY67F62K.js';import {b}from'./chunk-5CVDMZUI.js';import {a,b as b$1,c,e}from'./chunk-USNXQOMJ.js';import {b as b$2}from'./chunk-6NRQMG26.js';import {useEffect}from'react';import {BellIcon}from'lucide-react';import {Link}from'react-router-dom';import A from'swr';import {jsx,jsxs}from'react/jsx-runtime';function T(t){let{data:i}=A(t?g(t).activitySummary():null,f$1,{refreshInterval:3e4});return i}function f(t){return t>99?"99+":t.toString()}function $({projectId:t}){let i=T(t),e$1=i?.needsActionCount??0,r=i?.unreadCount??0;useEffect(()=>{let n=b();if(n)return n.setBadgeCount(e$1),()=>{n.setBadgeCount(0);}},[e$1]);let s=e$1>0?`Activity: ${f(e$1)} waiting for you`:r>0?`Activity: ${f(r)} unread`:"Activity";return jsx(a,{children:jsxs(b$1,{children:[jsx(c,{asChild:true,children:jsx(b$2,{asChild:true,"aria-label":s,className:"fk:relative fk:h-8 fk:w-8 fk:rounded-full",size:"icon",variant:"ghost",children:jsxs(Link,{to:`/${t}/ai/activity`,children:[jsx(BellIcon,{className:"fk:size-4"}),e$1>0?jsx("span",{className:"fk:absolute fk:-right-1 fk:-top-1 fk:flex fk:h-4 fk:min-w-4 fk:items-center fk:justify-center fk:rounded-full fk:bg-amber-500 fk:px-1 fk:text-[0.625rem] fk:font-semibold fk:leading-none fk:text-white",children:f(e$1)}):r>0?jsx("span",{className:"fk:absolute fk:right-1 fk:top-1 fk:size-2 fk:rounded-full fk:bg-success"}):null]})})}),jsx(e,{children:s})]})})}export{T as a,$ as b};//# sourceMappingURL=chunk-7ERLYAPR.js.map
2
+ //# sourceMappingURL=chunk-7ERLYAPR.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/apps/ai/activity-nav-button.tsx"],"names":["useActivitySummary","projectId","data","useSWR","paths","fetcher","formatCount","count","ActivityNavButton","summary","needsAction","unread","useEffect","desktop","getDesktop","label","jsx","TooltipProvider","jsxs","Tooltip","TooltipTrigger","Button","Link","BellIcon","TooltipContent"],"mappings":"mWAeO,SAASA,CAAAA,CAAmBC,EAA4D,CAC7F,GAAM,CAAE,IAAA,CAAAC,CAAK,EAAIC,CAAAA,CAAwBF,CAAAA,CAAYG,EAAMH,CAAS,CAAA,CAAE,iBAAgB,CAAI,IAAA,CAAMI,IAAS,CACvG,eAAA,CAAiB,GACnB,CAAC,CAAA,CAED,OAAOH,CACT,CAEA,SAASI,EAAYC,CAAAA,CAAuB,CAC1C,OAAOA,CAAAA,CAAQ,EAAA,CAAK,MAAQA,CAAAA,CAAM,QAAA,EACpC,CAGO,SAASC,EAAkB,CAAE,SAAA,CAAAP,CAAU,CAAA,CAAuC,CACnF,IAAMQ,CAAAA,CAAUT,CAAAA,CAAmBC,CAAS,CAAA,CACtCS,GAAAA,CAAcD,GAAS,gBAAA,EAAoB,CAAA,CAC3CE,EAASF,CAAAA,EAAS,WAAA,EAAe,EAGvCG,SAAAA,CAAU,IAAM,CACd,IAAMC,CAAAA,CAAUC,GAAW,CAE3B,GAAKD,EAIL,OAAAA,CAAAA,CAAQ,cAAcH,GAAW,CAAA,CAE1B,IAAM,CACXG,CAAAA,CAAQ,aAAA,CAAc,CAAC,EACzB,CACF,EAAG,CAACH,GAAW,CAAC,CAAA,CAEhB,IAAMK,EACJL,GAAAA,CAAc,CAAA,CACV,aAAaJ,CAAAA,CAAYI,GAAW,CAAC,CAAA,gBAAA,CAAA,CACrCC,CAAAA,CAAS,EACP,CAAA,UAAA,EAAaL,CAAAA,CAAYK,CAAM,CAAC,CAAA,OAAA,CAAA,CAChC,WAER,OACEK,GAAAA,CAACC,EAAA,CACC,QAAA,CAAAC,KAACC,GAAAA,CAAA,CACC,UAAAH,GAAAA,CAACI,CAAAA,CAAA,CAAe,OAAA,CAAO,IAAA,CACrB,SAAAJ,GAAAA,CAACK,GAAAA,CAAA,CAAO,OAAA,CAAO,IAAA,CAAC,YAAA,CAAYN,CAAAA,CAAO,SAAA,CAAU,2CAAA,CAA4C,KAAK,MAAA,CAAO,OAAA,CAAQ,QAC3G,QAAA,CAAAG,IAAAA,CAACI,KAAA,CAAK,EAAA,CAAI,IAAIrB,CAAS,CAAA,YAAA,CAAA,CACrB,UAAAe,GAAAA,CAACO,QAAAA,CAAA,CAAS,SAAA,CAAU,WAAA,CAAY,EAC/Bb,GAAAA,CAAc,CAAA,CACbM,GAAAA,CAAC,MAAA,CAAA,CAAK,SAAA,CAAU,yMAAA,CACb,SAAAV,CAAAA,CAAYI,GAAW,EAC1B,CAAA,CACEC,CAAAA,CAAS,EACXK,GAAAA,CAAC,MAAA,CAAA,CAAK,UAAU,yEAAA,CAA0E,CAAA,CACxF,MACN,CAAA,CACF,CAAA,CACF,EACAA,GAAAA,CAACQ,CAAAA,CAAA,CAAgB,QAAA,CAAAT,CAAAA,CAAM,CAAA,CAAA,CACzB,CAAA,CACF,CAEJ","file":"chunk-BMX4URYN.js","sourcesContent":["import { useEffect } from 'react';\nimport type { JSX } from 'react';\nimport { BellIcon } from 'lucide-react';\nimport { Link } from 'react-router-dom';\nimport useSWR from 'swr';\nimport { Button } from '../../ui/primitives/button';\nimport { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../../ui/primitives/tooltip';\nimport { getDesktop } from '../../core/desktop';\nimport { fetcher, paths } from './api';\nimport type { ActivitySummary } from './types';\n\n/**\n * The project's Activity badge counts. `ActivityNotifier` refreshes the same\n * SWR key on every poll, so every reader stays in sync with one request.\n */\nexport function useActivitySummary(projectId: string | undefined): ActivitySummary | undefined {\n const { data } = useSWR<ActivitySummary>(projectId ? paths(projectId).activitySummary() : null, fetcher, {\n refreshInterval: 30_000,\n });\n\n return data;\n}\n\nfunction formatCount(count: number): string {\n return count > 99 ? '99+' : count.toString();\n}\n\n/** Navbar shortcut to Activity, so pending items are visible from every app. */\nexport function ActivityNavButton({ projectId }: { projectId: string }): JSX.Element {\n const summary = useActivitySummary(projectId);\n const needsAction = summary?.needsActionCount ?? 0;\n const unread = summary?.unreadCount ?? 0;\n // The desktop app shows what waits for you on its dock or taskbar icon;\n // leaving the project or signing out clears it.\n useEffect(() => {\n const desktop = getDesktop();\n\n if (!desktop) {\n return;\n }\n\n desktop.setBadgeCount(needsAction);\n\n return () => {\n desktop.setBadgeCount(0);\n };\n }, [needsAction]);\n\n const label =\n needsAction > 0\n ? `Activity: ${formatCount(needsAction)} waiting for you`\n : unread > 0\n ? `Activity: ${formatCount(unread)} unread`\n : 'Activity';\n\n return (\n <TooltipProvider>\n <Tooltip>\n <TooltipTrigger asChild>\n <Button asChild aria-label={label} className=\"fk:relative fk:h-8 fk:w-8 fk:rounded-full\" size=\"icon\" variant=\"ghost\">\n <Link to={`/${projectId}/ai/activity`}>\n <BellIcon className=\"fk:size-4\" />\n {needsAction > 0 ? (\n <span className=\"fk:absolute fk:-right-1 fk:-top-1 fk:flex fk:h-4 fk:min-w-4 fk:items-center fk:justify-center fk:rounded-full fk:bg-amber-500 fk:px-1 fk:text-[0.625rem] fk:font-semibold fk:leading-none fk:text-white\">\n {formatCount(needsAction)}\n </span>\n ) : unread > 0 ? (\n <span className=\"fk:absolute fk:right-1 fk:top-1 fk:size-2 fk:rounded-full fk:bg-success\" />\n ) : null}\n </Link>\n </Button>\n </TooltipTrigger>\n <TooltipContent>{label}</TooltipContent>\n </Tooltip>\n </TooltipProvider>\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/apps/ai/activity-nav-button.tsx"],"names":["useActivitySummary","projectId","data","useSWR","paths","fetcher","formatCount","count","ActivityNavButton","summary","needsAction","unread","useEffect","desktop","getDesktop","label","jsx","TooltipProvider","jsxs","Tooltip","TooltipTrigger","Button","Link","BellIcon","TooltipContent"],"mapp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AC3G,QAAA,CAAAG,IAAAA,CAACI,KAAA,CAAK,EAAA,CAAI,IAAIrB,CAAS,CAAA,YAAA,CAAA,CACrB,UAAAe,GAAAA,CAACO,QAAAA,CAAA,CAAS,SAAA,CAAU,WAAA,CAAY,EAC/Bb,GAAAA,CAAc,CAAA,CACbM,GAAAA,CAAC,MAAA,CAAA,CAAK,SAAA,CAAU,yMAAA,CACb,SAAAV,CAAAA,CAAYI,GAAW,EAC1B,CAAA,CACEC,CAAAA,CAAS,EACXK,GAAAA,CAAC,MAAA,CAAA,CAAK,UAAU,yEAAA,CAA0E,CAAA,CACxF,MACN,CAAA,CACF,CAAA,CACF,EACAA,GAAAA,CAACQ,CAAAA,CAAA,CAAgB,QAAA,CAAAT,CAAAA,CAAM,CAAA,CAAA,CACzB,CAAA,CACF,CAEJ","file":"chunk-7ERLYAPR.js","sourcesContent":["import { useEffect } from 'react';\nimport type { JSX } from 'react';\nimport { BellIcon } from 'lucide-react';\nimport { Link } from 'react-router-dom';\nimport useSWR from 'swr';\nimport { Button } from '../../ui/primitives/button';\nimport { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../../ui/primitives/tooltip';\nimport { getDesktop } from '../../core/desktop';\nimport { fetcher, paths } from './api';\nimport type { ActivitySummary } from './types';\n\n/**\n * The project's Activity badge counts. `ActivityNotifier` refreshes the same\n * SWR key on every poll, so every reader stays in sync with one request.\n */\nexport function useActivitySummary(projectId: string | undefined): ActivitySummary | undefined {\n const { data } = useSWR<ActivitySummary>(projectId ? paths(projectId).activitySummary() : null, fetcher, {\n refreshInterval: 30_000,\n });\n\n return data;\n}\n\nfunction formatCount(count: number): string {\n return count > 99 ? '99+' : count.toString();\n}\n\n/** Navbar shortcut to Activity, so pending items are visible from every app. */\nexport function ActivityNavButton({ projectId }: { projectId: string }): JSX.Element {\n const summary = useActivitySummary(projectId);\n const needsAction = summary?.needsActionCount ?? 0;\n const unread = summary?.unreadCount ?? 0;\n // The desktop app shows what waits for you on its dock or taskbar icon;\n // leaving the project or signing out clears it.\n useEffect(() => {\n const desktop = getDesktop();\n\n if (!desktop) {\n return;\n }\n\n desktop.setBadgeCount(needsAction);\n\n return () => {\n desktop.setBadgeCount(0);\n };\n }, [needsAction]);\n\n const label =\n needsAction > 0\n ? `Activity: ${formatCount(needsAction)} waiting for you`\n : unread > 0\n ? `Activity: ${formatCount(unread)} unread`\n : 'Activity';\n\n return (\n <TooltipProvider>\n <Tooltip>\n <TooltipTrigger asChild>\n <Button asChild aria-label={label} className=\"fk:relative fk:h-8 fk:w-8 fk:rounded-full\" size=\"icon\" variant=\"ghost\">\n <Link to={`/${projectId}/ai/activity`}>\n <BellIcon className=\"fk:size-4\" />\n {needsAction > 0 ? (\n <span className=\"fk:absolute fk:-right-1 fk:-top-1 fk:flex fk:h-4 fk:min-w-4 fk:items-center fk:justify-center fk:rounded-full fk:bg-amber-500 fk:px-1 fk:text-[0.625rem] fk:font-semibold fk:leading-none fk:text-white\">\n {formatCount(needsAction)}\n </span>\n ) : unread > 0 ? (\n <span className=\"fk:absolute fk:right-1 fk:top-1 fk:size-2 fk:rounded-full fk:bg-success\" />\n ) : null}\n </Link>\n </Button>\n </TooltipTrigger>\n <TooltipContent>{label}</TooltipContent>\n </Tooltip>\n </TooltipProvider>\n );\n}\n"]}
@@ -0,0 +1,3 @@
1
+ import'./index.css';import {a as a$1}from'./chunk-HKN6BX5U.js';var l=20*1024*1024,L=200,k=20,d=["pdf","docx","pptx","md","markdown","txt","html","htm"],P=d.map(e=>`.${e}`).join(","),p="PDF, Word, PowerPoint, Markdown, text or HTML",w=new Set(d);function m(e){let t=/\.([a-z0-9]{1,8})$/i.exec(e.trim());return t?t[1].toLowerCase():null}function T(e){let t=m(e.name);return !t||!w.has(t)?`${e.name} is not a supported document. Add ${p} files.`:e.size<=0?`${e.name} is empty.`:e.size>l?`${e.name} is larger than ${K(l)}.`:null}function K(e){return e<1024?`${String(e)} B`:e<1024*1024?`${(e/1024).toFixed(e<10*1024?1:0)} KB`:`${(e/(1024*1024)).toFixed(e<10*1024*1024?1:0)} MB`}function I(e){let t=e.trim();if(!t)return {error:"Enter the address of a public page."};let n;try{n=new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:`https://${t}`);}catch{return {error:"Enter a valid address, for example https://example.com/handbook"}}return n.protocol!=="https:"?{error:"The address must use HTTPS."}:n.username||n.password?{error:"The address cannot include credentials."}:(n.hash="",{url:n.toString()})}var f={icon:"html",label:"Web page"},g={icon:"txt",label:"Text"},x={"application/pdf":{icon:"pdf",label:"PDF"},"application/vnd.openxmlformats-officedocument.wordprocessingml.document":{icon:"docx",label:"Word"},"application/vnd.openxmlformats-officedocument.presentationml.presentation":{icon:"pptx",label:"PowerPoint"},"text/markdown":{icon:"document",label:"Markdown"},"text/html":{icon:"html",label:"HTML"},"text/plain":g};function b(e){return e.kind==="url"?f:x[e.mimeType]??g}function A(e){return b(e).label}function u(e){return !!(e&&(e.state==="queued"||e.state==="extracting"||e.state==="embedding"||e.state==="publishing"))}function _(e,t){return e.status==="processing"||u(t)}function S(e){let{progress:t}=e;switch(e.state){case "queued":return "Waiting to be processed";case "extracting":return "Reading the document";case "embedding":return t?.passageCount?`Indexing passages (${String(t.embeddedCount??0)} of ${String(t.passageCount)})`:"Indexing passages";case "publishing":return "Publishing";default:return t?.message??e.state}}function $(e,t){let n=e.currentVersion,r=n?.status==="published",o=n?.passageCount??0,i=`${String(o)} ${o===1?"passage":"passages"}`;return u(t)?{label:r?"Re-indexing":"Indexing",detail:S(t),tone:"busy"}:e.status==="failed"||!r&&(t?.state==="failed"||n?.status==="failed")?{label:"Failed",detail:t?.error?.message??n?.error??"Indexing failed",tone:"error"}:e.status==="processing"||!r?{label:"Indexing",detail:"Waiting to be processed",tone:"busy"}:t?.state==="failed"?{label:"Ready",detail:`${i} \xB7 the last re-index failed: ${t.error?.message??"unknown error"}`,tone:"ready"}:n&&n.warnings.length>0?{label:"Ready",detail:`${i} \xB7 indexed with warnings`,tone:"ready"}:{label:"Ready",detail:i,tone:"ready"}}function F(e){let t=[];return e.page!==void 0&&t.push(`p. ${String(e.page)}`),e.slide!==void 0&&t.push(`slide ${String(e.slide)}`),e.headingPath&&e.headingPath.length>0&&t.push(e.headingPath.join(" \u203A ")),t.join(" \xB7 ")}function M(e){let[,t]=/^[A-Z_]+:\s*(.*)$/.exec(e)??[],n=t??e;return n.charAt(0).toUpperCase()+n.slice(1)}function R(e,t){return e.includes(t)?e.filter(n=>n!==t):[...e,t]}function W(e,t){return `/${encodeURIComponent(e)}/knowledge/${encodeURIComponent(t)}`}function C(e,t){let n=t?.trim()||(e.title??"").trim();return n||(e.recordId.length>12?`${e.recordId.slice(0,8)}\u2026`:e.recordId)}function G(e){let t=new Map;for(let n of e){let r=t.get(n.entityPlural);r||(r={entity:n.entity,entityPlural:n.entityPlural,links:[]},t.set(n.entityPlural,r)),r.links.push(n);}return [...t.values()]}function J(e,t){let n=new Set(t);return e.filter(r=>!n.has(r.id)).sort((r,o)=>+(o.status==="ready")-+(r.status==="ready"))}function h(e){return !e.startsWith("_")}function N(e,t){return e.find(n=>n.name===t)}function a(e){return e.menu?.label?.trim()||e.plural}function O(e,t){let n=new Set([...t].map(r=>r.entity));return e.filter(r=>h(r.name)&&!n.has(r.name)).sort((r,o)=>a(r).localeCompare(a(o)))}var c="flexkit-knowledge:viewMode";function V(){try{return a$1()?.getItem(c)==="grid"?"grid":"list"}catch{return "list"}}function D(e){try{a$1()?.setItem(c,e);}catch{}}
2
+ export{L as a,k as b,P as c,p as d,T as e,K as f,I as g,b as h,A as i,_ as j,$ as k,F as l,M as m,R as n,W as o,C as p,G as q,J as r,h as s,N as t,a as u,O as v,V as w,D as x};//# sourceMappingURL=chunk-7KLXWCDS.js.map
3
+ //# sourceMappingURL=chunk-7KLXWCDS.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/apps/knowledge/knowledge.ts"],"names":["KNOWLEDGE_MAX_FILE_BYTES","KNOWLEDGE_MAX_TITLE_LENGTH","KNOWLEDGE_PASSAGES_PAGE_SIZE","KNOWLEDGE_EXTENSIONS","KNOWLEDGE_ACCEPT","extension","KNOWLEDGE_FORMATS_LABEL","KNOWLEDGE_EXTENSION_SET","getExtension","filename","match","getKnowledgeFileProblem","file","formatFileSize","bytes","parseKnowledgeUrl","value","trimmed","url","WEB_PAGE_FORMAT","TEXT_FORMAT","KNOWLEDGE_FORMATS","getKnowledgeFormat","source","getKnowledgeKindLabel","isKnowledgeJobActive","job","isKnowledgeSourceBusy","describeJobPhase","progress","summarizeKnowledgeStatus","version","published","passages","readyDetail","formatKnowledgeLocator","locator","parts","formatKnowledgeWarning","warning","captured","text","toggleSpaceCode","current","code","entry","getKnowledgeSourcePath","projectId","sourceId","getKnowledgeLinkLabel","link","resolved","groupKnowledgeLinks","links","groups","group","getAttachableSources","sources","attachedIds","attached","a","b","isKnowledgeLinkableEntity","entityName","findEntityByName","schema","entity","getEntityLinkLabel","getLinkableEntities","linked","taken","VIEW_MODE_STORAGE_KEY","getStoredKnowledgeViewMode","getLocalStorage","setStoredKnowledgeViewMode","mode"],"mappings":"+DA6KO,IAAMA,CAAAA,CAA2B,GAAK,IAAA,CAAO,IAAA,CAEvCC,EAA6B,GAAA,CAG7BC,CAAAA,CAA+B,EAAA,CAEtCC,CAAAA,CAAuB,CAAC,KAAA,CAAO,OAAQ,MAAA,CAAQ,IAAA,CAAM,UAAA,CAAY,KAAA,CAAO,MAAA,CAAQ,KAAK,EAG9EC,CAAAA,CAAmBD,CAAAA,CAAqB,GAAA,CAAKE,CAAAA,EAAc,CAAA,CAAA,EAAIA,CAAS,EAAE,CAAA,CAAE,IAAA,CAAK,GAAG,CAAA,CAEpFC,CAAAA,CAA0B,gDAEjCC,CAAAA,CAA+C,IAAI,GAAA,CAAIJ,CAAoB,EAEjF,SAASK,EAAaC,CAAAA,CAAiC,CACrD,IAAMC,CAAAA,CAAQ,qBAAA,CAAsB,IAAA,CAAKD,EAAS,IAAA,EAAM,CAAA,CAExD,OAAO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AAI,GAAA,CAAI,CAAC,GAAGD,CAAM,EAAE,GAAA,CAAKnB,CAAAA,EAASA,CAAAA,CAAK,MAAM,CAAC,CAAA,CAE5D,OAAOe,CAAAA,CACJ,MAAA,CAAQC,CAAAA,EAAWJ,CAAAA,CAA0BI,CAAAA,CAAO,IAAI,GAAK,CAACI,CAAAA,CAAM,GAAA,CAAIJ,CAAAA,CAAO,IAAI,CAAC,EACpF,IAAA,CAAK,CAACN,EAAGC,CAAAA,GAAMM,CAAAA,CAAmBP,CAAC,CAAA,CAAE,aAAA,CAAcO,CAAAA,CAAmBN,CAAC,CAAC,CAAC,CAC9E,CAIA,IAAMU,CAAAA,CAAwB,4BAAA,CAGvB,SAASC,CAAAA,EAAgD,CAC9D,GAAI,CACF,OAAOC,GAAAA,EAAgB,EAAG,OAAA,CAAQF,CAAqB,CAAA,GAAM,MAAA,CAAS,OAAS,MACjF,CAAA,KAAQ,CACN,OAAO,MACT,CACF,CAEO,SAASG,CAAAA,CAA2BC,EAA+B,CACxE,GAAI,CACFF,GAAAA,EAAgB,EAAG,OAAA,CAAQF,EAAuBI,CAAI,EACxD,CAAA,KAAQ,CAER,CACF","file":"chunk-7KLXWCDS.js","sourcesContent":["import { getLocalStorage } from '../../core/local-storage';\n\n/**\n * Types and pure helpers of the Knowledge section: documents the team adds\n * so the agent can search and cite them. Everything here runs without React\n * so the list and detail pages stay thin and the rules are unit-tested.\n */\n\nexport type KnowledgeSourceKind = 'upload' | 'url';\n\nexport type KnowledgeSourceStatus = 'processing' | 'ready' | 'failed';\n\nexport type KnowledgeVersionStatus = 'processing' | 'published' | 'retired' | 'failed';\n\nexport type KnowledgeJobState =\n | 'queued'\n | 'extracting'\n | 'embedding'\n | 'publishing'\n | 'completed'\n | 'failed'\n | 'cancelled';\n\nexport interface KnowledgeLocator {\n page?: number;\n slide?: number;\n headingPath?: string[];\n charStart: number;\n charEnd: number;\n}\n\nexport interface KnowledgeVersion {\n id: string;\n status: KnowledgeVersionStatus;\n sha256: string | null;\n extractionVersion: number;\n passageCount: number;\n warnings: string[];\n error: string | null;\n publishedAt: string | null;\n createdAt: string;\n}\n\nexport interface KnowledgeSource {\n id: string;\n title: string;\n kind: KnowledgeSourceKind;\n originUrl: string | null;\n mimeType: string;\n path: string | null;\n size: number | null;\n sha256: string | null;\n /** Space codes that may read the source; empty means every project member. */\n spaces: string[];\n agentVisible: boolean;\n status: KnowledgeSourceStatus;\n createdBy: string | null;\n createdAt: string;\n updatedAt: string;\n /** The published version, or the newest one while the first ingestion runs. */\n currentVersion: KnowledgeVersion | null;\n /** The opening of the document's text, carried by listings for the grid's cards. */\n preview?: string | null;\n /** When the list was searched: whether the title or the content matched. */\n matchedIn?: 'title' | 'content' | null;\n}\n\nexport interface KnowledgeJobProgress {\n phase: KnowledgeJobState;\n message?: string;\n passageCount?: number;\n embeddedCount?: number;\n warnings?: string[];\n}\n\nexport interface KnowledgeJobError {\n code: string;\n message: string;\n hint?: string;\n}\n\nexport interface KnowledgeJob {\n id: string;\n sourceId: string;\n versionId: string;\n state: KnowledgeJobState;\n progress: KnowledgeJobProgress | null;\n error: KnowledgeJobError | null;\n createdAt: string;\n updatedAt: string;\n startedAt: string | null;\n completedAt: string | null;\n}\n\nexport interface KnowledgePassage {\n id: string;\n order: number;\n text: string;\n locator: KnowledgeLocator;\n}\n\nexport interface KnowledgeSourcesList {\n count: number;\n hasMore: boolean;\n sources: KnowledgeSource[];\n}\n\nexport interface KnowledgeSourceDetail {\n job: KnowledgeJob | null;\n source: KnowledgeSource;\n}\n\nexport interface KnowledgePassagesPage {\n passages: KnowledgePassage[];\n source: { id: string; title: string };\n total: number;\n version: { id: string; passageCount: number };\n}\n\n/** A record a document is attached to, as the platform lists it. */\nexport interface KnowledgeLink {\n entity: string;\n entityPlural: string;\n recordId: string;\n /** The record's display value when the platform could read it; null when the Studio must resolve it. */\n title: string | null;\n createdAt: string;\n}\n\n/** An entity type a document applies to: every record of the type inherits it. */\nexport interface KnowledgeEntityLink {\n entity: string;\n entityPlural: string;\n}\n\nexport interface KnowledgeLinksList {\n links: KnowledgeLink[];\n entities: KnowledgeEntityLink[];\n}\n\nexport interface KnowledgeRecordSources {\n /** Attached to the record itself. */\n sources: KnowledgeSource[];\n /** Attached to the record's entity type (and not to the record). */\n inherited: KnowledgeSource[];\n}\n\nexport interface KnowledgeEntitySources {\n sources: KnowledgeSource[];\n}\n\nexport interface KnowledgeRecordRef {\n entity: string;\n recordId: string;\n}\n\n/** What a document is attached to: a record, or every record of the entity when `recordId` is absent. */\nexport interface KnowledgeLinkTarget {\n entity: string;\n recordId?: string;\n}\n\nexport interface KnowledgeSourcePatch {\n agentVisible?: boolean;\n spaces?: string[];\n title?: string;\n}\n\n/** What registering a document returns: queued for indexing, or already present. */\nexport type RegisterKnowledgeSourceResult =\n | { duplicate: true; source: KnowledgeSource }\n | { duplicate?: false; job: KnowledgeJob; source: KnowledgeSource; version: KnowledgeVersion };\n\nexport const KNOWLEDGE_MAX_FILE_BYTES = 20 * 1024 * 1024;\n\nexport const KNOWLEDGE_MAX_TITLE_LENGTH = 200;\n\n/** Passages the API returns per page of a source. */\nexport const KNOWLEDGE_PASSAGES_PAGE_SIZE = 20;\n\nconst KNOWLEDGE_EXTENSIONS = ['pdf', 'docx', 'pptx', 'md', 'markdown', 'txt', 'html', 'htm'] as const;\n\n/** Value of the file input's `accept` attribute. */\nexport const KNOWLEDGE_ACCEPT = KNOWLEDGE_EXTENSIONS.map((extension) => `.${extension}`).join(',');\n\nexport const KNOWLEDGE_FORMATS_LABEL = 'PDF, Word, PowerPoint, Markdown, text or HTML';\n\nconst KNOWLEDGE_EXTENSION_SET: ReadonlySet<string> = new Set(KNOWLEDGE_EXTENSIONS);\n\nfunction getExtension(filename: string): string | null {\n const match = /\\.([a-z0-9]{1,8})$/i.exec(filename.trim());\n\n return match ? match[1]!.toLowerCase() : null;\n}\n\n/** Why a file cannot be added, or null when it can; mirrors the server rules so the user hears it before uploading. */\nexport function getKnowledgeFileProblem(file: { name: string; size: number }): string | null {\n const extension = getExtension(file.name);\n\n if (!extension || !KNOWLEDGE_EXTENSION_SET.has(extension)) {\n return `${file.name} is not a supported document. Add ${KNOWLEDGE_FORMATS_LABEL} files.`;\n }\n\n if (file.size <= 0) {\n return `${file.name} is empty.`;\n }\n\n if (file.size > KNOWLEDGE_MAX_FILE_BYTES) {\n return `${file.name} is larger than ${formatFileSize(KNOWLEDGE_MAX_FILE_BYTES)}.`;\n }\n\n return null;\n}\n\nexport function formatFileSize(bytes: number): string {\n if (bytes < 1024) {\n return `${String(bytes)} B`;\n }\n\n if (bytes < 1024 * 1024) {\n return `${(bytes / 1024).toFixed(bytes < 10 * 1024 ? 1 : 0)} KB`;\n }\n\n return `${(bytes / (1024 * 1024)).toFixed(bytes < 10 * 1024 * 1024 ? 1 : 0)} MB`;\n}\n\n/** A public page address the server will accept: https, no credentials, hash dropped. */\nexport function parseKnowledgeUrl(value: string): { error: string } | { url: string } {\n const trimmed = value.trim();\n\n if (!trimmed) {\n return { error: 'Enter the address of a public page.' };\n }\n\n let url: URL;\n\n try {\n url = new URL(/^[a-z][a-z0-9+.-]*:\\/\\//i.test(trimmed) ? trimmed : `https://${trimmed}`);\n } catch {\n return { error: 'Enter a valid address, for example https://example.com/handbook' };\n }\n\n if (url.protocol !== 'https:') {\n return { error: 'The address must use HTTPS.' };\n }\n\n if (url.username || url.password) {\n return { error: 'The address cannot include credentials.' };\n }\n\n url.hash = '';\n\n return { url: url.toString() };\n}\n\n/** The Untitled UI file icon drawn for a format (see `KnowledgeTypeIcon`). */\nexport type KnowledgeFileIcon = 'pdf' | 'docx' | 'pptx' | 'document' | 'txt' | 'html';\n\nexport interface KnowledgeFormat {\n /** How people call the format: \"PDF\", \"Word\", \"Web page\". */\n label: string;\n icon: KnowledgeFileIcon;\n}\n\nconst WEB_PAGE_FORMAT: KnowledgeFormat = { icon: 'html', label: 'Web page' };\nconst TEXT_FORMAT: KnowledgeFormat = { icon: 'txt', label: 'Text' };\n\n/** The formats the platform indexes, by media type; anything else it accepts reads as text. */\nexport const KNOWLEDGE_FORMATS: { readonly [mimeType: string]: KnowledgeFormat } = {\n 'application/pdf': { icon: 'pdf', label: 'PDF' },\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': { icon: 'docx', label: 'Word' },\n 'application/vnd.openxmlformats-officedocument.presentationml.presentation': { icon: 'pptx', label: 'PowerPoint' },\n 'text/markdown': { icon: 'document', label: 'Markdown' },\n 'text/html': { icon: 'html', label: 'HTML' },\n 'text/plain': TEXT_FORMAT,\n};\n\n/** The format of a document: a web page by its kind, else by its media type. */\nexport function getKnowledgeFormat(source: Pick<KnowledgeSource, 'kind' | 'mimeType'>): KnowledgeFormat {\n if (source.kind === 'url') {\n return WEB_PAGE_FORMAT;\n }\n\n return KNOWLEDGE_FORMATS[source.mimeType] ?? TEXT_FORMAT;\n}\n\nexport function getKnowledgeKindLabel(source: Pick<KnowledgeSource, 'kind' | 'mimeType'>): string {\n return getKnowledgeFormat(source).label;\n}\n\nexport type KnowledgeStatusTone = 'muted' | 'ready' | 'busy' | 'error';\n\nexport interface KnowledgeStatusSummary {\n /** Short badge text. */\n label: string;\n /** One line under the title. */\n detail: string;\n tone: KnowledgeStatusTone;\n}\n\nexport function isKnowledgeJobActive(job: KnowledgeJob | null | undefined): boolean {\n return Boolean(\n job &&\n (job.state === 'queued' || job.state === 'extracting' || job.state === 'embedding' || job.state === 'publishing')\n );\n}\n\n/** Whether the source changes on its own right now, so the page should poll. */\nexport function isKnowledgeSourceBusy(source: Pick<KnowledgeSource, 'status'>, job?: KnowledgeJob | null): boolean {\n return source.status === 'processing' || isKnowledgeJobActive(job);\n}\n\nfunction describeJobPhase(job: KnowledgeJob): string {\n const { progress } = job;\n\n switch (job.state) {\n case 'queued':\n return 'Waiting to be processed';\n case 'extracting':\n return 'Reading the document';\n case 'embedding': {\n if (progress?.passageCount) {\n return `Indexing passages (${String(progress.embeddedCount ?? 0)} of ${String(progress.passageCount)})`;\n }\n\n return 'Indexing passages';\n }\n case 'publishing':\n return 'Publishing';\n default:\n return progress?.message ?? job.state;\n }\n}\n\n/**\n * One status for the list row and the detail header. A source keeps serving\n * its published version while a re-index runs or fails, so the badge speaks\n * about the document, and the detail line about what is happening to it.\n */\nexport function summarizeKnowledgeStatus(source: KnowledgeSource, job?: KnowledgeJob | null): KnowledgeStatusSummary {\n const version = source.currentVersion;\n const published = version?.status === 'published';\n const passages = version?.passageCount ?? 0;\n const readyDetail = `${String(passages)} ${passages === 1 ? 'passage' : 'passages'}`;\n\n if (isKnowledgeJobActive(job)) {\n return {\n label: published ? 'Re-indexing' : 'Indexing',\n detail: describeJobPhase(job!),\n tone: 'busy',\n };\n }\n\n if (source.status === 'failed' || (!published && (job?.state === 'failed' || version?.status === 'failed'))) {\n const message = job?.error?.message ?? version?.error ?? 'Indexing failed';\n\n return { label: 'Failed', detail: message, tone: 'error' };\n }\n\n if (source.status === 'processing' || !published) {\n return { label: 'Indexing', detail: 'Waiting to be processed', tone: 'busy' };\n }\n\n if (job?.state === 'failed') {\n return {\n label: 'Ready',\n detail: `${readyDetail} · the last re-index failed: ${job.error?.message ?? 'unknown error'}`,\n tone: 'ready',\n };\n }\n\n if (version && version.warnings.length > 0) {\n return { label: 'Ready', detail: `${readyDetail} · indexed with warnings`, tone: 'ready' };\n }\n\n return { label: 'Ready', detail: readyDetail, tone: 'ready' };\n}\n\n/** Where a passage sits, the way a citation reads: \"p. 3 · Returns › Window\". */\nexport function formatKnowledgeLocator(locator: KnowledgeLocator): string {\n const parts: string[] = [];\n\n if (locator.page !== undefined) {\n parts.push(`p. ${String(locator.page)}`);\n }\n\n if (locator.slide !== undefined) {\n parts.push(`slide ${String(locator.slide)}`);\n }\n\n if (locator.headingPath && locator.headingPath.length > 0) {\n parts.push(locator.headingPath.join(' › '));\n }\n\n return parts.join(' · ');\n}\n\n/** Splits a stored warning such as \"TEXT_TRUNCATED: only the first…\" into readable text. */\nexport function formatKnowledgeWarning(warning: string): string {\n const [, captured] = /^[A-Z_]+:\\s*(.*)$/.exec(warning) ?? [];\n const text = captured ?? warning;\n\n return text.charAt(0).toUpperCase() + text.slice(1);\n}\n\n/** The spaces a source will carry after toggling one; empty means every member. */\nexport function toggleSpaceCode(current: string[], code: string): string[] {\n return current.includes(code) ? current.filter((entry) => entry !== code) : [...current, code];\n}\n\n/** The document page in the Knowledge app; absolute so it works from any app. */\nexport function getKnowledgeSourcePath(projectId: string, sourceId: string): string {\n return `/${encodeURIComponent(projectId)}/knowledge/${encodeURIComponent(sourceId)}`;\n}\n\n/**\n * What a linked record is called: the label the Studio resolved from the\n * record itself, else what the platform could read, else a shortened id so\n * the row still identifies the record.\n */\nexport function getKnowledgeLinkLabel(\n link: Pick<KnowledgeLink, 'recordId' | 'title'>,\n resolved?: string | null\n): string {\n const text = resolved?.trim() || (link.title ?? '').trim();\n\n if (text) {\n return text;\n }\n\n return link.recordId.length > 12 ? `${link.recordId.slice(0, 8)}…` : link.recordId;\n}\n\nexport interface KnowledgeLinkGroup {\n entity: string;\n entityPlural: string;\n links: KnowledgeLink[];\n}\n\n/** Links grouped per entity in first-seen order, so each group resolves its labels with one query. */\nexport function groupKnowledgeLinks(links: KnowledgeLink[]): KnowledgeLinkGroup[] {\n const groups = new Map<string, KnowledgeLinkGroup>();\n\n for (const link of links) {\n let group = groups.get(link.entityPlural);\n\n if (!group) {\n group = { entity: link.entity, entityPlural: link.entityPlural, links: [] };\n groups.set(link.entityPlural, group);\n }\n\n group.links.push(link);\n }\n\n return [...groups.values()];\n}\n\n/** The documents a picker may still attach to a record: the ones not attached yet, usable ones first. */\nexport function getAttachableSources(sources: KnowledgeSource[], attachedIds: Iterable<string>): KnowledgeSource[] {\n const attached = new Set(attachedIds);\n\n return sources\n .filter((source) => !attached.has(source.id))\n .sort((a, b) => Number(b.status === 'ready') - Number(a.status === 'ready'));\n}\n\n/** Whether documents may be attached to the entity: built-in ones (assets, tags) are not something a document is about. */\nexport function isKnowledgeLinkableEntity(entityName: string): boolean {\n return !entityName.startsWith('_');\n}\n\n/** The deployed entity with this name, if the Studio knows it. */\nexport function findEntityByName<T extends { name: string }>(schema: T[], entityName: string): T | undefined {\n return schema.find((entity) => entity.name === entityName);\n}\n\n/** How an entity type is called in the Knowledge views: its sidebar label, else its plural. */\nexport function getEntityLinkLabel(entity: { menu?: { label?: string }; plural: string }): string {\n return entity.menu?.label?.trim() || entity.plural;\n}\n\n/**\n * The entity types a document can still be attached to: the project's own\n * entities (built-in ones such as assets and tags are not something a\n * document is about) minus the ones already linked, by label.\n */\nexport function getLinkableEntities<T extends { menu?: { label?: string }; name: string; plural: string }>(\n schema: T[],\n linked: Iterable<Pick<KnowledgeEntityLink, 'entity'>>\n): T[] {\n const taken = new Set([...linked].map((link) => link.entity));\n\n return schema\n .filter((entity) => isKnowledgeLinkableEntity(entity.name) && !taken.has(entity.name))\n .sort((a, b) => getEntityLinkLabel(a).localeCompare(getEntityLinkLabel(b)));\n}\n\nexport type KnowledgeViewMode = 'list' | 'grid';\n\nconst VIEW_MODE_STORAGE_KEY = 'flexkit-knowledge:viewMode';\n\n/** The list is the default; the choice is remembered per browser, like the asset manager's. */\nexport function getStoredKnowledgeViewMode(): KnowledgeViewMode {\n try {\n return getLocalStorage()?.getItem(VIEW_MODE_STORAGE_KEY) === 'grid' ? 'grid' : 'list';\n } catch {\n return 'list';\n }\n}\n\nexport function setStoredKnowledgeViewMode(mode: KnowledgeViewMode): void {\n try {\n getLocalStorage()?.setItem(VIEW_MODE_STORAGE_KEY, mode);\n } catch {\n // Private mode or blocked storage: the choice lasts for the session only.\n }\n}\n"]}
@@ -1,2 +1,2 @@
1
- import'./index.css';import {a,c,d,f as f$1,g as g$1,e as e$1,i as i$1,h as h$1}from'./chunk-2NXQF2F7.js';import {b as b$1}from'./chunk-ZZRA4567.js';import {i}from'./chunk-A7XHA2P6.js';import {f}from'./chunk-H2RWSC56.js';import {qa}from'./chunk-DGIY4SKN.js';import {e,g,h,j as j$1,o,n}from'./chunk-SZEGGBOC.js';import {b}from'./chunk-32ZU4MLE.js';import {b as b$2}from'./chunk-6NRQMG26.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){qa.info(`"${e.source.title}" is already in Knowledge.`);return}qa.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=i(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,projectId:a$1}=le(),l=b$1(),[c$1,p]=useState(false),[f,b]=useState(false);if(!i||!a$1)return null;let X=i;async function H(){b(true);try{await X.deleteSource(r.id),qa.success(`Removed "${r.title}".`),p(!1),t(),de();}catch(w){qa.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(b$2,{"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,{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$1,onOpenChange:p,children:jsxs(c,{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$1,{disabled:f,children:"Cancel"}),jsxs(h$1,{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-4IEOAKKK.js.map
2
- //# sourceMappingURL=chunk-4IEOAKKK.js.map
1
+ import'./index.css';import {a,c,d,f as f$1,g as g$1,e as e$1,i,h as h$2}from'./chunk-2NXQF2F7.js';import {b as b$1}from'./chunk-ZZRA4567.js';import {h}from'./chunk-7KLXWCDS.js';import {f}from'./chunk-PLZUH56T.js';import {qa}from'./chunk-DGIY4SKN.js';import {e,g,h as h$1,j as j$1,o,n}from'./chunk-SZEGGBOC.js';import {b}from'./chunk-32ZU4MLE.js';import {b as b$2}from'./chunk-6NRQMG26.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){qa.info(`"${e.source.title}" is already in Knowledge.`);return}qa.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$1,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),qa.success(`Removed "${r.title}".`),p(!1),t(),de();}catch(w){qa.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(b$2,{"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$1,onOpenChange:p,children:jsxs(c,{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-7KRDPQXX.js.map
2
+ //# sourceMappingURL=chunk-7KRDPQXX.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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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,IAAA,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-4IEOAKKK.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,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,CACZ,MAAM,IAAIH,CAAAA,CAAaG,CAAAA,CAAS,MA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,CAAK,iBAAA,CAAA,CAEpE,GACF,CAAA,CAAA,CACF,CAAA,CACF,GACF,CAEJ","file":"chunk-7KRDPQXX.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"]}