@flexkit/studio 0.2.34 → 0.2.36

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 (110) hide show
  1. package/dist/{activity-nav-button-ZHQOZBCC.js → activity-nav-button-KOOMUTOW.js} +2 -2
  2. package/dist/{activity-nav-button-ZHQOZBCC.js.map → activity-nav-button-KOOMUTOW.js.map} +1 -1
  3. package/dist/chat-page-NDVHLH5Q.js +4 -0
  4. package/dist/chat-page-NDVHLH5Q.js.map +1 -0
  5. package/dist/chunk-27JTWTU6.js +2 -0
  6. package/dist/{chunk-3OBELKJU.js.map → chunk-27JTWTU6.js.map} +1 -1
  7. package/dist/chunk-2PBDHGRR.js +2 -0
  8. package/dist/chunk-2PBDHGRR.js.map +1 -0
  9. package/dist/{chunk-6AJRQSFO.js → chunk-474MQNDK.js} +3 -3
  10. package/dist/{chunk-6AJRQSFO.js.map → chunk-474MQNDK.js.map} +1 -1
  11. package/dist/{chunk-XYFS6X74.js → chunk-CGMKGENV.js} +2 -2
  12. package/dist/{chunk-XYFS6X74.js.map → chunk-CGMKGENV.js.map} +1 -1
  13. package/dist/chunk-FF5EBXYN.js +30 -0
  14. package/dist/chunk-FF5EBXYN.js.map +1 -0
  15. package/dist/chunk-FJS4SN3K.js +378 -0
  16. package/dist/chunk-FJS4SN3K.js.map +1 -0
  17. package/dist/chunk-FXUD4JRG.js +2 -0
  18. package/dist/chunk-FXUD4JRG.js.map +1 -0
  19. package/dist/{chunk-HR4QZ5TD.js → chunk-GTR4M2BQ.js} +3 -3
  20. package/dist/chunk-GTR4M2BQ.js.map +1 -0
  21. package/dist/{chunk-RBGXXVF4.js → chunk-HXPETSXC.js} +3 -3
  22. package/dist/{chunk-RBGXXVF4.js.map → chunk-HXPETSXC.js.map} +1 -1
  23. package/dist/{chunk-WU2KCXBC.js → chunk-L5Z56DDM.js} +2 -2
  24. package/dist/{chunk-WU2KCXBC.js.map → chunk-L5Z56DDM.js.map} +1 -1
  25. package/dist/{chunk-7JA6SI5H.js → chunk-LTM3MW2D.js} +2 -2
  26. package/dist/{chunk-7JA6SI5H.js.map → chunk-LTM3MW2D.js.map} +1 -1
  27. package/dist/{chunk-36DLIVZF.js → chunk-LVKBKU6Q.js} +2 -2
  28. package/dist/{chunk-36DLIVZF.js.map → chunk-LVKBKU6Q.js.map} +1 -1
  29. package/dist/chunk-LXLEUEWT.js +2 -0
  30. package/dist/chunk-LXLEUEWT.js.map +1 -0
  31. package/dist/chunk-MHEFVYKP.js +2 -0
  32. package/dist/chunk-MHEFVYKP.js.map +1 -0
  33. package/dist/{chunk-YC7PBLTK.js → chunk-NKDQQHCL.js} +2 -2
  34. package/dist/{chunk-YC7PBLTK.js.map → chunk-NKDQQHCL.js.map} +1 -1
  35. package/dist/chunk-OJ4RI6IQ.js +4 -0
  36. package/dist/{chunk-2FCVATRT.js.map → chunk-OJ4RI6IQ.js.map} +1 -1
  37. package/dist/chunk-PLCI2RJA.js +3 -0
  38. package/dist/chunk-PLCI2RJA.js.map +1 -0
  39. package/dist/{chunk-PSECMZJC.js → chunk-SOA2F7Z6.js} +3 -3
  40. package/dist/{chunk-PSECMZJC.js.map → chunk-SOA2F7Z6.js.map} +1 -1
  41. package/dist/{chunk-VRDTHLA3.js → chunk-TWA6OG5U.js} +3 -3
  42. package/dist/{chunk-VRDTHLA3.js.map → chunk-TWA6OG5U.js.map} +1 -1
  43. package/dist/{chunk-CHNQZU2P.js → chunk-VIBGMCLS.js} +2 -2
  44. package/dist/{chunk-CHNQZU2P.js.map → chunk-VIBGMCLS.js.map} +1 -1
  45. package/dist/{chunk-DFBG7PUJ.js → chunk-YJ4NWJCC.js} +4 -4
  46. package/dist/{chunk-DFBG7PUJ.js.map → chunk-YJ4NWJCC.js.map} +1 -1
  47. package/dist/entry-XHH3NKN2.js +2 -0
  48. package/dist/{entry-APJ4V7PW.js.map → entry-XHH3NKN2.js.map} +1 -1
  49. package/dist/index.d.ts +5 -1
  50. package/dist/index.js +7 -7
  51. package/dist/index.js.map +1 -1
  52. package/dist/list-R64THLZD.js +2 -0
  53. package/dist/{list-7WFALOUT.js.map → list-R64THLZD.js.map} +1 -1
  54. package/dist/{list-7IHDJM54.js → list-XIE55HYD.js} +3 -3
  55. package/dist/{list-7IHDJM54.js.map → list-XIE55HYD.js.map} +1 -1
  56. package/dist/{pages-BV3ABSFQ.js → pages-OWXBU64L.js} +3 -3
  57. package/dist/{pages-BV3ABSFQ.js.map → pages-OWXBU64L.js.map} +1 -1
  58. package/dist/{plugin-pages-OWGJPPWV.js → plugin-pages-JBJQHBIN.js} +2 -2
  59. package/dist/{plugin-pages-OWGJPPWV.js.map → plugin-pages-JBJQHBIN.js.map} +1 -1
  60. package/dist/{project-selector-V5N2724B.js → project-selector-L2WZ3MB5.js} +2 -2
  61. package/dist/{project-selector-V5N2724B.js.map → project-selector-L2WZ3MB5.js.map} +1 -1
  62. package/dist/record-links-BEKOPDDR.js +2 -0
  63. package/dist/{record-links-3P3XSW66.js.map → record-links-BEKOPDDR.js.map} +1 -1
  64. package/dist/{root-F2GTYDJM.js → root-B5XP6VYU.js} +2 -2
  65. package/dist/{root-F2GTYDJM.js.map → root-B5XP6VYU.js.map} +1 -1
  66. package/dist/{root-NIL2UHKS.js → root-DUQULYRX.js} +2 -2
  67. package/dist/{root-NIL2UHKS.js.map → root-DUQULYRX.js.map} +1 -1
  68. package/dist/{root-GBBZ3DX5.js → root-I22KNOFC.js} +3 -3
  69. package/dist/{root-GBBZ3DX5.js.map → root-I22KNOFC.js.map} +1 -1
  70. package/dist/{root-J62PBDZ2.js → root-O4DMQLEH.js} +2 -2
  71. package/dist/{root-J62PBDZ2.js.map → root-O4DMQLEH.js.map} +1 -1
  72. package/dist/root-RUOT5OSO.js +23 -0
  73. package/dist/{root-RGZZYETM.js.map → root-RUOT5OSO.js.map} +1 -1
  74. package/dist/root-VLD6GNZL.js +14 -0
  75. package/dist/root-VLD6GNZL.js.map +1 -0
  76. package/dist/{search-IIGNCQEZ.js → search-4UQR6ENH.js} +2 -2
  77. package/dist/{search-IIGNCQEZ.js.map → search-4UQR6ENH.js.map} +1 -1
  78. package/dist/{skills-pages-T52MF4DO.js → skills-pages-VUIOUEYQ.js} +2 -2
  79. package/dist/{skills-pages-T52MF4DO.js.map → skills-pages-VUIOUEYQ.js.map} +1 -1
  80. package/dist/source-L54C4T3X.js +2 -0
  81. package/dist/{source-IJAAJDGW.js.map → source-L54C4T3X.js.map} +1 -1
  82. package/package.json +2 -2
  83. package/dist/chat-page-7XT4K75G.js +0 -4
  84. package/dist/chat-page-7XT4K75G.js.map +0 -1
  85. package/dist/chunk-2FCVATRT.js +0 -4
  86. package/dist/chunk-3OBELKJU.js +0 -2
  87. package/dist/chunk-4PUMSUJL.js +0 -30
  88. package/dist/chunk-4PUMSUJL.js.map +0 -1
  89. package/dist/chunk-ERDARDGB.js +0 -2
  90. package/dist/chunk-ERDARDGB.js.map +0 -1
  91. package/dist/chunk-HR4QZ5TD.js.map +0 -1
  92. package/dist/chunk-KO2JLLUJ.js +0 -2
  93. package/dist/chunk-KO2JLLUJ.js.map +0 -1
  94. package/dist/chunk-PC5Z37LT.js +0 -378
  95. package/dist/chunk-PC5Z37LT.js.map +0 -1
  96. package/dist/chunk-U6NFYYTF.js +0 -2
  97. package/dist/chunk-U6NFYYTF.js.map +0 -1
  98. package/dist/chunk-U6VZY3V2.js +0 -3
  99. package/dist/chunk-U6VZY3V2.js.map +0 -1
  100. package/dist/chunk-XMOSCJOI.js +0 -2
  101. package/dist/chunk-XMOSCJOI.js.map +0 -1
  102. package/dist/chunk-YDVO6XWD.js +0 -2
  103. package/dist/chunk-YDVO6XWD.js.map +0 -1
  104. package/dist/entry-APJ4V7PW.js +0 -2
  105. package/dist/list-7WFALOUT.js +0 -2
  106. package/dist/record-links-3P3XSW66.js +0 -2
  107. package/dist/root-LYRL7VPN.js +0 -14
  108. package/dist/root-LYRL7VPN.js.map +0 -1
  109. package/dist/root-RGZZYETM.js +0 -23
  110. package/dist/source-IJAAJDGW.js +0 -2
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/get-display-attribute.ts","../src/core/attribute-scope.ts","../src/graphql-client/queries.ts"],"names":["getDisplayAttribute","entity","attr","getAttributeScope","attribute","FULL_ASSET_CONNECTION_LIMIT","LIST_ASSET_CONNECTION_LIMIT","NESTED_RELATIONSHIP_LIMIT","stringTypes","temporalTypes","assetFields","assetFieldsWithoutLqip","listAssetPreviewFields","isAssetRelationshipAttribute","hasOrderedAssetConnectionProperties","tagSchema","isAssetAttribute","getOrderedAssetsFromConnection","connection","typedConnection","edges","totalCount","result","edge","index","a","b","getKnownAssetSortOrders","assets","asset","unwrapNode","value","getAssetConnectionNodeFields","includeLqip","previewOnly","getAssetConnectionSelection","attributeName","includeProperties","first","propertiesSelection","nodeFields","connectionArguments","getConnectionCount","getEntityCount","results","entityNamePlural","total","getConnectionCountSelection","fieldName","whereArgument","getTopLevelCountSelection","includeCount","countMode","DEFAULT_SCOPE_KEY","defaultValueSelection","defaultScope","getDisplayAttributeSelection","primaryAttribute","scope","schema","forList","additionalScope","defaultValue","field","nestedEntity","find","propEq","fieldAttribute","localAttributeQuery","getFullRelatedEntityAttributesSelection","relatedEntity","relatedAcc","relatedAttribute","relationshipEntity","relationshipAttribute","getAttributesByName","attributes","attributesByName","shouldSelectAttributeInList","getSortNotNullWhere","sort","primarySort","sortAttributeName","sortAttribute","getEntityQuery","options","requestedSelection","selection","filters","entitySchema","getEntitySchema","entityName","displayAttribute","heading","operationName","getOperationEntityName","globalAttributesList","getAttributeListByScope","imageAttributes","getImageAttributes","localAttributes","defaultScopedAttr","acc","scopedAttribute","localAttributesList","imageFieldsSelection","imageAttributesList","relationshipAttributesList","primarySelection","relatedLimit","attributesNameList","mapQueryResult","count","items","sliceFirstThreeItems","values","primaryAttributeName","item","scopedNode","mappedQueryResult","_id","updatedAt","globalAttributes","relationshipAttributes","relatedEntityName","localValue","primaryAttributeScope","relatedItems","relatedNode","primaryScopedNode","mapQueryResultForFormFields","attributeSchema","localAttribute","getValueByScope","rawValue","aggregateCount","option","getEntityUpdateMutation","entityId","originalData","dataToMutate","pluralizedEntityName","capitalize","data","filterOutInvalidAttributes","globalAttributesUpdate","localAttributesUpdate","imageAttributesUpdate","relationshipAttributesUpdate","responseType","attributeNamesList","formatResponseFieldsForMutation","nonUpdatableAttributes","omit","pick","type","attributeType","schemaAttributes","operation","toPairs","valueToStringify","typedValue","stringifyValue","getLinkedAssetId","attributeValue","nextId","originalId","disconnect","stringifyStringLiteral","connect","imageAttributesCreate","assetId","dataType","inputType","relationship","orderedAssetRelationshipUpdate","disconnectIds","uniq","idsToConnect","node","originalValue","orderedConnections","orderedConnectionIds","originalSortOrderById","getRelationshipSortOrderById","disconnectedIds","newConnections","reorderedConnections","originalSortOrder","getOrderedAssetDisconnectString","getOrderedAssetConnectString","reorder","getOrderedAssetReorderString","fieldValue","sortOrder","ids","disconnectString","connections","getOrderedAssetConnectNodes","connectString","updateString","globalAttributesArray","localAttributesArray","relationshipAttributesArray","fields","relationshipMode","relationshipEntityName","relationshipEntityAttributes","list","multipleRelationshipAttributes","str","getEntityDeleteMutation","idList","localAttributesDelete","getEntityDeleteWhere","localIds","id","idFilter","getEntityCreateMutation","entityData","localAttributesCreate","relationshipAttributesCreate","isMultipleRelationship","hasRelationships","connectNodes","getRelatedItemsQuery","queryEntityName","getEntityAssetConnectionQuery","normalizedEntityName","assetSchema","getLocalAttributeIdsFromUpdateResponse","response","updateKey","payload","entities","nodeId"],"mappings":"iHAOO,SAASA,CAAAA,CAAoBC,CAAAA,CAAmD,CACrF,GAAKA,GAAQ,UAAA,CAAW,MAAA,CAIxB,OAAIA,CAAAA,CAAO,QACFA,CAAAA,CAAO,UAAA,CAAW,IAAA,CAAMC,CAAAA,EAASA,EAAK,IAAA,GAASD,CAAAA,CAAO,OAAO,CAAA,EAAKA,CAAAA,CAAO,UAAA,CAAW,CAAC,CAAA,CAGvFA,EAAO,UAAA,CAAW,CAAC,CA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,OAAIA,CAAAA,GAAqB,SAAA,CAChBwL,CAAAA,CAGFpK,IAAAA,CAAKC,OAAOrB,CAAAA,CAAkB,QAAQ,CAAC,CAAA,CAAEc,CAAM,CACxD,CAMO,SAAS2K,EAAAA,CACdC,CAAAA,CACA1L,EACAc,CAAAA,CACqC,CACrC,GAAI,CAAC4K,CAAAA,EAAY,OAAOA,CAAAA,EAAa,QAAA,CACnC,OAAO,EAAC,CAGV,IAAM9I,CAAAA,CAAeC,CAAAA,CAAgB/B,EAAQd,CAAgB,CAAA,CAE7D,GAAI,CAAC4C,CAAAA,CACH,OAAO,GAGT,IAAM+I,CAAAA,CAAY,SAAS1F,CAAAA,CAAWjG,CAAgB,CAAC,CAAA,CAAA,CACjD4L,CAAAA,CAAWF,CAAAA,CAAwCC,CAAS,EAElE,GAAI,CAACC,GAAW,OAAOA,CAAAA,EAAY,SACjC,OAAO,EAAC,CAGV,IAAMC,EAAYD,CAAAA,CAAuC5L,CAAgB,EACnE5C,CAAAA,CAAS,KAAA,CAAM,QAAQyO,CAAQ,CAAA,CAAIA,EAAS,CAAC,CAAA,CAAI,OAEvD,OAAI,CAACzO,GAAU,OAAOA,CAAAA,EAAW,SACxB,EAAC,CAGHwF,CAAAA,CAAa,UAAA,CAAW,OAA4C,CAAC0G,CAAAA,CAAK/L,IAAc,CAC7F,GAAID,EAAkBC,CAAS,CAAA,GAAM,OAAA,CACnC,OAAO+L,EAIT,IAAMwC,CAAAA,CADO7M,EAAY7B,CAAAA,CAAsCG,CAAAA,CAAU,IAAI,CAAC,CAAA,EACzD,GAAA,CAErB,OAAI,OAAOuO,CAAAA,EAAW,QAAA,EAAYA,EAAO,MAAA,GAAW,CAAA,CAC3CxC,EAGF,CACL,GAAGA,EACH,CAAC/L,CAAAA,CAAU,IAAI,EAAGuO,CACpB,CACF,CAAA,CAAG,EAAE,CACP","file":"chunk-FJS4SN3K.js","sourcesContent":["import type { Attribute, Entity } from './types';\n\n/**\n * Resolve the attribute used as the entity's human-readable label.\n * Uses `entity.display` when it matches an attribute name; otherwise the first attribute.\n * The effective display attribute must not be space-bound (enforced at define/deploy time).\n */\nexport function getDisplayAttribute(entity: Entity | undefined): Attribute | undefined {\n if (!entity?.attributes.length) {\n return undefined;\n }\n\n if (entity.display) {\n return entity.attributes.find((attr) => attr.name === entity.display) ?? entity.attributes[0];\n }\n\n return entity.attributes[0];\n}\n","import type { Attribute, ScopeType } from './types';\n\nexport function getAttributeScope(attribute: Attribute): ScopeType {\n if (attribute.dataType === 'asset') {\n return 'global';\n }\n\n return attribute.scope;\n}\n","import { find, omit, pick, propEq, toPairs, uniq } from 'ramda';\nimport { getAttributeScope } from '../core/attribute-scope';\nimport { getDisplayAttribute } from '../core/get-display-attribute';\nimport { assetSchema } from '../entities/assets-schema';\nimport { tagSchema } from '../entities/tags-schema';\nimport type { User } from '../auth/types';\nimport type { Attribute, Entity, DataType, Schema, ScopeType, MultipleRelationshipConnection } from '../core/types';\nimport type {\n AttributeValue,\n EntityItem,\n EntityQueryResults,\n FormEntityItem,\n FormFieldValue,\n MappedEntityItem,\n MappedEntityQueryResults,\n MappedFormEntityQueryResults,\n EntityQueryResult,\n ImageValue,\n OrderedAssetValue,\n EntityQuerySelection,\n} from './types';\n\ntype EntityQuery = {\n queryEntityName: string;\n query: string;\n};\n\nexport type EntityQueryCountMode = 'aggregate' | 'total';\nexport type SortNotNullWhere = {\n NOT: {\n [attributeName: string]: {\n eq: null;\n };\n };\n};\n\n/** Page size for asset connections in forms (galleries, ordered assets). */\nexport const FULL_ASSET_CONNECTION_LIMIT = 25;\n/** List grids render at most 3 stacked asset thumbnails (plus a \"+N\" badge). */\nconst LIST_ASSET_CONNECTION_LIMIT = 3;\n/** Grids preview at most 3 nested relationship values (sliceFirstThreeItems). */\nconst NESTED_RELATIONSHIP_LIMIT = 3;\n\nconst stringTypes: DataType[] = ['id', 'string'];\nconst temporalTypes: DataType[] = ['date', 'datetime', 'duration', 'time'];\nconst assetFields = `_id\n originalFilename\n mimeType\n path\n url\n size\n height\n width\n lqip`;\n\nconst assetFieldsWithoutLqip = `_id\n originalFilename\n mimeType\n path\n url\n size\n height\n width`;\n/** List grids resolve thumbnails from the asset URL; extra metadata is unused. */\nconst listAssetPreviewFields = `_id\n path\n url`;\n\ntype AssetRelationshipConnection = {\n aggregate?: {\n count?: {\n nodes?: number;\n };\n };\n edges?: {\n properties?: {\n sortOrder?: number | null;\n } | null;\n node?: OrderedAssetValue | null;\n }[];\n};\n\nfunction isAssetRelationshipAttribute(attribute: Attribute | undefined): boolean {\n if (!attribute) {\n return false;\n }\n\n return (\n getAttributeScope(attribute) === 'relationship' &&\n attribute.relationship?.mode === 'multiple' &&\n attribute.relationship.entity === '_asset'\n );\n}\n\nfunction hasOrderedAssetConnectionProperties(attribute: Attribute | undefined, entity: Entity | undefined): boolean {\n if (!attribute || !isAssetRelationshipAttribute(attribute)) {\n return false;\n }\n\n return entity?.name !== tagSchema.name || attribute.name !== 'assets';\n}\n\nfunction isAssetAttribute(attribute: Attribute | undefined): boolean {\n return attribute?.dataType === 'asset' || attribute?.inputType === 'asset';\n}\n\nexport function getOrderedAssetsFromConnection(connection: unknown): OrderedAssetValue[] {\n const typedConnection = connection as AssetRelationshipConnection | undefined;\n const edges = typedConnection?.edges ?? [];\n // Edges are bounded by `first`; the aggregate count carries the real total so\n // consumers (e.g. the \"+N\" badge in list grids) do not undercount.\n const totalCount = typedConnection?.aggregate?.count?.nodes ?? edges.length;\n\n return edges\n .reduce<OrderedAssetValue[]>((result, edge, index) => {\n if (!edge.node) {\n return result;\n }\n\n result.push({\n ...edge.node,\n sortOrder: edge.properties?.sortOrder ?? index,\n totalCount,\n });\n\n return result;\n }, [])\n .sort((a, b) => (a.sortOrder ?? Number.MAX_SAFE_INTEGER) - (b.sortOrder ?? Number.MAX_SAFE_INTEGER));\n}\n\n/** Build the sort-order map update mutations use to detect new vs existing assets. */\nexport function getKnownAssetSortOrders(assets: OrderedAssetValue[]): { [id: string]: number } {\n return assets.reduce<{ [id: string]: number }>((result, asset, index) => {\n if (!asset._id) {\n return result;\n }\n\n return {\n ...result,\n [asset._id]: asset.sortOrder ?? index,\n };\n }, {});\n}\n\n/**\n * Relationship fields are list-typed in the generated schema ([Type!]!), so\n * single-valued fields (local attributes, global assets, single-mode\n * relationships) come back as arrays of 0..1 nodes. Unwraps to the first node,\n * tolerating the legacy single-object shape.\n */\nfunction unwrapNode(value: unknown): AttributeValue | null {\n if (Array.isArray(value)) {\n return (value[0] as AttributeValue | undefined) ?? null;\n }\n\n return (value as AttributeValue | null) ?? null;\n}\n\n/**\n * Asset connections must always be bounded: without `first` the generated\n * Cypher expands every connected asset per row (tags with thousands of assets\n * made list queries take seconds). The aggregate count is still selected, so\n * consumers can show \"+N more\" from `totalCount`.\n */\nfunction getAssetConnectionNodeFields(includeLqip: boolean, previewOnly: boolean): string {\n if (previewOnly) {\n return listAssetPreviewFields;\n }\n\n if (includeLqip) {\n return assetFields;\n }\n\n return assetFieldsWithoutLqip;\n}\n\nfunction getAssetConnectionSelection(\n attributeName: string,\n includeProperties = true,\n includeLqip = true,\n first = FULL_ASSET_CONNECTION_LIMIT,\n previewOnly = false\n): string {\n const propertiesSelection = includeProperties\n ? ` properties {\\n` + ` sortOrder\\n` + ` }\\n`\n : '';\n const nodeFields = getAssetConnectionNodeFields(includeLqip, previewOnly);\n // Edge sort input only exists when the relationship carries properties.\n const connectionArguments = includeProperties\n ? `(first: ${first}, sort: [{ edge: { sortOrder: ASC } }])`\n : `(first: ${first})`;\n\n return (\n ` ${attributeName}Connection${connectionArguments} {\\n` +\n ` aggregate {\\n` +\n ` count {\\n` +\n ` nodes\\n` +\n ` }\\n` +\n ` }\\n` +\n ` edges {\\n` +\n propertiesSelection +\n ` node {\\n` +\n ` ${nodeFields}\\n` +\n ` }\\n` +\n ` }\\n` +\n ` }\\n`\n );\n}\n\n/**\n * Counts moved inside connection fields in Neo4j GraphQL v7:\n * xConnection \\{ aggregate \\{ count \\{ nodes \\} \\} \\}. Reads that shape back.\n */\nfunction getConnectionCount(value: unknown): number {\n const aggregate = (value as { aggregate?: { count?: { nodes?: number } } } | null | undefined)?.aggregate;\n\n return aggregate?.count?.nodes ?? 0;\n}\n\nfunction getEntityCount(results: EntityQueryResults, entityNamePlural: string): number {\n const total = results[`${entityNamePlural}Total`];\n\n if (typeof total === 'number') {\n return total;\n }\n\n return getConnectionCount(results[`${entityNamePlural}Connection`]);\n}\n\nfunction getConnectionCountSelection(fieldName: string, whereArgument = ''): string {\n return (\n ` ${fieldName}Connection${whereArgument} {\\n` +\n ` aggregate {\\n` +\n ` count {\\n` +\n ` nodes\\n` +\n ` }\\n` +\n ` }\\n` +\n ` }\\n`\n );\n}\n\nfunction getTopLevelCountSelection(\n entityNamePlural: string,\n includeCount: boolean,\n countMode: EntityQueryCountMode\n): string {\n if (!includeCount) {\n return '';\n }\n\n if (countMode === 'total') {\n return ` ${entityNamePlural}Total\\n`;\n }\n\n return getConnectionCountSelection(entityNamePlural, '(where: $where)');\n}\n\n/** The default scope when a project names none; also the key results carry the default value under. */\nexport const DEFAULT_SCOPE_KEY = 'default';\n\n/**\n * Selects the default scope's value under the key `default`, whatever the\n * project named its default scope (`default: eu`), so results always read\n * the fallback value as `.default`.\n */\nexport function defaultValueSelection(defaultScope: string): string {\n return defaultScope === DEFAULT_SCOPE_KEY ? DEFAULT_SCOPE_KEY : `${DEFAULT_SCOPE_KEY}: ${defaultScope}`;\n}\n\n/**\n * Selection set for a related entity's display attribute only — enough for list-grid\n * relationship columns (mapQueryResult / sliceFirstThreeItems).\n */\nfunction getDisplayAttributeSelection(\n primaryAttribute: Attribute | undefined,\n scope: string,\n schema: Schema,\n forList = false,\n defaultScope = DEFAULT_SCOPE_KEY\n): string {\n if (!primaryAttribute) {\n return '';\n }\n\n const additionalScope = scope === defaultScope ? '' : `${scope}\\n `;\n const defaultValue = defaultValueSelection(defaultScope);\n\n if (isAssetAttribute(primaryAttribute)) {\n if (forList) {\n return ` ${primaryAttribute.name} {\\n _id\\n path\\n url\\n }\\n`;\n }\n\n return ` ${primaryAttribute.name} {\\n ${assetFields}\\n }\\n`;\n }\n\n if (getAttributeScope(primaryAttribute) === 'local') {\n return ` ${primaryAttribute.name} {\\n _id\\n ${defaultValue}\\n ${additionalScope}}\\n`;\n }\n\n if (getAttributeScope(primaryAttribute) === 'relationship') {\n const field = primaryAttribute.relationship?.field;\n\n if (!field) {\n return ` ${primaryAttribute.name}\\n`;\n }\n\n const nestedEntity = find(propEq(primaryAttribute.relationship?.entity, 'name'))(schema) as Entity | undefined;\n const fieldAttribute = find(propEq(field, 'name'))(nestedEntity?.attributes ?? []) as Attribute | undefined;\n const localAttributeQuery =\n fieldAttribute && getAttributeScope(fieldAttribute) === 'local'\n ? `{\\n _id\\n ${defaultValue}\\n ${additionalScope}}\\n`\n : '';\n\n if (primaryAttribute.relationship?.mode === 'single') {\n return ` ${primaryAttribute.name} {\\n ${field} ${localAttributeQuery}}\\n`;\n }\n\n return ` ${primaryAttribute.name} (limit: 3, offset: 0) {\\n ${field} ${localAttributeQuery}}\\n`;\n }\n\n return ` ${primaryAttribute.name}\\n`;\n}\n\nfunction getFullRelatedEntityAttributesSelection(\n relatedEntity: Entity | undefined,\n scope: string,\n schema: Schema,\n defaultScope = DEFAULT_SCOPE_KEY\n): string {\n const defaultValue = defaultValueSelection(defaultScope);\n\n return (\n relatedEntity?.attributes.reduce((relatedAcc, relatedAttribute) => {\n const additionalScope = scope === defaultScope ? '' : `${scope}\\n `;\n\n // Related-entity assets only render as CDN-path thumbnails in grids; the\n // base64 lqip payload is form-field-only and skipped at this depth.\n if (isAssetAttribute(relatedAttribute)) {\n return `${relatedAcc}\\n ${relatedAttribute.name} {\\n ${assetFieldsWithoutLqip}\\n }\\n `;\n }\n\n if (getAttributeScope(relatedAttribute) === 'local') {\n return `${relatedAcc}\\n ${relatedAttribute.name} {\\n _id\\n ${defaultValue}\\n ${additionalScope}\\n}\\n `;\n }\n\n if (getAttributeScope(relatedAttribute) === 'relationship') {\n const relationshipEntity = find(propEq(relatedAttribute.relationship?.entity, 'name'))(schema) as\n | Entity\n | undefined;\n const relationshipAttribute = find(propEq(relatedAttribute.relationship?.field, 'name'))(\n relationshipEntity?.attributes ?? []\n ) as Attribute;\n const localAttributeQuery =\n getAttributeScope(relationshipAttribute) === 'local'\n ? `{\\n _id\\n ${defaultValue}\\n ${additionalScope}}\\n `\n : '';\n\n if (relatedAttribute.relationship?.mode === 'single') {\n return `${relatedAcc}\\n ${relatedAttribute.name} {\\n ${relatedAttribute.relationship.field} ${localAttributeQuery}}\\n `;\n }\n\n if (relatedAttribute.relationship?.field) {\n return `${relatedAcc}\\n ${relatedAttribute.name} (limit: ${NESTED_RELATIONSHIP_LIMIT}, offset: 0) {\\n ${relatedAttribute.relationship.field} ${localAttributeQuery}}\\n `;\n }\n }\n\n return `${relatedAcc}\\n ${relatedAttribute.name}\\n `;\n }, '') ?? ''\n );\n}\n\nfunction getAttributesByName(attributes: Attribute[]): { [name: string]: Attribute | undefined } {\n const attributesByName: { [name: string]: Attribute | undefined } = {};\n\n for (const attribute of attributes) {\n attributesByName[attribute.name] = attribute;\n }\n\n return attributesByName;\n}\n\nfunction shouldSelectAttributeInList(attribute: Attribute | undefined): boolean {\n if (!attribute) {\n return false;\n }\n\n // Computed asset URL is hidden from the grid but required to preview and copy links.\n if (attribute.name === 'url') {\n return true;\n }\n\n if (attribute.hidden === true || attribute.name === 'lqip') {\n return false;\n }\n\n return true;\n}\n\nexport function getSortNotNullWhere(sort: unknown, entity: Entity | undefined): SortNotNullWhere | undefined {\n if (!Array.isArray(sort) || sort.length === 0) {\n return undefined;\n }\n\n const [primarySort] = sort;\n\n if (!primarySort || typeof primarySort !== 'object') {\n return undefined;\n }\n\n const [sortAttributeName] = Object.keys(primarySort);\n\n if (!sortAttributeName || ['_id', '_createdAt', '_updatedAt'].includes(sortAttributeName)) {\n return undefined;\n }\n\n const sortAttribute = entity?.attributes.find((attribute) => attribute.name === sortAttributeName);\n\n if (\n !sortAttribute ||\n getAttributeScope(sortAttribute) !== 'global' ||\n sortAttribute.dataType === 'asset'\n ) {\n return undefined;\n }\n\n return {\n NOT: {\n [sortAttributeName]: {\n eq: null,\n },\n },\n };\n}\n\nexport function getEntityQuery(\n entityNamePlural: string,\n scope: string,\n schema: Schema,\n options?: {\n selection?: EntityQuerySelection;\n /**\n * The top-level aggregate count is a filtered label scan on the server.\n * Pagination pages (fetchMore) skip it — the total from the first page\n * still stands.\n */\n includeCount?: boolean;\n countMode?: EntityQueryCountMode;\n operationName?: string;\n /** The project's default scope (the one with `isDefault`). */\n defaultScope?: string;\n }\n): EntityQuery {\n const defaultScope = options?.defaultScope ?? DEFAULT_SCOPE_KEY;\n const defaultValue = defaultValueSelection(defaultScope);\n const requestedSelection = options?.selection ?? 'full';\n const selection = requestedSelection === 'display' ? 'list' : requestedSelection;\n const includeCount = options?.includeCount ?? true;\n const countMode = options?.countMode ?? 'aggregate';\n const filters = `(where: $where, limit: $limit, offset: $offset, sort: $sort)`;\n const entitySchema = getEntitySchema(schema, entityNamePlural);\n const entityName = entitySchema?.name ?? entityNamePlural;\n const displayAttribute = getDisplayAttribute(entitySchema);\n const attributes = requestedSelection === 'display'\n ? (displayAttribute ? [displayAttribute] : [])\n : entitySchema?.attributes ?? [];\n const attributesByName = getAttributesByName(attributes);\n const heading = `$where: ${entityName}Where, $limit: Int, $offset: Int, $sort: [${entityName}Sort!]`;\n const operationName = options?.operationName ?? `Get${getOperationEntityName(entityNamePlural)}`;\n\n if (!entitySchema) {\n throw new Error(`Entity '${entityName}' not found in the schema`);\n }\n\n if (attributes.length === 0) {\n throw new Error(`Entity '${entityName}' has no attributes defined in the schema`);\n }\n\n const globalAttributesList: string = getAttributeListByScope('global', attributes)\n .filter((attributeName) => {\n if (attributeName === '_updatedAt') {\n return false;\n }\n\n if (selection === 'list') {\n return requestedSelection === 'display' || shouldSelectAttributeInList(attributesByName[attributeName]);\n }\n\n return true;\n })\n .join('\\n ');\n const imageAttributes = getImageAttributes(attributes).filter((attributeName) =>\n selection !== 'list' || requestedSelection === 'display' || shouldSelectAttributeInList(attributesByName[attributeName])\n );\n const localAttributes: readonly string[] = getAttributeListByScope(['local'], attributes).filter((attributeName) => {\n if (selection !== 'list') {\n return true;\n }\n\n return requestedSelection === 'display' || shouldSelectAttributeInList(attributesByName[attributeName]);\n });\n const defaultScopedAttr = localAttributes.reduce(\n (acc, attribute) => `${acc}\\n ${attribute} {\\n _id\\n ${defaultValue}\\n }\\n `,\n ''\n );\n const scopedAttribute = localAttributes.reduce(\n (acc, attribute) => `${acc}\\n ${attribute} {\\n _id\\n ${defaultValue}\\n ${scope}\\n }\\n `,\n ''\n );\n const localAttributesList: string = scope === defaultScope ? defaultScopedAttr : scopedAttribute;\n let imageFieldsSelection = `_id\\n path\\n url`;\n\n if (selection !== 'list') {\n imageFieldsSelection =\n `_id\\n originalFilename\\n mimeType\\n path\\n url\\n size\\n height\\n width\\n lqip`;\n }\n\n const imageAttributesList: string = imageAttributes.reduce((acc, attribute) => {\n return `${acc}\\n ${attribute} {\\n ${imageFieldsSelection}\\n }\\n `;\n }, '');\n\n const relationshipAttributes = attributes.filter((attribute) => getAttributeScope(attribute) === 'relationship');\n const relationshipAttributesList: string = relationshipAttributes.reduce((acc, attribute) => {\n if (selection === 'list' && requestedSelection !== 'display' && attribute.hidden === true) {\n return acc;\n }\n\n if (isAssetRelationshipAttribute(attribute)) {\n return `${acc}\\n${getAssetConnectionSelection(\n attribute.name,\n hasOrderedAssetConnectionProperties(attribute, entitySchema),\n selection !== 'list',\n selection === 'list' ? LIST_ASSET_CONNECTION_LIMIT : FULL_ASSET_CONNECTION_LIMIT,\n selection === 'list'\n )}`;\n }\n\n const relatedEntity = find(propEq(attribute.relationship?.entity, 'name'))(schema) as Entity | undefined;\n\n if (selection === 'list') {\n const displayAttribute = getDisplayAttribute(relatedEntity);\n const primarySelection = getDisplayAttributeSelection(displayAttribute, scope, schema, true, defaultScope);\n const relatedLimit = attribute.relationship?.mode === 'single' ? 1 : 3;\n\n return (\n `${acc}\\n ${attribute.name} (limit: ${relatedLimit}, offset: 0) {\\n` +\n ` _id\\n` +\n `${primarySelection}` +\n ` }\\n `\n );\n }\n\n const attributesNameList = getFullRelatedEntityAttributesSelection(relatedEntity, scope, schema, defaultScope);\n\n return (\n `${getConnectionCountSelection(attribute.name).trim()}` +\n `${acc}\\n ${attribute.name} (limit: 25, offset: 0) { _id ${attributesNameList}` +\n `}\\n `\n );\n }, '');\n\n return {\n queryEntityName: entityNamePlural,\n query:\n `query ${operationName}(${heading}) {\\n` +\n getTopLevelCountSelection(entityNamePlural, includeCount, countMode) +\n ` ${entityNamePlural}${filters} {\\n` +\n ` _id\\n` +\n ` _updatedAt\\n` +\n ` ${globalAttributesList}` +\n ` ${localAttributesList}` +\n ` ${imageAttributesList}` +\n ` ${relationshipAttributesList}` +\n `}\\n` +\n `}\\n`,\n };\n}\n\n/**\n * Map the GraphQl results JSON to a key-value pair array. The values inside the scopedAttributes key are flattened to the first level.\n */\nexport function mapQueryResult(\n entityNamePlural: string,\n scope: string,\n results: EntityQueryResults,\n schema: Schema\n): MappedEntityQueryResults {\n const entitySchema = getEntitySchema(schema, entityNamePlural);\n const attributes = entitySchema?.attributes ?? [];\n\n if (attributes.length === 0) {\n return {\n count: 0,\n results: [],\n };\n }\n\n const count = getEntityCount(results, entityNamePlural);\n const items = results[entityNamePlural] as EntityQueryResult[];\n const sliceFirstThreeItems = (values: EntityItem[], primaryAttribute: Attribute): string => {\n const primaryAttributeName = primaryAttribute.name;\n\n return values\n .slice(0, 3)\n .map((item) => {\n if (getAttributeScope(primaryAttribute) !== 'local') {\n return item[primaryAttributeName];\n }\n\n const scopedNode = unwrapNode(item[primaryAttributeName]);\n\n return scopedNode?.[scope] ?? scopedNode?.default;\n })\n .join(', ');\n };\n const mappedQueryResult = items.map((entity) => {\n const { _id } = entity;\n const updatedAt = typeof entity._updatedAt === 'string' ? entity._updatedAt : '';\n const globalAttributes = getAttributeListByScope('global', attributes)\n .filter((attributeName) => attributeName !== '_updatedAt')\n .reduce((acc, attributeName) => ({ ...acc, [attributeName]: entity[attributeName] }), {});\n const localAttributes = getAttributeListByScope('local', attributes).reduce((acc, attributeName) => {\n const scopedAttribute = unwrapNode(entity[attributeName]);\n\n return {\n ...acc,\n [attributeName]: scopedAttribute?.[scope] ? scopedAttribute[scope] : scopedAttribute?.default,\n };\n }, {});\n const imageAttributes = getImageAttributes(attributes).reduce(\n (acc, attributeName) => ({ ...acc, [attributeName]: unwrapNode(entity[attributeName]) }),\n {}\n );\n const relationshipAttributes = getAttributeListByScope(['relationship'], attributes).reduce(\n (acc, attributeName) => {\n const relationshipAttribute = find(propEq(attributeName, 'name'))(attributes) as Attribute;\n const relatedEntityName = relationshipAttribute.relationship?.entity ?? '';\n const relatedEntity = find(propEq(relatedEntityName, 'name'))(schema) as Entity | undefined;\n const primaryAttribute = getDisplayAttribute(relatedEntity);\n const localValue = entity[attributeName];\n\n if (isAssetRelationshipAttribute(relationshipAttribute)) {\n const assets = getOrderedAssetsFromConnection(entity[`${attributeName}Connection`]);\n\n return {\n ...acc,\n [attributeName]: assets,\n };\n }\n\n if (!primaryAttribute) {\n throw new Error(`There is an error in the schema for the relationship attribute \"${attributeName}\"`);\n }\n\n const primaryAttributeName = primaryAttribute.name;\n const primaryAttributeScope = getAttributeScope(primaryAttribute);\n\n // All relationship fields are lists in the schema, so the mode from the\n // JSON schema (not the value shape) decides single vs multiple mapping.\n if (relationshipAttribute.relationship?.mode === 'multiple') {\n const relatedItems = (Array.isArray(localValue) ? localValue : []) as EntityItem[];\n\n return {\n ...acc,\n [attributeName]: sliceFirstThreeItems(relatedItems, primaryAttribute),\n };\n }\n\n const relatedNode = unwrapNode(localValue);\n\n if (primaryAttributeScope === 'global') {\n return {\n ...acc,\n [attributeName]: relatedNode?.[primaryAttributeName],\n };\n }\n\n const primaryScopedNode = unwrapNode(relatedNode?.[primaryAttributeName]);\n\n return {\n ...acc,\n [attributeName]: primaryScopedNode?.[scope] ?? primaryScopedNode?.default,\n };\n },\n {}\n );\n\n return {\n _id,\n ...globalAttributes,\n ...localAttributes,\n ...imageAttributes,\n ...relationshipAttributes,\n _updatedAt: updatedAt,\n };\n });\n\n return {\n count,\n results: mappedQueryResult,\n };\n}\n\n/**\n * Like mapQueryResult but the local attribute values are returned as an object:\n * \\{_id: string, value: string, disabled: boolean, scope: string\\}.\n */\nexport function mapQueryResultForFormFields(\n entityNamePlural: string,\n scope: string,\n results: EntityQueryResults,\n schema: Schema,\n defaultScope = DEFAULT_SCOPE_KEY\n): MappedFormEntityQueryResults {\n const entitySchema = getEntitySchema(schema, entityNamePlural);\n const attributes = entitySchema?.attributes ?? [];\n\n if (attributes.length === 0) {\n return {\n count: 0,\n results: [],\n };\n }\n\n const count = getEntityCount(results, entityNamePlural);\n const items = results[entityNamePlural] as EntityQueryResult[];\n const mappedQueryResult = items.map((entity) => {\n const globalAttributes = getAttributeListByScope('global', attributes).reduce(\n (acc, attribute) => ({\n ...acc,\n [attribute]: {\n value: entity[attribute],\n disabled: false,\n scope: 'default',\n _id: '',\n },\n }),\n {}\n );\n const localAttributes = getAttributeListByScope('local', attributes).reduce((acc, attributeName) => {\n const attributeSchema = find(propEq(attributeName, 'name'))(attributes) as Attribute;\n const localAttribute = unwrapNode(entity[attributeName]);\n\n return {\n ...acc,\n [attributeName]: {\n value: localAttribute ? getValueByScope(localAttribute, scope, defaultScope) : null,\n disabled: Boolean(\n localAttribute &&\n localAttribute[scope] === null &&\n getAttributeScope(attributeSchema) === 'local' &&\n scope !== defaultScope\n ),\n scope,\n _id: localAttribute ? localAttribute._id : null,\n },\n };\n }, {});\n const imageAttributes = getImageAttributes(attributes).reduce(\n (acc, attribute) => ({\n ...acc,\n [attribute]: {\n value: unwrapNode(entity[attribute]),\n disabled: false,\n scope: 'default',\n _id: '',\n },\n }),\n {}\n );\n const relationshipAttributes = getAttributeListByScope(['relationship'], attributes).reduce(\n (acc, attributeName) => {\n const relationshipAttribute = find(propEq(attributeName, 'name'))(attributes) as Attribute;\n const rawValue = entity[attributeName];\n // Single-mode relationships come back as lists of 0..1 nodes; multiple\n // mode keeps the array so downstream grids receive it unchanged.\n const value = (\n relationshipAttribute.relationship?.mode === 'single' ? unwrapNode(rawValue) : rawValue\n ) as AttributeValue | null;\n const _id = value?._id;\n const aggregateCount = getConnectionCount(entity[`${attributeName}Connection`]);\n\n if (isAssetRelationshipAttribute(relationshipAttribute)) {\n const assets = getOrderedAssetsFromConnection(entity[`${attributeName}Connection`]);\n\n return {\n ...acc,\n [attributeName]: {\n count: aggregateCount,\n _id,\n knownAssetSortOrders: getKnownAssetSortOrders(assets),\n value: assets,\n disabled: false,\n scope,\n },\n };\n }\n\n return {\n ...acc,\n [attributeName]: {\n count: aggregateCount,\n _id,\n value,\n disabled: false,\n scope,\n },\n };\n },\n {}\n );\n\n return { ...globalAttributes, ...localAttributes, ...imageAttributes, ...relationshipAttributes };\n });\n\n return {\n count,\n results: mappedQueryResult,\n };\n}\n\n/**\n * Attribute values can be an object or an array of objects if the attribute is a multi-select.\n */\nfunction getValueByScope(\n attribute: AttributeValue | AttributeValue[],\n scope: string,\n defaultScope: string\n): FormFieldValue[] | AttributeValue | AttributeValue[] | string | null {\n if (Array.isArray(attribute)) {\n return attribute.reduce((result: FormFieldValue[], attr: AttributeValue) => {\n if (attr[scope] ?? attr.default) {\n const option = {\n _id: attr._id,\n disabled: Boolean(attr.scope === null && scope !== defaultScope),\n scope,\n value: attr[scope] ?? attr.default,\n };\n\n result.push(option);\n }\n\n return result;\n }, []);\n }\n\n return attribute[scope] ?? attribute.default ?? null;\n}\n\n/**\n * Returns a string with the GraphQl query needed to mutate the dataToMutate object for the given entity and scope.\n */\nexport function getEntityUpdateMutation(\n entityNamePlural: string,\n entityId: string,\n scope: string,\n schema: Schema,\n originalData: FormEntityItem,\n dataToMutate: FormEntityItem,\n options?: { currentUser?: User; responseFields?: string; defaultScope?: string }\n): string {\n const entitySchema = getEntitySchema(schema, entityNamePlural);\n const entityName = entitySchema?.name ?? entityNamePlural;\n const attributes = entitySchema?.attributes ?? [];\n const pluralizedEntityName = capitalize(entityNamePlural);\n\n if (attributes.length === 0) {\n return '';\n }\n\n const data = filterOutInvalidAttributes(attributes, dataToMutate);\n const globalAttributes = globalAttributesUpdate(attributes, data);\n const localAttributes = localAttributesUpdate(entityId, attributes, data, scope);\n const imageAttributes = imageAttributesUpdate(attributes, originalData, data);\n const relationshipAttributes = relationshipAttributesUpdate(attributes, originalData, data);\n const responseType = entityNamePlural;\n const attributeNamesList =\n options?.responseFields ??\n formatResponseFieldsForMutation(schema, entityNamePlural, scope, options?.defaultScope ?? DEFAULT_SCOPE_KEY);\n const operationName = `Update${getOperationEntityName(entityNamePlural)}`;\n\n return (\n `mutation ${operationName}($where: ${entityName}Where) {\\n` +\n ` update${pluralizedEntityName}(\\n` +\n ` where: $where\\n` +\n ` update: {${globalAttributes}${localAttributes}${imageAttributes}${relationshipAttributes}\\n }\\n` +\n ` ) {\\n` +\n ` ${responseType} {\\n` +\n ` _id\\n` +\n ` ${attributeNamesList}` +\n ` }\\n` +\n ` }\\n` +\n `}\\n`\n );\n}\n\n/**\n * Filter out any attribute received from the form that does not exist in the schema.\n */\nfunction filterOutInvalidAttributes(attributes: Attribute[], dataToMutate: FormEntityItem): FormEntityItem {\n // Read-only attributes are never written by the Studio.\n const nonUpdatableAttributes: readonly string[] = attributes\n .filter((attribute) => attribute.readOnly === true)\n .map((attribute) => attribute.name);\n const data = omit(nonUpdatableAttributes, dataToMutate);\n\n return pick(\n attributes.map((attribute) => attribute.name) as unknown as readonly [number, ...number[]],\n data\n ) as FormEntityItem;\n}\n\n/**\n * Filter attributes by scope: local, global or relationship.\n */\nfunction getAttributeListByScope(type: ScopeType | ScopeType[], attributes: Attribute[]): Attribute['name'][] {\n if (Array.isArray(type)) {\n return type.reduce((acc: Attribute['name'][], attributeType: ScopeType) => {\n return acc.concat(getAttributeListByScope(attributeType, attributes));\n }, []);\n }\n\n const filteredAttributes = attributes.filter(\n (attribute) => getAttributeScope(attribute) === type && attribute.inputType !== 'asset'\n );\n\n return filteredAttributes.map((attribute) => attribute.name);\n}\n\n/**\n * Get all attributes that are of type image.\n */\nfunction getImageAttributes(attributes: Attribute[]): Attribute['name'][] {\n const filteredAttributes = attributes.filter(isAssetAttribute);\n\n return filteredAttributes.map((attribute) => attribute.name);\n}\n\n/**\n * Update inputs require the dedicated set operator in Neo4j GraphQL v7\n * (name: \\{ set: value \\}); create inputs still take plain values.\n */\nfunction globalAttributesUpdate(\n schemaAttributes: Attribute[],\n data: FormEntityItem,\n operation: 'create' | 'update' = 'update'\n): string {\n const globalAttributes = pick(getAttributeListByScope('global', schemaAttributes) as [string], data);\n const attributesString = toPairs(globalAttributes).reduce((acc, [attributeName, value]) => {\n const attributeSchema = find(propEq(attributeName, 'name'))(schemaAttributes) as Attribute;\n const valueToStringify = Array.isArray(value?.value) ? null : (value?.value ?? null);\n const typedValue = stringifyValue(attributeSchema.dataType, valueToStringify);\n\n // Omit empty optional globals on create — `field: ` with no value is invalid GraphQL.\n if (operation === 'create' && (typedValue === null || typedValue === '')) {\n return acc;\n }\n\n if (operation === 'update') {\n return `${acc}\\n ${attributeName}: { set: ${typedValue} }`;\n }\n\n return `${acc}\\n ${attributeName}: ${typedValue}`;\n }, '');\n\n return attributesString;\n}\n\n/**\n * Returns the asset _id of a field value when it points at a real asset.\n * Cleared fields keep a stub value without a path, so path is required too.\n */\nfunction getLinkedAssetId(value: ImageValue | null | undefined): string {\n if (!value?._id || !value.path) {\n return '';\n }\n\n return value._id;\n}\n\n/**\n * Asset nodes are created up front by the /assets endpoint, so entity saves\n * only connect/disconnect them by _id. Disconnect runs before connect so the\n * field keeps at most one linked asset.\n */\nfunction imageAttributesUpdate(\n schemaAttributes: Attribute[],\n originalData: FormEntityItem,\n data: FormEntityItem\n): string {\n const imageAttributes = pick(getImageAttributes(schemaAttributes) as [string], data);\n const attributesArray: [string, FormFieldValue][] = toPairs(imageAttributes);\n const attributesString: string = attributesArray.reduce((acc, [attributeName, attributeValue]) => {\n const nextId = getLinkedAssetId(attributeValue.value as ImageValue | null);\n const originalId = getLinkedAssetId(originalData[attributeName]?.value as ImageValue | null | undefined);\n\n if (nextId === originalId) {\n return acc;\n }\n\n const disconnect = originalId\n ? ` {\\n disconnect: [{\\n where: {\\n node: {\\n _id: { eq: ${stringifyStringLiteral(originalId)} }\\n }\\n }\\n }]\\n }\\n`\n : '';\n const connect = nextId\n ? ` {\\n connect: [{\\n where: {\\n node: {\\n _id: { eq: ${stringifyStringLiteral(nextId)} }\\n }\\n }\\n }]\\n }\\n`\n : '';\n\n return `${acc}\\n ${attributeName}: [\\n${disconnect}${connect} ]`;\n }, '');\n\n return attributesString;\n}\n\nfunction imageAttributesCreate(schemaAttributes: Attribute[], data: FormEntityItem): string {\n const imageAttributes = pick(getImageAttributes(schemaAttributes) as [string], data);\n const attributesArray: [string, FormFieldValue][] = toPairs(imageAttributes);\n const attributesString: string = attributesArray.reduce((acc, [attributeName, attributeValue]) => {\n const assetId = getLinkedAssetId(attributeValue.value as ImageValue | null);\n\n if (!assetId) {\n return acc;\n }\n\n return (\n `${acc}\\n ${attributeName}: {\\n` +\n ` connect: [{\\n` +\n ` where: {\\n` +\n ` node: {\\n` +\n ` _id: { eq: ${stringifyStringLiteral(assetId)} }\\n` +\n ` }\\n` +\n ` }\\n` +\n ` }]\\n` +\n ` }`\n );\n }, '');\n\n return attributesString;\n}\n\nfunction localAttributesUpdate(\n entityId: string,\n schemaAttributes: Attribute[],\n data: FormEntityItem,\n scope: string\n): string {\n const localAttributes = pick(getAttributeListByScope('local', schemaAttributes) as [string], data);\n const attributesArray: [string, FormFieldValue][] = toPairs(localAttributes);\n const attributesString: string = attributesArray.reduce((acc, [attributeName, attributeValue]) => {\n const attributeSchema = find(propEq(attributeName, 'name'))(schemaAttributes) as Attribute;\n const { dataType } = attributeSchema;\n const typedValue =\n attributeValue.disabled || Array.isArray(attributeValue.value)\n ? 'null'\n : stringifyValue(dataType, attributeValue.value);\n\n if (attributeValue._id) {\n return `${acc}\\n ${attributeName}: [{\\n update: {\\n node: {\\n ${scope}: { set: ${typedValue} }\\n }\\n }\\n }]`;\n }\n\n // Match localAttributesCreate: never create nodes for empty values. Empty\n // locals used to stringify to the string \"null\" and create with a\n // deterministic id; the next save then hit a unique-constraint failure\n // because the form still had no _id for those fields.\n if (\n attributeValue.disabled ||\n Array.isArray(attributeValue.value) ||\n attributeValue.value === undefined ||\n attributeValue.value === null ||\n attributeValue.value === '' ||\n typedValue === null ||\n typedValue === ''\n ) {\n return acc;\n }\n\n return (\n `${acc}\\n ${attributeName}: [{\\n` +\n ` create: {\\n` +\n ` node: {\\n` +\n ` _id: ${stringifyStringLiteral(`${entityId}:${attributeName}`)}\\n` +\n ` _type: \"${dataType}\"\\n` +\n ` ${scope}: ${typedValue}\\n` +\n ` }\\n` +\n ` }\\n` +\n ` }]`\n );\n }, '');\n\n return attributesString;\n}\n\nfunction relationshipAttributesUpdate(\n schemaAttributes: Attribute[],\n originalData: FormEntityItem,\n data: FormEntityItem\n): string {\n const relationshipAttributes = pick(getAttributeListByScope('relationship', schemaAttributes) as [string], data);\n const attributesArray = toPairs(relationshipAttributes);\n const attributesString: string = attributesArray.reduce((acc, [attributeName, attributeValue]) => {\n const attributeSchema = find(propEq(attributeName, 'name'))(schemaAttributes) as Attribute;\n const { inputType, relationship } = attributeSchema;\n\n if (inputType === 'relationship' && relationship?.mode === 'single') {\n const originalId = originalData[attributeName]._id ?? '';\n const nextId = attributeValue._id ?? '';\n\n if (originalId === nextId) {\n return acc;\n }\n\n // Relationship fields are lists in the schema; disconnect runs before\n // connect so the field keeps at most one related node.\n const disconnect = originalId\n ? ` {\\n disconnect: [{\\n where: {\\n node: {\\n _id: { eq: ${stringifyStringLiteral(originalId)} }\\n }\\n }\\n }]\\n }\\n`\n : '';\n const connect = nextId\n ? ` {\\n connect: [{\\n where: {\\n node: {\\n _id: { eq: ${stringifyStringLiteral(nextId)} }\\n }\\n }\\n }]\\n }\\n`\n : '';\n\n return `${acc}\\n ${attributeName}: [\\n${disconnect}${connect} ]`;\n }\n\n if (inputType === 'relationship' && relationship?.mode === 'multiple') {\n if (relationship.entity === '_asset') {\n return `${acc}${orderedAssetRelationshipUpdate(attributeName, originalData[attributeName], attributeValue)}`;\n }\n\n // Neo4j GraphQL v7 expects list-shaped connect/disconnect entries with\n // `where.node`. The old `disconnect.where.OR` form drops the filter and\n // disconnects every related node.\n const disconnectIds = uniq(attributeValue.relationships?.disconnect ?? []).filter(Boolean);\n const connections = (attributeValue.relationships?.connect as MultipleRelationshipConnection | null) ?? [];\n const idsToConnect = connections.map((node) => stringifyStringLiteral(node._id)).join(', ');\n const disconnect = disconnectIds.length\n ? ` {\\n disconnect: [\\n${disconnectIds\n .map(\n (_id) =>\n ` {\\n where: {\\n node: {\\n _id: { eq: ${stringifyStringLiteral(_id)} }\\n }\\n }\\n }\\n`\n )\n .join('')} ]\\n }\\n`\n : '';\n const connect = idsToConnect\n ? ` {\\n connect: [{\\n where: {\\n node: {\\n _id: { in: [${idsToConnect}] }\\n }\\n }\\n }]\\n }\\n`\n : '';\n\n if (!disconnect && !connect) {\n return acc;\n }\n\n return `${acc}\\n ${attributeName}: [\\n${disconnect}${connect} ]`;\n }\n\n return `${acc}\\n`;\n }, '');\n\n return attributesString;\n}\n\nfunction orderedAssetRelationshipUpdate(\n attributeName: string,\n originalValue: FormFieldValue | undefined,\n attributeValue: FormFieldValue\n): string {\n const connections = (attributeValue.relationships?.connect as MultipleRelationshipConnection | null) ?? [];\n const orderedConnections = connections.map((connection, index) => ({\n ...connection,\n sortOrder: connection.sortOrder ?? index,\n }));\n const orderedConnectionIds = orderedConnections.map((connection) => connection._id);\n // Merge paged-in server assets from the live field so load-more edges are not\n // mistaken for brand-new connects (which would duplicate relationship edges).\n const originalSortOrderById = {\n ...getRelationshipSortOrderById(originalValue),\n ...(originalValue?.knownAssetSortOrders ?? {}),\n ...(attributeValue.knownAssetSortOrders ?? {}),\n };\n const disconnectedIds = uniq(attributeValue.relationships?.disconnect ?? []).filter(\n (_id) => _id && !orderedConnectionIds.includes(_id)\n );\n // In Neo4j GraphQL v7 connect always creates a new relationship, so\n // reconnecting an already-connected asset would duplicate the edge. New\n // assets are connected; existing ones with a changed sortOrder get a nested\n // update on the edge instead.\n const newConnections = orderedConnections.filter((connection) => originalSortOrderById[connection._id] === undefined);\n const reorderedConnections = orderedConnections.filter((connection) => {\n const originalSortOrder = originalSortOrderById[connection._id];\n\n return originalSortOrder !== undefined && originalSortOrder !== connection.sortOrder;\n });\n const disconnect = getOrderedAssetDisconnectString(disconnectedIds);\n const connect = getOrderedAssetConnectString(newConnections);\n const reorder = getOrderedAssetReorderString(reorderedConnections);\n\n if (!disconnect && !connect && !reorder) {\n return '';\n }\n\n return `\\n ${attributeName}: [\\n${disconnect}${connect}${reorder} ]`;\n}\n\nfunction getRelationshipSortOrderById(fieldValue: FormFieldValue | undefined): { [id: string]: number } {\n const value = fieldValue?.value;\n\n if (!Array.isArray(value)) {\n return {};\n }\n\n return value.reduce<{ [id: string]: number }>((result, item, index) => {\n if (typeof item !== 'object' || !item || !('_id' in item)) {\n return result;\n }\n\n const { _id } = item;\n\n if (typeof _id !== 'string' || _id.length === 0) {\n return result;\n }\n\n const sortOrder = 'sortOrder' in item && typeof item.sortOrder === 'number' ? item.sortOrder : index;\n\n return {\n ...result,\n [_id]: sortOrder,\n };\n }, {});\n}\n\nfunction getOrderedAssetDisconnectString(ids: string[]): string {\n if (ids.length === 0) {\n return '';\n }\n\n const nodes = ids.reduce((disconnectString, _id) => {\n return `${disconnectString} {\\n where: { node: { _id: { eq: ${stringifyStringLiteral(_id)} } } }\\n }\\n`;\n }, '');\n\n return ` {\\n disconnect: [\\n${nodes} ]\\n }\\n`;\n}\n\nfunction getOrderedAssetConnectString(connections: MultipleRelationshipConnection): string {\n if (connections.length === 0) {\n return '';\n }\n\n const nodes = getOrderedAssetConnectNodes(connections);\n\n return ` {\\n connect: [\\n${nodes} ]\\n }\\n`;\n}\n\nfunction getOrderedAssetConnectNodes(connections: MultipleRelationshipConnection): string {\n return connections.reduce((connectString, connection, index) => {\n const sortOrder = connection.sortOrder ?? index;\n\n return (\n `${connectString} {\\n` +\n ` where: { node: { _id: { eq: ${stringifyStringLiteral(connection._id)} } } }\\n` +\n ` edge: { sortOrder: ${sortOrder} }\\n` +\n ` }\\n`\n );\n }, '');\n}\n\nfunction getOrderedAssetReorderString(connections: MultipleRelationshipConnection): string {\n if (connections.length === 0) {\n return '';\n }\n\n const nodes = connections.reduce((updateString, connection, index) => {\n const sortOrder = connection.sortOrder ?? index;\n\n return (\n `${updateString} {\\n` +\n ` update: {\\n` +\n ` where: { node: { _id: { eq: ${stringifyStringLiteral(connection._id)} } } }\\n` +\n ` edge: { sortOrder: { set: ${sortOrder} } }\\n` +\n ` }\\n` +\n ` }\\n`\n );\n }, '');\n\n return nodes;\n}\n\nfunction stringifyValue(\n type: DataType,\n value: boolean | number | string | MappedEntityItem | EntityItem | AttributeValue | ImageValue | null | undefined\n): string | null {\n if (temporalTypes.includes(type)) {\n return value?.toString() ? stringifyStringLiteral(value.toString()) : null;\n }\n\n if (stringTypes.includes(type)) {\n // null/undefined must be GraphQL null, not the string literal \"null\".\n if (value === undefined || value === null) {\n return null;\n }\n\n return stringifyStringLiteral(value.toString());\n }\n\n // Empty optional numbers/booleans must not stringify to \"\" (breaks GraphQL as `field: `).\n if (value === undefined || value === null || value === '') {\n return null;\n }\n\n return value.toString();\n}\n\nfunction stringifyNullableString(value: string | null | undefined): string {\n return value ? stringifyStringLiteral(value) : 'null';\n}\n\nfunction stringifyStringLiteral(value: string): string {\n return JSON.stringify(value);\n}\n\nfunction formatResponseFieldsForMutation(\n schema: Schema,\n entityNamePlural: string,\n scope: string,\n defaultScope: string\n): string {\n const defaultValue = defaultValueSelection(defaultScope);\n const entitySchema = getEntitySchema(schema, entityNamePlural);\n const schemaAttributes = entitySchema?.attributes ?? [];\n const globalAttributesArray = getAttributeListByScope('global', schemaAttributes);\n const localAttributesArray = getAttributeListByScope('local', schemaAttributes);\n const relationshipAttributesArray = getAttributeListByScope('relationship', schemaAttributes);\n\n let fields = globalAttributesArray.reduce((acc, attributeName: string) => {\n return `${acc}${attributeName}\\n `;\n }, '');\n\n fields += localAttributesArray.reduce((acc, attributeName: string) => {\n return `${acc} ${attributeName} {\\n _id\\n ${scope}\\n }\\n `;\n }, '');\n\n fields += relationshipAttributesArray.reduce((acc, attributeName: string) => {\n const relationshipAttribute = find(propEq(attributeName, 'name'))(schemaAttributes) as Attribute | undefined;\n const relationshipMode = relationshipAttribute?.relationship?.mode ?? 'single';\n\n if (isAssetRelationshipAttribute(relationshipAttribute)) {\n return `${acc}${getAssetConnectionSelection(\n attributeName,\n hasOrderedAssetConnectionProperties(relationshipAttribute, entitySchema)\n )}`;\n }\n\n const relationshipEntityName = relationshipAttribute?.relationship?.entity ?? '';\n const relationshipEntitySchema = find(propEq(relationshipEntityName, 'name'))(schema) as Entity | undefined;\n const relationshipEntityAttributes = relationshipEntitySchema?.attributes ?? [];\n const primaryAttributeName =\n relationshipAttribute?.relationship?.field ?? '[invalid_relationship_field_name_in_schema]';\n const primaryAttribute = find(propEq(primaryAttributeName, 'name'))(relationshipEntityAttributes) as Attribute;\n const primaryAttributeScope = getAttributeScope(primaryAttribute);\n let list = '';\n\n if (relationshipMode === 'single') {\n if (primaryAttributeScope === 'global') {\n list = ` ${attributeName} {\\n _id\\n ${primaryAttributeName}\\n }\\n `;\n }\n\n if (primaryAttributeScope === 'local') {\n list = ` ${attributeName} {\\n _id\\n ${primaryAttributeName} {\\n _id\\n ${defaultValue}\\n ${scope}\\n }\\n }\\n `;\n }\n }\n\n if (relationshipMode === 'multiple' && relationshipEntityAttributes.length) {\n const multipleRelationshipAttributes = relationshipEntityAttributes.reduce((str, attribute) => {\n if (getAttributeScope(attribute) === 'local') {\n return `${str} ${attribute.name} {\\n _id\\n ${defaultValue}\\n ${scope}\\n }\\n`;\n }\n\n if (getAttributeScope(attribute) === 'relationship') {\n const additionalScope = scope === defaultScope ? '' : `${scope}\\n `;\n const relationshipEntity = find(propEq(attribute.relationship?.entity, 'name'))(schema) as Entity | undefined;\n const relationshipAttribute = find(propEq(attribute.relationship?.field, 'name'))(\n relationshipEntity?.attributes ?? []\n ) as Attribute;\n const localAttributeQuery =\n getAttributeScope(relationshipAttribute) === 'local'\n ? `{\\n _id\\n ${defaultValue}\\n ${additionalScope}}\\n `\n : '';\n\n if (attribute.relationship?.mode === 'single') {\n return `${str} ${attribute.name} {\\n ${attribute.relationship.field} ${localAttributeQuery}}\\n `;\n }\n\n if (attribute.relationship?.field) {\n return `${str} ${attribute.name} (limit: ${NESTED_RELATIONSHIP_LIMIT}, offset: 0) {\\n ${attribute.relationship.field} ${localAttributeQuery}}\\n `;\n }\n }\n\n // Display-only at this depth; lqip is a form-field concern.\n if (isAssetAttribute(attribute)) {\n return `${str} ${attribute.name} {\\n ${assetFieldsWithoutLqip}\\n }\\n`;\n }\n\n return `${str} ${attribute.name}\\n `;\n }, '');\n\n list =\n getConnectionCountSelection(attributeName) +\n ` ${attributeName} (limit: 25, offset: 0) {\\n${multipleRelationshipAttributes}` +\n ` }\\n`;\n }\n\n return `${acc}${list}`;\n }, '');\n\n return fields;\n}\n\n/**\n * Returns a string with the GraphQl mutation needed to delete one or more entities.\n */\nexport function getEntityDeleteMutation(\n entityName: string,\n schema: Schema,\n ids: string | readonly string[]\n): string {\n const idList = typeof ids === 'string' ? [ids] : [...ids];\n const entitySchema = find(propEq(entityName, 'name'))(schema) as Entity | undefined;\n const attributes = entitySchema?.attributes ?? [];\n const pluralizedEntityName = capitalize(entitySchema?.plural ?? '');\n const localAttributes = localAttributesDelete(attributes, idList);\n const operationName = `Delete${getOperationEntityName(entitySchema?.plural ?? entityName)}`;\n\n if (entityName === '_asset') {\n return (\n `mutation ${operationName}($where: ${entityName}Where) {\\n` +\n ` delete_assets(\\n` +\n ` where: $where\\n` +\n ` ) {\\n` +\n ` nodesDeleted\\n` +\n ` relationshipsDeleted\\n` +\n ` }\\n` +\n `}\\n`\n );\n }\n\n return (\n `mutation ${operationName}($where: ${entityName}Where) {\\n` +\n ` delete${pluralizedEntityName}(\\n` +\n ` where: $where\\n` +\n `${localAttributes ? ` delete: {\\n ${localAttributes}\\n }\\n` : ''}` +\n ` ) {\\n` +\n ` nodesDeleted\\n` +\n ` relationshipsDeleted\\n` +\n ` }\\n` +\n `}\\n`\n );\n}\n\nexport function getEntityDeleteWhere(ids: string | readonly string[]): { _id: { eq: string } } | { _id: { in: string[] } } {\n const idList = typeof ids === 'string' ? [ids] : [...ids];\n\n if (idList.length === 1) {\n return { _id: { eq: idList[0] as string } };\n }\n\n return { _id: { in: idList } };\n}\n\nfunction localAttributesDelete(schemaAttributes: Attribute[], ids: readonly string[]): string {\n const localAttributes = getAttributeListByScope('local', schemaAttributes);\n const attributesString: string = localAttributes.reduce((acc, attributeName) => {\n const localIds = ids.map((id) => stringifyStringLiteral(`${id}:${attributeName}`)).join(', ');\n const idFilter = ids.length === 1 ? `_id: { eq: ${localIds} }` : `_id: { in: [${localIds}] }`;\n\n return (\n `${acc}\\n` +\n ` ${attributeName}: [{\\n` +\n ` where: {\\n` +\n ` node: {\\n` +\n ` ${idFilter}\\n` +\n ` }\\n` +\n ` }\\n` +\n ` }]`\n );\n }, '');\n\n return attributesString;\n}\n\nexport function getEntityCreateMutation(\n entityNamePlural: string,\n schema: Schema,\n entityData: FormEntityItem,\n _id: string,\n options?: { currentUser?: User; defaultScope?: string }\n): string {\n // A new record's values go to the default scope.\n const defaultScope = options?.defaultScope ?? DEFAULT_SCOPE_KEY;\n const entitySchema = getEntitySchema(schema, entityNamePlural);\n const attributes = entitySchema?.attributes ?? [];\n const pluralizedEntityName = capitalize(entitySchema?.plural ?? '');\n\n if (attributes.length === 0) {\n return '';\n }\n\n const data = filterOutInvalidAttributes(attributes, entityData);\n const globalAttributes = globalAttributesUpdate(attributes, data, 'create');\n const localAttributes = localAttributesCreate(attributes, data, defaultScope, _id);\n const imageAttributes = imageAttributesCreate(attributes, data);\n const relationshipAttributes = relationshipAttributesCreate(attributes, data);\n const responseType = entityNamePlural;\n const attributeNamesList = formatResponseFieldsForMutation(schema, responseType, defaultScope, defaultScope);\n const operationName = `Create${getOperationEntityName(entityNamePlural)}`;\n\n return (\n `mutation ${operationName} {\\n` +\n ` create${pluralizedEntityName}(\\n` +\n ` input: [{\\n` +\n ` _id: ${stringifyStringLiteral(_id)}` +\n ` ${globalAttributes}` +\n ` ${localAttributes}\\n` +\n ` ${imageAttributes}\\n` +\n ` ${relationshipAttributes}\\n` +\n ` }]\\n` +\n ` ) {\\n` +\n ` ${responseType} {\\n` +\n ` _id\\n` +\n ` ${attributeNamesList}` +\n ` }\\n` +\n ` }\\n` +\n `}\\n`\n );\n}\n\nfunction localAttributesCreate(\n schemaAttributes: Attribute[],\n data: FormEntityItem,\n defaultScope: string,\n _id: string\n): string {\n const localAttributes = pick(getAttributeListByScope('local', schemaAttributes) as [string], data);\n const attributesArray = toPairs(localAttributes);\n const attributesString: string = attributesArray.reduce((acc, [attributeName, attributeValue]) => {\n if (attributeValue?.value === undefined || attributeValue.value === null || attributeValue.value === '') {\n return acc;\n }\n\n const attributeSchema = find(propEq(attributeName, 'name'))(schemaAttributes) as Attribute;\n const typedValue = Array.isArray(attributeValue.value)\n ? 'null'\n : stringifyValue(attributeSchema.dataType, attributeValue.value);\n\n return (\n `${acc}\\n` +\n ` ${attributeName}: {\\n` +\n ` create: [{\\n` +\n ` node: {\\n` +\n ` _id: ${stringifyStringLiteral(`${_id}:${attributeName}`)}\\n` +\n ` _type: \"${attributeSchema.dataType}\"\\n` +\n ` ${defaultScope}: ${typedValue}\\n` +\n ` }\\n` +\n ` }]\\n` +\n ` }`\n );\n }, '');\n\n return attributesString;\n}\n\nfunction relationshipAttributesCreate(schemaAttributes: Attribute[], data: FormEntityItem): string {\n const relationshipAttributes = pick(getAttributeListByScope('relationship', schemaAttributes) as [string], data);\n const attributesArray = toPairs(relationshipAttributes);\n const attributesString: string = attributesArray.reduce((acc, [attributeName, attributeValue]) => {\n const attributeSchema = find(propEq(attributeName, 'name'))(schemaAttributes) as Attribute;\n const { inputType, relationship } = attributeSchema;\n\n if (inputType === 'relationship' && relationship?.mode === 'single') {\n if (!attributeValue._id) {\n return acc;\n }\n\n const connect = `connect: [{\\n where: {\\n node: {\\n _id: { eq: ${stringifyStringLiteral(attributeValue._id)} }\\n }\\n }\\n }]\\n`;\n\n return `${acc}\\n ${attributeName}: {\\n ${connect} }`;\n }\n\n const isMultipleRelationship = inputType === 'relationship' && relationship?.mode === 'multiple';\n const hasRelationships =\n Array.isArray(attributeValue.relationships?.connect) && attributeValue.relationships.connect.length > 0;\n if (isMultipleRelationship && hasRelationships) {\n const connections = (attributeValue.relationships?.connect as MultipleRelationshipConnection | null) ?? [];\n\n if (relationship?.entity === '_asset') {\n const connectNodes = getOrderedAssetConnectNodes(\n connections.map((connection, index) => ({\n ...connection,\n sortOrder: connection.sortOrder ?? index,\n }))\n );\n\n return `${acc}\\n ${attributeName}: {\\n connect: [\\n${connectNodes} ]\\n }`;\n }\n\n const idsToConnect = connections.map((node) => stringifyStringLiteral(node._id)).join(', ');\n const connect = idsToConnect\n ? `connect: {\\n where: {\\n node: {\\n _id: { in: [${idsToConnect}] }\\n }\\n }\\n }\\n`\n : '';\n\n return `${acc}\\n ${attributeName}: {\\n ${connect} }`;\n }\n\n return `${acc}\\n`;\n }, '');\n\n return attributesString;\n}\n\nexport function getRelatedItemsQuery({\n defaultScope,\n relatedEntityName,\n scope,\n schema,\n}: {\n attributeName: string;\n defaultScope?: string;\n relatedEntityName: string;\n scope: string;\n schema: Schema;\n}): EntityQuery {\n const entitySchema = find(propEq(relatedEntityName, 'name'))(schema) as Entity | undefined;\n const queryEntityName = entitySchema?.plural ?? '';\n\n if (!queryEntityName) {\n return {\n queryEntityName: '',\n query: '',\n };\n }\n\n return getEntityQuery(queryEntityName, scope, schema, {\n selection: 'list',\n operationName: `GetRelated${getOperationEntityName(queryEntityName)}`,\n defaultScope,\n });\n}\n\n/**\n * Pages an entity's ordered asset connection beyond the initial form `first`.\n * Callers grow `first` (e.g. loaded + page size) so already-fetched edges are\n * re-returned in sortOrder and can be merged without a cursor.\n */\nexport function getEntityAssetConnectionQuery({\n attributeName,\n entityName,\n entityNamePlural,\n schema,\n}: {\n attributeName: string;\n entityName: string;\n entityNamePlural: string;\n schema: Schema;\n}): EntityQuery {\n const entitySchema = getEntitySchema(schema, entityNamePlural);\n const attribute = find(propEq(attributeName, 'name'))(entitySchema?.attributes ?? []) as Attribute | undefined;\n const includeProperties = hasOrderedAssetConnectionProperties(attribute, entitySchema);\n const propertiesSelection = includeProperties\n ? ` properties {\\n` + ` sortOrder\\n` + ` }\\n`\n : '';\n const connectionArguments = includeProperties\n ? '(first: $first, sort: [{ edge: { sortOrder: ASC } }])'\n : '(first: $first)';\n const operationName = `Get${getOperationEntityName(entityName)}AssetConnection`;\n\n return {\n queryEntityName: entityNamePlural,\n query:\n `query ${operationName}($where: ${entityName}Where, $first: Int) {\\n` +\n ` ${entityNamePlural}(where: $where) {\\n` +\n ` ${attributeName}Connection${connectionArguments} {\\n` +\n ` aggregate {\\n` +\n ` count {\\n` +\n ` nodes\\n` +\n ` }\\n` +\n ` }\\n` +\n ` edges {\\n` +\n propertiesSelection +\n ` node {\\n` +\n ` ${assetFields}\\n` +\n ` }\\n` +\n ` }\\n` +\n ` }\\n` +\n ` }\\n` +\n `}\\n`,\n };\n}\n\nconst capitalize = (str: string): string => {\n return str.charAt(0).toUpperCase() + str.slice(1);\n};\n\nexport function getOperationEntityName(entityName: string): string {\n const normalizedEntityName = entityName\n .split(/[^0-9A-Za-z]+/)\n .filter(Boolean)\n .map(capitalize)\n .join('');\n\n if (!normalizedEntityName) {\n return 'Entity';\n }\n\n if (/^[A-Za-z_]/.test(normalizedEntityName)) {\n return normalizedEntityName;\n }\n\n return `Entity${normalizedEntityName}`;\n}\n\nexport function getEntitySchema(schema: Schema, entityNamePlural: string): Entity | undefined {\n if (entityNamePlural === '_assets') {\n return assetSchema;\n }\n\n return find(propEq(entityNamePlural, 'plural'))(schema) as Entity | undefined;\n}\n\n/**\n * Pulls local-attribute node _ids out of an update mutation response so the\n * form can adopt them without a full refetch (which re-dirties the drawer).\n */\nexport function getLocalAttributeIdsFromUpdateResponse(\n response: unknown,\n entityNamePlural: string,\n schema: Schema\n): { [attributeName: string]: string } {\n if (!response || typeof response !== 'object') {\n return {};\n }\n\n const entitySchema = getEntitySchema(schema, entityNamePlural);\n\n if (!entitySchema) {\n return {};\n }\n\n const updateKey = `update${capitalize(entityNamePlural)}`;\n const payload = (response as { [key: string]: unknown })[updateKey];\n\n if (!payload || typeof payload !== 'object') {\n return {};\n }\n\n const entities = (payload as { [key: string]: unknown })[entityNamePlural];\n const entity = Array.isArray(entities) ? entities[0] : undefined;\n\n if (!entity || typeof entity !== 'object') {\n return {};\n }\n\n return entitySchema.attributes.reduce<{ [attributeName: string]: string }>((ids, attribute) => {\n if (getAttributeScope(attribute) !== 'local') {\n return ids;\n }\n\n const node = unwrapNode((entity as { [key: string]: unknown })[attribute.name]);\n const nodeId = node?._id;\n\n if (typeof nodeId !== 'string' || nodeId.length === 0) {\n return ids;\n }\n\n return {\n ...ids,\n [attribute.name]: nodeId,\n };\n }, {});\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import'./index.css';import {e,d,a,c,b as b$1}from'./chunk-474MQNDK.js';import {f}from'./chunk-2PBDHGRR.js';import {r,s,i,k,j}from'./chunk-FJS4SN3K.js';import {b}from'./chunk-TWA6OG5U.js';import {useState,useRef,useMemo,useEffect,useCallback}from'react';import {uniqBy,prop}from'ramda';import {gql,NetworkStatus}from'@apollo/client';import {useQuery}from'@apollo/client/react';var q=null,z=new Set,St=[],Y=new Set,H=new Set,W=new Set;function $t(t,e){if(t==="_asset"||t==="_assets")return `Get${r(b.plural)}`;let r$1=e.find(o=>o.plural===t),n=e.find(o=>o.name===t),i=r$1?.plural??n?.plural??t;return `Get${r(i)}`}function Qt(t){return Y.add(t),()=>{Y.delete(t);}}function Pt(t){return H.add(t),()=>{H.delete(t);}}function vt(t){return W.add(t),()=>{W.delete(t);}}function zt(t,e,r){let n=new Set(r.filter(Boolean));if(n.size>0)for(let i of H)i(e,n);return qt(t,e)}function Yt(t,e){let r=e.filter(n=>!!n._id);if(r.length!==0)for(let n of W)n(t,r);}function qt(t,e){return z.add(e),new Promise((r,n)=>{St.push({resolve:r,reject:n}),q&&clearTimeout(q),q=setTimeout(()=>{let i=new Set(z),o=St.splice(0);z.clear(),q=null,Promise.all([...Y].map(s=>Promise.resolve(s(i)))).then(()=>{for(let{resolve:s}of o)s();}).catch(s=>{console.error("Error refreshing entity lists:",s);for(let{reject:h}of o)h(s);});},50);})}function oe({entityNamePlural:t,schema:e$1,scope:r$1,variables:n,isForm:i$1,selection:o="full",includeCount:s$1=true,fetchPolicy:h}){let[b,l]=useState({count:0,results:[]}),[_,O]=useState(false),[U,Z]=useState(false),[N,xt]=useState(null),k=useRef(false),P=useRef(false),m=useRef(0),v=useRef(null),M=useRef(null),c$1=f(),A=`${t}Total`,Tt=s(e$1,t),V=n?.where===void 0&&(Tt?.spaces?.length??0)===0&&(N?.field!==A||N.schema!==e$1)?"total":"aggregate",jt=useMemo(()=>gql(i(t,r$1,e$1,{selection:o,countMode:V,includeCount:s$1,defaultScope:c$1}).query),[t,r$1,e$1,o,V,s$1,c$1]),tt=useMemo(()=>gql(i(t,r$1,e$1,{selection:o,includeCount:false,defaultScope:c$1}).query),[t,r$1,e$1,o,c$1]),{schemaErrorMessage:B,setSchemaErrorMessage:G}=e(),{loading:I,data:E,fetchMore:et,refetch:rt,error:nt,networkStatus:w}=useQuery(jt,{variables:n,notifyOnNetworkStatusChange:true,fetchPolicy:h}),st=useRef(et),K=useRef(rt),ot=useRef(tt),it=useRef(w),ut=useRef(n);st.current=et,K.current=rt,ot.current=tt,ut.current=n;let J=s$1&&d(nt,A),ct=V==="total"&&J,R=J?void 0:nt,x=J&&!E?.[t],at=a(R),S=c(R),{isProjectDisabled:Dt,isProjectReadOnly:_t}=(()=>{if(at?.statusCode===403){let u=b$1(at.bodyText);if(u&&typeof u.code=="string"){if(u.code==="PROJECT_PAUSED")return {isProjectDisabled:true,isProjectReadOnly:false};if(u.code==="READ_ONLY_MODE")return {isProjectDisabled:false,isProjectReadOnly:true}}return {isProjectDisabled:true,isProjectReadOnly:false}}return {isProjectDisabled:false,isProjectReadOnly:false}})();useEffect(()=>{ct&&xt({field:A,schema:e$1});},[e$1,ct,A]);let At=useCallback(u=>{if(k.current||P.current)return;k.current=true,O(true);let{limit:d}=u.variables,y=m.current;st.current({...u,query:ot.current,variables:{...ut.current,...u.variables,offset:y,limit:d}}).then(({data:Q})=>{let f=D({data:Q,entityNamePlural:t,isForm:i$1,schema:e$1,scope:r$1,defaultScope:c$1}),p=f.results.length;m.current=y+(p===0?0:Math.min(p,d)),l(a=>{let L=uniqBy(prop("_id"),[...a.results,...f.results]);return L.length===a.results.length?{count:a.results.length,results:a.results}:{count:f.count||a.count,results:L}});}).catch(Q=>{console.error("Error fetching more data:",Q);}).finally(()=>{k.current=false,O(false);});},[c$1,t,i$1,e$1,r$1]),It=useCallback(u=>{if(P.current)return Promise.resolve();let d=u?.preserve===true;return P.current=true,k.current=false,O(false),d||(v.current=null,M.current=null,m.current=0,Z(true),l({count:0,results:[]})),K.current().then(({data:y})=>{let Q=JSON.stringify({entityNamePlural:t,scope:r$1,selection:o,includeCount:s$1,variables:n}),f=D({data:y,entityNamePlural:t,isForm:i$1,schema:e$1,scope:r$1,defaultScope:c$1});v.current=Q,M.current=null,m.current=F(n)+f.results.length,l(f);}).catch(y=>{console.error("Error reloading data:",y);}).finally(()=>{P.current=false,Z(false);})},[c$1,t,i$1,e$1,r$1,o,s$1,n]);return useEffect(()=>{if(S){G(S);return}E&&B&&!R&&G(null);},[E,R,B,S,G]),useEffect(()=>{if(R||S||x)return;let u=JSON.stringify({entityNamePlural:t,scope:r$1,selection:o,includeCount:s$1,variables:n});if(v.current===u)return;if(I&&M.current!==u){M.current=u,m.current=0,l({count:0,results:[]});return}if(I)return;let d=D({data:E,entityNamePlural:t,isForm:i$1,schema:e$1,scope:r$1,defaultScope:c$1});v.current=u,M.current=null,m.current=F(n)+d.results.length,l(d);},[c$1,E,R,t,i$1,I,x,e$1,S,r$1,o,s$1,n]),useEffect(()=>{let u=it.current;if(it.current=w,R||S||P.current||x||u!==NetworkStatus.refetch||w!==NetworkStatus.ready||!E)return;let d=JSON.stringify({entityNamePlural:t,scope:r$1,selection:o,includeCount:s$1,variables:n}),y=D({data:E,entityNamePlural:t,isForm:i$1,schema:e$1,scope:r$1,defaultScope:c$1});v.current=d,M.current=null,m.current=F(n)+y.results.length,l(y);},[c$1,E,R,t,i$1,x,w,e$1,S,r$1,o,s$1,n]),useEffect(()=>{if(i$1)return;let u=`Get${r(t)}`,d=Qt(f=>{if(!(!f.has(u)||k.current||P.current))return K.current().then(({data:p})=>{let a=JSON.stringify({entityNamePlural:t,scope:r$1,selection:o,includeCount:s$1,variables:n}),L=D({data:p,entityNamePlural:t,isForm:i$1,schema:e$1,scope:r$1,defaultScope:c$1});v.current=a,M.current=null,m.current=F(n)+L.results.length,l(L);}).catch(p=>{console.error("Error soft-refreshing entity list:",p);})}),y=Pt((f,p)=>{f===u&&l(a=>{let L=a.results.filter(ft=>{let dt=typeof ft._id=="string"?ft._id:void 0;return !dt||!p.has(dt)}),lt=a.results.length-L.length;return lt===0?a:{count:Math.max(0,a.count-lt),results:L}});}),Q=vt((f,p)=>{f===u&&l(a=>Vt(a,p,n?.sort));});return ()=>{d(),y(),Q();}},[c$1,t,i$1,e$1,r$1,o,s$1,n]),{isLoading:I&&w!==NetworkStatus.refetch||U||x,isLoadingMore:_,fetchMore:At,reload:It,count:b.count,data:b.results,isProjectDisabled:Dt,isProjectReadOnly:_t,schemaErrorMessage:B}}function F(t){let e=t?.offset;return typeof e=="number"&&Number.isFinite(e)?e:0}function D(t){let e=t.entityNamePlural;return t.data?.[e]?t.isForm?k(t.entityNamePlural,t.scope,t.data,t.schema,t.defaultScope):j(t.entityNamePlural,t.scope,t.data,t.schema):{count:0,results:[]}}function Vt(t,e,r){let n=new Map(e.map(s=>[s._id,s])),i=false,o=t.results.map(s=>{let h=typeof s._id=="string"?s._id:void 0;if(!h)return s;let b=n.get(h);return b?(i=true,{...s,...b.attributes}):s});return i?{count:t.count,results:Bt(o,r)}:t}function Bt(t,e){if(!Array.isArray(e)||e.length===0)return t;let[r]=e;if(!r||typeof r!="object")return t;let[n]=Object.entries(r),[i,o]=n??[];if(!i||o!=="ASC"&&o!=="DESC")return t;let s=o==="DESC"?-1:1;return [...t].sort((h,b)=>{let l=h[i],_=b[i],O=typeof l=="string"?l:"",U=typeof _=="string"?_:"";return O.localeCompare(U)*s})}export{$t as a,zt as b,Yt as c,qt as d,oe as e};//# sourceMappingURL=chunk-FXUD4JRG.js.map
2
+ //# sourceMappingURL=chunk-FXUD4JRG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/graphql-client/refetch-entity-lists.ts","../src/graphql-client/use-entity-query.ts"],"names":["refetchTimer","pendingQueryNames","pendingResolvers","listeners","removalListeners","patchListeners","getEntityListQueryName","entityNameOrPlural","schema","getOperationEntityName","assetSchema","byPlural","entity","byName","plural","subscribeEntityListRefetch","listener","subscribeEntityListRemoval","subscribeEntityListPatch","scheduleEntityListRemoval","apolloClient","queryName","entityIds","ids","scheduleEntityListRefetch","scheduleEntityListPatch","patches","nextPatches","patch","_apolloClient","resolve","reject","names","resolvers","finish","error","fail","useEntityQuery","entityNamePlural","scope","variables","isForm","selection","includeCount","fetchPolicy","result","setResult","useState","isLoadingMore","setIsLoadingMore","isReloading","setIsReloading","unsupportedTotalCount","setUnsupportedTotalCount","isLoadingMoreRef","useRef","isReloadingRef","nextOffsetRef","syncedQueryKeyRef","pendingQueryKeyRef","defaultScope","useDefaultScope","totalCountField","entitySchema","getEntitySchema","countMode","queryDocument","useMemo","gql","getEntityQuery","fetchMoreDocument","schemaErrorMessage","setSchemaErrorMessage","useGraphQLError","isLoading","data","fetchNextPage","refetch","networkStatus","useQuery","fetchNextPageRef","refetchRef","fetchMoreDocumentRef","previousNetworkStatusRef","variablesRef","isMissingTotalCountField","isMissingGraphQLFieldError","shouldFallbackToAggregate","effectiveError","isTotalCountFallbackLoading","serverError","getServerError","schemaMismatchMessage","getGraphQLSchemaMismatchMessage","isProjectDisabled","isProjectReadOnly","responseBody","parseErrorBody","useEffect","fetchMore","useCallback","args","limit","offset","res","mappedFetchMoreResults","mapResults","pageLength","prevRows","merged","uniqBy","prop","fetchError","reload","options","preserve","queryKey","mapped","getVariablesOffset","previousStatus","NetworkStatus","listQueryName","unsubscribeRefetch","queryNames","unsubscribeRemoval","prev","nextResults","row","rowId","removedCount","unsubscribePatch","applyEntityListPatches","mapQueryResultForFormFields","mapQueryResult","sort","patchById","didPatch","sortEntityListResults","results","primarySort","primarySortEntry","sortField","sortDirection","direction","left","right","leftValue","rightValue","leftText","rightText"],"mappings":"wXAcA,IAAIA,CAAAA,CAAqD,KACnDC,CAAAA,CAAoB,IAAI,GAAA,CACxBC,EAAAA,CAAqF,EAAC,CACtFC,EAAY,IAAI,GAAA,CAChBC,EAAmB,IAAI,GAAA,CACvBC,EAAiB,IAAI,GAAA,CAEpB,SAASC,EAAAA,CAAuBC,CAAAA,CAA4BC,CAAAA,CAAwB,CACzF,GAAID,CAAAA,GAAuB,UAAYA,CAAAA,GAAuB,SAAA,CAC5D,OAAO,CAAA,GAAA,EAAME,CAAAA,CAAuBC,CAAAA,CAAY,MAAM,CAAC,CAAA,CAAA,CAGzD,IAAMC,GAAAA,CAAWH,CAAAA,CAAO,KAAMI,CAAAA,EAAWA,CAAAA,CAAO,SAAWL,CAAkB,CAAA,CACvEM,CAAAA,CAASL,CAAAA,CAAO,IAAA,CAAMI,CAAAA,EAAWA,EAAO,IAAA,GAASL,CAAkB,EACnEO,CAAAA,CAASH,G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AAA,CAAW,OAAOF,CAAAA,EAAc,QAAA,CAAWA,CAAAA,CAAY,EAAA,CACvDG,CAAAA,CAAY,OAAOF,GAAe,QAAA,CAAWA,CAAAA,CAAa,GAEhE,OAAOC,CAAAA,CAAS,cAAcC,CAAS,CAAA,CAAIN,CAC7C,CAAC,CACH","file":"chunk-FXUD4JRG.js","sourcesContent":["import type { ApolloClient } from '@apollo/client';\nimport type { Schema } from '../core/types';\nimport { assetSchema } from '../entities/assets-schema';\nimport { getOperationEntityName } from './queries';\n\ntype EntityListRefreshListener = (queryNames: ReadonlySet<string>) => void | Promise<void>;\ntype EntityListRemovalListener = (queryName: string, entityIds: ReadonlySet<string>) => void;\ntype EntityListPatchListener = (queryName: string, patches: EntityListRowPatch[]) => void;\n\nexport type EntityListRowPatch = {\n _id: string;\n attributes: { [key: string]: string };\n};\n\nlet refetchTimer: ReturnType<typeof setTimeout> | null = null;\nconst pendingQueryNames = new Set<string>();\nconst pendingResolvers: Array<{ resolve: () => void; reject: (error: unknown) => void }> = [];\nconst listeners = new Set<EntityListRefreshListener>();\nconst removalListeners = new Set<EntityListRemovalListener>();\nconst patchListeners = new Set<EntityListPatchListener>();\n\nexport function getEntityListQueryName(entityNameOrPlural: string, schema: Schema): string {\n if (entityNameOrPlural === '_asset' || entityNameOrPlural === '_assets') {\n return `Get${getOperationEntityName(assetSchema.plural)}`;\n }\n\n const byPlural = schema.find((entity) => entity.plural === entityNameOrPlural);\n const byName = schema.find((entity) => entity.name === entityNameOrPlural);\n const plural = byPlural?.plural ?? byName?.plural ?? entityNameOrPlural;\n\n return `Get${getOperationEntityName(plural)}`;\n}\n\n/**\n * Subscribe to soft list refreshes. Listeners should refetch their own query and\n * remap local paginated state (useEntityQuery ignores Apollo cache writes after sync).\n */\nexport function subscribeEntityListRefetch(listener: EntityListRefreshListener): () => void {\n listeners.add(listener);\n\n return () => {\n listeners.delete(listener);\n };\n}\n\n/**\n * Subscribe to optimistic row removals (e.g. after delete) before the soft-refetch lands.\n */\nexport function subscribeEntityListRemoval(listener: EntityListRemovalListener): () => void {\n removalListeners.add(listener);\n\n return () => {\n removalListeners.delete(listener);\n };\n}\n\n/**\n * Subscribe to in-place row patches (e.g. tag connect/disconnect) without a full list refetch.\n */\nexport function subscribeEntityListPatch(listener: EntityListPatchListener): () => void {\n patchListeners.add(listener);\n\n return () => {\n patchListeners.delete(listener);\n };\n}\n\n/**\n * Immediately drop rows from mounted lists, then soft-refetch to sync counts/pages.\n */\nexport function scheduleEntityListRemoval(\n apolloClient: ApolloClient,\n queryName: string,\n entityIds: string[]\n): Promise<void> {\n const ids = new Set(entityIds.filter(Boolean));\n\n if (ids.size > 0) {\n for (const listener of removalListeners) {\n listener(queryName, ids);\n }\n }\n\n return scheduleEntityListRefetch(apolloClient, queryName);\n}\n\n/**\n * Patch mounted list rows in place. Use when a mutation cannot change list cardinality\n * (e.g. tag connect/disconnect) so we avoid a full GetAssets soft-refetch.\n */\nexport function scheduleEntityListPatch(queryName: string, patches: EntityListRowPatch[]): void {\n const nextPatches = patches.filter((patch) => Boolean(patch._id));\n\n if (nextPatches.length === 0) {\n return;\n }\n\n for (const listener of patchListeners) {\n listener(queryName, nextPatches);\n }\n}\n\n/**\n * Ask mounted entity lists to soft-refresh. Debounced so batch deletes coalesce.\n */\nexport function scheduleEntityListRefetch(_apolloClient: ApolloClient, queryName: string): Promise<void> {\n pendingQueryNames.add(queryName);\n\n return new Promise<void>((resolve, reject) => {\n pendingResolvers.push({ resolve, reject });\n\n if (refetchTimer) {\n clearTimeout(refetchTimer);\n }\n\n refetchTimer = setTimeout(() => {\n const names = new Set(pendingQueryNames);\n const resolvers = pendingResolvers.splice(0);\n pendingQueryNames.clear();\n refetchTimer = null;\n\n void Promise.all([...listeners].map((listener) => Promise.resolve(listener(names))))\n .then(() => {\n for (const { resolve: finish } of resolvers) {\n finish();\n }\n })\n .catch((error: unknown) => {\n console.error('Error refreshing entity lists:', error);\n\n for (const { reject: fail } of resolvers) {\n fail(error);\n }\n });\n }, 50);\n });\n}\n","import { useDefaultScope } from '../core/default-scope';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { prop, uniqBy } from 'ramda';\nimport { gql, NetworkStatus } from '@apollo/client';\nimport type { OperationVariables } from '@apollo/client';\nimport { useQuery } from '@apollo/client/react';\nimport {\n getGraphQLSchemaMismatchMessage,\n getServerError,\n isMissingGraphQLFieldError,\n parseErrorBody,\n} from './error-utils';\nimport {\n getEntityQuery,\n getEntitySchema,\n getOperationEntityName,\n mapQueryResult,\n mapQueryResultForFormFields,\n} from './queries';\nimport {\n subscribeEntityListPatch,\n subscribeEntityListRefetch,\n subscribeEntityListRemoval,\n type EntityListRowPatch,\n} from './refetch-entity-lists';\nimport { useGraphQLError } from './graphql-context';\nimport type {\n EntityQueryAggregate,\n EntityQueryResults,\n FormEntityItem,\n MappedEntityQueryResults,\n MappedEntityItem,\n MappedFormEntityQueryResults,\n UseEntityQueryParams,\n ImageValue,\n} from './types';\n\ntype FetchMoreOptions = {\n // `offset` is accepted for call-site compatibility but overridden by nextOffsetRef.\n // `where`/`sort` are inherited from the active query unless overridden here.\n variables: OperationVariables & { offset: number; limit: number };\n};\ntype Results = (MappedEntityQueryResults | MappedFormEntityQueryResults) | { count: 0; results: [] };\n\nexport function useEntityQuery({\n entityNamePlural,\n schema,\n scope,\n variables,\n isForm,\n selection = 'full',\n includeCount = true,\n fetchPolicy,\n}: UseEntityQueryParams): {\n count: number;\n data: MappedEntityItem[] | FormEntityItem[] | ImageValue[] | undefined;\n fetchMore: (args: FetchMoreOptions) => void;\n isLoading: boolean;\n isLoadingMore: boolean;\n isProjectDisabled: boolean;\n isProjectReadOnly: boolean;\n reload: (options?: { preserve?: boolean }) => Promise<void>;\n schemaErrorMessage: string | null;\n} {\n const [result, setResult] = useState<Results>({\n count: 0,\n results: [],\n });\n const [isLoadingMore, setIsLoadingMore] = useState(false);\n const [isReloading, setIsReloading] = useState(false);\n const [unsupportedTotalCount, setUnsupportedTotalCount] = useState<{\n field: string;\n schema: UseEntityQueryParams['schema'];\n } | null>(null);\n const isLoadingMoreRef = useRef(false);\n const isReloadingRef = useRef(false);\n // Next offset for fetchMore — advanced by each requested page window, not by the\n // deduplicated row count. Using unique rows.length as offset collapses when pages\n // overlap (unstable sorts / tied timestamps) into irregular steps like 25→35→42.\n const nextOffsetRef = useRef(0);\n // Tracks the query identity we last synced into local result state.\n // fetchMore updates Apollo `data` without changing this identity; syncing those\n // updates would wipe accumulated pages and retrigger infinite load-more.\n // Must include entity/scope — variables alone collide across entity navigations.\n const syncedQueryKeyRef = useRef<string | null>(null);\n const pendingQueryKeyRef = useRef<string | null>(null);\n const defaultScope = useDefaultScope();\n const totalCountField = `${entityNamePlural}Total`;\n const entitySchema = getEntitySchema(schema, entityNamePlural);\n const canUseTotalCount =\n variables?.where === undefined &&\n (entitySchema?.spaces?.length ?? 0) === 0 &&\n (unsupportedTotalCount?.field !== totalCountField || unsupportedTotalCount.schema !== schema);\n const countMode = canUseTotalCount ? 'total' : 'aggregate';\n const queryDocument = useMemo(\n () =>\n gql(getEntityQuery(entityNamePlural, scope, schema, { selection, countMode, includeCount, defaultScope }).query),\n [entityNamePlural, scope, schema, selection, countMode, includeCount, defaultScope]\n );\n // fetchMore pages skip the top-level aggregate count (a filtered label scan\n // on the server); the total from the first page still stands.\n const fetchMoreDocument = useMemo(\n () => gql(getEntityQuery(entityNamePlural, scope, schema, { selection, includeCount: false, defaultScope }).query),\n [entityNamePlural, scope, schema, selection, defaultScope]\n );\n const { schemaErrorMessage, setSchemaErrorMessage } = useGraphQLError();\n const {\n loading: isLoading,\n data,\n fetchMore: fetchNextPage,\n refetch,\n error,\n networkStatus,\n } = useQuery<EntityQueryResults & EntityQueryAggregate>(queryDocument, {\n variables,\n notifyOnNetworkStatusChange: true,\n fetchPolicy,\n });\n const fetchNextPageRef = useRef(fetchNextPage);\n const refetchRef = useRef(refetch);\n const fetchMoreDocumentRef = useRef(fetchMoreDocument);\n const previousNetworkStatusRef = useRef(networkStatus);\n const variablesRef = useRef(variables);\n fetchNextPageRef.current = fetchNextPage;\n refetchRef.current = refetch;\n fetchMoreDocumentRef.current = fetchMoreDocument;\n variablesRef.current = variables;\n\n // Parse 403 error response to determine the specific error code\n const isMissingTotalCountField = includeCount && isMissingGraphQLFieldError(error, totalCountField);\n const shouldFallbackToAggregate = countMode === 'total' && isMissingTotalCountField;\n const effectiveError = isMissingTotalCountField ? undefined : error;\n const isTotalCountFallbackLoading = isMissingTotalCountField && !data?.[entityNamePlural];\n const serverError = getServerError(effectiveError);\n const schemaMismatchMessage = getGraphQLSchemaMismatchMessage(effectiveError);\n\n const { isProjectDisabled, isProjectReadOnly } = (() => {\n if (serverError?.statusCode === 403) {\n const responseBody = parseErrorBody<{ code?: string }>(serverError.bodyText);\n\n if (responseBody && typeof responseBody.code === 'string') {\n if (responseBody.code === 'PROJECT_PAUSED') {\n return {\n isProjectDisabled: true,\n isProjectReadOnly: false,\n };\n }\n\n if (responseBody.code === 'READ_ONLY_MODE') {\n return {\n isProjectDisabled: false,\n isProjectReadOnly: true,\n };\n }\n }\n\n return {\n isProjectDisabled: true,\n isProjectReadOnly: false,\n };\n }\n\n return {\n isProjectDisabled: false,\n isProjectReadOnly: false,\n };\n })();\n\n useEffect(() => {\n if (!shouldFallbackToAggregate) {\n return;\n }\n\n setUnsupportedTotalCount({ field: totalCountField, schema });\n }, [schema, shouldFallbackToAggregate, totalCountField]);\n\n const fetchMore = useCallback(\n (args: FetchMoreOptions): void => {\n if (isLoadingMoreRef.current || isReloadingRef.current) {\n return;\n }\n\n isLoadingMoreRef.current = true;\n setIsLoadingMore(true);\n\n const { limit } = args.variables;\n const offset = nextOffsetRef.current;\n\n fetchNextPageRef\n .current({\n ...args,\n query: fetchMoreDocumentRef.current,\n variables: {\n // fetchMore uses a count-free document, so Apollo will not inherit\n // the original operation's where/sort unless we pass them again.\n ...variablesRef.current,\n ...args.variables,\n offset,\n limit,\n },\n })\n .then(({ data: res }) => {\n const mappedFetchMoreResults = mapResults({\n data: res,\n entityNamePlural,\n isForm,\n schema,\n scope,\n defaultScope,\n });\n // Advance by the fetched page window (capped at limit), not by how many unique\n // rows survived client-side merge. Cap protects against Apollo returning a\n // merged cache blob larger than the requested page.\n const pageLength = mappedFetchMoreResults.results.length;\n nextOffsetRef.current = offset + (pageLength === 0 ? 0 : Math.min(pageLength, limit));\n\n setResult((prevRows) => {\n const merged = uniqBy(prop('_id'), [\n ...prevRows.results,\n ...mappedFetchMoreResults.results,\n ]) as Results['results'];\n\n // Empty/duplicate pages must end pagination, otherwise load-more loops forever\n // when aggregate count is ahead of rows that the where-clause can actually return.\n if (merged.length === prevRows.results.length) {\n return {\n count: prevRows.results.length,\n results: prevRows.results,\n } as Results;\n }\n\n // Count-free pagination pages report 0; the first page's total stands.\n return {\n count: mappedFetchMoreResults.count || prevRows.count,\n results: merged,\n } as Results;\n });\n })\n .catch((fetchError: unknown) => {\n console.error('Error fetching more data:', fetchError);\n })\n .finally(() => {\n isLoadingMoreRef.current = false;\n setIsLoadingMore(false);\n });\n },\n [defaultScope, entityNamePlural, isForm, schema, scope]\n );\n\n const reload = useCallback(\n (options?: { preserve?: boolean }): Promise<void> => {\n if (isReloadingRef.current) {\n return Promise.resolve();\n }\n\n const preserve = options?.preserve === true;\n\n isReloadingRef.current = true;\n isLoadingMoreRef.current = false;\n setIsLoadingMore(false);\n\n if (!preserve) {\n syncedQueryKeyRef.current = null;\n pendingQueryKeyRef.current = null;\n nextOffsetRef.current = 0;\n setIsReloading(true);\n setResult({ count: 0, results: [] });\n }\n\n return refetchRef\n .current()\n .then(({ data: res }) => {\n const queryKey = JSON.stringify({ entityNamePlural, scope, selection, includeCount, variables });\n const mapped = mapResults({ data: res, entityNamePlural, isForm, schema, scope, defaultScope });\n\n syncedQueryKeyRef.current = queryKey;\n pendingQueryKeyRef.current = null;\n nextOffsetRef.current = getVariablesOffset(variables) + mapped.results.length;\n setResult(mapped);\n })\n .catch((fetchError: unknown) => {\n console.error('Error reloading data:', fetchError);\n })\n .finally(() => {\n isReloadingRef.current = false;\n setIsReloading(false);\n });\n },\n [defaultScope, entityNamePlural, isForm, schema, scope, selection, includeCount, variables]\n );\n\n useEffect(() => {\n if (schemaMismatchMessage) {\n setSchemaErrorMessage(schemaMismatchMessage);\n\n return;\n }\n\n if (data && schemaErrorMessage && !effectiveError) {\n setSchemaErrorMessage(null);\n }\n }, [data, effectiveError, schemaErrorMessage, schemaMismatchMessage, setSchemaErrorMessage]);\n\n useEffect(() => {\n if (effectiveError || schemaMismatchMessage || isTotalCountFallbackLoading) {\n return;\n }\n\n const queryKey = JSON.stringify({ entityNamePlural, scope, selection, includeCount, variables });\n\n // Already synced for this query identity — ignore Apollo `data` updates from fetchMore.\n if (syncedQueryKeyRef.current === queryKey) {\n return;\n }\n\n if (isLoading && pendingQueryKeyRef.current !== queryKey) {\n pendingQueryKeyRef.current = queryKey;\n nextOffsetRef.current = 0;\n setResult({ count: 0, results: [] });\n\n return;\n }\n\n if (isLoading) {\n return;\n }\n\n const mapped = mapResults({ data, entityNamePlural, isForm, schema, scope, defaultScope });\n syncedQueryKeyRef.current = queryKey;\n pendingQueryKeyRef.current = null;\n nextOffsetRef.current = getVariablesOffset(variables) + mapped.results.length;\n setResult(mapped);\n }, [\n defaultScope,\n data,\n effectiveError,\n entityNamePlural,\n isForm,\n isLoading,\n isTotalCountFallbackLoading,\n schema,\n schemaMismatchMessage,\n scope,\n selection,\n includeCount,\n variables,\n ]);\n\n // After an Apollo refetch (delete/upload), replace accumulated pages with the\n // fresh first page. fetchMore uses NetworkStatus.fetchMore and is ignored.\n useEffect(() => {\n const previousStatus = previousNetworkStatusRef.current;\n previousNetworkStatusRef.current = networkStatus;\n\n if (effectiveError || schemaMismatchMessage || isReloadingRef.current || isTotalCountFallbackLoading) {\n return;\n }\n\n if (previousStatus !== NetworkStatus.refetch || networkStatus !== NetworkStatus.ready || !data) {\n return;\n }\n\n const queryKey = JSON.stringify({ entityNamePlural, scope, selection, includeCount, variables });\n const mapped = mapResults({ data, entityNamePlural, isForm, schema, scope, defaultScope });\n syncedQueryKeyRef.current = queryKey;\n pendingQueryKeyRef.current = null;\n nextOffsetRef.current = getVariablesOffset(variables) + mapped.results.length;\n setResult(mapped);\n }, [\n defaultScope,\n data,\n effectiveError,\n entityNamePlural,\n isForm,\n isTotalCountFallbackLoading,\n networkStatus,\n schema,\n schemaMismatchMessage,\n scope,\n selection,\n includeCount,\n variables,\n ]);\n\n // Soft-refresh after mutations (tags, deletes, uploads). Local paginated state\n // ignores Apollo cache writes, so we must refetch and remap explicitly.\n useEffect(() => {\n if (isForm) {\n return;\n }\n\n const listQueryName = `Get${getOperationEntityName(entityNamePlural)}`;\n\n const unsubscribeRefetch = subscribeEntityListRefetch((queryNames) => {\n if (!queryNames.has(listQueryName) || isLoadingMoreRef.current || isReloadingRef.current) {\n return;\n }\n\n return refetchRef\n .current()\n .then(({ data: res }) => {\n const queryKey = JSON.stringify({ entityNamePlural, scope, selection, includeCount, variables });\n const mapped = mapResults({ data: res, entityNamePlural, isForm, schema, scope, defaultScope });\n syncedQueryKeyRef.current = queryKey;\n pendingQueryKeyRef.current = null;\n nextOffsetRef.current = getVariablesOffset(variables) + mapped.results.length;\n setResult(mapped);\n })\n .catch((fetchError: unknown) => {\n console.error('Error soft-refreshing entity list:', fetchError);\n });\n });\n\n const unsubscribeRemoval = subscribeEntityListRemoval((queryName, entityIds) => {\n if (queryName !== listQueryName) {\n return;\n }\n\n setResult((prev) => {\n const nextResults = prev.results.filter((row) => {\n const rowId = typeof row._id === 'string' ? row._id : undefined;\n\n return !rowId || !entityIds.has(rowId);\n });\n const removedCount = prev.results.length - nextResults.length;\n\n if (removedCount === 0) {\n return prev;\n }\n\n return {\n count: Math.max(0, prev.count - removedCount),\n results: nextResults,\n } as Results;\n });\n });\n\n const unsubscribePatch = subscribeEntityListPatch((queryName, patches) => {\n if (queryName !== listQueryName) {\n return;\n }\n\n setResult((prev) => applyEntityListPatches(prev, patches, variables?.sort));\n });\n\n return () => {\n unsubscribeRefetch();\n unsubscribeRemoval();\n unsubscribePatch();\n };\n }, [defaultScope, entityNamePlural, isForm, schema, scope, selection, includeCount, variables]);\n\n return {\n // Refetch keeps existing rows visible; only initial load / explicit reload show as loading.\n isLoading:\n (isLoading && networkStatus !== NetworkStatus.refetch) || isReloading || isTotalCountFallbackLoading,\n isLoadingMore,\n fetchMore,\n reload,\n count: result.count,\n data: result.results,\n isProjectDisabled,\n isProjectReadOnly,\n schemaErrorMessage,\n };\n}\n\nfunction getVariablesOffset(variables: OperationVariables | undefined): number {\n const offset = variables?.offset;\n\n return typeof offset === 'number' && Number.isFinite(offset) ? offset : 0;\n}\n\nfunction mapResults(\n args: {\n data: (EntityQueryResults & EntityQueryAggregate) | undefined;\n defaultScope: string;\n } & UseEntityQueryParams\n): MappedEntityQueryResults | MappedFormEntityQueryResults {\n const entityNamePlural = args.entityNamePlural as keyof FormEntityItem;\n\n if (!args.data?.[entityNamePlural]) {\n return { count: 0, results: [] };\n }\n\n return args.isForm\n ? mapQueryResultForFormFields(args.entityNamePlural, args.scope, args.data, args.schema, args.defaultScope)\n : mapQueryResult(args.entityNamePlural, args.scope, args.data, args.schema);\n}\n\nfunction applyEntityListPatches(\n prev: Results,\n patches: EntityListRowPatch[],\n sort: unknown\n): Results {\n const patchById = new Map(patches.map((patch) => [patch._id, patch]));\n let didPatch = false;\n const nextResults = prev.results.map((row) => {\n const rowId = typeof row._id === 'string' ? row._id : undefined;\n\n if (!rowId) {\n return row;\n }\n\n const patch = patchById.get(rowId);\n\n if (!patch) {\n return row;\n }\n\n didPatch = true;\n\n return {\n ...row,\n ...patch.attributes,\n };\n });\n\n if (!didPatch) {\n return prev;\n }\n\n return {\n count: prev.count,\n results: sortEntityListResults(nextResults, sort),\n } as Results;\n}\n\nfunction sortEntityListResults<T extends { [key: string]: unknown }>(results: T[], sort: unknown): T[] {\n if (!Array.isArray(sort) || sort.length === 0) {\n return results;\n }\n\n const [primarySort] = sort;\n\n if (!primarySort || typeof primarySort !== 'object') {\n return results;\n }\n\n const [primarySortEntry] = Object.entries(primarySort as { [key: string]: unknown });\n const [sortField, sortDirection] = primarySortEntry ?? [];\n\n if (!sortField || (sortDirection !== 'ASC' && sortDirection !== 'DESC')) {\n return results;\n }\n\n const direction = sortDirection === 'DESC' ? -1 : 1;\n\n return [...results].sort((left, right) => {\n const leftValue = left[sortField];\n const rightValue = right[sortField];\n const leftText = typeof leftValue === 'string' ? leftValue : '';\n const rightText = typeof rightValue === 'string' ? rightValue : '';\n\n return leftText.localeCompare(rightText) * direction;\n });\n}\n"]}
@@ -1,3 +1,3 @@
1
- import'./index.css';import {d as d$1}from'./chunk-VRDTHLA3.js';import {c}from'./chunk-MBBE4RND.js';import {mutate}from'swr';function i(t){return `/api/flexkit/${t}/starter`}async function d(t,e,a,c="Something went wrong. Please try again."){try{let s=await fetch(t,{method:e,credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),r=await s.json().catch(()=>({}));return s.ok?{ok:!0,...r}:{ok:!1,code:r.code??"unknown_error",message:r.error??c}}catch{return {ok:false,code:"network_error",message:"Flexkit is not reachable. Check your connection and try again."}}}function w(t){return d(c.me,"PATCH",{displayName:t})}function b(t,e){return d(i(t),"POST",e)}function g(t){return t?.state==="queued"||t?.state==="deploying"||t?.state==="seeding"}function T(t){return [`I'm setting up Flexkit for my business: ${t.trim()}`,"","Design a schema for it: propose the entities, fields and relationships we need to run it day to day, and market scopes if we sell in more than one market. Keep it practical and complete enough to use from the start. Once the schema is deployed, offer to add a few realistic sample records."].join(`
2
- `)}var x=["Which variants are running low on stock, and what is already on order?","Why are Orb Pendant Lamps being returned? Look at the returns, reviews and support tickets.","Which products are missing prices, titles or SEO copy in the UK or US?","Show last month\u2019s revenue by market and sales channel.","Which open support tickets need attention today?"],v=["Design a schema for my business. Ask me what you need to know first.","Set up a product catalog with variants, prices per market and stock per warehouse.","Help me import my products from a spreadsheet."];function _(t){let e=t.trim();return e?e.length>48?"Project names can be up to 48 characters.":null:"Give your project a name."}function O(t,e,a){switch(t){case "starter":return {kind:"starter",template:"commerce",sampleData:e};case "describe":return {kind:"describe",description:a};case "empty":return {kind:"empty"}}}var h=2e3,f=300,u=new Set;async function y(t){let e=await fetch(i(t),{credentials:"include"});return e.ok?(await e.json()).starter??"missing":null}function k(t){return t.state==="seeding"||t.state==="completed"}function F({fetchStatus:t,projectId:e,publish:a=r=>mutate(i(e),{starter:r},{revalidate:false}),revalidate:c=d$1,sleep:s=r=>new Promise(o=>setTimeout(o,r))}){if(u.has(e))return;u.add(e);let r=t??(()=>y(e));(async()=>{let o=false;try{for(let l=0;l<f;l+=1){await s(h);let n=null;try{n=await r();}catch{n=null;}if(n==="missing")return;if(n!==null&&(await a(n),!o&&k(n)&&(o=!0,await c(e)),!g(n)))return}}finally{u.delete(e);}})();}export{i as a,d as b,w as c,b as d,g as e,T as f,x as g,v as h,_ as i,O as j,F as k};//# sourceMappingURL=chunk-HR4QZ5TD.js.map
3
- //# sourceMappingURL=chunk-HR4QZ5TD.js.map
1
+ import'./index.css';import {d as d$1}from'./chunk-TWA6OG5U.js';import {c}from'./chunk-MBBE4RND.js';import {mutate}from'swr';function i(t){return `/api/flexkit/${t}/starter`}async function d(t,e,a,c="Something went wrong. Please try again."){try{let s=await fetch(t,{method:e,credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),r=await s.json().catch(()=>({}));return s.ok?{...r,ok:!0}:{ok:!1,code:r.code??"unknown_error",message:r.error??c}}catch{return {ok:false,code:"network_error",message:"Flexkit is not reachable. Check your connection and try again."}}}function w(t){return d(c.me,"PATCH",{displayName:t})}function b(t,e){return d(i(t),"POST",e)}function g(t){return t?.state==="queued"||t?.state==="deploying"||t?.state==="seeding"}function T(t){return [`I'm setting up Flexkit for my business: ${t.trim()}`,"","Design a schema for it: propose the entities, fields and relationships we need to run it day to day, and market scopes if we sell in more than one market. Keep it practical and complete enough to use from the start. Once the schema is deployed, offer to add a few realistic sample records."].join(`
2
+ `)}var x=["Which variants are running low on stock, and what is already on order?","Why are Orb Pendant Lamps being returned? Look at the returns, reviews and support tickets.","Which products are missing prices, titles or SEO copy in the UK or US?","Show last month\u2019s revenue by market and sales channel.","Which open support tickets need attention today?"],v=["Design a schema for my business. Ask me what you need to know first.","Set up a product catalog with variants, prices per market and stock per warehouse.","Help me import my products from a spreadsheet."];function _(t){let e=t.trim();return e?e.length>48?"Project names can be up to 48 characters.":null:"Give your project a name."}function O(t,e,a){switch(t){case "starter":return {kind:"starter",template:"commerce",sampleData:e};case "describe":return {kind:"describe",description:a};case "empty":return {kind:"empty"}}}var h=2e3,f=300,u=new Set;async function y(t){let e=await fetch(i(t),{credentials:"include"});return e.ok?(await e.json()).starter??"missing":null}function k(t){return t.state==="seeding"||t.state==="completed"}function F({fetchStatus:t,projectId:e,publish:a=r=>mutate(i(e),{starter:r},{revalidate:false}),revalidate:c=d$1,sleep:s=r=>new Promise(o=>setTimeout(o,r))}){if(u.has(e))return;u.add(e);let r=t??(()=>y(e));(async()=>{let o=false;try{for(let l=0;l<f;l+=1){await s(h);let n=null;try{n=await r();}catch{n=null;}if(n==="missing")return;if(n!==null&&(await a(n),!o&&k(n)&&(o=!0,await c(e)),!g(n)))return}}finally{u.delete(e);}})();}export{i as a,d as b,w as c,b as d,g as e,T as f,x as g,v as h,_ as i,O as j,k,F as l};//# sourceMappingURL=chunk-GTR4M2BQ.js.map
3
+ //# sourceMappingURL=chunk-GTR4M2BQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/config/onboarding.ts","../src/apps/ai/starter-watch.ts"],"names":["starterPath","projectId","send","url","method","body","fallbackMessage","response","json","saveDisplayName","displayName","userApiPaths","applyStarter","starter","isStarterRunning","status","describeBusinessPrompt","description","COMMERCE_STARTER_PROMPTS","EMPTY_STARTER_PROMPTS","validateProjectName","name","trimmed","toProjectStart","kind","sampleData","POLL_INTERVAL_MS","POLL_LIMIT","watching","fetchStarter","starterSchemaDeployed","watchStarter","fetchStatus","publish","mutate","revalidate","revalidateProjectSchema","sleep","ms","resolve","load","schemaLoaded","attempt"],"mappings":"4HAuBO,SAASA,CAAAA,CAAYC,CAAAA,CAA2B,CACrD,OAAO,gBAAgBA,CAAS,CAAA,QAAA,CAClC,CAKA,eAAsBC,CAAAA,CACpBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,EAAkB,yCAAA,CACqB,CACvC,GAAI,CACF,IAAMC,CAAAA,CAAW,MAAM,KAAA,CAAMJ,EAAK,CAChC,MAAA,CAAAC,CAAAA,CACA,WAAA,CAAa,aAAA,CACb,OAAA,CAAS,CAAE,cAAA,CAAgB,kBAAmB,CAAA,CAC9C,IAAA,CAAM,IAAA,CAAK,SAAA,CAAUC,CAAI,CAC3B,CAAC,CAAA,CACKG,EAAQ,MAAMD,CAAAA,CAAS,IAAA,EAAK,CAAE,KAAA,CAAM,KAAO,EAAC,CAAE,EAEpD,OAAIA,CAAAA,CAAS,EAAA,CACJ,CAAE,GAAGC,CAAAA,CAAM,EAAA,CAAI,CAAA,CAAK,EAGtB,CACL,EAAA,CAAI,CAAA,CAAA,CACJ,IAAA,CAAMA,EAAK,IAAA,EAAQ,eAAA,CACnB,OAAA,CAASA,CAAAA,CAAK,OAASF,CACzB,CACF,CAAA,KAAQ,CACN,OAAO,CACL,EAAA,CAAI,KAAA,CACJ,KAAM,eAAA,CACN,OAAA,CAAS,gEACX,CACF,CACF,CAGO,SAASG,CAAAA,CAAgBC,EAAsD,CACpF,OAAOR,CAAAA,CAAKS,CAAAA,CAAa,EAAA,CAAI,OAAA,CAAS,CAAE,WAAA,CAAAD,CAAY,CAAC,CACvD,CAGO,SAASE,CAAAA,CACdX,CAAAA,CACAY,CAAAA,CACgE,CAChE,OAAOX,CAAAA,CAAiCF,CAAAA,CAAYC,CAAS,CAAA,CAAG,MAAA,CAAQY,CAAO,CACjF,CAEO,SAASC,CAAAA,CAAiBC,CAAAA,CAAmD,CAClF,OAAOA,CA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AAAA,GAAW,IAAA,GAIf,MAAMkB,CAAAA,CAAQlB,CAAM,CAAA,CAEhB,CAAC0B,CAAAA,EAAgBX,CAAAA,CAAsBf,CAAM,CAAA,GAC/C0B,CAAAA,CAAe,CAAA,CAAA,CACf,MAAMN,CAAAA,CAAWlC,CAAS,CAAA,CAAA,CAGxB,CAACa,CAAAA,CAAiBC,CAAM,CAAA,CAAA,CAC1B,MAEJ,CACF,CAAA,OAAE,CACAa,CAAAA,CAAS,MAAA,CAAO3B,CAAS,EAC3B,CACF,CAAA,IACF","file":"chunk-GTR4M2BQ.js","sourcesContent":["import { userApiPaths } from '../api-paths';\n\n/** Starter templates a new project can begin from; the backend owns their schema and sample data. */\nexport type StarterTemplate = 'commerce';\n\nexport type StarterStatus = {\n template: StarterTemplate;\n sampleData: boolean;\n state: 'queued' | 'deploying' | 'seeding' | 'completed' | 'failed';\n progress?: { done: number; total: number };\n error?: string;\n completedAt?: string;\n};\n\n/** How the user chose to start a new project, carried to its AI chat in the navigation state. */\nexport type ProjectStart =\n | { kind: 'starter'; template: StarterTemplate; sampleData: boolean }\n | { kind: 'describe'; description: string }\n | { kind: 'empty' };\n\n/** Navigation state the onboarding hands the AI chat of a new project. */\nexport type OnboardingNavigationState = { onboardingPrompt?: string };\n\nexport function starterPath(projectId: string): string {\n return `/api/flexkit/${projectId}/starter`;\n}\n\nexport type Failure = { ok: false; code: string; message: string };\n\n/** A JSON request to the hosted BFF, with its failures mapped to a message the UI can show. */\nexport async function send<T>(\n url: string,\n method: 'PATCH' | 'POST',\n body: unknown,\n fallbackMessage = 'Something went wrong. Please try again.'\n): Promise<({ ok: true } & T) | Failure> {\n try {\n const response = await fetch(url, {\n method,\n credentials: 'same-origin',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n });\n const json = (await response.json().catch(() => ({}))) as { code?: string; error?: string } & T;\n\n if (response.ok) {\n return { ...json, ok: true };\n }\n\n return {\n ok: false,\n code: json.code ?? 'unknown_error',\n message: json.error ?? fallbackMessage,\n };\n } catch {\n return {\n ok: false,\n code: 'network_error',\n message: 'Flexkit is not reachable. Check your connection and try again.',\n };\n }\n}\n\n/** Hosted mode: saves the signed-in user's display name. */\nexport function saveDisplayName(displayName: string): Promise<{ ok: true } | Failure> {\n return send(userApiPaths.me, 'PATCH', { displayName });\n}\n\n/** Applies a starter template to a new, empty project; the schema and sample data arrive in the background. */\nexport function applyStarter(\n projectId: string,\n starter: { template: StarterTemplate; sampleData: boolean }\n): Promise<({ ok: true } & { starter: StarterStatus }) | Failure> {\n return send<{ starter: StarterStatus }>(starterPath(projectId), 'POST', starter);\n}\n\nexport function isStarterRunning(status: StarterStatus | null | undefined): boolean {\n return status?.state === 'queued' || status?.state === 'deploying' || status?.state === 'seeding';\n}\n\n/** The first message of a project whose owner described the business instead of picking a template. */\nexport function describeBusinessPrompt(description: string): string {\n return [\n `I'm setting up Flexkit for my business: ${description.trim()}`,\n '',\n 'Design a schema for it: propose the entities, fields and relationships we need to run it day to day, and market scopes if we sell in more than one market. Keep it practical and complete enough to use from the start. Once the schema is deployed, offer to add a few realistic sample records.',\n ].join('\\n');\n}\n\n/** Questions the commerce sample store can answer; each one finds a problem planted in the data. */\nexport const COMMERCE_STARTER_PROMPTS = [\n 'Which variants are running low on stock, and what is already on order?',\n 'Why are Orb Pendant Lamps being returned? Look at the returns, reviews and support tickets.',\n 'Which products are missing prices, titles or SEO copy in the UK or US?',\n 'Show last month’s revenue by market and sales channel.',\n 'Which open support tickets need attention today?',\n] as const;\n\nexport const EMPTY_STARTER_PROMPTS = [\n 'Design a schema for my business. Ask me what you need to know first.',\n 'Set up a product catalog with variants, prices per market and stock per warehouse.',\n 'Help me import my products from a spreadsheet.',\n] as const;\n\n/** Only what the field can tell; the backend owns the character rules and says what it refuses. */\nexport function validateProjectName(name: string): string | null {\n const trimmed = name.trim();\n\n if (!trimmed) {\n return 'Give your project a name.';\n }\n\n if (trimmed.length > 48) {\n return 'Project names can be up to 48 characters.';\n }\n\n return null;\n}\n\n/** The choice on the last step, as sent to the backend and the AI chat. */\nexport function toProjectStart(kind: ProjectStart['kind'], sampleData: boolean, description: string): ProjectStart {\n switch (kind) {\n case 'starter':\n return { kind: 'starter', template: 'commerce', sampleData };\n case 'describe':\n return { kind: 'describe', description };\n case 'empty':\n return { kind: 'empty' };\n }\n}\n","import { mutate } from 'swr';\nimport { isStarterRunning, starterPath, type StarterStatus } from '../../core/config/onboarding';\nimport { revalidateProjectSchema } from '../../core/config/use-project-schemas';\n\nconst POLL_INTERVAL_MS = 2_000;\n/** About ten minutes; a starter usually finishes in two. */\nconst POLL_LIMIT = 300;\nconst watching = new Set<string>();\n\n/** `null` = transient failure (keep polling). */\nexport type StarterFetcher = () => Promise<StarterStatus | null | 'missing'>;\n\nasync function fetchStarter(projectId: string): Promise<StarterStatus | null | 'missing'> {\n const response = await fetch(starterPath(projectId), { credentials: 'include' });\n\n if (!response.ok) {\n return null;\n }\n\n const body = (await response.json()) as { starter?: StarterStatus | null };\n\n return body.starter ?? 'missing';\n}\n\n/** The schema is live once the starter got past its deploy. */\nexport function starterSchemaDeployed(status: StarterStatus): boolean {\n return status.state === 'seeding' || status.state === 'completed';\n}\n\n/**\n * Follows a running starter until it settles, independently of which\n * component started it and of navigation inside the Studio. Shares its\n * results through the SWR cache of `starterPath`, and reloads the project\n * schema once, as soon as the starter's schema is deployed.\n */\nexport function watchStarter({\n fetchStatus,\n projectId,\n publish = (status) => mutate(starterPath(projectId), { starter: status }, { revalidate: false }),\n revalidate = revalidateProjectSchema,\n sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)),\n}: {\n fetchStatus?: StarterFetcher;\n projectId: string;\n publish?: (_status: StarterStatus) => Promise<unknown>;\n revalidate?: (_projectId: string) => Promise<unknown>;\n sleep?: (_ms: number) => Promise<void>;\n}): void {\n if (watching.has(projectId)) {\n return;\n }\n\n watching.add(projectId);\n\n const load = fetchStatus ?? (() => fetchStarter(projectId));\n\n void (async () => {\n let schemaLoaded = false;\n\n try {\n for (let attempt = 0; attempt < POLL_LIMIT; attempt += 1) {\n await sleep(POLL_INTERVAL_MS);\n\n let status: StarterStatus | null | 'missing' = null;\n\n try {\n status = await load();\n } catch {\n status = null;\n }\n\n if (status === 'missing') {\n return;\n }\n\n if (status === null) {\n continue;\n }\n\n await publish(status);\n\n if (!schemaLoaded && starterSchemaDeployed(status)) {\n schemaLoaded = true;\n await revalidate(projectId);\n }\n\n if (!isStarterRunning(status)) {\n return;\n }\n }\n } finally {\n watching.delete(projectId);\n }\n })();\n}\n"]}
@@ -1,7 +1,7 @@
1
- import'./index.css';import {b}from'./chunk-CAZ6EUR2.js';import {b as b$2}from'./chunk-2DXR5NJV.js';import {e as e$1,a as a$2,b as b$1}from'./chunk-6AJRQSFO.js';import {g as g$2,b as b$5}from'./chunk-MBBE4RND.js';import {Y,Z,aa,ba,_,ca,n}from'./chunk-RULCANNM.js';import {e as e$2,g as g$1,h,j}from'./chunk-A4DPLZZF.js';import {e,f,g}from'./chunk-G5N6HEPW.js';import {b as b$4}from'./chunk-5JUG4BEF.js';import {k,p,q,s,t}from'./chunk-S7Z6KKIN.js';import {a,b as b$3,c as c$1,d,e as e$3}from'./chunk-N33S7BSG.js';import {a as a$1,c}from'./chunk-X3SHNHHM.js';import {AlertCircle,X,ChevronDown,ArrowUp,ArrowDown,Star,CircleCheck,CircleX,Check,Copy}from'lucide-react';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import {useRef,useState,useEffect,useCallback,useMemo}from'react';import {useReactTable,getSortedRowModel,getPaginationRowModel,getFilteredRowModel,getCoreRowModel,flexRender}from'@tanstack/react-table';import {useVirtualizer}from'@tanstack/react-virtual';import {gql}from'@apollo/client';import {useMutation}from'@apollo/client/react';import {getText,getSchema,getTextSerializersFromSchema}from'@tiptap/core';import {Node}from'@tiptap/pm/model';import {TiptapLink,TiptapImage,UploadImagesPlugin,TaskList,TaskItem,HorizontalRule,StarterKit,CodeBlockLowlight,Youtube,Twitter,Mathematics,CharacterCount,Placeholder,AIHighlight,TiptapUnderline,HighlightExtension,TextStyle,Color,CustomKeymap,GlobalDragHandle}from'novel';import {Markdown}from'tiptap-markdown';import {cx}from'class-variance-authority';import {createLowlight,common}from'lowlight';import {defaultStyles,FileIcon}from'react-file-icon';import {isValid,format}from'date-fns';function Xr(){return jsxs(e,{variant:"destructive",children:[jsx(AlertCircle,{className:"fk:h-4 fk:w-4"}),jsx(f,{children:"Project Paused"}),jsxs(g,{children:["This project has been paused. To troubleshoot this error, please"," ",jsx("a",{className:"fk:text-blue-500 fk:underline",href:"https://flexkit.io/docs/errors/project-paused",target:"_blank",rel:"noopener noreferrer",children:"follow these steps"}),"."]})]})}function Kr(){let{schemaErrorMessage:e$2}=e$1();if(!e$2)return jsx(Fragment,{});let[t,n,...r]=e$2.split(`
1
+ import'./index.css';import {b}from'./chunk-CAZ6EUR2.js';import {b as b$2}from'./chunk-2DXR5NJV.js';import {e as e$1,a as a$2,b as b$1}from'./chunk-474MQNDK.js';import {g as g$2,b as b$5}from'./chunk-MBBE4RND.js';import {Y,Z,aa,ba,_,ca,n}from'./chunk-RULCANNM.js';import {e as e$2,g as g$1,h,j}from'./chunk-A4DPLZZF.js';import {e,f,g}from'./chunk-G5N6HEPW.js';import {b as b$4}from'./chunk-5JUG4BEF.js';import {k,p,q,s,t}from'./chunk-S7Z6KKIN.js';import {a,b as b$3,c as c$1,d,e as e$3}from'./chunk-N33S7BSG.js';import {a as a$1,c}from'./chunk-X3SHNHHM.js';import {AlertCircle,X,ChevronDown,ArrowUp,ArrowDown,Star,CircleCheck,CircleX,Check,Copy}from'lucide-react';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import {useRef,useState,useEffect,useCallback,useMemo}from'react';import {useReactTable,getSortedRowModel,getPaginationRowModel,getFilteredRowModel,getCoreRowModel,flexRender}from'@tanstack/react-table';import {useVirtualizer}from'@tanstack/react-virtual';import {gql}from'@apollo/client';import {useMutation}from'@apollo/client/react';import {getText,getSchema,getTextSerializersFromSchema}from'@tiptap/core';import {Node}from'@tiptap/pm/model';import {TiptapLink,TiptapImage,UploadImagesPlugin,TaskList,TaskItem,HorizontalRule,StarterKit,CodeBlockLowlight,Youtube,Twitter,Mathematics,CharacterCount,Placeholder,AIHighlight,TiptapUnderline,HighlightExtension,TextStyle,Color,CustomKeymap,GlobalDragHandle}from'novel';import {Markdown}from'tiptap-markdown';import {cx}from'class-variance-authority';import {createLowlight,common}from'lowlight';import {defaultStyles,FileIcon}from'react-file-icon';import {isValid,format}from'date-fns';function Xr(){return jsxs(e,{variant:"destructive",children:[jsx(AlertCircle,{className:"fk:h-4 fk:w-4"}),jsx(f,{children:"Project Paused"}),jsxs(g,{children:["This project has been paused. To troubleshoot this error, please"," ",jsx("a",{className:"fk:text-blue-500 fk:underline",href:"https://flexkit.io/docs/errors/project-paused",target:"_blank",rel:"noopener noreferrer",children:"follow these steps"}),"."]})]})}function Kr(){let{schemaErrorMessage:e$2}=e$1();if(!e$2)return jsx(Fragment,{});let[t,n,...r]=e$2.split(`
2
2
  `);return jsxs(e,{className:"fk:mb-4",variant:"destructive",children:[jsx(AlertCircle,{className:"fk:h-4 fk:w-4"}),jsx(f,{children:"Schema mismatch"}),jsxs(g,{children:[jsx("p",{children:t}),n?jsx("p",{className:"fk:mt-1",children:n}):null,r.length>0?jsx("ul",{className:"fk:mt-2 fk:list-disc fk:pl-4",children:r.map(o=>jsx("li",{children:o.replace(/^- /,"")},o))}):null]})]})}function lt({scrollHeight:e,scrollTop:t,clientHeight:n}){if(n<=0)return false;let r=t>0?Math.max(600,n):1;return e-t-n<r}var ln=36,cn=15,fn=2,ut=40;function pt(e){if(!e)return;let t=e.split(/\s+/);if(t.includes("fk:h-20"))return 80;if(t.includes("fk:h-10"))return 40;if(t.includes("fk:h-9"))return 36}function un(e,t){return e??pt(t)??ln}function lo({classNames:e,columns:t,data:n,entityName:r,hasMore:o=false,initialSelectionState:l,isLoadingMore:s=false,onEntitySelectionChange:b$1,onLoadMore:u,onScroll:k,onSortingChange:S,pageSize:M,rowHeightEstimate:g,rowAdditionState:i,rowDeletionState:T,scrollToTopKey:X,sorting:de,toolbarComponent:j}){let y=useRef(null),{schemaErrorMessage:N}=e$1(),[C,me]=useState(l??{}),[Ot,Ut]=useState({}),[zt,Bt]=useState([]),[Xt,jt]=useState([]),$t=de??Xt;useEffect(()=>{y.current?.scrollTo({top:0,left:0});},[r,X]),useEffect(()=>{if(!l)return;let a=Object.keys(C).sort().join(","),c=Object.keys(l).sort().join(",");a!==c&&me(l);},[l,C]);function Jt(a){if(S){S(a);return}jt(a);}let V=useReactTable({data:n,columns:t,state:{sorting:$t,columnVisibility:Ot,rowSelection:C,columnFilters:zt},initialState:{pagination:{pageSize:M??50}},enableRowSelection:true,onRowSelectionChange:Kt,onSortingChange:Jt,onColumnFiltersChange:Bt,onColumnVisibilityChange:Ut,getCoreRowModel:getCoreRowModel(),getFilteredRowModel:getFilteredRowModel(),getPaginationRowModel:getPaginationRowModel(),getSortedRowModel:getSortedRowModel(),getRowId:a=>a._id,manualFiltering:true,manualPagination:true,manualSorting:true,meta:{getRowBackground:a=>mn(a,T,i)}}),{rows:$}=V.getRowModel(),Pe=un(g,e?.row),qt=pt(e?.row)!=null,Le=useVirtualizer({count:$.length,estimateSize:()=>Pe,getItemKey:a=>$[a]?.id??a,getScrollElement:()=>y.current,overscan:cn,scrollMargin:ut}),F=V.getVisibleLeafColumns(),Ie=V.getHeaderGroups(),R=Ie.length===1,K=useVirtualizer({horizontal:true,count:F.length,estimateSize:a=>F[a].getSize(),getItemKey:a=>F[a].id,getScrollElement:()=>y.current,overscan:fn,enabled:R}),Gt=JSON.stringify(F.map(a=>[a.id,a.getSize()]));useEffect(()=>{K.measure();},[Gt,K]);let H=K.getVirtualItems(),W=R?H[0]?.index??0:0,_e=R?(H[H.length-1]?.index??-1)+1:F.length,Y$1=R?H[0]?.start??0:0,Q=R?Math.max(0,K.getTotalSize()-(H[H.length-1]?.end??0)):0,Ve=Le.getVirtualItems(),{paddingTop:Fe,paddingBottom:He}=dn(Ve,Le.getTotalSize(),ut),pe=useRef(u),Oe=useRef(o),ge=useRef(s);pe.current=u,Oe.current=o,ge.current=s;let ke=useCallback(a=>{if(!pe.current||!Oe.current||ge.current)return;let c=a??y.current;c&&lt(c)&&(ge.current=true,pe.current());},[]),Ue=b();useEffect(()=>{Ue&&ke();},[ke,$.length,o,s,Ue]);function Kt(a){let c=Object.keys(typeof a=="function"?a(C):a);me(a),b$1?.(c);}function Wt(a){k?.(a),ke(a.currentTarget);}return N?jsx(Fragment,{}):jsxs("div",{className:a$1("fk:flex fk:h-full fk:min-h-0 fk:w-full fk:min-w-0 fk:flex-col fk:gap-4",e?.wrapper),children:[j&&j(V),jsx("div",{className:"fk:relative fk:min-h-0 fk:min-w-0 fk:flex-1 fk:-mb-px",children:jsx(a,{delayDuration:400,children:jsxs(Y,{className:a$1("fk:grid fk:pb-20",e?.table),"aria-colcount":F.length,style:{minWidth:V.getTotalSize()},containerClassName:e?.tableContainer,onScroll:Wt,ref:y,children:[jsx(Z,{className:"fk:sticky fk:top-0 fk:z-20 fk:grid",children:Ie.map(a=>jsxs(aa,{className:"fk:flex fk:w-full",children:[Y$1>0?jsx(le,{width:Y$1,header:true}):null,(R?a.headers.slice(W,_e):a.headers).map((c,P)=>jsxs(ba,{"aria-colindex":R?W+P+1:void 0,className:a$1("fk:flex fk:shrink-0 fk:items-center",c.column.id==="actions"&&"fk:pl-0"),colSpan:c.colSpan,style:c.getSize()?{width:`${c.getSize().toString()}px`}:{},children:[c.isPlaceholder?null:flexRender(c.column.columnDef.header,c.getContext()),s?jsx("div",{"aria-hidden":true,className:"fk:pointer-events-none fk:absolute fk:top-10.25 fk:right-px fk:left-px fk:z-20 fk:h-0.5 fk:overflow-hidden fk:opacity-4",children:jsx("div",{className:"fk:animate-progress fk:h-full fk:w-full fk:bg-foreground"})}):null]},c.id)),Q>0?jsx(le,{width:Q,header:true}):null]},a.id))}),jsx(_,{className:"fk:grid fk:relative",children:$.length===0?jsx(aa,{children:jsx(ca,{className:"fk:h-24 fk:text-center",colSpan:t.length,children:"No results."})}):jsxs(Fragment,{children:[Fe>0?jsx(dt,{height:Fe}):null,Ve.map(a=>{let c=$[a.index];return jsxs(aa,{className:a$1(V.options.meta.getRowBackground(c),"fk:flex fk:w-full fk:overflow-hidden fk:transition-none",!qt&&g==null&&"fk:h-9",e?.row),"data-index":a.index,"data-state":c.getIsSelected()&&"selected",style:{height:`${Pe.toString()}px`},children:[Y$1>0?jsx(le,{width:Y$1}):null,c.getVisibleCells().slice(W,_e).map((P,Yt)=>jsx(ca,{className:a$1("fk:flex fk:shrink-0 fk:items-center fk:truncate",P.column.id==="actions"&&"fk:pl-1!"),"aria-colindex":W+Yt+1,style:{width:P.column.getSize()},children:flexRender(P.column.columnDef.cell,P.getContext())},P.id)),Q>0?jsx(le,{width:Q}):null]},a.key)}),He>0?jsx(dt,{height:He}):null]})})]})})})]})}function dn(e,t,n){if(e.length===0)return {paddingTop:0,paddingBottom:0};let r=e[0]?.start??0,o=e[e.length-1]?.end??0;return {paddingTop:Math.max(0,r-n),paddingBottom:Math.max(0,t-(o-n))}}function le({width:e,header:t=false}){return jsx(t?"th":"td",{"aria-hidden":true,style:{width:e,flexShrink:0,padding:0,border:0}})}function dt({height:e}){return jsx("tr",{"aria-hidden":true,className:"fk:pointer-events-none fk:border-0",style:{display:"block",height:`${e.toString()}px`},children:jsx("td",{className:"fk:p-0 fk:border-0"})})}function mn(e,t,n){return t?.includes(e.original._id)?"fk:bg-row-removed fk:hover:bg-row-removed-hover":n?.some(r=>r._id===e.original._id)?"fk:bg-row-added fk:hover:bg-row-added-hover":""}function po({table:e}){let[t]=e.getState().sorting;if(!t)return null;let r=e.getColumn(t.id)?.columnDef.meta?.label??t.id,o=t.desc?"desc":"asc";return jsxs(c,{"aria-label":`Clear sorting by ${r}`,className:"fk:h-8 fk:px-2 fk:lg:px-3 fk:text-success fk:border-none",onClick:()=>{e.resetSorting();},size:"sm",variant:"outline",children:["Sorted by ",r," ",o,jsx(X,{className:"fk:ml-1 fk:h-4 fk:w-4"})]})}function So(){let[e,t]=useState(false),[n,r]=useState(gql`
3
3
  mutation updateEntity($any: Any) {
4
4
  any
5
5
  }
6
- `),[o,l]=useState({}),[s,{data:b,loading:u,error:k}]=useMutation(n,o),S=a$2(k),{isProjectDisabled:M,isProjectReadOnly:g}=(()=>{if(S?.statusCode===403){let i=b$1(S.bodyText);if(i&&typeof i.code=="string"){if(i.code==="PROJECT_PAUSED")return {isProjectDisabled:true,isProjectReadOnly:false};if(i.code==="READ_ONLY_MODE")return {isProjectDisabled:false,isProjectReadOnly:true}}return {isProjectDisabled:true,isProjectReadOnly:false}}return {isProjectDisabled:false,isProjectReadOnly:false}})();return useEffect(()=>{e&&(s(),t(false));},[e,s]),[t,r,l,{data:b,loading:u,error:k,isProjectDisabled:M,isProjectReadOnly:g}]}function Se({column:e,title:t,className:n}){if(!e.getCanSort())return jsx("div",{className:a$1("fk:flex fk:items-center",n),children:t});let r=e.getIsSorted()==="asc",o=e.getIsSorted()==="desc";return jsxs("div",{className:a$1("fk:flex fk:w-full fk:items-center fk:justify-between fk:gap-1",n),children:[jsx("span",{className:"fk:truncate",children:t}),jsxs(e$2,{children:[jsx(g$1,{asChild:true,children:jsx("button",{"aria-label":`Sort ${t}`,className:"fk:inline-flex fk:shrink-0 fk:items-center fk:justify-center fk:rounded-sm fk:p-0.5 fk:text-muted-foreground fk:outline-hidden fk:hover:bg-accent fk:hover:text-accent-foreground fk:focus-visible:ring-1 fk:focus-visible:ring-ring fk:corner-squircle",type:"button",children:jsx(ChevronDown,{className:"fk:h-3.5 fk:w-3.5"})})}),jsxs(h,{align:"end",className:"fk:w-44",children:[jsxs(j,{"aria-checked":r,className:a$1(r&&"fk:bg-accent fk:text-accent-foreground"),onSelect:()=>{if(r){e.clearSorting();return}e.toggleSorting(false);},role:"menuitemcheckbox",children:[jsx(ArrowUp,{className:a$1("fk:h-4 fk:w-4",r&&"fk:text-white")}),"Sort Ascending"]}),jsxs(j,{"aria-checked":o,className:a$1(o&&"fk:bg-accent fk:text-accent-foreground"),onSelect:()=>{if(o){e.clearSorting();return}e.toggleSorting(true);},role:"menuitemcheckbox",children:[jsx(ArrowDown,{className:a$1("fk:h-4 fk:w-4",o&&"fk:text-white")}),"Sort Descending"]})]})]})]})}function xe({value:e}){return jsx("div",{className:"fk:flex fk:w-full fk:justify-center",children:e?jsx(CircleCheck,{className:"fk:w-4 fk:h-4 fk:text-emerald-500"}):jsx(CircleX,{className:"fk:w-4 fk:h-4 fk:text-muted-foreground"})})}var ht=500,En=3e3;function w({value:e}){let t=useRef(null),n=useRef(null),[r,o]=useState(false),[l,s]=useState(false);useEffect(()=>()=>{n.current&&clearTimeout(n.current);},[]);function b(){let g=t.current;return g?g.scrollWidth>g.clientWidth:false}async function u(g){if(g.preventDefault(),g.stopPropagation(),!!e){try{await navigator.clipboard.writeText(e);}catch{return}o(true),s(true),n.current&&clearTimeout(n.current),n.current=setTimeout(()=>{o(false),s(false);},En);}}function k(){b();}function S(g){if(!r){if(g){s(b());return}s(false);}}if(!e)return jsx("div",{className:"fk:truncate"});let M=e.length>ht?`${e.slice(0,ht)}\u2026`:e;return jsxs(b$3,{open:l,onOpenChange:S,children:[jsx(c$1,{asChild:true,children:jsxs("button",{"aria-label":"Copy value",className:a$1("fk:group/copyable fk:relative fk:flex fk:w-full fk:min-w-0 fk:items-center fk:rounded-sm fk:border-0 fk:bg-transparent fk:px-0.5 fk:-mx-0.5 fk:py-0.5 fk:text-left fk:text-inherit fk:font-inherit fk:corner-squircle","fk:cursor-pointer fk:transition-[transform,background-color] fk:duration-75 fk:ease-out","fk:hover:bg-muted/50 fk:active:translate-y-px fk:active:scale-[0.98] fk:active:bg-muted/70","fk:focus-visible:outline-hidden fk:focus-visible:ring-1 fk:focus-visible:ring-ring"),onClick:u,onPointerEnter:k,type:"button",children:[jsx("span",{className:"fk:min-w-0 fk:flex-1 fk:truncate fk:pr-4",ref:t,children:e}),jsx("span",{"aria-hidden":true,className:a$1("fk:pointer-events-none fk:absolute fk:right-0.5 fk:top-1/2 fk:flex fk:-translate-y-1/2 fk:items-center fk:justify-center","fk:rounded-sm fk:bg-muted/80 fk:p-0.5 fk:text-muted-foreground fk:shadow-sm fk:ring-1 fk:ring-border/60 fk:corner-squircle","fk:transition-opacity fk:duration-100",r?"fk:opacity-100 fk:text-foreground":"fk:opacity-0 fk:group-hover/copyable:opacity-100 fk:group-focus-visible/copyable:opacity-100"),children:r?jsx(Check,{className:"fk:size-3"}):jsx(Copy,{className:"fk:size-3"})})]})}),jsx(e$3,{className:"fk:max-w-xs fk:wrap-break-word",children:r?"Copied to clipboard":M})]})}function B({value:e}){let t=typeof e=="object"||Array.isArray(e)?JSON.stringify(e):e;return t=t==="null"||t==null?"":String(t),jsx(w,{value:t})}var Zn=AIHighlight,er=Placeholder,tr=TiptapLink.configure({HTMLAttributes:{class:cx("fk:text-muted-foreground fk:underline fk:underline-offset-[3px] fk:hover:text-primary fk:transition-colors fk:cursor-pointer")}}),nr=Markdown.configure({html:true,tightLists:true,tightListClass:"tight",bulletListMarker:"-",linkify:false,breaks:false,transformPastedText:false,transformCopiedText:false}),rr=TiptapImage.extend({addProseMirrorPlugins(){return [UploadImagesPlugin({imageClass:cx("fk:opacity-40 fk:rounded-lg fk:border fk:border-stone-200 fk:corner-squircle")})]}}).configure({allowBase64:true,HTMLAttributes:{class:cx("fk:rounded-lg fk:border fk:border-muted fk:corner-squircle")}}),or=TaskList.configure({HTMLAttributes:{class:cx("fk:not-prose fk:pl-2 ")}}),ir=TaskItem.configure({HTMLAttributes:{class:cx("fk:flex gap-2 fk:items-start fk:my-2")},nested:true}),ar=HorizontalRule.configure({HTMLAttributes:{class:cx("mt-4 mb-6 border-t border-muted-foreground")}}),sr=StarterKit.configure({bulletList:{HTMLAttributes:{class:cx("fk:list-disc fk:list-outside fk:leading-3 fk:-mt-2")}},orderedList:{HTMLAttributes:{class:cx("fk:list-decimal fk:list-outside fk:leading-3 fk:-mt-2")}},listItem:{HTMLAttributes:{class:cx("fk:leading-normal fk:-mb-2")}},blockquote:{HTMLAttributes:{class:cx("fk:border-l-4 fk:border-primary")}},codeBlock:false,code:{HTMLAttributes:{class:cx("fk:rounded-md fk:bg-muted fk:px-1.5 fk:py-1 fk:font-mono fk:font-medium fk:corner-squircle"),spellcheck:"false"}},horizontalRule:false,dropcursor:{color:"#DBEAFE",width:4},gapcursor:false}),lr=CodeBlockLowlight.configure({lowlight:createLowlight(common)}),cr=Youtube.configure({HTMLAttributes:{class:cx("fk:rounded-lg fk:border fk:border-muted fk:corner-squircle")},inline:false}),fr=Twitter.configure({HTMLAttributes:{class:cx("fk:not-prose")},inline:false}),ur=Mathematics.configure({HTMLAttributes:{class:cx("fk:text-foreground fk:rounded-sm fk:p-1 fk:hover:bg-muted fk:cursor-pointer fk:corner-squircle")},katexOptions:{throwOnError:false}}),dr=CharacterCount.configure(),Tt=[sr,er,tr,rr,or,ir,ar,Zn,lr,cr,fr,ur,dr,TiptapUnderline,nr,HighlightExtension,TextStyle,Color,CustomKeymap,GlobalDragHandle];var ve;function hr(){let e=getSchema(Tt);return {schema:e,textSerializers:getTextSerializersFromSchema(e)}}function yt(e,t=100){if(!e)return "";try{let n=JSON.parse(e);return ve??=hr(),getText(Node.fromJSON(ve.schema,n),{textSerializers:ve.textSerializers}).substring(0,t)}catch{return e.substring(0,t)}}function St({value:e}){let t=useMemo(()=>yt(e),[e]);return jsx(w,{value:t})}var wt=250,xr=25e5,v=new Map,Ce=new Map,Ae=new Set,xt=new Map;function ce(e){if(xt.has(e))return;let t=new Image;t.decoding="async",t.src=e,xt.set(e,t);}function fe(e){let t=v.get(e);t&&v.set(e,{...t,lastUsedAt:Date.now()});}function vr(){if(v.size<=wt)return;let e=Array.from(v.entries()).sort((n,r)=>n[1].lastUsedAt-r[1].lastUsedAt),t=Math.max(1,Math.ceil(wt*.1));for(let n=0;n<t&&n<e.length;n+=1){let[r,o]=e[n];v.delete(r),URL.revokeObjectURL(o.objectUrl);}}async function Cr(e){if(Ae.has(e)){ce(e);return}if(v.has(e)){fe(e);return}let t=Ce.get(e);if(t){await t;return}let n=(async()=>{try{let r=await fetch(e,{mode:"cors",cache:"force-cache"});if(!r.ok){ce(e);return}let o=await r.blob();if(o.size>xr)return;let l=URL.createObjectURL(o);v.set(e,{objectUrl:l,byteSize:o.size,lastUsedAt:Date.now()}),vr();}catch(r){r instanceof TypeError&&Ae.add(e),ce(e);}})();Ce.set(e,n),await n,Ce.delete(e);}function vt(e){let t=useMemo(()=>{if(!e)return null;let o=v.get(e);return o?(fe(e),o.objectUrl):null},[e]),[n,r]=useState(t);return useEffect(()=>{if(!e){r(null);return}if(Ae.has(e)){ce(e),r(null);return}let o=v.get(e);if(o){fe(e),r(o.objectUrl);return}r(null);let l=false;return Cr(e).then(()=>{let s=v.get(e);s&&(l||(fe(e),r(s.objectUrl)));}),()=>{l=true;}},[e]),n}var De="fk:bg-[#fafafa] [--asset-checker:#f0f0f0] [background-image:linear-gradient(45deg,var(--asset-checker)_25%,transparent_25%),linear-gradient(-45deg,var(--asset-checker)_25%,transparent_25%),linear-gradient(45deg,transparent_75%,var(--asset-checker)_75%),linear-gradient(-45deg,transparent_75%,var(--asset-checker)_75%)] [background-position:0_0,0_4px,4px_-4px,-4px_0px] [background-size:8px_8px] fk:dark:bg-[#222] dark:[--asset-checker:#2a2a2a]";function Ct({value:e}){return Array.isArray(e)?jsx(Mr,{value:e}):jsx(Er,{value:e})}function Er({value:e}){let t=e?.path??"",n=!!t,r=n&&/\.(png|jpe?g|gif|webp|avif|svg)$/i.test(t),o=u=>{let[k]=u.split("?"),S=k.split(".");return S.length>1?S.pop().toLowerCase():"file"},l=n?t.endsWith(".svg")?`${b$5}${t}`:`${b$5}${t}?w=84&h=84&f=webp`:null,s=n?t.endsWith(".svg")?`${b$5}${t}`:`${b$5}${t}?w=624&h=624&f=webp`:"",b=vt(l);return n?jsx("div",{className:"fk:z-10",children:r?jsxs(b$3,{children:[jsx(c$1,{asChild:true,children:jsx("img",{alt:"asset",className:`fk:w-7 fk:h-7 fk:cursor-zoom-in fk:overflow-hidden fk:rounded-md fk:object-contain ${De} fk:corner-squircle`,decoding:"async",src:b??void 0})}),jsx(d,{children:jsx(e$3,{children:jsx("img",{alt:"asset",className:`fk:w-52 fk:h-52 fk:overflow-hidden fk:rounded-md fk:object-contain ${De} fk:corner-squircle`,decoding:"async",src:s})})})]}):jsxs(b$3,{children:[jsx(c$1,{asChild:true,children:jsx("div",{className:"fk:w-7 fk:h-7 fk:rounded-sm fk:bg-transparent fk:flex fk:items-center fk:justify-center fk:[&>svg]:h-full fk:[&>svg]:w-auto fk:corner-squircle",children:(()=>{let u=o(t),k=defaultStyles[u];return jsx(FileIcon,{extension:u,...k||{}})})()})}),jsx(d,{children:jsx(e$3,{children:jsx("div",{className:"fk:text-sm fk:text-muted-foreground",children:"Preview not available"})})})]})}):null}function Mr({value:e}){let t=e.filter(o=>!!o.path).slice(0,3),n=Math.max(e[0]?.totalCount??0,e.length);if(t.length===0)return n>0?jsx("div",{className:"fk:flex fk:items-center",children:jsx("span",{className:"fk:text-xs fk:text-muted-foreground",children:n===1?"1 asset":`${n} assets`})}):null;let r=n-t.length;return jsxs("div",{className:"fk:flex fk:items-center",children:[jsx("div",{className:"fk:flex fk:-space-x-2",children:t.map(o=>jsx("img",{alt:"asset",className:`fk:h-7 fk:w-7 fk:overflow-hidden fk:rounded-md fk:object-contain ${De} fk:corner-squircle`,decoding:"async",src:`${b$5}${o.path}?w=84&h=84&f=webp`},o._id))}),r>0?jsxs("span",{className:"fk:ml-2 fk:text-xs fk:text-muted-foreground",children:["+",r]}):null]})}function Me({value:e}){if(e==null||e===""||typeof e!="string")return jsx(w,{value:""});let t=new Date(e);if(!isValid(t))return jsx(w,{value:""});let n=format(t,"MMM d, yyyy")+" at "+format(t,"HH:mm");return jsx(w,{value:n})}function Rr(e){return "groupLabel"in e}function Pr(e){return e.flatMap(t=>Rr(t)?t.items:[t])}function Lr(e,t){if(!t)return e;let n=Pr(t).find(r=>String(r.value)===e);return n?n.label:e}function Et({value:e,options:t}){if(e==null)return jsx(w,{value:""});let n=String(e),r=Lr(n,t?.list);return jsx(w,{value:r})}function Nt({value:e}){return !e||!e.split(",").length?null:jsx("div",{className:"fk:flex fk:flex-wrap fk:gap-1 fk:max-w-full truncate",children:e.split(",").map(t=>jsx(b$4,{className:"fk:px-2.5 fk:py-0 fk:font-normal fk:text-[0.6875rem] fk:leading-4",variant:"secondary",children:t},t))})}function Rt(e,t=5){let n=Number.isFinite(t)&&t>=1?Math.floor(t):5,r=typeof e=="string"&&e.trim()!==""?Number(e):e;if(typeof r!="number"||!Number.isFinite(r))return null;let o=Math.min(n,Math.max(0,Math.round(r)));return {filled:o,max:n,label:`${String(o)} out of ${String(n)} stars`}}function Pt({value:e,options:t}){let n=Rt(e,t?.max);return n?jsx("span",{"aria-label":n.label,className:"fk:inline-flex fk:items-center fk:gap-0.5",role:"img",title:n.label,children:Array.from({length:n.max},(r,o)=>jsx(Star,{"aria-hidden":true,className:o<n.filled?"fk:h-3.5 fk:w-3.5 fk:fill-amber-400 fk:text-amber-400":"fk:h-3.5 fk:w-3.5 fk:fill-transparent fk:text-muted-foreground/40",strokeWidth:1.5},o))}):jsx("span",{})}var _r=/\.(png|jpe?g|gif|webp|avif|svg)$/i;function Lt(e){try{let{pathname:t}=new URL(e);return t.split("/").pop()||t}catch{let[t]=e.split("?");return t}}function It(e){return e.originalFilename?e.originalFilename:e.path?e.path:e.url?Lt(e.url):""}function _t(e){let t=It(e),[n]=t.split("?"),r=n.split(".");return r.length>1?r.pop().toLowerCase():"file"}function Vt(e){return e.mimeType?e.mimeType.startsWith("image/"):_r.test(It(e))}function Re(e,t){if(!e||!t||Lt(e).toLowerCase().endsWith(".svg"))return e;let n=new URLSearchParams({f:"webp",h:String(t.height),w:String(t.width)}),r=e.includes("?")?"&":"?";return `${e}${r}${n.toString()}`}var Or=FileIcon,Ft="fk:bg-[#fafafa] [--asset-checker:#f0f0f0] [background-image:linear-gradient(45deg,var(--asset-checker)_25%,transparent_25%),linear-gradient(-45deg,var(--asset-checker)_25%,transparent_25%),linear-gradient(45deg,transparent_75%,var(--asset-checker)_75%),linear-gradient(-45deg,transparent_75%,var(--asset-checker)_75%)] [background-position:0_0,0_4px,4px_-4px,-4px_0px] [background-size:8px_8px] fk:dark:bg-[#222] dark:[--asset-checker:#2a2a2a]";function Ht({value:e}){let[t$1,n]=useState(false),r=e?.url??"";if(!e||!r&&!e.path&&!e.originalFilename)return null;if(!(Vt(e)&&!!r)){let u=_t(e),k=defaultStyles[u];return jsx("div",{className:"fk:z-10",children:jsx(a,{children:jsxs(b$3,{children:[jsx(c$1,{asChild:true,children:jsx("div",{className:"fk:w-7 fk:h-7 fk:rounded-sm fk:bg-transparent fk:flex fk:items-center fk:justify-center fk:[&>svg]:h-full fk:[&>svg]:w-auto fk:corner-squircle",children:jsx(Or,{extension:u,...k||{}})})}),jsx(d,{children:jsx(e$3,{children:jsx("div",{className:"fk:text-sm fk:text-muted-foreground",children:"Preview not available"})})})]})})})}let l=Re(r,{width:84,height:84}),s$1=Re(r,{width:624,height:624});function b(u){u.stopPropagation(),n(true);}return jsx("div",{className:"fk:z-10",children:jsxs(a,{children:[jsxs(b$3,{children:[jsx(c$1,{asChild:true,children:jsx("img",{src:l,alt:"asset",className:`fk:w-12 fk:h-12 fk:cursor-zoom-in fk:overflow-hidden fk:rounded-md fk:object-contain ${Ft} fk:corner-squircle`,onClick:b})}),jsx(d,{children:jsx(e$3,{children:jsx("img",{src:s$1,alt:"asset",className:`fk:w-52 fk:h-52 fk:overflow-hidden fk:rounded-md fk:object-contain ${Ft} fk:corner-squircle`})})})]}),jsx(k,{open:t$1,onOpenChange:n,children:jsxs(p,{className:"fk:sm:max-w-4xl fk:p-3",children:[jsxs(q,{children:[jsx(s,{className:"fk:sr-only",children:"Asset preview"}),jsx(t,{className:"fk:sr-only",children:"Enlarged asset preview"})]}),jsx("img",{src:r,alt:"asset",className:"fk:max-h-[85vh] fk:w-full fk:overflow-hidden fk:rounded-md fk:object-contain fk:corner-squircle"})]})})]})})}var Ur=new Set(["text","number","datetime","switch","select"]);function Xi({attributesSchema:e,checkboxSelect:t,actionsComponent:n$1,enableColumnSorting:r=false}){let[,o]=g$2(),l=b$2(e,o.user?.spaces),s={datetime:"datetime",editor:"editor",asset:"asset",number:"text",relationship:"text",select:"select",switch:"boolean",text:"text",textarea:"text"},b={boolean:xe,date:B,datetime:Me,editor:St,asset:Ct,number:B,relationship:B,select:Et,switch:xe,text:B,textarea:B,tags:Nt,rating:Pt,assetPreviewField:Ht},u=l.map(i=>{if(i.name==="_updatedAt")return null;let T=(i.inputType==="relationship"&&i.relationship?.entity==="_asset"?"asset":void 0)??i.previewType??s[i.inputType],X=b[T]??b.text;if(i.hidden===true)return null;let de=T==="tags",j=r&&i.scope==="global"&&Ur.has(i.inputType);return {accessorKey:i.name,filterFn:(y,N,C)=>de?true:(Array.isArray(C)?C:[C]).includes(y.getValue(N)),header:({column:y})=>j?jsx(Se,{column:y,title:i.label}):jsx("div",{className:"fk:flex fk:items-center",children:i.label}),cell:({row:y})=>{let N=X;return T==="select"||T==="rating"?jsx(N,{value:y.getValue(i.name),options:i.options}):T==="assetPreviewField"?jsx(N,{value:y.original}):jsx(N,{value:y.getValue(i.name)})},enableSorting:j,enableHiding:true,meta:{label:i.label},size:i.options?.size??150}}).filter(i=>i!==null),k={id:"actions",cell:({row:i})=>n$1?n$1(i):null,size:80},S={accessorKey:"_updatedAt",header:({column:i})=>r?jsx(Se,{column:i,title:"Updated At"}):jsx("div",{className:"fk:flex fk:items-center",children:"Updated At"}),cell:({row:i})=>jsx(Me,{value:i.getValue("_updatedAt")}),enableSorting:r,enableHiding:false,meta:{label:"Updated At"},size:220},M={id:"select",cell:({row:i,table:T})=>jsx(n,{"aria-label":"Select row",checked:i.getIsSelected(),onCheckedChange:X=>{T.toggleAllPageRowsSelected(false),i.toggleSelected(!!X);}}),enableSorting:false,enableHiding:false,size:50},g={id:"select",header:({table:i})=>jsx(n,{className:"fk:dark:bg-white/15","aria-label":"Select all",checked:i.getIsAllPageRowsSelected()||i.getIsSomePageRowsSelected()&&"indeterminate",onCheckedChange:T=>{i.toggleAllPageRowsSelected(!!T);}}),cell:({row:i})=>jsx(n,{"aria-label":"Select row",checked:i.getIsSelected(),onCheckedChange:T=>{i.toggleSelected(!!T);}}),enableSorting:false,enableHiding:false,size:50};return [...t==="single"?[M]:[],...t==="multiple"?[g]:[],...n$1?[k]:[],...u,S]}export{Xr as a,Kr as b,lt as c,lo as d,po as e,So as f,Tt as g,It as h,_t as i,Vt as j,Re as k,Se as l,Xi as m};//# sourceMappingURL=chunk-RBGXXVF4.js.map
7
- //# sourceMappingURL=chunk-RBGXXVF4.js.map
6
+ `),[o,l]=useState({}),[s,{data:b,loading:u,error:k}]=useMutation(n,o),S=a$2(k),{isProjectDisabled:M,isProjectReadOnly:g}=(()=>{if(S?.statusCode===403){let i=b$1(S.bodyText);if(i&&typeof i.code=="string"){if(i.code==="PROJECT_PAUSED")return {isProjectDisabled:true,isProjectReadOnly:false};if(i.code==="READ_ONLY_MODE")return {isProjectDisabled:false,isProjectReadOnly:true}}return {isProjectDisabled:true,isProjectReadOnly:false}}return {isProjectDisabled:false,isProjectReadOnly:false}})();return useEffect(()=>{e&&(s(),t(false));},[e,s]),[t,r,l,{data:b,loading:u,error:k,isProjectDisabled:M,isProjectReadOnly:g}]}function Se({column:e,title:t,className:n}){if(!e.getCanSort())return jsx("div",{className:a$1("fk:flex fk:items-center",n),children:t});let r=e.getIsSorted()==="asc",o=e.getIsSorted()==="desc";return jsxs("div",{className:a$1("fk:flex fk:w-full fk:items-center fk:justify-between fk:gap-1",n),children:[jsx("span",{className:"fk:truncate",children:t}),jsxs(e$2,{children:[jsx(g$1,{asChild:true,children:jsx("button",{"aria-label":`Sort ${t}`,className:"fk:inline-flex fk:shrink-0 fk:items-center fk:justify-center fk:rounded-sm fk:p-0.5 fk:text-muted-foreground fk:outline-hidden fk:hover:bg-accent fk:hover:text-accent-foreground fk:focus-visible:ring-1 fk:focus-visible:ring-ring fk:corner-squircle",type:"button",children:jsx(ChevronDown,{className:"fk:h-3.5 fk:w-3.5"})})}),jsxs(h,{align:"end",className:"fk:w-44",children:[jsxs(j,{"aria-checked":r,className:a$1(r&&"fk:bg-accent fk:text-accent-foreground"),onSelect:()=>{if(r){e.clearSorting();return}e.toggleSorting(false);},role:"menuitemcheckbox",children:[jsx(ArrowUp,{className:a$1("fk:h-4 fk:w-4",r&&"fk:text-white")}),"Sort Ascending"]}),jsxs(j,{"aria-checked":o,className:a$1(o&&"fk:bg-accent fk:text-accent-foreground"),onSelect:()=>{if(o){e.clearSorting();return}e.toggleSorting(true);},role:"menuitemcheckbox",children:[jsx(ArrowDown,{className:a$1("fk:h-4 fk:w-4",o&&"fk:text-white")}),"Sort Descending"]})]})]})]})}function xe({value:e}){return jsx("div",{className:"fk:flex fk:w-full fk:justify-center",children:e?jsx(CircleCheck,{className:"fk:w-4 fk:h-4 fk:text-emerald-500"}):jsx(CircleX,{className:"fk:w-4 fk:h-4 fk:text-muted-foreground"})})}var ht=500,En=3e3;function w({value:e}){let t=useRef(null),n=useRef(null),[r,o]=useState(false),[l,s]=useState(false);useEffect(()=>()=>{n.current&&clearTimeout(n.current);},[]);function b(){let g=t.current;return g?g.scrollWidth>g.clientWidth:false}async function u(g){if(g.preventDefault(),g.stopPropagation(),!!e){try{await navigator.clipboard.writeText(e);}catch{return}o(true),s(true),n.current&&clearTimeout(n.current),n.current=setTimeout(()=>{o(false),s(false);},En);}}function k(){b();}function S(g){if(!r){if(g){s(b());return}s(false);}}if(!e)return jsx("div",{className:"fk:truncate"});let M=e.length>ht?`${e.slice(0,ht)}\u2026`:e;return jsxs(b$3,{open:l,onOpenChange:S,children:[jsx(c$1,{asChild:true,children:jsxs("button",{"aria-label":"Copy value",className:a$1("fk:group/copyable fk:relative fk:flex fk:w-full fk:min-w-0 fk:items-center fk:rounded-sm fk:border-0 fk:bg-transparent fk:px-0.5 fk:-mx-0.5 fk:py-0.5 fk:text-left fk:text-inherit fk:font-inherit fk:corner-squircle","fk:cursor-pointer fk:transition-[transform,background-color] fk:duration-75 fk:ease-out","fk:hover:bg-muted/50 fk:active:translate-y-px fk:active:scale-[0.98] fk:active:bg-muted/70","fk:focus-visible:outline-hidden fk:focus-visible:ring-1 fk:focus-visible:ring-ring"),onClick:u,onPointerEnter:k,type:"button",children:[jsx("span",{className:"fk:min-w-0 fk:flex-1 fk:truncate fk:pr-4",ref:t,children:e}),jsx("span",{"aria-hidden":true,className:a$1("fk:pointer-events-none fk:absolute fk:right-0.5 fk:top-1/2 fk:flex fk:-translate-y-1/2 fk:items-center fk:justify-center","fk:rounded-sm fk:bg-muted/80 fk:p-0.5 fk:text-muted-foreground fk:shadow-sm fk:ring-1 fk:ring-border/60 fk:corner-squircle","fk:transition-opacity fk:duration-100",r?"fk:opacity-100 fk:text-foreground":"fk:opacity-0 fk:group-hover/copyable:opacity-100 fk:group-focus-visible/copyable:opacity-100"),children:r?jsx(Check,{className:"fk:size-3"}):jsx(Copy,{className:"fk:size-3"})})]})}),jsx(e$3,{className:"fk:max-w-xs fk:wrap-break-word",children:r?"Copied to clipboard":M})]})}function B({value:e}){let t=typeof e=="object"||Array.isArray(e)?JSON.stringify(e):e;return t=t==="null"||t==null?"":String(t),jsx(w,{value:t})}var Zn=AIHighlight,er=Placeholder,tr=TiptapLink.configure({HTMLAttributes:{class:cx("fk:text-muted-foreground fk:underline fk:underline-offset-[3px] fk:hover:text-primary fk:transition-colors fk:cursor-pointer")}}),nr=Markdown.configure({html:true,tightLists:true,tightListClass:"tight",bulletListMarker:"-",linkify:false,breaks:false,transformPastedText:false,transformCopiedText:false}),rr=TiptapImage.extend({addProseMirrorPlugins(){return [UploadImagesPlugin({imageClass:cx("fk:opacity-40 fk:rounded-lg fk:border fk:border-stone-200 fk:corner-squircle")})]}}).configure({allowBase64:true,HTMLAttributes:{class:cx("fk:rounded-lg fk:border fk:border-muted fk:corner-squircle")}}),or=TaskList.configure({HTMLAttributes:{class:cx("fk:not-prose fk:pl-2 ")}}),ir=TaskItem.configure({HTMLAttributes:{class:cx("fk:flex gap-2 fk:items-start fk:my-2")},nested:true}),ar=HorizontalRule.configure({HTMLAttributes:{class:cx("mt-4 mb-6 border-t border-muted-foreground")}}),sr=StarterKit.configure({bulletList:{HTMLAttributes:{class:cx("fk:list-disc fk:list-outside fk:leading-3 fk:-mt-2")}},orderedList:{HTMLAttributes:{class:cx("fk:list-decimal fk:list-outside fk:leading-3 fk:-mt-2")}},listItem:{HTMLAttributes:{class:cx("fk:leading-normal fk:-mb-2")}},blockquote:{HTMLAttributes:{class:cx("fk:border-l-4 fk:border-primary")}},codeBlock:false,code:{HTMLAttributes:{class:cx("fk:rounded-md fk:bg-muted fk:px-1.5 fk:py-1 fk:font-mono fk:font-medium fk:corner-squircle"),spellcheck:"false"}},horizontalRule:false,dropcursor:{color:"#DBEAFE",width:4},gapcursor:false}),lr=CodeBlockLowlight.configure({lowlight:createLowlight(common)}),cr=Youtube.configure({HTMLAttributes:{class:cx("fk:rounded-lg fk:border fk:border-muted fk:corner-squircle")},inline:false}),fr=Twitter.configure({HTMLAttributes:{class:cx("fk:not-prose")},inline:false}),ur=Mathematics.configure({HTMLAttributes:{class:cx("fk:text-foreground fk:rounded-sm fk:p-1 fk:hover:bg-muted fk:cursor-pointer fk:corner-squircle")},katexOptions:{throwOnError:false}}),dr=CharacterCount.configure(),Tt=[sr,er,tr,rr,or,ir,ar,Zn,lr,cr,fr,ur,dr,TiptapUnderline,nr,HighlightExtension,TextStyle,Color,CustomKeymap,GlobalDragHandle];var ve;function hr(){let e=getSchema(Tt);return {schema:e,textSerializers:getTextSerializersFromSchema(e)}}function yt(e,t=100){if(!e)return "";try{let n=JSON.parse(e);return ve??=hr(),getText(Node.fromJSON(ve.schema,n),{textSerializers:ve.textSerializers}).substring(0,t)}catch{return e.substring(0,t)}}function St({value:e}){let t=useMemo(()=>yt(e),[e]);return jsx(w,{value:t})}var wt=250,xr=25e5,v=new Map,Ce=new Map,Ae=new Set,xt=new Map;function ce(e){if(xt.has(e))return;let t=new Image;t.decoding="async",t.src=e,xt.set(e,t);}function fe(e){let t=v.get(e);t&&v.set(e,{...t,lastUsedAt:Date.now()});}function vr(){if(v.size<=wt)return;let e=Array.from(v.entries()).sort((n,r)=>n[1].lastUsedAt-r[1].lastUsedAt),t=Math.max(1,Math.ceil(wt*.1));for(let n=0;n<t&&n<e.length;n+=1){let[r,o]=e[n];v.delete(r),URL.revokeObjectURL(o.objectUrl);}}async function Cr(e){if(Ae.has(e)){ce(e);return}if(v.has(e)){fe(e);return}let t=Ce.get(e);if(t){await t;return}let n=(async()=>{try{let r=await fetch(e,{mode:"cors",cache:"force-cache"});if(!r.ok){ce(e);return}let o=await r.blob();if(o.size>xr)return;let l=URL.createObjectURL(o);v.set(e,{objectUrl:l,byteSize:o.size,lastUsedAt:Date.now()}),vr();}catch(r){r instanceof TypeError&&Ae.add(e),ce(e);}})();Ce.set(e,n),await n,Ce.delete(e);}function vt(e){let t=useMemo(()=>{if(!e)return null;let o=v.get(e);return o?(fe(e),o.objectUrl):null},[e]),[n,r]=useState(t);return useEffect(()=>{if(!e){r(null);return}if(Ae.has(e)){ce(e),r(null);return}let o=v.get(e);if(o){fe(e),r(o.objectUrl);return}r(null);let l=false;return Cr(e).then(()=>{let s=v.get(e);s&&(l||(fe(e),r(s.objectUrl)));}),()=>{l=true;}},[e]),n}var De="fk:bg-[#fafafa] [--asset-checker:#f0f0f0] [background-image:linear-gradient(45deg,var(--asset-checker)_25%,transparent_25%),linear-gradient(-45deg,var(--asset-checker)_25%,transparent_25%),linear-gradient(45deg,transparent_75%,var(--asset-checker)_75%),linear-gradient(-45deg,transparent_75%,var(--asset-checker)_75%)] [background-position:0_0,0_4px,4px_-4px,-4px_0px] [background-size:8px_8px] fk:dark:bg-[#222] dark:[--asset-checker:#2a2a2a]";function Ct({value:e}){return Array.isArray(e)?jsx(Mr,{value:e}):jsx(Er,{value:e})}function Er({value:e}){let t=e?.path??"",n=!!t,r=n&&/\.(png|jpe?g|gif|webp|avif|svg)$/i.test(t),o=u=>{let[k]=u.split("?"),S=k.split(".");return S.length>1?S.pop().toLowerCase():"file"},l=n?t.endsWith(".svg")?`${b$5}${t}`:`${b$5}${t}?w=84&h=84&f=webp`:null,s=n?t.endsWith(".svg")?`${b$5}${t}`:`${b$5}${t}?w=624&h=624&f=webp`:"",b=vt(l);return n?jsx("div",{className:"fk:z-10",children:r?jsxs(b$3,{children:[jsx(c$1,{asChild:true,children:jsx("img",{alt:"asset",className:`fk:w-7 fk:h-7 fk:cursor-zoom-in fk:overflow-hidden fk:rounded-md fk:object-contain ${De} fk:corner-squircle`,decoding:"async",src:b??void 0})}),jsx(d,{children:jsx(e$3,{children:jsx("img",{alt:"asset",className:`fk:w-52 fk:h-52 fk:overflow-hidden fk:rounded-md fk:object-contain ${De} fk:corner-squircle`,decoding:"async",src:s})})})]}):jsxs(b$3,{children:[jsx(c$1,{asChild:true,children:jsx("div",{className:"fk:w-7 fk:h-7 fk:rounded-sm fk:bg-transparent fk:flex fk:items-center fk:justify-center fk:[&>svg]:h-full fk:[&>svg]:w-auto fk:corner-squircle",children:(()=>{let u=o(t),k=defaultStyles[u];return jsx(FileIcon,{extension:u,...k||{}})})()})}),jsx(d,{children:jsx(e$3,{children:jsx("div",{className:"fk:text-sm fk:text-muted-foreground",children:"Preview not available"})})})]})}):null}function Mr({value:e}){let t=e.filter(o=>!!o.path).slice(0,3),n=Math.max(e[0]?.totalCount??0,e.length);if(t.length===0)return n>0?jsx("div",{className:"fk:flex fk:items-center",children:jsx("span",{className:"fk:text-xs fk:text-muted-foreground",children:n===1?"1 asset":`${n} assets`})}):null;let r=n-t.length;return jsxs("div",{className:"fk:flex fk:items-center",children:[jsx("div",{className:"fk:flex fk:-space-x-2",children:t.map(o=>jsx("img",{alt:"asset",className:`fk:h-7 fk:w-7 fk:overflow-hidden fk:rounded-md fk:object-contain ${De} fk:corner-squircle`,decoding:"async",src:`${b$5}${o.path}?w=84&h=84&f=webp`},o._id))}),r>0?jsxs("span",{className:"fk:ml-2 fk:text-xs fk:text-muted-foreground",children:["+",r]}):null]})}function Me({value:e}){if(e==null||e===""||typeof e!="string")return jsx(w,{value:""});let t=new Date(e);if(!isValid(t))return jsx(w,{value:""});let n=format(t,"MMM d, yyyy")+" at "+format(t,"HH:mm");return jsx(w,{value:n})}function Rr(e){return "groupLabel"in e}function Pr(e){return e.flatMap(t=>Rr(t)?t.items:[t])}function Lr(e,t){if(!t)return e;let n=Pr(t).find(r=>String(r.value)===e);return n?n.label:e}function Et({value:e,options:t}){if(e==null)return jsx(w,{value:""});let n=String(e),r=Lr(n,t?.list);return jsx(w,{value:r})}function Nt({value:e}){return !e||!e.split(",").length?null:jsx("div",{className:"fk:flex fk:flex-wrap fk:gap-1 fk:max-w-full truncate",children:e.split(",").map(t=>jsx(b$4,{className:"fk:px-2.5 fk:py-0 fk:font-normal fk:text-[0.6875rem] fk:leading-4",variant:"secondary",children:t},t))})}function Rt(e,t=5){let n=Number.isFinite(t)&&t>=1?Math.floor(t):5,r=typeof e=="string"&&e.trim()!==""?Number(e):e;if(typeof r!="number"||!Number.isFinite(r))return null;let o=Math.min(n,Math.max(0,Math.round(r)));return {filled:o,max:n,label:`${String(o)} out of ${String(n)} stars`}}function Pt({value:e,options:t}){let n=Rt(e,t?.max);return n?jsx("span",{"aria-label":n.label,className:"fk:inline-flex fk:items-center fk:gap-0.5",role:"img",title:n.label,children:Array.from({length:n.max},(r,o)=>jsx(Star,{"aria-hidden":true,className:o<n.filled?"fk:h-3.5 fk:w-3.5 fk:fill-amber-400 fk:text-amber-400":"fk:h-3.5 fk:w-3.5 fk:fill-transparent fk:text-muted-foreground/40",strokeWidth:1.5},o))}):jsx("span",{})}var _r=/\.(png|jpe?g|gif|webp|avif|svg)$/i;function Lt(e){try{let{pathname:t}=new URL(e);return t.split("/").pop()||t}catch{let[t]=e.split("?");return t}}function It(e){return e.originalFilename?e.originalFilename:e.path?e.path:e.url?Lt(e.url):""}function _t(e){let t=It(e),[n]=t.split("?"),r=n.split(".");return r.length>1?r.pop().toLowerCase():"file"}function Vt(e){return e.mimeType?e.mimeType.startsWith("image/"):_r.test(It(e))}function Re(e,t){if(!e||!t||Lt(e).toLowerCase().endsWith(".svg"))return e;let n=new URLSearchParams({f:"webp",h:String(t.height),w:String(t.width)}),r=e.includes("?")?"&":"?";return `${e}${r}${n.toString()}`}var Or=FileIcon,Ft="fk:bg-[#fafafa] [--asset-checker:#f0f0f0] [background-image:linear-gradient(45deg,var(--asset-checker)_25%,transparent_25%),linear-gradient(-45deg,var(--asset-checker)_25%,transparent_25%),linear-gradient(45deg,transparent_75%,var(--asset-checker)_75%),linear-gradient(-45deg,transparent_75%,var(--asset-checker)_75%)] [background-position:0_0,0_4px,4px_-4px,-4px_0px] [background-size:8px_8px] fk:dark:bg-[#222] dark:[--asset-checker:#2a2a2a]";function Ht({value:e}){let[t$1,n]=useState(false),r=e?.url??"";if(!e||!r&&!e.path&&!e.originalFilename)return null;if(!(Vt(e)&&!!r)){let u=_t(e),k=defaultStyles[u];return jsx("div",{className:"fk:z-10",children:jsx(a,{children:jsxs(b$3,{children:[jsx(c$1,{asChild:true,children:jsx("div",{className:"fk:w-7 fk:h-7 fk:rounded-sm fk:bg-transparent fk:flex fk:items-center fk:justify-center fk:[&>svg]:h-full fk:[&>svg]:w-auto fk:corner-squircle",children:jsx(Or,{extension:u,...k||{}})})}),jsx(d,{children:jsx(e$3,{children:jsx("div",{className:"fk:text-sm fk:text-muted-foreground",children:"Preview not available"})})})]})})})}let l=Re(r,{width:84,height:84}),s$1=Re(r,{width:624,height:624});function b(u){u.stopPropagation(),n(true);}return jsx("div",{className:"fk:z-10",children:jsxs(a,{children:[jsxs(b$3,{children:[jsx(c$1,{asChild:true,children:jsx("img",{src:l,alt:"asset",className:`fk:w-12 fk:h-12 fk:cursor-zoom-in fk:overflow-hidden fk:rounded-md fk:object-contain ${Ft} fk:corner-squircle`,onClick:b})}),jsx(d,{children:jsx(e$3,{children:jsx("img",{src:s$1,alt:"asset",className:`fk:w-52 fk:h-52 fk:overflow-hidden fk:rounded-md fk:object-contain ${Ft} fk:corner-squircle`})})})]}),jsx(k,{open:t$1,onOpenChange:n,children:jsxs(p,{className:"fk:sm:max-w-4xl fk:p-3",children:[jsxs(q,{children:[jsx(s,{className:"fk:sr-only",children:"Asset preview"}),jsx(t,{className:"fk:sr-only",children:"Enlarged asset preview"})]}),jsx("img",{src:r,alt:"asset",className:"fk:max-h-[85vh] fk:w-full fk:overflow-hidden fk:rounded-md fk:object-contain fk:corner-squircle"})]})})]})})}var Ur=new Set(["text","number","datetime","switch","select"]);function Xi({attributesSchema:e,checkboxSelect:t,actionsComponent:n$1,enableColumnSorting:r=false}){let[,o]=g$2(),l=b$2(e,o.user?.spaces),s={datetime:"datetime",editor:"editor",asset:"asset",number:"text",relationship:"text",select:"select",switch:"boolean",text:"text",textarea:"text"},b={boolean:xe,date:B,datetime:Me,editor:St,asset:Ct,number:B,relationship:B,select:Et,switch:xe,text:B,textarea:B,tags:Nt,rating:Pt,assetPreviewField:Ht},u=l.map(i=>{if(i.name==="_updatedAt")return null;let T=(i.inputType==="relationship"&&i.relationship?.entity==="_asset"?"asset":void 0)??i.previewType??s[i.inputType],X=b[T]??b.text;if(i.hidden===true)return null;let de=T==="tags",j=r&&i.scope==="global"&&Ur.has(i.inputType);return {accessorKey:i.name,filterFn:(y,N,C)=>de?true:(Array.isArray(C)?C:[C]).includes(y.getValue(N)),header:({column:y})=>j?jsx(Se,{column:y,title:i.label}):jsx("div",{className:"fk:flex fk:items-center",children:i.label}),cell:({row:y})=>{let N=X;return T==="select"||T==="rating"?jsx(N,{value:y.getValue(i.name),options:i.options}):T==="assetPreviewField"?jsx(N,{value:y.original}):jsx(N,{value:y.getValue(i.name)})},enableSorting:j,enableHiding:true,meta:{label:i.label},size:i.options?.size??150}}).filter(i=>i!==null),k={id:"actions",cell:({row:i})=>n$1?n$1(i):null,size:80},S={accessorKey:"_updatedAt",header:({column:i})=>r?jsx(Se,{column:i,title:"Updated At"}):jsx("div",{className:"fk:flex fk:items-center",children:"Updated At"}),cell:({row:i})=>jsx(Me,{value:i.getValue("_updatedAt")}),enableSorting:r,enableHiding:false,meta:{label:"Updated At"},size:220},M={id:"select",cell:({row:i,table:T})=>jsx(n,{"aria-label":"Select row",checked:i.getIsSelected(),onCheckedChange:X=>{T.toggleAllPageRowsSelected(false),i.toggleSelected(!!X);}}),enableSorting:false,enableHiding:false,size:50},g={id:"select",header:({table:i})=>jsx(n,{className:"fk:dark:bg-white/15","aria-label":"Select all",checked:i.getIsAllPageRowsSelected()||i.getIsSomePageRowsSelected()&&"indeterminate",onCheckedChange:T=>{i.toggleAllPageRowsSelected(!!T);}}),cell:({row:i})=>jsx(n,{"aria-label":"Select row",checked:i.getIsSelected(),onCheckedChange:T=>{i.toggleSelected(!!T);}}),enableSorting:false,enableHiding:false,size:50};return [...t==="single"?[M]:[],...t==="multiple"?[g]:[],...n$1?[k]:[],...u,S]}export{Xr as a,Kr as b,lt as c,lo as d,po as e,So as f,Tt as g,It as h,_t as i,Vt as j,Re as k,Se as l,Xi as m};//# sourceMappingURL=chunk-HXPETSXC.js.map
7
+ //# sourceMappingURL=chunk-HXPETSXC.js.map