codicent-app-sdk 0.3.120 → 0.4.0

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 (413) hide show
  1. package/README.md +173 -26
  2. package/dist/cjs/_virtual/jsQR.js +1 -0
  3. package/dist/cjs/bootstrap.d.ts +112 -0
  4. package/dist/cjs/bootstrap.d.ts.map +1 -0
  5. package/dist/cjs/bootstrap.js +1 -0
  6. package/dist/cjs/components/AiInput.js +1 -1
  7. package/dist/cjs/components/AudioIcon.js +1 -1
  8. package/dist/cjs/components/BulkUploadDialog.d.ts +16 -0
  9. package/dist/cjs/components/BulkUploadDialog.d.ts.map +1 -0
  10. package/dist/cjs/components/BulkUploadDialog.js +1 -0
  11. package/dist/cjs/components/ChatInput.js +1 -1
  12. package/dist/cjs/components/ChatMessage.js +1 -1
  13. package/dist/cjs/components/CombinedPlaceholderDialog.js +1 -1
  14. package/dist/cjs/components/ErrorBoundary.d.ts +17 -0
  15. package/dist/cjs/components/ErrorBoundary.d.ts.map +1 -0
  16. package/dist/cjs/components/ErrorBoundary.js +1 -0
  17. package/dist/cjs/components/Footer.js +1 -1
  18. package/dist/cjs/components/GenericJsonRenderer.d.ts +20 -0
  19. package/dist/cjs/components/GenericJsonRenderer.d.ts.map +1 -0
  20. package/dist/cjs/components/GenericJsonRenderer.js +1 -0
  21. package/dist/cjs/components/Header.js +1 -1
  22. package/dist/cjs/components/HtmlView.js +1 -1
  23. package/dist/cjs/components/LanguageSelector.d.ts +11 -0
  24. package/dist/cjs/components/LanguageSelector.d.ts.map +1 -0
  25. package/dist/cjs/components/LanguageSelector.js +1 -0
  26. package/dist/cjs/components/ListView.d.ts +39 -0
  27. package/dist/cjs/components/ListView.d.ts.map +1 -0
  28. package/dist/cjs/components/ListView.js +1 -0
  29. package/dist/cjs/components/MessageInput.js +1 -1
  30. package/dist/cjs/components/MessageItem.js +1 -1
  31. package/dist/cjs/components/OfflineMessage.d.ts +6 -0
  32. package/dist/cjs/components/OfflineMessage.d.ts.map +1 -0
  33. package/dist/cjs/components/OfflineMessage.js +1 -0
  34. package/dist/cjs/components/Profile.js +1 -1
  35. package/dist/cjs/components/Prompt.js +1 -1
  36. package/dist/cjs/components/QrScanner.d.ts +12 -0
  37. package/dist/cjs/components/QrScanner.d.ts.map +1 -0
  38. package/dist/cjs/components/QrScanner.js +1 -0
  39. package/dist/cjs/components/RecordModal.d.ts +13 -0
  40. package/dist/cjs/components/RecordModal.d.ts.map +1 -0
  41. package/dist/cjs/components/RecordModal.js +1 -0
  42. package/dist/cjs/components/SnapFooter.js +1 -1
  43. package/dist/cjs/components/TextHeader.js +1 -1
  44. package/dist/cjs/components/TypingIndicator.js +1 -1
  45. package/dist/cjs/components/UploadFile.js +1 -1
  46. package/dist/cjs/components/UrlProcessor.js +1 -1
  47. package/dist/cjs/components/VoiceIcon.js +1 -1
  48. package/dist/cjs/components/index.d.ts +9 -0
  49. package/dist/cjs/components/index.d.ts.map +1 -1
  50. package/dist/cjs/config/index.d.ts +1 -0
  51. package/dist/cjs/config/index.d.ts.map +1 -1
  52. package/dist/cjs/config/index.js +1 -1
  53. package/dist/cjs/hooks/index.d.ts +3 -0
  54. package/dist/cjs/hooks/index.d.ts.map +1 -1
  55. package/dist/cjs/hooks/useAuthState.d.ts.map +1 -1
  56. package/dist/cjs/hooks/useAuthState.js +1 -1
  57. package/dist/cjs/hooks/useCodicentState.js +1 -1
  58. package/dist/cjs/hooks/useDebugLogs.d.ts +6 -0
  59. package/dist/cjs/hooks/useDebugLogs.d.ts.map +1 -0
  60. package/dist/cjs/hooks/useDebugLogs.js +1 -0
  61. package/dist/cjs/hooks/useObserveDataSchemas.d.ts +42 -0
  62. package/dist/cjs/hooks/useObserveDataSchemas.d.ts.map +1 -0
  63. package/dist/cjs/hooks/useObserveDataSchemas.js +1 -0
  64. package/dist/cjs/index.d.ts +2 -0
  65. package/dist/cjs/index.d.ts.map +1 -1
  66. package/dist/cjs/index.js +1 -1
  67. package/dist/cjs/node_modules/@auth0/auth0-react/dist/auth0-react.esm.js +1 -0
  68. package/dist/cjs/node_modules/@fluentui/react-button/lib/contexts/ButtonContext.js +1 -1
  69. package/dist/cjs/node_modules/@fluentui/react-checkbox/lib/components/Checkbox/Checkbox.js +1 -0
  70. package/dist/cjs/node_modules/@fluentui/react-checkbox/lib/components/Checkbox/renderCheckbox.js +1 -0
  71. package/dist/cjs/node_modules/@fluentui/react-checkbox/lib/components/Checkbox/useCheckbox.js +1 -0
  72. package/dist/cjs/node_modules/@fluentui/react-checkbox/lib/components/Checkbox/useCheckboxStyles.styles.js +1 -0
  73. package/dist/cjs/node_modules/@fluentui/react-combobox/lib/components/Combobox/useCombobox.js +1 -1
  74. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/Dialog/Dialog.js +1 -0
  75. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/Dialog/renderDialog.js +1 -0
  76. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/Dialog/useDialog.js +1 -0
  77. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/Dialog/useDialogContextValues.js +1 -0
  78. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/DialogActions/DialogActions.js +1 -0
  79. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/DialogActions/renderDialogActions.js +1 -0
  80. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/DialogActions/useDialogActions.js +1 -0
  81. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/DialogActions/useDialogActionsStyles.styles.js +1 -0
  82. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/DialogBackdropMotion.js +1 -0
  83. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/DialogBody/DialogBody.js +1 -0
  84. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/DialogBody/renderDialogBody.js +1 -0
  85. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/DialogBody/useDialogBody.js +1 -0
  86. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/DialogBody/useDialogBodyStyles.styles.js +1 -0
  87. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/DialogContent/DialogContent.js +1 -0
  88. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/DialogContent/renderDialogContent.js +1 -0
  89. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/DialogContent/useDialogContent.js +1 -0
  90. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/DialogContent/useDialogContentStyles.styles.js +1 -0
  91. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/DialogSurface/DialogSurface.js +1 -0
  92. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/DialogSurface/renderDialogSurface.js +1 -0
  93. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/DialogSurface/useDialogSurface.js +1 -0
  94. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/DialogSurface/useDialogSurfaceContextValues.js +1 -0
  95. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/DialogSurface/useDialogSurfaceStyles.styles.js +1 -0
  96. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/DialogSurfaceMotion.js +1 -0
  97. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/DialogTitle/DialogTitle.js +1 -0
  98. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/DialogTitle/renderDialogTitle.js +1 -0
  99. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/DialogTitle/useDialogTitle.js +1 -0
  100. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/DialogTitle/useDialogTitleStyles.styles.js +1 -0
  101. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/DialogTrigger/DialogTrigger.js +1 -0
  102. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/DialogTrigger/renderDialogTrigger.js +1 -0
  103. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/DialogTrigger/useDialogTrigger.js +1 -0
  104. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/components/MotionRefForwarder.js +1 -0
  105. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/contexts/dialogContext.js +1 -0
  106. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/contexts/dialogSurfaceContext.js +1 -0
  107. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/utils/useDisableBodyScroll.js +1 -0
  108. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/utils/useDisableBodyScroll.styles.js +1 -0
  109. package/dist/cjs/node_modules/@fluentui/react-dialog/lib/utils/useFocusFirstElement.js +1 -0
  110. package/dist/cjs/node_modules/@fluentui/react-icons/lib/contexts/IconDirectionContext.js +1 -1
  111. package/dist/cjs/node_modules/@fluentui/react-icons/lib/sizedIcons/chunk-0.js +1 -1
  112. package/dist/cjs/node_modules/@fluentui/react-icons/lib/sizedIcons/chunk-1.js +1 -1
  113. package/dist/cjs/node_modules/@fluentui/react-icons/lib/sizedIcons/chunk-14.js +1 -1
  114. package/dist/cjs/node_modules/@fluentui/react-icons/lib/sizedIcons/chunk-3.js +1 -1
  115. package/dist/cjs/node_modules/@fluentui/react-icons/lib/sizedIcons/chunk-5.js +1 -1
  116. package/dist/cjs/node_modules/@fluentui/react-icons/lib/sizedIcons/chunk-6.js +1 -1
  117. package/dist/cjs/node_modules/@fluentui/react-icons/lib/sizedIcons/chunk-7.js +1 -1
  118. package/dist/cjs/node_modules/@fluentui/react-menu/lib/components/Menu/useMenu.js +1 -1
  119. package/dist/cjs/node_modules/@fluentui/react-menu/lib/components/MenuItem/useMenuItem.js +1 -1
  120. package/dist/cjs/node_modules/@fluentui/react-message-bar/lib/components/MessageBarActions/MessageBarActions.js +1 -0
  121. package/dist/cjs/node_modules/@fluentui/react-message-bar/lib/components/MessageBarActions/renderMessageBarActions.js +1 -0
  122. package/dist/cjs/node_modules/@fluentui/react-message-bar/lib/components/MessageBarActions/useMessageBarActions.js +1 -0
  123. package/dist/cjs/node_modules/@fluentui/react-message-bar/lib/components/MessageBarActions/useMessageBarActionsContextValues.js +1 -0
  124. package/dist/cjs/node_modules/@fluentui/react-message-bar/lib/components/MessageBarActions/useMessageBarActionsStyles.styles.js +1 -0
  125. package/dist/cjs/node_modules/@fluentui/react-message-bar/lib/components/MessageBarTitle/MessageBarTitle.js +1 -0
  126. package/dist/cjs/node_modules/@fluentui/react-message-bar/lib/components/MessageBarTitle/renderMessageBarTitle.js +1 -0
  127. package/dist/cjs/node_modules/@fluentui/react-message-bar/lib/components/MessageBarTitle/useMessageBarTitle.js +1 -0
  128. package/dist/cjs/node_modules/@fluentui/react-message-bar/lib/components/MessageBarTitle/useMessageBarTitleStyles.styles.js +1 -0
  129. package/dist/cjs/node_modules/@fluentui/react-motion/lib/slots/presenceMotionSlot.js +1 -0
  130. package/dist/cjs/node_modules/@fluentui/react-motion-components-preview/lib/components/Fade/Fade.js +1 -0
  131. package/dist/cjs/node_modules/@fluentui/react-positioning/lib/utils/mergeArrowOffset.js +1 -0
  132. package/dist/cjs/node_modules/@fluentui/react-provider/lib/components/FluentProvider/FluentProvider.js +1 -0
  133. package/dist/cjs/node_modules/@fluentui/react-provider/lib/components/FluentProvider/createCSSRuleFromTheme.js +1 -0
  134. package/dist/cjs/node_modules/@fluentui/react-provider/lib/components/FluentProvider/renderFluentProvider.js +1 -0
  135. package/dist/cjs/node_modules/@fluentui/react-provider/lib/components/FluentProvider/useFluentProvider.js +1 -0
  136. package/dist/cjs/node_modules/@fluentui/react-provider/lib/components/FluentProvider/useFluentProviderContextValues.js +1 -0
  137. package/dist/cjs/node_modules/@fluentui/react-provider/lib/components/FluentProvider/useFluentProviderStyles.styles.js +1 -0
  138. package/dist/cjs/node_modules/@fluentui/react-provider/lib/components/FluentProvider/useFluentProviderThemeStyleTag.js +1 -0
  139. package/dist/cjs/node_modules/@fluentui/react-search/lib/components/SearchBox/useSearchBox.js +1 -1
  140. package/dist/cjs/node_modules/@fluentui/react-shared-contexts/lib/CustomStyleHooksContext/CustomStyleHooksContext.js +1 -1
  141. package/dist/cjs/node_modules/@fluentui/react-shared-contexts/lib/OverridesContext/OverridesContext.js +1 -1
  142. package/dist/cjs/node_modules/@fluentui/react-shared-contexts/lib/ProviderContext/ProviderContext.js +1 -1
  143. package/dist/cjs/node_modules/@fluentui/react-shared-contexts/lib/ThemeClassNameContext/ThemeClassNameContext.js +1 -1
  144. package/dist/cjs/node_modules/@fluentui/react-shared-contexts/lib/ThemeContext/ThemeContext.js +1 -0
  145. package/dist/cjs/node_modules/@fluentui/react-shared-contexts/lib/TooltipVisibilityContext/TooltipContext.js +1 -0
  146. package/dist/cjs/node_modules/@fluentui/react-tabster/lib/hooks/useIsNavigatingWithKeyboard.js +1 -0
  147. package/dist/cjs/node_modules/@fluentui/react-timepicker-compat/lib/components/TimePicker/useTimePicker.js +1 -1
  148. package/dist/cjs/node_modules/@fluentui/react-tooltip/lib/components/Tooltip/Tooltip.js +1 -0
  149. package/dist/cjs/node_modules/@fluentui/react-tooltip/lib/components/Tooltip/private/constants.js +1 -0
  150. package/dist/cjs/node_modules/@fluentui/react-tooltip/lib/components/Tooltip/renderTooltip.js +1 -0
  151. package/dist/cjs/node_modules/@fluentui/react-tooltip/lib/components/Tooltip/useTooltip.js +1 -0
  152. package/dist/cjs/node_modules/@fluentui/react-tooltip/lib/components/Tooltip/useTooltipStyles.styles.js +1 -0
  153. package/dist/cjs/node_modules/@fluentui/react-utilities/lib/ssr/SSRContext.js +1 -1
  154. package/dist/cjs/node_modules/@fluentui/tokens/lib/alias/lightColor.js +1 -0
  155. package/dist/cjs/node_modules/@fluentui/tokens/lib/alias/lightColorPalette.js +1 -0
  156. package/dist/cjs/node_modules/@fluentui/tokens/lib/global/borderRadius.js +1 -0
  157. package/dist/cjs/node_modules/@fluentui/tokens/lib/global/colorPalette.js +1 -0
  158. package/dist/cjs/node_modules/@fluentui/tokens/lib/global/colors.js +1 -0
  159. package/dist/cjs/node_modules/@fluentui/tokens/lib/global/curves.js +1 -0
  160. package/dist/cjs/node_modules/@fluentui/tokens/lib/global/durations.js +1 -0
  161. package/dist/cjs/node_modules/@fluentui/tokens/lib/global/fonts.js +1 -0
  162. package/dist/cjs/node_modules/@fluentui/tokens/lib/global/spacings.js +1 -0
  163. package/dist/cjs/node_modules/@fluentui/tokens/lib/global/strokeWidths.js +1 -0
  164. package/dist/cjs/node_modules/@fluentui/tokens/lib/sharedColorNames.js +1 -0
  165. package/dist/cjs/node_modules/@fluentui/tokens/lib/statusColorMapping.js +1 -0
  166. package/dist/cjs/node_modules/@fluentui/tokens/lib/utils/createLightTheme.js +1 -0
  167. package/dist/cjs/node_modules/@fluentui/tokens/lib/utils/shadows.js +1 -0
  168. package/dist/cjs/node_modules/@griffel/react/TextDirectionContext.esm.js +1 -1
  169. package/dist/cjs/node_modules/jsqr/dist/jsQR.js +1 -0
  170. package/dist/cjs/pages/AppFrame.js +1 -1
  171. package/dist/cjs/pages/Chat.js +1 -1
  172. package/dist/cjs/pages/Compose.js +1 -1
  173. package/dist/cjs/pages/CrmPage.js +1 -1
  174. package/dist/cjs/pages/CrmPagePersistent.js +1 -1
  175. package/dist/cjs/pages/Debug.d.ts +4 -0
  176. package/dist/cjs/pages/Debug.d.ts.map +1 -0
  177. package/dist/cjs/pages/Debug.js +1 -0
  178. package/dist/cjs/pages/FormAccept.js +1 -1
  179. package/dist/cjs/pages/FormInvite.js +1 -1
  180. package/dist/cjs/pages/FormPage.d.ts +11 -0
  181. package/dist/cjs/pages/FormPage.d.ts.map +1 -0
  182. package/dist/cjs/pages/FormPage.js +1 -0
  183. package/dist/cjs/pages/Help.d.ts +7 -0
  184. package/dist/cjs/pages/Help.d.ts.map +1 -0
  185. package/dist/cjs/pages/Help.js +1 -0
  186. package/dist/cjs/pages/HtmlViewer.js +1 -1
  187. package/dist/cjs/pages/Login.js +1 -1
  188. package/dist/cjs/pages/Purchase.js +1 -1
  189. package/dist/cjs/pages/QrScan.d.ts +12 -0
  190. package/dist/cjs/pages/QrScan.d.ts.map +1 -0
  191. package/dist/cjs/pages/QrScan.js +1 -0
  192. package/dist/cjs/pages/Sales.js +1 -1
  193. package/dist/cjs/pages/SchemaEditor.d.ts +2 -0
  194. package/dist/cjs/pages/SchemaEditor.d.ts.map +1 -0
  195. package/dist/cjs/pages/SchemaEditor.js +1 -0
  196. package/dist/cjs/pages/Search.js +1 -1
  197. package/dist/cjs/pages/Snap.js +1 -1
  198. package/dist/cjs/pages/index.d.ts +5 -0
  199. package/dist/cjs/pages/index.d.ts.map +1 -1
  200. package/dist/cjs/services/codicent.d.ts +6 -0
  201. package/dist/cjs/services/codicent.d.ts.map +1 -1
  202. package/dist/cjs/services/codicent.js +1 -1
  203. package/dist/cjs/types/index.d.ts +188 -0
  204. package/dist/cjs/types/index.d.ts.map +1 -0
  205. package/dist/cjs/utils/appState.d.ts.map +1 -1
  206. package/dist/cjs/utils/appState.js +1 -1
  207. package/dist/esm/_virtual/jsQR.js +1 -0
  208. package/dist/esm/bootstrap.d.ts +112 -0
  209. package/dist/esm/bootstrap.d.ts.map +1 -0
  210. package/dist/esm/bootstrap.js +1 -0
  211. package/dist/esm/components/AiInput.js +1 -1
  212. package/dist/esm/components/AudioIcon.js +1 -1
  213. package/dist/esm/components/BulkUploadDialog.d.ts +16 -0
  214. package/dist/esm/components/BulkUploadDialog.d.ts.map +1 -0
  215. package/dist/esm/components/BulkUploadDialog.js +1 -0
  216. package/dist/esm/components/ChatInput.js +1 -1
  217. package/dist/esm/components/ChatMessage.js +1 -1
  218. package/dist/esm/components/CombinedPlaceholderDialog.js +1 -1
  219. package/dist/esm/components/ErrorBoundary.d.ts +17 -0
  220. package/dist/esm/components/ErrorBoundary.d.ts.map +1 -0
  221. package/dist/esm/components/ErrorBoundary.js +1 -0
  222. package/dist/esm/components/Footer.js +1 -1
  223. package/dist/esm/components/GenericJsonRenderer.d.ts +20 -0
  224. package/dist/esm/components/GenericJsonRenderer.d.ts.map +1 -0
  225. package/dist/esm/components/GenericJsonRenderer.js +1 -0
  226. package/dist/esm/components/Header.js +1 -1
  227. package/dist/esm/components/HtmlView.js +1 -1
  228. package/dist/esm/components/LanguageSelector.d.ts +11 -0
  229. package/dist/esm/components/LanguageSelector.d.ts.map +1 -0
  230. package/dist/esm/components/LanguageSelector.js +1 -0
  231. package/dist/esm/components/ListView.d.ts +39 -0
  232. package/dist/esm/components/ListView.d.ts.map +1 -0
  233. package/dist/esm/components/ListView.js +1 -0
  234. package/dist/esm/components/MessageInput.js +1 -1
  235. package/dist/esm/components/MessageItem.js +1 -1
  236. package/dist/esm/components/OfflineMessage.d.ts +6 -0
  237. package/dist/esm/components/OfflineMessage.d.ts.map +1 -0
  238. package/dist/esm/components/OfflineMessage.js +1 -0
  239. package/dist/esm/components/Profile.js +1 -1
  240. package/dist/esm/components/Prompt.js +1 -1
  241. package/dist/esm/components/QrScanner.d.ts +12 -0
  242. package/dist/esm/components/QrScanner.d.ts.map +1 -0
  243. package/dist/esm/components/QrScanner.js +1 -0
  244. package/dist/esm/components/RecordModal.d.ts +13 -0
  245. package/dist/esm/components/RecordModal.d.ts.map +1 -0
  246. package/dist/esm/components/RecordModal.js +1 -0
  247. package/dist/esm/components/SnapFooter.js +1 -1
  248. package/dist/esm/components/TextHeader.js +1 -1
  249. package/dist/esm/components/TypingIndicator.js +1 -1
  250. package/dist/esm/components/UploadFile.js +1 -1
  251. package/dist/esm/components/UrlProcessor.js +1 -1
  252. package/dist/esm/components/VoiceIcon.js +1 -1
  253. package/dist/esm/components/index.d.ts +9 -0
  254. package/dist/esm/components/index.d.ts.map +1 -1
  255. package/dist/esm/config/index.d.ts +1 -0
  256. package/dist/esm/config/index.d.ts.map +1 -1
  257. package/dist/esm/config/index.js +1 -1
  258. package/dist/esm/hooks/index.d.ts +3 -0
  259. package/dist/esm/hooks/index.d.ts.map +1 -1
  260. package/dist/esm/hooks/useAuthState.d.ts.map +1 -1
  261. package/dist/esm/hooks/useAuthState.js +1 -1
  262. package/dist/esm/hooks/useCodicentState.js +1 -1
  263. package/dist/esm/hooks/useDebugLogs.d.ts +6 -0
  264. package/dist/esm/hooks/useDebugLogs.d.ts.map +1 -0
  265. package/dist/esm/hooks/useDebugLogs.js +1 -0
  266. package/dist/esm/hooks/useObserveDataSchemas.d.ts +42 -0
  267. package/dist/esm/hooks/useObserveDataSchemas.d.ts.map +1 -0
  268. package/dist/esm/hooks/useObserveDataSchemas.js +1 -0
  269. package/dist/esm/index.d.ts +2 -0
  270. package/dist/esm/index.d.ts.map +1 -1
  271. package/dist/esm/index.js +1 -1
  272. package/dist/esm/node_modules/@auth0/auth0-react/dist/auth0-react.esm.js +1 -0
  273. package/dist/esm/node_modules/@fluentui/react-button/lib/contexts/ButtonContext.js +1 -1
  274. package/dist/esm/node_modules/@fluentui/react-checkbox/lib/components/Checkbox/Checkbox.js +1 -0
  275. package/dist/esm/node_modules/@fluentui/react-checkbox/lib/components/Checkbox/renderCheckbox.js +1 -0
  276. package/dist/esm/node_modules/@fluentui/react-checkbox/lib/components/Checkbox/useCheckbox.js +1 -0
  277. package/dist/esm/node_modules/@fluentui/react-checkbox/lib/components/Checkbox/useCheckboxStyles.styles.js +1 -0
  278. package/dist/esm/node_modules/@fluentui/react-combobox/lib/components/Combobox/useCombobox.js +1 -1
  279. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/Dialog/Dialog.js +1 -0
  280. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/Dialog/renderDialog.js +1 -0
  281. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/Dialog/useDialog.js +1 -0
  282. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/Dialog/useDialogContextValues.js +1 -0
  283. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/DialogActions/DialogActions.js +1 -0
  284. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/DialogActions/renderDialogActions.js +1 -0
  285. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/DialogActions/useDialogActions.js +1 -0
  286. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/DialogActions/useDialogActionsStyles.styles.js +1 -0
  287. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/DialogBackdropMotion.js +1 -0
  288. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/DialogBody/DialogBody.js +1 -0
  289. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/DialogBody/renderDialogBody.js +1 -0
  290. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/DialogBody/useDialogBody.js +1 -0
  291. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/DialogBody/useDialogBodyStyles.styles.js +1 -0
  292. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/DialogContent/DialogContent.js +1 -0
  293. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/DialogContent/renderDialogContent.js +1 -0
  294. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/DialogContent/useDialogContent.js +1 -0
  295. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/DialogContent/useDialogContentStyles.styles.js +1 -0
  296. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/DialogSurface/DialogSurface.js +1 -0
  297. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/DialogSurface/renderDialogSurface.js +1 -0
  298. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/DialogSurface/useDialogSurface.js +1 -0
  299. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/DialogSurface/useDialogSurfaceContextValues.js +1 -0
  300. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/DialogSurface/useDialogSurfaceStyles.styles.js +1 -0
  301. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/DialogSurfaceMotion.js +1 -0
  302. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/DialogTitle/DialogTitle.js +1 -0
  303. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/DialogTitle/renderDialogTitle.js +1 -0
  304. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/DialogTitle/useDialogTitle.js +1 -0
  305. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/DialogTitle/useDialogTitleStyles.styles.js +1 -0
  306. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/DialogTrigger/DialogTrigger.js +1 -0
  307. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/DialogTrigger/renderDialogTrigger.js +1 -0
  308. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/DialogTrigger/useDialogTrigger.js +1 -0
  309. package/dist/esm/node_modules/@fluentui/react-dialog/lib/components/MotionRefForwarder.js +1 -0
  310. package/dist/esm/node_modules/@fluentui/react-dialog/lib/contexts/dialogContext.js +1 -0
  311. package/dist/esm/node_modules/@fluentui/react-dialog/lib/contexts/dialogSurfaceContext.js +1 -0
  312. package/dist/esm/node_modules/@fluentui/react-dialog/lib/utils/useDisableBodyScroll.js +1 -0
  313. package/dist/esm/node_modules/@fluentui/react-dialog/lib/utils/useDisableBodyScroll.styles.js +1 -0
  314. package/dist/esm/node_modules/@fluentui/react-dialog/lib/utils/useFocusFirstElement.js +1 -0
  315. package/dist/esm/node_modules/@fluentui/react-icons/lib/contexts/IconDirectionContext.js +1 -1
  316. package/dist/esm/node_modules/@fluentui/react-icons/lib/sizedIcons/chunk-0.js +1 -1
  317. package/dist/esm/node_modules/@fluentui/react-icons/lib/sizedIcons/chunk-1.js +1 -1
  318. package/dist/esm/node_modules/@fluentui/react-icons/lib/sizedIcons/chunk-14.js +1 -1
  319. package/dist/esm/node_modules/@fluentui/react-icons/lib/sizedIcons/chunk-3.js +1 -1
  320. package/dist/esm/node_modules/@fluentui/react-icons/lib/sizedIcons/chunk-5.js +1 -1
  321. package/dist/esm/node_modules/@fluentui/react-icons/lib/sizedIcons/chunk-6.js +1 -1
  322. package/dist/esm/node_modules/@fluentui/react-icons/lib/sizedIcons/chunk-7.js +1 -1
  323. package/dist/esm/node_modules/@fluentui/react-menu/lib/components/Menu/useMenu.js +1 -1
  324. package/dist/esm/node_modules/@fluentui/react-menu/lib/components/MenuItem/useMenuItem.js +1 -1
  325. package/dist/esm/node_modules/@fluentui/react-message-bar/lib/components/MessageBarActions/MessageBarActions.js +1 -0
  326. package/dist/esm/node_modules/@fluentui/react-message-bar/lib/components/MessageBarActions/renderMessageBarActions.js +1 -0
  327. package/dist/esm/node_modules/@fluentui/react-message-bar/lib/components/MessageBarActions/useMessageBarActions.js +1 -0
  328. package/dist/esm/node_modules/@fluentui/react-message-bar/lib/components/MessageBarActions/useMessageBarActionsContextValues.js +1 -0
  329. package/dist/esm/node_modules/@fluentui/react-message-bar/lib/components/MessageBarActions/useMessageBarActionsStyles.styles.js +1 -0
  330. package/dist/esm/node_modules/@fluentui/react-message-bar/lib/components/MessageBarTitle/MessageBarTitle.js +1 -0
  331. package/dist/esm/node_modules/@fluentui/react-message-bar/lib/components/MessageBarTitle/renderMessageBarTitle.js +1 -0
  332. package/dist/esm/node_modules/@fluentui/react-message-bar/lib/components/MessageBarTitle/useMessageBarTitle.js +1 -0
  333. package/dist/esm/node_modules/@fluentui/react-message-bar/lib/components/MessageBarTitle/useMessageBarTitleStyles.styles.js +1 -0
  334. package/dist/esm/node_modules/@fluentui/react-motion/lib/slots/presenceMotionSlot.js +1 -0
  335. package/dist/esm/node_modules/@fluentui/react-motion-components-preview/lib/components/Fade/Fade.js +1 -0
  336. package/dist/esm/node_modules/@fluentui/react-positioning/lib/utils/mergeArrowOffset.js +1 -0
  337. package/dist/esm/node_modules/@fluentui/react-provider/lib/components/FluentProvider/FluentProvider.js +1 -0
  338. package/dist/esm/node_modules/@fluentui/react-provider/lib/components/FluentProvider/createCSSRuleFromTheme.js +1 -0
  339. package/dist/esm/node_modules/@fluentui/react-provider/lib/components/FluentProvider/renderFluentProvider.js +1 -0
  340. package/dist/esm/node_modules/@fluentui/react-provider/lib/components/FluentProvider/useFluentProvider.js +1 -0
  341. package/dist/esm/node_modules/@fluentui/react-provider/lib/components/FluentProvider/useFluentProviderContextValues.js +1 -0
  342. package/dist/esm/node_modules/@fluentui/react-provider/lib/components/FluentProvider/useFluentProviderStyles.styles.js +1 -0
  343. package/dist/esm/node_modules/@fluentui/react-provider/lib/components/FluentProvider/useFluentProviderThemeStyleTag.js +1 -0
  344. package/dist/esm/node_modules/@fluentui/react-search/lib/components/SearchBox/useSearchBox.js +1 -1
  345. package/dist/esm/node_modules/@fluentui/react-shared-contexts/lib/CustomStyleHooksContext/CustomStyleHooksContext.js +1 -1
  346. package/dist/esm/node_modules/@fluentui/react-shared-contexts/lib/OverridesContext/OverridesContext.js +1 -1
  347. package/dist/esm/node_modules/@fluentui/react-shared-contexts/lib/ProviderContext/ProviderContext.js +1 -1
  348. package/dist/esm/node_modules/@fluentui/react-shared-contexts/lib/ThemeClassNameContext/ThemeClassNameContext.js +1 -1
  349. package/dist/esm/node_modules/@fluentui/react-shared-contexts/lib/ThemeContext/ThemeContext.js +1 -0
  350. package/dist/esm/node_modules/@fluentui/react-shared-contexts/lib/TooltipVisibilityContext/TooltipContext.js +1 -0
  351. package/dist/esm/node_modules/@fluentui/react-tabster/lib/hooks/useIsNavigatingWithKeyboard.js +1 -0
  352. package/dist/esm/node_modules/@fluentui/react-timepicker-compat/lib/components/TimePicker/useTimePicker.js +1 -1
  353. package/dist/esm/node_modules/@fluentui/react-tooltip/lib/components/Tooltip/Tooltip.js +1 -0
  354. package/dist/esm/node_modules/@fluentui/react-tooltip/lib/components/Tooltip/private/constants.js +1 -0
  355. package/dist/esm/node_modules/@fluentui/react-tooltip/lib/components/Tooltip/renderTooltip.js +1 -0
  356. package/dist/esm/node_modules/@fluentui/react-tooltip/lib/components/Tooltip/useTooltip.js +1 -0
  357. package/dist/esm/node_modules/@fluentui/react-tooltip/lib/components/Tooltip/useTooltipStyles.styles.js +1 -0
  358. package/dist/esm/node_modules/@fluentui/react-utilities/lib/ssr/SSRContext.js +1 -1
  359. package/dist/esm/node_modules/@fluentui/tokens/lib/alias/lightColor.js +1 -0
  360. package/dist/esm/node_modules/@fluentui/tokens/lib/alias/lightColorPalette.js +1 -0
  361. package/dist/esm/node_modules/@fluentui/tokens/lib/global/borderRadius.js +1 -0
  362. package/dist/esm/node_modules/@fluentui/tokens/lib/global/colorPalette.js +1 -0
  363. package/dist/esm/node_modules/@fluentui/tokens/lib/global/colors.js +1 -0
  364. package/dist/esm/node_modules/@fluentui/tokens/lib/global/curves.js +1 -0
  365. package/dist/esm/node_modules/@fluentui/tokens/lib/global/durations.js +1 -0
  366. package/dist/esm/node_modules/@fluentui/tokens/lib/global/fonts.js +1 -0
  367. package/dist/esm/node_modules/@fluentui/tokens/lib/global/spacings.js +1 -0
  368. package/dist/esm/node_modules/@fluentui/tokens/lib/global/strokeWidths.js +1 -0
  369. package/dist/esm/node_modules/@fluentui/tokens/lib/sharedColorNames.js +1 -0
  370. package/dist/esm/node_modules/@fluentui/tokens/lib/statusColorMapping.js +1 -0
  371. package/dist/esm/node_modules/@fluentui/tokens/lib/utils/createLightTheme.js +1 -0
  372. package/dist/esm/node_modules/@fluentui/tokens/lib/utils/shadows.js +1 -0
  373. package/dist/esm/node_modules/@griffel/react/TextDirectionContext.esm.js +1 -1
  374. package/dist/esm/node_modules/jsqr/dist/jsQR.js +1 -0
  375. package/dist/esm/pages/AppFrame.js +1 -1
  376. package/dist/esm/pages/Chat.js +1 -1
  377. package/dist/esm/pages/Compose.js +1 -1
  378. package/dist/esm/pages/CrmPage.js +1 -1
  379. package/dist/esm/pages/CrmPagePersistent.js +1 -1
  380. package/dist/esm/pages/Debug.d.ts +4 -0
  381. package/dist/esm/pages/Debug.d.ts.map +1 -0
  382. package/dist/esm/pages/Debug.js +1 -0
  383. package/dist/esm/pages/FormAccept.js +1 -1
  384. package/dist/esm/pages/FormInvite.js +1 -1
  385. package/dist/esm/pages/FormPage.d.ts +11 -0
  386. package/dist/esm/pages/FormPage.d.ts.map +1 -0
  387. package/dist/esm/pages/FormPage.js +1 -0
  388. package/dist/esm/pages/Help.d.ts +7 -0
  389. package/dist/esm/pages/Help.d.ts.map +1 -0
  390. package/dist/esm/pages/Help.js +1 -0
  391. package/dist/esm/pages/HtmlViewer.js +1 -1
  392. package/dist/esm/pages/Login.js +1 -1
  393. package/dist/esm/pages/Purchase.js +1 -1
  394. package/dist/esm/pages/QrScan.d.ts +12 -0
  395. package/dist/esm/pages/QrScan.d.ts.map +1 -0
  396. package/dist/esm/pages/QrScan.js +1 -0
  397. package/dist/esm/pages/Sales.js +1 -1
  398. package/dist/esm/pages/SchemaEditor.d.ts +2 -0
  399. package/dist/esm/pages/SchemaEditor.d.ts.map +1 -0
  400. package/dist/esm/pages/SchemaEditor.js +1 -0
  401. package/dist/esm/pages/Search.js +1 -1
  402. package/dist/esm/pages/Snap.js +1 -1
  403. package/dist/esm/pages/index.d.ts +5 -0
  404. package/dist/esm/pages/index.d.ts.map +1 -1
  405. package/dist/esm/services/codicent.d.ts +6 -0
  406. package/dist/esm/services/codicent.d.ts.map +1 -1
  407. package/dist/esm/services/codicent.js +1 -1
  408. package/dist/esm/types/index.d.ts +188 -0
  409. package/dist/esm/types/index.d.ts.map +1 -0
  410. package/dist/esm/utils/appState.d.ts.map +1 -1
  411. package/dist/esm/utils/appState.js +1 -1
  412. package/dist/index.d.ts +521 -28
  413. package/package.json +4 -3
@@ -1 +1 @@
1
- "use strict";var t,e=require("../node_modules/@stripe/stripe-js/dist/index.js"),o=require("../utils/MessageContent.js");require("../node_modules/tinycolor2/esm/tinycolor.js"),require("react/jsx-runtime"),require("react"),require("../_virtual/index.js"),require("../config/index.js"),require("../utils/cacheManager.js"),require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js"),require("../lib/wavtools/lib/wav_stream_player.js"),require("../lib/wavtools/lib/wav_recorder.js");let a="https://codicent.com/",n="-";const s=t=>{t&&"string"==typeof t?(a=t.endsWith("/")?t:t+"/","undefined"!=typeof window&&void 0!==window.Codicent&&"function"==typeof window.Codicent.init&&window.Codicent.init({token:n,baseUrl:a})):console.warn("Invalid base URL provided, using default")},i=()=>void 0!==window.Codicent&&(window.Codicent.handleMessage=function(t){const e=new CustomEvent("codicent-log",{detail:{message:t}});window.dispatchEvent(e)},window.Codicent.init({token:n,baseUrl:a}),!0);let r=i();if(!r){const t=setInterval((()=>{r=i(),r&&clearInterval(t)}),100)}class c{constructor(t){this.createDataMessage=async(t,e,o)=>await window.Codicent.data.create({codicent:o||this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e,o,a,n)=>await window.Codicent.data.read({codicent:o||this.codicent,tag:t,search:e,start:a,length:n}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.updateDataMessage=async(t,e,o)=>await window.Codicent.data.update({id:t,data:e,codicent:o||this.codicent}),this.deleteDataMessage=async(t,e)=>await window.Codicent.data.delete({id:t,codicent:e||this.codicent}),this.getAppTheme=async()=>{try{const t=await window.Codicent.getDataMessages({tags:["app-theme"],codicent:this.codicent});return t.length>0?t[0].data:null}catch(t){return console.error("Error fetching app theme:",t),null}},this.getAppButtons=async()=>{const t=(await window.Codicent.getDataMessages({tags:[this.options.BUTTON_TAG],codicent:this.codicent})).map((t=>t.data));return t.sort(((t,e)=>t.title>e.title?1:-1)),t},this.getAppTasks=async()=>(await window.Codicent.getMessages({search:`@${this.codicent} #app-task`,length:50})).map((t=>{const e=new o.default(t.content).content.split("\n"),a=e[0],n=e.slice(1).join("\n");return{id:t.id,title:a,content:n}})),this.getAppPrompts=async()=>(await window.Codicent.getDataMessages({tags:["chatprompt"],codicent:this.codicent})).map((t=>t.data)).map((({title:t,prompt:e})=>({title:t,prompt:e}))),this.uploadFile=async(t,e)=>await window.Codicent.upload(e,t),this.getFileInfo=async t=>await window.Codicent.getFileInfo(t),this.generateApiToken=async(t,e)=>{const o=await fetch(`${a}api/GenerateApiToken?project=${this.codicent}${t?`&expires=${t.toISOString()}`:""}${e?`&forUserNickname=${e}`:""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);return await o.text()},this.sendMessage=(t,e,o)=>window.Codicent.postMessage({message:`@${o||this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e,o)=>window.Codicent.getChatReply4({message:t,codicent:o||this.codicent,messageId:e}),this.getMessagesFast=async(t,e,o=100,n=void 0,s,i=0)=>{const r=await this.request(`${a}app/AppGetMessages`,"POST",{headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:s||this.codicent,search:e,start:i,length:o})});let c=await r.json();if(c.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),n){const t=await this.getPublicFlow(n);c=c.concat(t),c.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return c},this.getMessages=async(t,e,o=10)=>{let a=[];const n=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:o});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(n)).forEach((t=>{a=a.concat(t)})),e)try{const t=await this.getPublicFlow(e);a=a.concat(t)}catch(t){console.warn("Error fetching public flow, PUBLIC_TAG missing in codicent?",t)}return a=a.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id)))),a.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),a},this.registerUser=async(t,e,o,n)=>{const s=await fetch(`${a}app/RegisterAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!s.ok)return"";const i=await s.text();return window.Codicent.init({token:n,baseUrl:a}),i},this.loginUser=async(t,e)=>{try{const o=await fetch(`${a}app/LoginAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!o.ok)return 404===o.status||400===o.status?null:401===o.status?(this.handleUnauthorized(),null):"";const n=await o.text();return this.setToken(n),n}catch(t){return console.warn("Error logging in user:",t),""}},this.nicknameExists=async t=>{const e=await fetch(`${a}app/NicknameExists?nickname=${encodeURIComponent(t)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"]]});if(!e.ok)return!1;return await e.json()},this.logout=()=>{this.setToken("")},this.isRegistered=()=>null!==localStorage.getItem("codicent_nickname"),this.getApps=async()=>{try{const t=await fetch(`${a}app/AppGetApps`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw t.status,new Error(`${t.statusText}`);const e=(await t.json()).filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id))&&(this.options.APP_NAME||t.id.startsWith(this.options.APP_PREFIX))));return e}catch(t){return console.warn("Error fetching apps:",t),null}},this.addFollower=async(t,e)=>{const o=await fetch(`${a}app/AddFollower?nickname=${t}&followerNickname=${e}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText||"Failed to add follower!"}`);return await o.json()},this.cloneProject=async(t,e)=>{const o=await fetch(`${a}app/CloneProject?project=${t}&newProject=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);let n=await o.json();if(n){const t='#data #app-theme \n{\n "textcolor": "#212121",\n "backgroundcolor": "#273044",\n "color": "#ffffff",\n "logo": "https://codicent.com/logo512.png",\n "title": "",\n "themeColor": "#581d71",\n "buttonColor": "#c0c0c0",\n "buttonTextColor": "#000000",\n "font": "Montserrat",\n "welcome": "Hej {{username}}!",\n "chatPlaceholder": "Tjena, Loociz här! Vad vill du?",\n "textPlaceholder": "Skriv det du vill spara, så tar jag (Loociz alltså) hand om det!",\n "transcriptionInstructions": "Tryck på knappen för att start och sedan stoppa ljudinspelning."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}if(n){const t='#data #app-button\n{\n "title": "Ta fram företagsinfo",\n "url": "/#/chat?text=Hej!%20Jag%20vill%20spara%20f%C3%B6retagsinfo.%20Guida%20mig%20steg%20f%C3%B6r%20steg%2C%20ett%20i%20taget%2C%20tills%20vi%20har%20all%20info%20om%20mitt%20f%C3%B6retag.%20Exempel%20p%C3%A5%20data%3A%20f%C3%B6retagsnamn%20eller%20id%C3%A9namn%2C%20org.nr.%2C%20%C3%A4gare%2C%20kontaktinformation%2C%20vision%2C%20aff%C3%A4rsid%C3%A9%2C%20mm."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}}}return n},this.getNickname=async()=>{try{const t=n.split(".")[1],e=atob(t),o=JSON.parse(e),s=o.sub||o.userId,i=await fetch(`${a}app/GetNickname?userId=${s}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!i.ok)throw 401===i.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${i.statusText}`);return await i.text()}catch{return""}},this.getChatInstructions=async()=>{try{const t=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:1});if(t.length>0)return t[0].content}catch{console.warn("Error fetching chat instructions")}return""},this.updateChatInstructions=async t=>{try{const e=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:100}),o=`@${this.codicent} #instructions\n${t}`;e.length>0?e[0].content!==o&&(console.log("updating instructions",o),await window.Codicent.postMessage({message:o,type:"text",parentId:e[0].id})):(console.log("new instructions",o),await window.Codicent.postMessage({message:o,type:"text"}))}catch{console.warn("Error updating chat instructions")}},this.getUserInfo=async(t,e=!1)=>{const o=await fetch(`${a}app/GetUserInfo?nickname=${t}${e?"&t="+Date.now():""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);const n=await o.json(),{email:s,picture:i,description:r,followers:c,properties:h,owner:d}=n;return{nickname:t,email:s,name:r,picture:i,followers:c,properties:h,owner:d}},this.updateUserInfo=async({nickname:t,email:e,name:o,picture:n})=>{const s=await fetch(`${a}app/AddOrUpdateUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({nickname:t,email:e,name:o,picture:n,description:""})});if(!s.ok)throw s.status,new Error(`${s.statusText}`);return await this.getUserInfo(t,!0)},this.requestInvite=async(t,e)=>{const o=await fetch(`${a}app/CreateInvitationOrRequest?forUserNickname=${t}&toProjectNickname=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`requestInvite() => ${o.statusText}`),!1)},this.getProjectInfo=this.getUserInfo,this.updateMembersAccess=async(t,e)=>{const o=await fetch(`${a}app/AddOrUpdateProjectProperty?project=${t}&key=APP_EDITORS&value=${e.join(",")}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`updateMembersAccess() => ${o.statusText}`),!1)},this.getMembersAccess=async t=>{const e=(await this.getProjectInfo(t,!0)).properties.find((t=>"APP_EDITORS"===t.name));return e&&e.value?e.value.split(","):[]},this.getMemberInfo=async(t,e)=>{const o=await fetch(`${a}app/GetMemberInfo?projectNickname=${encodeURIComponent(t)}&memberNickname=${encodeURIComponent(e)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);return await o.json()},this.setToken=t=>{n=t,n&&window.Codicent.init({token:n,baseUrl:a})},this.getToken=()=>n,this.checkPurchaseStatus=async()=>{const t=await fetch(`${a}payments/GetPaymentStatus`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw new Error("Failed to check purchase status");const{isPaid:e}=await t.json();return e},this.checkSubscriptionStatus=async()=>{if(!this.options.SUBSCRIPTION_NEEDED)return"active";const t=await fetch(`${a}payments/GetSubscriptionStatus?t=${Date.now()}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`],["Cache-Control","no-cache, no-store, must-revalidate"],["Pragma","no-cache"],["Expires","0"]]});if(!t.ok)throw new Error("Failed to check subscription status");const{status:e}=await t.json();return e},this.createCheckoutSession=async t=>{const e=this.options.STRIPE_SOURCE,o={priceId:t,successUrl:window.location.href,cancelUrl:window.location.href};e&&(o.source=e);const n=await fetch(`${a}payments/CreateCheckoutSession`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify(o)});if(!n.ok)throw new Error("Failed to create checkout session");const{id:s}=await n.json();return s},this.redirectToCheckout=async t=>{const o=await e.loadStripe(this.options.STRIPE_PUBLIC_KEY);if(!o)throw new Error("Stripe failed to load");const a=await this.createCheckoutSession(t),{error:n}=await o.redirectToCheckout({sessionId:a});if(n)throw new Error(n.message)},this.getChatHistory=async t=>{const e=await fetch(`${a}api/GetMessageHistory?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get chat history");let o=await e.json();return o=o.filter((t=>!t.content.includes("#function_result")&&!t.content.includes("#finish_reason_function_call"))),o},this.getPublicFlow=async t=>{const e=await fetch(`${a}app/GetPublicFlow?codicent=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get public flow");const o=await e.json();return o.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),o},this.getMessageContent=async t=>{const e=await fetch(`${a}app/GetMessageContent?id=${t}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(e.ok){const t=await e.json();return{content:t.content,url:t.url}}return{content:"",url:""}},this.logAction=async(t,e)=>{if(!this.options.APP_LOG_CODICENT)return"";const o={content:`@${this.options.APP_LOG_CODICENT} #debug #${e}\n${t}`,type:"text"},n=await fetch(`${a}app/AddChatMessage`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.options.APP_LOG_TOKEN}`]],body:JSON.stringify(o)});if(!n.ok)throw new Error(`${n.statusText||"Failed to post log message!"}`);return(await n.json()).id},this.createApp=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.APP_PREFIX}${t}`;if(!await this.nicknameExists(e)){if(await this.cloneProject(this.options.APP_TEMPLATE,e)){if(this.options.ANONYMOUS_TOKEN)try{const t=this.options.ANONYMOUS_TOKEN.split(".")[1],o=atob(t),a=JSON.parse(o).nickname;if(!await this.addFollower(e,a))throw new Error("Failed to add follower: "+a)}catch(t){console.error("Error extracting adding anonymous follower:",t)}return e}}}}catch(t){console.error("Error creating app:",t)}return null},this.findUsername=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.USER_PREFIX}${t}`;if(!await this.nicknameExists(e))return e}}catch(t){console.warn("Error finding username:",t)}return null},this.getForms=async()=>{const t=await this.request(`${a}app/GetForms?codicent=${this.codicent}`,"GET",{headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await t.json()},this.getFormById=async t=>{const e=await fetch(`${a}app/GetFormById?id=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await e.json()},this.getTodoStatus=async t=>{const e=await fetch(`${a}app/GetTodoStatus?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return e.ok?await e.text():(e.status,console.warn(`getTodoStatus() => ${e.statusText}`),"unknown")},this.updateTodoStatus=async(t,e)=>{const o=await fetch(`${a}app/UpdateTodoStatus?messageId=${t}&status=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)return console.warn(`updateTodoStatus() => ${o.statusText}`),!1;return await o.json()},this.codicent="",this.options=t,s(t.API_BASE_URL)}async request(t,e,o={}){const a={};o.headers&&o.headers.forEach((([t,e])=>{a[t]=e}));const n=await fetch(t,{...o,method:e,headers:a});if(!n.ok)throw 401===n.status&&this.handleUnauthorized(),new Error(`${n.statusText}`);return n}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}async getRealtimeSessionToken(t="alloy",e="openai"){const o=`${a}realtime/session?voice=${t}&provider=${e}`,n=await fetch(o,{headers:{Authorization:`Bearer ${this.getToken()}`}});if(!n.ok)throw new Error(`Failed to fetch session token: ${n.statusText}`);const s=await n.json(),i=s.client_secret?.value;if(!i)throw new Error("No ephemeral key returned from session endpoint");return i}async getRealtimeConfig(t="openai"){try{const e=`${a}realtime/config?provider=${t}`,o=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${this.getToken()}`}});return o.ok?await o.json():null}catch(t){return console.warn("Failed to fetch realtime config:",t),null}}}t=c,c.getImageUrl=(t,e)=>`${a}app/GetImage?fileId=${t}&width=${e}`,c.getFileUrl=(t,e)=>`${a}app/DownloadFile?fileId=${t}${e?`&extension=${e}`:""}`,c.downloadFile=async e=>{fetch(t.getFileUrl(e.id)).then((t=>{if(t.headers.forEach(((t,e)=>{console.log(`${e}: ${t}`)})),t.ok)return t.blob();throw new Error("Network response was not ok.")})).then((t=>{const o=window.URL.createObjectURL(t),a=document.createElement("a");a.style.display="none",a.href=o,a.download=e.filename,document.body.appendChild(a),a.click(),window.URL.revokeObjectURL(o)})).catch((t=>{console.error("There was a problem with the fetch operation:",t)}))},c.getMiniChatReplyOld=async(t,e="codicent-mini",o)=>{let s={project:e,message:t};o&&(s.messageId=o);const i=await fetch(`${a}app/GetAi2ChatReply`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(s)});if(!i.ok)return void i.status;return(await i.json()).content.replace("@codicent-mini","").trim()},c.getMiniChatReply=async(t,e="codicent-mini",o,s=3e5,i=2e3)=>{const r={project:e,message:t};let c;o&&(r.messageId=o);try{const t=await fetch(`${a}app/StartAi2ChatAsync`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(r)});if(!t.ok)return t.status,void console.error(`Failed to start AI chat: ${t.status}`);if(c=(await t.json()).promptMessageId,!c)return void console.error("No promptMessageId returned from server")}catch(t){return void console.error("Error starting AI chat:",t)}const h=Date.now();for(;Date.now()-h<s;)try{const t=await fetch(`${a}app/GetAi2ChatReplyStatus?promptMessageId=${c}`,{method:"GET",headers:[["Authorization",`Bearer ${n}`]]});if(202===t.status){await new Promise((t=>setTimeout(t,i)));continue}if(!t.ok)return void console.error(`Error polling AI chat status: ${t.status}`);const o=await t.json();return o.content.replace(`@${e}`,"").replace("@codicent-mini","").trim()}catch(t){return void console.error("Error polling AI chat status:",t)}console.error("Polling timeout reached for AI chat")},c.getTranslations=async(t,e,o="codicent-mini")=>{const s=await fetch(`${a}app/GetTranslations`,{method:"POST",headers:{"Content-Type":"application/json; charset=utf-8",Authorization:`Bearer ${n}`},body:JSON.stringify({project:o,text:t,targetLanguage:e})});if(!s.ok)throw s.status,new Error(`Failed to get translations: ${s.statusText}`);return await s.json()},exports.CodicentService=c,exports.setBaseUrl=s;
1
+ "use strict";var t,e=require("../node_modules/@stripe/stripe-js/dist/index.js"),o=require("../utils/MessageContent.js");require("../node_modules/tinycolor2/esm/tinycolor.js"),require("react/jsx-runtime"),require("react"),require("../_virtual/index.js"),require("../config/index.js"),require("../utils/cacheManager.js"),require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js"),require("../lib/wavtools/lib/wav_stream_player.js"),require("../lib/wavtools/lib/wav_recorder.js");let a="https://codicent.com/",n="-";const s=t=>{t&&"string"==typeof t?(a=t.endsWith("/")?t:t+"/","undefined"!=typeof window&&void 0!==window.Codicent&&"function"==typeof window.Codicent.init&&window.Codicent.init({token:n,baseUrl:a})):console.warn("Invalid base URL provided, using default")},i=()=>void 0!==window.Codicent&&(window.Codicent.handleMessage=function(t){const e=new CustomEvent("codicent-log",{detail:{message:t}});window.dispatchEvent(e)},window.Codicent.init({token:n,baseUrl:a}),!0);let r=i();if(!r){const t=setInterval((()=>{r=i(),r&&clearInterval(t)}),100)}class c{constructor(t){this.createDataMessage=async(t,e,o)=>await window.Codicent.data.create({codicent:o||this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e,o,a,n)=>await window.Codicent.data.read({codicent:o||this.codicent,tag:t,search:e,start:a,length:n}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.updateDataMessage=async(t,e,o)=>await window.Codicent.data.update({id:t,data:e,codicent:o||this.codicent}),this.deleteDataMessage=async(t,e)=>await window.Codicent.data.delete({id:t,codicent:e||this.codicent}),this.getSchema=async(t,e)=>{try{const e=await fetch(`${this.options.API_BASE_URL}api/GetSchema/${t}`,{method:"GET",headers:{Authorization:`Bearer ${this.options.APP_LOG_TOKEN}`,"Content-Type":"application/json"}});if(!e.ok){if(404===e.status)return null;throw new Error(`Failed to fetch schema: ${e.statusText}`)}const o=await e.text();return JSON.parse(o)}catch(e){return console.error(`Error fetching schema for tag ${t}:`,e),null}},this.getAppTheme=async()=>{try{const t=await window.Codicent.getDataMessages({tags:["app-theme"],codicent:this.codicent});return t.length>0?t[0].data:null}catch(t){return console.error("Error fetching app theme:",t),null}},this.getAppButtons=async()=>{const t=(await window.Codicent.getDataMessages({tags:[this.options.BUTTON_TAG],codicent:this.codicent})).map((t=>t.data));return t.sort(((t,e)=>t.title>e.title?1:-1)),t},this.getAppTasks=async()=>(await window.Codicent.getMessages({search:`@${this.codicent} #app-task`,length:50})).map((t=>{const e=new o.default(t.content).content.split("\n"),a=e[0],n=e.slice(1).join("\n");return{id:t.id,title:a,content:n}})),this.getAppPrompts=async()=>(await window.Codicent.getDataMessages({tags:["chatprompt"],codicent:this.codicent})).map((t=>t.data)).map((({title:t,prompt:e})=>({title:t,prompt:e}))),this.uploadFile=async(t,e)=>await window.Codicent.upload(e,t),this.getFileInfo=async t=>await window.Codicent.getFileInfo(t),this.generateApiToken=async(t,e)=>{const o=await fetch(`${a}api/GenerateApiToken?project=${this.codicent}${t?`&expires=${t.toISOString()}`:""}${e?`&forUserNickname=${e}`:""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);return await o.text()},this.sendMessage=(t,e,o)=>window.Codicent.postMessage({message:`@${o||this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e,o)=>window.Codicent.getChatReply4({message:t,codicent:o||this.codicent,messageId:e}),this.getMessagesFast=async(t,e,o=100,n=void 0,s,i=0)=>{const r=await this.request(`${a}app/AppGetMessages`,"POST",{headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:s||this.codicent,search:e,start:i,length:o})});let c=await r.json();if(c.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),n){const t=await this.getPublicFlow(n);c=c.concat(t),c.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return c},this.getMessages=async(t,e,o=10)=>{let a=[];const n=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:o});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(n)).forEach((t=>{a=a.concat(t)})),e)try{const t=await this.getPublicFlow(e);a=a.concat(t)}catch(t){console.warn("Error fetching public flow, PUBLIC_TAG missing in codicent?",t)}return a=a.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id)))),a.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),a},this.registerUser=async(t,e,o,n)=>{const s=await fetch(`${a}app/RegisterAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!s.ok)return"";const i=await s.text();return window.Codicent.init({token:n,baseUrl:a}),i},this.loginUser=async(t,e)=>{try{const o=await fetch(`${a}app/LoginAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!o.ok)return 404===o.status||400===o.status?null:401===o.status?(this.handleUnauthorized(),null):"";const n=await o.text();return this.setToken(n),n}catch(t){return console.warn("Error logging in user:",t),""}},this.nicknameExists=async t=>{const e=await fetch(`${a}app/NicknameExists?nickname=${encodeURIComponent(t)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"]]});if(!e.ok)return!1;return await e.json()},this.logout=()=>{this.setToken("")},this.isRegistered=()=>null!==localStorage.getItem("codicent_nickname"),this.getApps=async()=>{try{const t=await fetch(`${a}app/AppGetApps`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw t.status,new Error(`${t.statusText}`);const e=(await t.json()).filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id))&&(this.options.APP_NAME||t.id.startsWith(this.options.APP_PREFIX))));return e}catch(t){return console.warn("Error fetching apps:",t),null}},this.addFollower=async(t,e)=>{const o=await fetch(`${a}app/AddFollower?nickname=${t}&followerNickname=${e}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText||"Failed to add follower!"}`);return await o.json()},this.cloneProject=async(t,e)=>{const o=await fetch(`${a}app/CloneProject?project=${t}&newProject=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);let n=await o.json();if(n){const t='#data #app-theme \n{\n "textcolor": "#212121",\n "backgroundcolor": "#273044",\n "color": "#ffffff",\n "logo": "https://codicent.com/logo512.png",\n "title": "",\n "themeColor": "#581d71",\n "buttonColor": "#c0c0c0",\n "buttonTextColor": "#000000",\n "font": "Montserrat",\n "welcome": "Hej {{username}}!",\n "chatPlaceholder": "Tjena, Loociz här! Vad vill du?",\n "textPlaceholder": "Skriv det du vill spara, så tar jag (Loociz alltså) hand om det!",\n "transcriptionInstructions": "Tryck på knappen för att start och sedan stoppa ljudinspelning."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}if(n){const t='#data #app-button\n{\n "title": "Ta fram företagsinfo",\n "url": "/#/chat?text=Hej!%20Jag%20vill%20spara%20f%C3%B6retagsinfo.%20Guida%20mig%20steg%20f%C3%B6r%20steg%2C%20ett%20i%20taget%2C%20tills%20vi%20har%20all%20info%20om%20mitt%20f%C3%B6retag.%20Exempel%20p%C3%A5%20data%3A%20f%C3%B6retagsnamn%20eller%20id%C3%A9namn%2C%20org.nr.%2C%20%C3%A4gare%2C%20kontaktinformation%2C%20vision%2C%20aff%C3%A4rsid%C3%A9%2C%20mm."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}}}return n},this.getNickname=async()=>{try{const t=n.split(".")[1],e=atob(t),o=JSON.parse(e),s=o.sub||o.userId,i=await fetch(`${a}app/GetNickname?userId=${s}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!i.ok)throw 401===i.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${i.statusText}`);return await i.text()}catch{return""}},this.getChatInstructions=async()=>{try{const t=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:1});if(t.length>0)return t[0].content}catch{console.warn("Error fetching chat instructions")}return""},this.updateChatInstructions=async t=>{try{const e=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:100}),o=`@${this.codicent} #instructions\n${t}`;e.length>0?e[0].content!==o&&(console.log("updating instructions",o),await window.Codicent.postMessage({message:o,type:"text",parentId:e[0].id})):(console.log("new instructions",o),await window.Codicent.postMessage({message:o,type:"text"}))}catch{console.warn("Error updating chat instructions")}},this.getUserInfo=async(t,e=!1)=>{const o=await fetch(`${a}app/GetUserInfo?nickname=${t}${e?"&t="+Date.now():""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);const n=await o.json(),{email:s,picture:i,description:r,followers:c,properties:h,owner:d}=n;return{nickname:t,email:s,name:r,picture:i,followers:c,properties:h,owner:d}},this.updateUserInfo=async({nickname:t,email:e,name:o,picture:n})=>{const s=await fetch(`${a}app/AddOrUpdateUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({nickname:t,email:e,name:o,picture:n,description:""})});if(!s.ok)throw s.status,new Error(`${s.statusText}`);return await this.getUserInfo(t,!0)},this.requestInvite=async(t,e)=>{const o=await fetch(`${a}app/CreateInvitationOrRequest?forUserNickname=${t}&toProjectNickname=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`requestInvite() => ${o.statusText}`),!1)},this.getProjectInfo=this.getUserInfo,this.updateMembersAccess=async(t,e)=>{const o=await fetch(`${a}app/AddOrUpdateProjectProperty?project=${t}&key=APP_EDITORS&value=${e.join(",")}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`updateMembersAccess() => ${o.statusText}`),!1)},this.getMembersAccess=async t=>{const e=(await this.getProjectInfo(t,!0)).properties.find((t=>"APP_EDITORS"===t.name));return e&&e.value?e.value.split(","):[]},this.getMemberInfo=async(t,e)=>{const o=await fetch(`${a}app/GetMemberInfo?projectNickname=${encodeURIComponent(t)}&memberNickname=${encodeURIComponent(e)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);return await o.json()},this.setToken=t=>{n=t,n&&window.Codicent.init({token:n,baseUrl:a})},this.getToken=()=>n,this.checkPurchaseStatus=async()=>{const t=await fetch(`${a}payments/GetPaymentStatus`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw new Error("Failed to check purchase status");const{isPaid:e}=await t.json();return e},this.checkSubscriptionStatus=async()=>{if(!this.options.SUBSCRIPTION_NEEDED)return"active";const t=await fetch(`${a}payments/GetSubscriptionStatus?t=${Date.now()}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`],["Cache-Control","no-cache, no-store, must-revalidate"],["Pragma","no-cache"],["Expires","0"]]});if(!t.ok)throw new Error("Failed to check subscription status");const{status:e}=await t.json();return e},this.createCheckoutSession=async t=>{const e=this.options.STRIPE_SOURCE,o=this.options.STRIPE_TRIAL_PERIOD_DAYS,n={priceId:t,successUrl:window.location.href,cancelUrl:window.location.href};e&&(n.source=e),o&&o>0&&(n.trialPeriodDays=o);const s=await fetch(`${a}payments/CreateCheckoutSession`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify(n)});if(!s.ok)throw new Error("Failed to create checkout session");const{id:i}=await s.json();return i},this.redirectToCheckout=async t=>{const o=await e.loadStripe(this.options.STRIPE_PUBLIC_KEY);if(!o)throw new Error("Stripe failed to load");const a=await this.createCheckoutSession(t),{error:n}=await o.redirectToCheckout({sessionId:a});if(n)throw new Error(n.message)},this.getChatHistory=async t=>{const e=await fetch(`${a}api/GetMessageHistory?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get chat history");let o=await e.json();return o=o.filter((t=>!t.content.includes("#function_result")&&!t.content.includes("#finish_reason_function_call"))),o},this.getPublicFlow=async t=>{const e=await fetch(`${a}app/GetPublicFlow?codicent=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get public flow");const o=await e.json();return o.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),o},this.getMessageContent=async t=>{const e=await fetch(`${a}app/GetMessageContent?id=${t}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(e.ok){const t=await e.json();return{content:t.content,url:t.url}}return{content:"",url:""}},this.logAction=async(t,e)=>{if(!this.options.APP_LOG_CODICENT)return"";const o={content:`@${this.options.APP_LOG_CODICENT} #debug #${e}\n${t}`,type:"text"},n=await fetch(`${a}app/AddChatMessage`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.options.APP_LOG_TOKEN}`]],body:JSON.stringify(o)});if(!n.ok)throw new Error(`${n.statusText||"Failed to post log message!"}`);return(await n.json()).id},this.createApp=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.APP_PREFIX}${t}`;if(!await this.nicknameExists(e)){if(await this.cloneProject(this.options.APP_TEMPLATE,e)){if(this.options.ANONYMOUS_TOKEN)try{const t=this.options.ANONYMOUS_TOKEN.split(".")[1],o=atob(t),a=JSON.parse(o).nickname;if(!await this.addFollower(e,a))throw new Error("Failed to add follower: "+a)}catch(t){console.error("Error extracting adding anonymous follower:",t)}return e}}}}catch(t){console.error("Error creating app:",t)}return null},this.findUsername=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.USER_PREFIX}${t}`;if(!await this.nicknameExists(e))return e}}catch(t){console.warn("Error finding username:",t)}return null},this.getForms=async()=>{const t=await this.request(`${a}app/GetForms?codicent=${this.codicent}`,"GET",{headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await t.json()},this.getFormById=async t=>{const e=await fetch(`${a}app/GetFormById?id=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await e.json()},this.getTodoStatus=async t=>{const e=await fetch(`${a}app/GetTodoStatus?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return e.ok?await e.text():(e.status,console.warn(`getTodoStatus() => ${e.statusText}`),"unknown")},this.updateTodoStatus=async(t,e)=>{const o=await fetch(`${a}app/UpdateTodoStatus?messageId=${t}&status=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)return console.warn(`updateTodoStatus() => ${o.statusText}`),!1;return await o.json()},this.codicent="",this.options=t,s(t.API_BASE_URL)}async request(t,e,o={}){const a={};o.headers&&o.headers.forEach((([t,e])=>{a[t]=e}));const n=await fetch(t,{...o,method:e,headers:a});if(!n.ok)throw 401===n.status&&this.handleUnauthorized(),new Error(`${n.statusText}`);return n}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}async getRealtimeSessionToken(t="alloy",e="openai"){const o=`${a}realtime/session?voice=${t}&provider=${e}`,n=await fetch(o,{headers:{Authorization:`Bearer ${this.getToken()}`}});if(!n.ok)throw new Error(`Failed to fetch session token: ${n.statusText}`);const s=await n.json(),i=s.client_secret?.value;if(!i)throw new Error("No ephemeral key returned from session endpoint");return i}async getRealtimeConfig(t="openai"){try{const e=`${a}realtime/config?provider=${t}`,o=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${this.getToken()}`}});return o.ok?await o.json():null}catch(t){return console.warn("Failed to fetch realtime config:",t),null}}}t=c,c.getImageUrl=(t,e)=>`${a}app/GetImage?fileId=${t}&width=${e}`,c.getFileUrl=(t,e)=>`${a}app/DownloadFile?fileId=${t}${e?`&extension=${e}`:""}`,c.downloadFile=async e=>{fetch(t.getFileUrl(e.id)).then((t=>{if(t.headers.forEach(((t,e)=>{console.log(`${e}: ${t}`)})),t.ok)return t.blob();throw new Error("Network response was not ok.")})).then((t=>{const o=window.URL.createObjectURL(t),a=document.createElement("a");a.style.display="none",a.href=o,a.download=e.filename,document.body.appendChild(a),a.click(),window.URL.revokeObjectURL(o)})).catch((t=>{console.error("There was a problem with the fetch operation:",t)}))},c.getMiniChatReplyOld=async(t,e="codicent-mini",o)=>{let s={project:e,message:t};o&&(s.messageId=o);const i=await fetch(`${a}app/GetAi2ChatReply`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(s)});if(!i.ok)return void i.status;return(await i.json()).content.replace("@codicent-mini","").trim()},c.getMiniChatReply=async(t,e="codicent-mini",o,s=3e5,i=2e3)=>{const r={project:e,message:t};let c;o&&(r.messageId=o);try{const t=await fetch(`${a}app/StartAi2ChatAsync`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(r)});if(!t.ok)return t.status,void console.error(`Failed to start AI chat: ${t.status}`);if(c=(await t.json()).promptMessageId,!c)return void console.error("No promptMessageId returned from server")}catch(t){return void console.error("Error starting AI chat:",t)}const h=Date.now();for(;Date.now()-h<s;)try{const t=await fetch(`${a}app/GetAi2ChatReplyStatus?promptMessageId=${c}`,{method:"GET",headers:[["Authorization",`Bearer ${n}`]]});if(202===t.status){await new Promise((t=>setTimeout(t,i)));continue}if(!t.ok)return void console.error(`Error polling AI chat status: ${t.status}`);const o=await t.json();return o.content.replace(`@${e}`,"").replace("@codicent-mini","").trim()}catch(t){return void console.error("Error polling AI chat status:",t)}console.error("Polling timeout reached for AI chat")},c.getTranslations=async(t,e,o="codicent-mini")=>{const s=await fetch(`${a}app/GetTranslations`,{method:"POST",headers:{"Content-Type":"application/json; charset=utf-8",Authorization:`Bearer ${n}`},body:JSON.stringify({project:o,text:t,targetLanguage:e})});if(!s.ok)throw s.status,new Error(`Failed to get translations: ${s.statusText}`);return await s.json()},exports.CodicentService=c,exports.setBaseUrl=s;
@@ -0,0 +1,188 @@
1
+ /**
2
+ * @fileoverview Public TypeScript type definitions for codicent-app-sdk
3
+ * @module codicent-app-sdk/types
4
+ * @public
5
+ */
6
+ /**
7
+ * Configuration for a button in the app navigation
8
+ * @public
9
+ */
10
+ export interface ButtonConfig {
11
+ /** Button title/label */
12
+ title: string;
13
+ /** Target URL or special action (e.g., "voice:...", "mailto:...", "./#/path") */
14
+ url: string;
15
+ /** Button type/style variant */
16
+ type?: string;
17
+ /** Required claim for button visibility (RBAC) */
18
+ claim?: string;
19
+ /** Inverse claim - hide button if user has this claim */
20
+ notClaim?: string;
21
+ /** Optional subtitle for compound buttons */
22
+ subtitle?: string;
23
+ /** Sub-buttons for multi-option buttons */
24
+ options?: ButtonConfig[];
25
+ }
26
+ import type { ColumnAction, ColumnDefinition } from "../components/ListView";
27
+ export type { ColumnAction, ColumnDefinition };
28
+ /**
29
+ * List definitions keyed by tag name (e.g., "customer2", "offertjson")
30
+ * @public
31
+ */
32
+ export interface ListDefinitions {
33
+ [tagName: string]: ColumnDefinition[];
34
+ }
35
+ /**
36
+ * AI chat instructions configuration
37
+ * @public
38
+ */
39
+ export interface ChatInstructions {
40
+ /** Text-based chat instructions (system prompt for chat AI) */
41
+ chat?: string;
42
+ /** Voice-based chat instructions (system prompt for voice AI) */
43
+ voice?: string;
44
+ }
45
+ /**
46
+ * Per-app configuration for multi-app SDK instances
47
+ * @public
48
+ */
49
+ export interface AppButtonsConfig {
50
+ /** Navigation buttons for this app */
51
+ buttons: ButtonConfig[];
52
+ /** Task definitions (legacy, may be deprecated) */
53
+ tasks: {
54
+ id: string;
55
+ title: string;
56
+ content: string;
57
+ }[];
58
+ /** Optional list of suggested questions for chat prompts */
59
+ questions?: string[];
60
+ /** Voice AI instructions for this app */
61
+ voiceInstructions: string;
62
+ /** Whether to show HTML view in this app */
63
+ showHtmlView?: boolean;
64
+ /** Text chat AI instructions for this app */
65
+ chatInstructions: string;
66
+ /** List view column definitions per tag */
67
+ listDefinitions?: ListDefinitions;
68
+ }
69
+ /**
70
+ * Translation dictionary: { [translationKey: string]: translatedText }
71
+ * @public
72
+ */
73
+ export interface TranslationDictionary {
74
+ [key: string]: string;
75
+ }
76
+ /**
77
+ * Translations map: { [languageCode: string]: TranslationDictionary }
78
+ * @public
79
+ */
80
+ export interface Translations {
81
+ [languageCode: string]: TranslationDictionary;
82
+ }
83
+ /**
84
+ * Feature module flags
85
+ * @public
86
+ */
87
+ export interface ModuleFlags {
88
+ /** Enable sales/CRM module */
89
+ sales?: boolean;
90
+ /** Enable voice AI module */
91
+ voice?: boolean;
92
+ /** Enable forms module */
93
+ forms?: boolean;
94
+ /** Enable search module */
95
+ search?: boolean;
96
+ /** Enable QR code scanning module */
97
+ qr?: boolean;
98
+ /** Enable snap/camera module */
99
+ snap?: boolean;
100
+ }
101
+ /**
102
+ * Props for ListView component
103
+ * @public
104
+ */
105
+ export interface ListViewProps {
106
+ /** Array of data records to display */
107
+ data: Record<string, unknown>[];
108
+ /** Column definitions (if omitted, auto-generates from data keys) */
109
+ columns?: ColumnDefinition[];
110
+ /** Enable edit action */
111
+ canEdit?: boolean;
112
+ /** Edit callback */
113
+ onEdit?: (item: Record<string, unknown>, index: number) => void;
114
+ /** Delete callback */
115
+ onDelete?: (item: Record<string, unknown>, index: number) => void;
116
+ /** Checkbox toggle callback */
117
+ onToggleCheckbox?: (item: Record<string, unknown>, key: string | string[], newValue: boolean, index: number) => void;
118
+ /** Callback when filtered data changes (for parent component to track) */
119
+ onFilteredDataChange?: (filteredData: Record<string, unknown>[]) => void;
120
+ }
121
+ /**
122
+ * Props for Chat component
123
+ * @public
124
+ */
125
+ export interface ChatProps {
126
+ /** Codicent/project to chat with */
127
+ codicent?: string;
128
+ /** Initial message to send on mount */
129
+ initialMessage?: string;
130
+ /** Custom chat instructions (overrides default) */
131
+ instructions?: string;
132
+ /** Show/hide message bar */
133
+ showMessageBar?: boolean;
134
+ /** Custom placeholder text for input */
135
+ placeholder?: string;
136
+ }
137
+ /**
138
+ * Schema definition for data tags
139
+ * @public
140
+ */
141
+ export interface SchemaDefinition {
142
+ /** JSON Schema for the tag */
143
+ schema: object;
144
+ /** UI hints for form generation */
145
+ uiSchema?: object;
146
+ }
147
+ export type { UserInfo, MemberInfo, AppInfo, Form, TranslationResponse, CodicentServiceOptions, } from "../services/codicent";
148
+ export type { AppConfig, AppConfigOptions } from "../config";
149
+ export type { CodicentAppState } from "../hooks/useCodicentApp";
150
+ /**
151
+ * Data message structure (returned by readDataMessages)
152
+ * Defined in global.d.ts as part of the Codicent global API
153
+ * @public
154
+ */
155
+ export interface DataMessage {
156
+ id: string;
157
+ fileId: string | null;
158
+ fileIds: string[];
159
+ data: {
160
+ [key: string]: string;
161
+ };
162
+ createdAt: string;
163
+ tags: string[];
164
+ mentions: string[];
165
+ }
166
+ /**
167
+ * File information structure
168
+ * @public
169
+ */
170
+ export interface FileInfo {
171
+ id: string;
172
+ filename: string;
173
+ contentType: string;
174
+ createdAt: string;
175
+ }
176
+ /**
177
+ * Generic message structure
178
+ * Note: There's also a Message interface in hooks/useChat that may differ
179
+ * @public
180
+ */
181
+ export interface CodicentMessage {
182
+ id: string;
183
+ content: string;
184
+ parentId?: string;
185
+ type?: string;
186
+ createdAt: Date;
187
+ }
188
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/types/index.ts"],"names":[],"mappings":"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"}
@@ -1 +1 @@
1
- {"version":3,"file":"appState.d.ts","sourceRoot":"","sources":["../../../src/utils/appState.ts"],"names":[],"mappings":"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"}
1
+ {"version":3,"file":"appState.d.ts","sourceRoot":"","sources":["../../../src/utils/appState.ts"],"names":[],"mappings":"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"}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("../_virtual/index.js"),e=require("../config/index.js"),i=require("./cacheManager.js");class n extends t.distExports.StateMachine{constructor(t,n){if(super(),this.context={isAuthenticated:void 0,hasAccess:!1,error:null,errorType:void 0,apps:[],hasApps:!1,appsLoaded:!1},this.currentStateName="",this.service=t,this.onStateChange=n,this.cacheManager=new i.CacheManager("state_machine"),e.getConfigValue("ENABLE_STATE_CACHE")&&e.getConfigValue("OPTIMISTIC_CACHE_LOAD")){const t=this.loadFromCache();t?this.hydrateFromCache(t):this.resetContext()}else this.resetContext();this.allStates=this.initializeStateMachine()}resetContext(){this.context={isAuthenticated:!1,isRegistered:void 0,hasValidPurchase:void 0,hasAccess:!1,selectedApp:void 0,error:null,errorType:void 0,accessToken:void 0,nickname:void 0,apps:[],hasApps:!1,appsLoaded:!1},e.getConfigValue("APP_NAME")?localStorage.removeItem("selectedApp"):this.context.selectedApp=localStorage.getItem("selectedApp")||void 0,e.getConfigValue("APP_PREFIX")&&this.context.selectedApp&&!this.context.selectedApp.startsWith(e.getConfigValue("APP_PREFIX"))?this.context.selectedApp=void 0:this.context.selectedApp}update(){super.update()}handlePurchase(){window.location.href="./#/purchase"}loadFromCache(){if(!e.getConfigValue("ENABLE_STATE_CACHE"))return null;const t=this.cacheManager.get("user_session");return t?this.isValidCacheStructure(t.data)?(console.log("AppStateMachine: Loaded session from cache",{nickname:t.data.nickname,selectedApp:t.data.selectedApp,appsCount:t.data.apps?.length||0,age:Math.round((Date.now()-t.cachedAt)/1e3)+"s"}),t.data):(console.warn("AppStateMachine: Invalid cache structure, clearing cache"),this.cacheManager.invalidate("user_session"),null):null}hydrateFromCache(t){this.context={...this.context,nickname:t.nickname,name:t.name,selectedApp:t.selectedApp,apps:t.apps,hasValidPurchase:t.hasValidPurchase,isRegistered:t.isRegistered,hasAccess:!0,hasApps:t.apps.length>0,appsLoaded:!0,isFromCache:!0,needsValidation:e.getConfigValue("VALIDATE_CACHE_IN_BACKGROUND")},t.selectedApp&&(this.service.codicent=t.selectedApp),e.getConfigValue("VALIDATE_CACHE_IN_BACKGROUND")&&this.scheduleBackgroundValidation()}isValidCacheStructure(t){return"object"==typeof t&&null!==t&&"string"==typeof t.nickname&&"string"==typeof t.selectedApp&&Array.isArray(t.apps)&&"boolean"==typeof t.isRegistered&&"boolean"==typeof t.hasValidPurchase}scheduleBackgroundValidation(){e.getConfigValue("VALIDATE_CACHE_IN_BACKGROUND")&&setTimeout((async()=>{try{const t=await Promise.all([this.validateRegistration(),this.validatePurchase(),this.validateApps()]);t.every((t=>t.valid))?(console.log("AppStateMachine: Background validation passed, updating cache"),this.saveToCache(),this.updateContext({needsValidation:!1})):(console.warn("AppStateMachine: Background validation failed",t),this.handleCacheValidationFailure(t))}catch(t){console.warn("AppStateMachine: Background validation error:",t)}}),100)}async validateRegistration(){try{const t=await this.service.getNickname();return{valid:t===this.context.nickname,data:{nickname:t}}}catch(t){return console.warn("AppStateMachine: Failed to validate registration",t),{valid:!1}}}async validatePurchase(){if(!e.getConfigValue("SUBSCRIPTION_NEEDED"))return{valid:!0};try{const t=await this.service.checkSubscriptionStatus();return{valid:"active"===t===this.context.hasValidPurchase,data:{hasValidPurchase:"active"===t}}}catch(t){return console.warn("AppStateMachine: Failed to validate purchase",t),{valid:!1}}}async validateApps(){try{let t=await this.service.getApps();if(null===t)return{valid:!1};e.getConfigValue("APP_PREFIX")&&(t=t.filter((t=>t.id.startsWith(e.getConfigValue("APP_PREFIX")))));return{valid:this.areAppsEqual(t,this.context.apps||[]),data:{apps:t}}}catch(t){return console.warn("AppStateMachine: Failed to validate apps",t),{valid:!1}}}areAppsEqual(t,e){return t.length===e.length&&t.every((t=>e.some((e=>e.id===t.id))))}handleCacheValidationFailure(t){"strict"===e.getConfigValue("CACHE_FAILURE_MODE")?(console.warn("AppStateMachine: Strict mode - invalidating cache"),this.cacheManager.invalidate("user_session"),this.updateContext({isFromCache:!1,needsValidation:!1,hasAccess:!1}),t[0].valid?!t[1].valid&&e.getConfigValue("SUBSCRIPTION_NEEDED")?this.current=this.allStates.needsPurchase:t[2].valid||(this.current=this.allStates.gettingApps):this.current=this.allStates.registering):(console.warn("AppStateMachine: Lenient mode - continuing with cache, marking as needing update"),this.updateContext({needsValidation:!0}),t.forEach((t=>{t.data&&this.updateContext(t.data)})),this.saveToCache()),this.update()}saveToCache(){if(!e.getConfigValue("ENABLE_STATE_CACHE"))return;if(!this.context.nickname||!this.context.selectedApp)return;const t={nickname:this.context.nickname,name:this.context.name||"",selectedApp:this.context.selectedApp,apps:this.context.apps||[],hasValidPurchase:this.context.hasValidPurchase||!1,isRegistered:this.context.isRegistered||!1,cachedAt:Date.now(),expiresAt:Date.now()+e.getConfigValue("SESSION_CACHE_TTL"),version:"1.0.0"};this.cacheManager.set("user_session",t,e.getConfigValue("SESSION_CACHE_TTL")),console.log("AppStateMachine: Saved session to cache")}initializeStateMachine(){const i=new t.distExports.State,n=new t.distExports.State({entering:()=>{this.context.selectedApp&&!this.service.codicent&&(this.service.codicent=this.context.selectedApp)}}),s=new t.distExports.State,a=new t.distExports.State,o=new t.distExports.State({entering:()=>{this.service.findUsername().then((t=>{t?this.service.nicknameExists(t).then((e=>{e?this.updateContext({error:"Användarnamnet finns redan.",errorType:"UsernameExists"}):this.service.registerUser(t,this.context.user.email,this.context.user.sub,this.context.accessToken).then((()=>{this.service.setToken(this.context.accessToken),this.updateContext({nickname:t,isRegistered:!0})})).catch((t=>{console.warn("Failed to register account",t),this.updateContext({error:"Ett fel uppstod vid registrering. Försök igen senare.",errorType:"ErrorRegistering"})}))})).catch((t=>{console.warn("Failed to check username",t),this.updateContext({error:"Ett fel uppstod vid kontroll av användarnamn.",errorType:"ErrorCheckingUsername"})})):this.updateContext({error:"Användarnamn kunde inte hittas.",errorType:"NoUsernameFound"})})).catch((t=>{console.warn("Failed to find username",t),this.updateContext({error:"Ett fel uppstod vid sökning av användarnamn.",errorType:"ErrorFindingUsername"})}))}}),r=new t.distExports.State,c=new t.distExports.State({entering:()=>{this.checkPurchase()}}),d=new t.distExports.State({entering:()=>{this.handlePurchase()}}),h=new t.distExports.State({entering:()=>{this.getApps()}}),p=new t.distExports.State,l=new t.distExports.State,g=new t.distExports.State({entering:()=>{e.getConfigValue("ENABLE_STATE_CACHE")&&!this.context.isFromCache&&this.saveToCache()}}),u=new t.distExports.State,A=new t.distExports.State({entering:()=>{this.context.nickname&&(localStorage.setItem("nickname",this.context.nickname),this.service.getUserInfo(this.context.nickname).then((t=>{const e=t?.name||t?.nickname||"";this.updateContext({name:e})})).catch((t=>this.updateContext({error:t.toString(),errorType:"ErrorLoadingUser"}))))}}),x=new t.distExports.State({entering:()=>{e.getConfigValue("ENABLE_STATE_CACHE")&&this.cacheManager.clear(),localStorage.removeItem("selectedApp"),localStorage.removeItem("nickname"),localStorage.removeItem("codicent"),sessionStorage.clear(),this.updateContext({isAuthenticated:!1,isRegistered:void 0,apps:[],hasApps:!1,selectedApp:void 0,accessToken:void 0,user:void 0,isFromCache:!1,needsValidation:!1}),setTimeout((()=>{this.current=this.allStates.initial}),1e3)}}),C=new t.distExports.State({entering:()=>{this.service.createApp().then((t=>{t?(this.service.codicent=t,this.updateContext({selectedApp:t,apps:[...this.context.apps||[],{id:t,title:t,logo:""}]})):this.updateContext({error:"Misslyckades att skapa din app. Försök igen senare.",errorType:"ErrorCreatingApp"})})).catch((t=>{console.warn("Error creating app",t),this.updateContext({error:"Misslyckades att skapa din app. Försök igen senare.",errorType:"ErrorCreatingApp"})}))}}),E=new t.distExports.State({entering:()=>{this.service.loginUser(this.context.user.sub,this.context.accessToken).then((t=>{null===t?this.updateContext({isRegistered:!1}):""===t?this.updateContext({isRegistered:!1,error:"Kunde inte logga in hos Codicent.",errorType:"CodicentLoginFailed"}):(this.service.setToken(this.context.accessToken),this.service.getNickname().then((t=>{t?this.updateContext({isRegistered:!0,nickname:t}):this.updateContext({error:"Kunde inte hitta användarnamn.",errorType:"ErrorFindingUsername"})})).catch((()=>{this.updateContext({error:"Fel vid hämtning av användarnamn.",errorType:"ErrorFindingUsername"})})))})).catch((()=>{this.updateContext({isRegistered:!1,error:"Fel vid inloggning hos Codicent.",errorType:"CodicentLoginError"})}))}}),T=new t.distExports.State({entering:()=>{this.service.setToken(e.getConfigValue("ANONYMOUS_TOKEN")),this.service.codicent=e.getConfigValue("ANONYMOUS_CODICENT")||e.getConfigValue("APP_NAME")||""}}),S=new t.distExports.State({entering:()=>{console.log("AppStateMachine: State - restoring from cache")}}),v=new t.distExports.State({entering:()=>{console.log("AppStateMachine: State - validating cache")}});i.addTransition(S,{condition:()=>!0===this.context.isFromCache&&e.getConfigValue("ENABLE_STATE_CACHE")}),i.addTransition(n,{condition:()=>!this.context.isFromCache||!e.getConfigValue("ENABLE_STATE_CACHE")}),S.addTransition(g,{condition:()=>!0===this.context.hasAccess&&!0===this.context.isFromCache}),S.addTransition(n,{condition:()=>!this.context.hasAccess||!this.context.isFromCache}),n.addTransition(a,{condition:()=>!0===this.context.isAuthenticated}),n.addTransition(u,{condition:()=>Boolean(this.context.error)}),n.addTransition(s,{condition:()=>!1===this.context.isAuthenticated}),s.addTransition(a,{condition:()=>!0===this.context.isAuthenticated}),s.addTransition(u,{condition:()=>!!this.context.error}),a.addTransition(E,{}),E.addTransition(o,{condition:()=>!1===this.context.isRegistered}),E.addTransition(r,{condition:()=>!0===this.context.isRegistered}),E.addTransition(u,{condition:()=>!!this.context.error}),r.addTransition(A,{condition:()=>!!this.context.nickname}),r.addTransition(u,{condition:()=>!this.context.nickname,action:()=>this.updateContext({error:"Missing nickname after registration",errorType:"ErrorLoadingUser"})}),c.addTransition(d,{condition:()=>!1===this.context.hasValidPurchase}),c.addTransition(h,{condition:()=>!0===this.context.hasValidPurchase}),h.addTransition(u,{condition:()=>!!this.context.error,action:()=>console.log("getting apps -> error")}),h.addTransition(p,{condition:()=>!!e.getConfigValue("APP_NAME")&&this.context.hasApps}),h.addTransition(C,{condition:()=>!e.getConfigValue("APP_NAME")&&this.context.appsLoaded&&0===this.context.apps.length,action:()=>this.updateContext({selectedApp:void 0})}),h.addTransition(p,{condition:()=>!e.getConfigValue("APP_NAME")&&this.context.hasApps&&this.context.apps.length>0}),C.addTransition(p,{condition:()=>!!this.context.selectedApp}),C.addTransition(u,{condition:()=>!!this.context.error}),p.addTransition(g,{condition:()=>!e.getConfigValue("APP_NAME")&&this.context.apps.some((t=>t.id===this.context.selectedApp)),action:()=>{this.service.codicent=this.context.selectedApp||"",localStorage.setItem("selectedApp",this.context.selectedApp||"")}}),p.addTransition(g,{condition:()=>!e.getConfigValue("APP_NAME")&&!this.context.selectedApp,action:()=>{const t=this.context.apps[0].id;this.context.selectedApp!==t&&(this.service.codicent=t,localStorage.setItem("selectedApp",t),this.updateContext({selectedApp:t}))}}),p.addTransition(g,{condition:()=>this.context.apps.some((t=>t.id===e.getConfigValue("APP_NAME"))),action:()=>{const t=e.getConfigValue("APP_NAME");this.context.selectedApp!==t&&(this.service.codicent=t,this.updateContext({selectedApp:t}))}}),p.addTransition(l,{condition:()=>!this.context.apps.some((t=>t.id===this.context.selectedApp||t.id===e.getConfigValue("APP_NAME"))),action:()=>console.log("checking access -> no access",this.context.apps,this.context.selectedApp,e.getConfigValue("APP_NAME"))}),g.addTransition(A,{condition:()=>!!localStorage.getItem("selectedApp")&&localStorage.getItem("selectedApp")!==this.context.selectedApp,action:()=>{this.service.codicent=localStorage.getItem("selectedApp")||"",this.updateContext({selectedApp:localStorage.getItem("selectedApp")||void 0})}}),o.addTransition(r,{condition:()=>!0===this.context.isRegistered}),o.addTransition(u,{condition:()=>!!this.context.error}),d.addTransition(c,{condition:()=>void 0===this.context.hasValidPurchase,action:()=>{window.history.replaceState({},document.title,window.location.pathname),this.checkPurchase()}}),[n,h,c,E,o].forEach((t=>{t.addTransition(u,{condition:()=>this.context.error?.includes("network")||this.context.error?.includes("connectivity")||!1}),t.addTransition(u,{condition:()=>!!this.context.error})})),[a,r,g,l].forEach((t=>{t.addTransition(x,{condition:()=>!1===this.context.isAuthenticated})})),r.addTransition(A,{condition:()=>!this.context.user&&!!this.context.nickname}),A.addTransition(c,{condition:()=>!!this.context.name&&e.getConfigValue("SUBSCRIPTION_NEEDED")}),A.addTransition(h,{condition:()=>!!this.context.name&&!e.getConfigValue("SUBSCRIPTION_NEEDED")}),u.addTransition(c,{condition:()=>!this.context.error&&"ErrorCheckingPurchase"!==this.context.errorType}),u.addTransition(h,{condition:()=>!this.context.error&&"ErrorGettingApps"!==this.context.errorType}),u.addTransition(p,{condition:()=>!this.context.error&&"ErrorCheckingAccess"!==this.context.errorType}),u.addTransition(A,{condition:()=>!this.context.error&&"ErrorLoadingUser"!==this.context.errorType}),u.addTransition(C,{condition:()=>!this.context.error&&"ErrorCreatingApp"!==this.context.errorType}),u.addTransition(E,{condition:()=>!this.context.error&&"CodicentLoginFailed"!==this.context.errorType}),x.addTransition(i,{condition:()=>!this.context.isAuthenticated&&!this.context.accessToken}),[i,g,s,u,x,n,a,r].forEach((t=>{t.addTransition(T,{condition:()=>!0===this.context.isAnonymous&&!!e.getConfigValue("ANONYMOUS_TOKEN")})}));const m={initial:i,authenticating:n,notAuthenticated:s,authenticated:a,checkingCodicentAccess:E,registering:o,registered:r,checkingPurchase:c,needsPurchase:d,gettingApps:h,creatingApp:C,checkingAccess:p,noAccess:l,error:u,loadingUser:A,loggingOut:x,hasAccess:g,anonymous:T,restoringFromCache:S,validatingCache:v};return this.states.push(...Object.values(m)),this.current=m.initial,m}get error(){return this.context.error}checkPurchase(){this.service.checkSubscriptionStatus().then((t=>this.updateContext({hasValidPurchase:"active"===t}))).catch((t=>this.updateContext({error:t.toString(),errorType:"ErrorCheckingPurchase"})))}getApps(){this.service.getApps().then((t=>{if(null===t)throw new Error("Failed to fetch apps.");e.getConfigValue("APP_PREFIX")&&(t=t.filter((t=>t.id.startsWith(e.getConfigValue("APP_PREFIX"))))),this.updateContext({apps:t,hasApps:!0,appsLoaded:!0}),this.context.selectedApp&&!t.some((t=>t.id===this.context.selectedApp))&&this.updateContext({selectedApp:void 0})})).catch((t=>this.updateContext({error:t.toString(),errorType:"ErrorGettingApps"})))}setUser(t){this.context.user=t}getContext(){return{...this.context}}updateContext(t){this.context={...this.context,...t}}getCurrentStateName(){const t=Object.entries(this.allStates).find((([t,e])=>e===this.current));return t?t[0]:""}logout(){e.getConfigValue("ENABLE_STATE_CACHE")&&this.cacheManager.clear(),localStorage.clear(),sessionStorage.clear(),this.resetContext()}setSelectedApp(t){localStorage.setItem("selectedApp",t),this.update()}isBusy(){return this.current===this.allStates.gettingApps||this.current===this.allStates.checkingPurchase||this.current===this.allStates.checkingAccess||this.current===this.allStates.checkingCodicentAccess||this.current===this.allStates.registering||this.current===this.allStates.loadingUser||this.current===this.allStates.creatingApp||this.current===this.allStates.loggingOut}}exports.AppStateMachine=n,exports.createAppStateMachine=(t,e)=>new n(t,e),exports.default=n;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("../_virtual/index.js"),e=require("../config/index.js"),i=require("./cacheManager.js");class n extends t.distExports.StateMachine{constructor(t,n){if(super(),this.context={isAuthenticated:void 0,hasAccess:!1,error:null,errorType:void 0,apps:[],hasApps:!1,appsLoaded:!1},this.currentStateName="",this.service=t,this.onStateChange=n,this.cacheManager=new i.CacheManager("state_machine"),e.getConfigValue("ENABLE_STATE_CACHE")&&e.getConfigValue("OPTIMISTIC_CACHE_LOAD")){const t=this.loadFromCache();t?this.hydrateFromCache(t):this.resetContext()}else this.resetContext();this.allStates=this.initializeStateMachine()}resetContext(){this.context={isAuthenticated:!1,isRegistered:void 0,hasValidPurchase:void 0,hasAccess:!1,selectedApp:void 0,error:null,errorType:void 0,accessToken:void 0,nickname:void 0,apps:[],hasApps:!1,appsLoaded:!1},e.getConfigValue("APP_NAME")?localStorage.removeItem("selectedApp"):this.context.selectedApp=localStorage.getItem("selectedApp")||void 0,e.getConfigValue("APP_PREFIX")&&this.context.selectedApp&&!this.context.selectedApp.startsWith(e.getConfigValue("APP_PREFIX"))?this.context.selectedApp=void 0:this.context.selectedApp}update(){super.update()}handlePurchase(){window.location.href="./#/purchase"}loadFromCache(){if(!e.getConfigValue("ENABLE_STATE_CACHE"))return null;const t=this.cacheManager.get("user_session");return t?this.isValidCacheStructure(t.data)?(console.log("AppStateMachine: Loaded session from cache",{nickname:t.data.nickname,selectedApp:t.data.selectedApp,appsCount:t.data.apps?.length||0,age:Math.round((Date.now()-t.cachedAt)/1e3)+"s"}),t.data):(console.warn("AppStateMachine: Invalid cache structure, clearing cache"),this.cacheManager.invalidate("user_session"),null):null}hydrateFromCache(t){this.context={...this.context,nickname:t.nickname,name:t.name,selectedApp:t.selectedApp,apps:t.apps,hasValidPurchase:t.hasValidPurchase,isRegistered:t.isRegistered,hasAccess:!0,hasApps:t.apps.length>0,appsLoaded:!0,isFromCache:!0,needsValidation:e.getConfigValue("VALIDATE_CACHE_IN_BACKGROUND")},t.selectedApp&&(this.service.codicent=t.selectedApp),e.getConfigValue("VALIDATE_CACHE_IN_BACKGROUND")&&this.scheduleBackgroundValidation()}isValidCacheStructure(t){return"object"==typeof t&&null!==t&&"string"==typeof t.nickname&&"string"==typeof t.selectedApp&&Array.isArray(t.apps)&&"boolean"==typeof t.isRegistered&&"boolean"==typeof t.hasValidPurchase}scheduleBackgroundValidation(){e.getConfigValue("VALIDATE_CACHE_IN_BACKGROUND")&&setTimeout((async()=>{try{const t=await Promise.all([this.validateRegistration(),this.validatePurchase(),this.validateApps()]);t.every((t=>t.valid))?(console.log("AppStateMachine: Background validation passed, updating cache"),this.saveToCache(),this.updateContext({needsValidation:!1})):(console.warn("AppStateMachine: Background validation failed",t),this.handleCacheValidationFailure(t))}catch(t){console.warn("AppStateMachine: Background validation error:",t)}}),100)}async validateRegistration(){try{const t=await this.service.getNickname();return{valid:t===this.context.nickname,data:{nickname:t}}}catch(t){return console.warn("AppStateMachine: Failed to validate registration",t),{valid:!1}}}async validatePurchase(){if(!e.getConfigValue("SUBSCRIPTION_NEEDED"))return{valid:!0};try{const t=await this.service.checkSubscriptionStatus(),e="active"===t||"trialing"===t;return{valid:e===this.context.hasValidPurchase,data:{hasValidPurchase:e}}}catch(t){return console.warn("AppStateMachine: Failed to validate purchase",t),{valid:!1}}}async validateApps(){try{let t=await this.service.getApps();if(null===t)return{valid:!1};e.getConfigValue("APP_PREFIX")&&(t=t.filter((t=>t.id.startsWith(e.getConfigValue("APP_PREFIX")))));return{valid:this.areAppsEqual(t,this.context.apps||[]),data:{apps:t}}}catch(t){return console.warn("AppStateMachine: Failed to validate apps",t),{valid:!1}}}areAppsEqual(t,e){return t.length===e.length&&t.every((t=>e.some((e=>e.id===t.id))))}handleCacheValidationFailure(t){"strict"===e.getConfigValue("CACHE_FAILURE_MODE")?(console.warn("AppStateMachine: Strict mode - invalidating cache"),this.cacheManager.invalidate("user_session"),this.updateContext({isFromCache:!1,needsValidation:!1,hasAccess:!1}),t[0].valid?!t[1].valid&&e.getConfigValue("SUBSCRIPTION_NEEDED")?this.current=this.allStates.needsPurchase:t[2].valid||(this.current=this.allStates.gettingApps):this.current=this.allStates.registering):(console.warn("AppStateMachine: Lenient mode - continuing with cache, marking as needing update"),this.updateContext({needsValidation:!0}),t.forEach((t=>{t.data&&this.updateContext(t.data)})),this.saveToCache()),this.update()}saveToCache(){if(!e.getConfigValue("ENABLE_STATE_CACHE"))return;if(!this.context.nickname||!this.context.selectedApp)return;const t={nickname:this.context.nickname,name:this.context.name||"",selectedApp:this.context.selectedApp,apps:this.context.apps||[],hasValidPurchase:this.context.hasValidPurchase||!1,isRegistered:this.context.isRegistered||!1,cachedAt:Date.now(),expiresAt:Date.now()+e.getConfigValue("SESSION_CACHE_TTL"),version:"1.0.0"};this.cacheManager.set("user_session",t,e.getConfigValue("SESSION_CACHE_TTL")),console.log("AppStateMachine: Saved session to cache")}initializeStateMachine(){const i=new t.distExports.State,n=new t.distExports.State({entering:()=>{this.context.selectedApp&&!this.service.codicent&&(this.service.codicent=this.context.selectedApp)}}),s=new t.distExports.State,a=new t.distExports.State,o=new t.distExports.State({entering:()=>{this.service.findUsername().then((t=>{t?this.service.nicknameExists(t).then((e=>{e?this.updateContext({error:"Användarnamnet finns redan.",errorType:"UsernameExists"}):this.service.registerUser(t,this.context.user.email,this.context.user.sub,this.context.accessToken).then((()=>{this.service.setToken(this.context.accessToken),this.updateContext({nickname:t,isRegistered:!0})})).catch((t=>{console.warn("Failed to register account",t),this.updateContext({error:"Ett fel uppstod vid registrering. Försök igen senare.",errorType:"ErrorRegistering"})}))})).catch((t=>{console.warn("Failed to check username",t),this.updateContext({error:"Ett fel uppstod vid kontroll av användarnamn.",errorType:"ErrorCheckingUsername"})})):this.updateContext({error:"Användarnamn kunde inte hittas.",errorType:"NoUsernameFound"})})).catch((t=>{console.warn("Failed to find username",t),this.updateContext({error:"Ett fel uppstod vid sökning av användarnamn.",errorType:"ErrorFindingUsername"})}))}}),r=new t.distExports.State,c=new t.distExports.State({entering:()=>{this.checkPurchase()}}),d=new t.distExports.State({entering:()=>{this.handlePurchase()}}),h=new t.distExports.State({entering:()=>{this.getApps()}}),p=new t.distExports.State,l=new t.distExports.State,g=new t.distExports.State({entering:()=>{e.getConfigValue("ENABLE_STATE_CACHE")&&!this.context.isFromCache&&this.saveToCache()}}),u=new t.distExports.State,A=new t.distExports.State({entering:()=>{this.context.nickname&&(localStorage.setItem("nickname",this.context.nickname),this.service.getUserInfo(this.context.nickname).then((t=>{const e=t?.name||t?.nickname||"";this.updateContext({name:e})})).catch((t=>this.updateContext({error:t.toString(),errorType:"ErrorLoadingUser"}))))}}),x=new t.distExports.State({entering:()=>{e.getConfigValue("ENABLE_STATE_CACHE")&&this.cacheManager.clear(),localStorage.removeItem("selectedApp"),localStorage.removeItem("nickname"),localStorage.removeItem("codicent"),sessionStorage.clear(),this.updateContext({isAuthenticated:!1,isRegistered:void 0,apps:[],hasApps:!1,selectedApp:void 0,accessToken:void 0,user:void 0,isFromCache:!1,needsValidation:!1}),setTimeout((()=>{this.current=this.allStates.initial}),1e3)}}),C=new t.distExports.State({entering:()=>{this.service.createApp().then((t=>{t?(this.service.codicent=t,this.updateContext({selectedApp:t,apps:[...this.context.apps||[],{id:t,title:t,logo:""}]})):this.updateContext({error:"Misslyckades att skapa din app. Försök igen senare.",errorType:"ErrorCreatingApp"})})).catch((t=>{console.warn("Error creating app",t),this.updateContext({error:"Misslyckades att skapa din app. Försök igen senare.",errorType:"ErrorCreatingApp"})}))}}),E=new t.distExports.State({entering:()=>{this.service.loginUser(this.context.user.sub,this.context.accessToken).then((t=>{null===t?this.updateContext({isRegistered:!1}):""===t?this.updateContext({isRegistered:!1,error:"Kunde inte logga in hos Codicent.",errorType:"CodicentLoginFailed"}):(this.service.setToken(this.context.accessToken),this.service.getNickname().then((t=>{t?this.updateContext({isRegistered:!0,nickname:t}):this.updateContext({error:"Kunde inte hitta användarnamn.",errorType:"ErrorFindingUsername"})})).catch((()=>{this.updateContext({error:"Fel vid hämtning av användarnamn.",errorType:"ErrorFindingUsername"})})))})).catch((()=>{this.updateContext({isRegistered:!1,error:"Fel vid inloggning hos Codicent.",errorType:"CodicentLoginError"})}))}}),T=new t.distExports.State({entering:()=>{this.service.setToken(e.getConfigValue("ANONYMOUS_TOKEN")),this.service.codicent=e.getConfigValue("ANONYMOUS_CODICENT")||e.getConfigValue("APP_NAME")||""}}),S=new t.distExports.State({entering:()=>{console.log("AppStateMachine: State - restoring from cache")}}),v=new t.distExports.State({entering:()=>{console.log("AppStateMachine: State - validating cache")}});i.addTransition(S,{condition:()=>!0===this.context.isFromCache&&e.getConfigValue("ENABLE_STATE_CACHE")}),i.addTransition(n,{condition:()=>!this.context.isFromCache||!e.getConfigValue("ENABLE_STATE_CACHE")}),S.addTransition(g,{condition:()=>!0===this.context.hasAccess&&!0===this.context.isFromCache}),S.addTransition(n,{condition:()=>!this.context.hasAccess||!this.context.isFromCache}),n.addTransition(a,{condition:()=>!0===this.context.isAuthenticated}),n.addTransition(u,{condition:()=>Boolean(this.context.error)}),n.addTransition(s,{condition:()=>!1===this.context.isAuthenticated}),s.addTransition(a,{condition:()=>!0===this.context.isAuthenticated}),s.addTransition(u,{condition:()=>!!this.context.error}),a.addTransition(E,{}),E.addTransition(o,{condition:()=>!1===this.context.isRegistered}),E.addTransition(r,{condition:()=>!0===this.context.isRegistered}),E.addTransition(u,{condition:()=>!!this.context.error}),r.addTransition(A,{condition:()=>!!this.context.nickname}),r.addTransition(u,{condition:()=>!this.context.nickname,action:()=>this.updateContext({error:"Missing nickname after registration",errorType:"ErrorLoadingUser"})}),c.addTransition(d,{condition:()=>!1===this.context.hasValidPurchase}),c.addTransition(h,{condition:()=>!0===this.context.hasValidPurchase}),h.addTransition(u,{condition:()=>!!this.context.error,action:()=>console.log("getting apps -> error")}),h.addTransition(p,{condition:()=>!!e.getConfigValue("APP_NAME")&&this.context.hasApps}),h.addTransition(C,{condition:()=>!e.getConfigValue("APP_NAME")&&this.context.appsLoaded&&0===this.context.apps.length,action:()=>this.updateContext({selectedApp:void 0})}),h.addTransition(p,{condition:()=>!e.getConfigValue("APP_NAME")&&this.context.hasApps&&this.context.apps.length>0}),C.addTransition(p,{condition:()=>!!this.context.selectedApp}),C.addTransition(u,{condition:()=>!!this.context.error}),p.addTransition(g,{condition:()=>!e.getConfigValue("APP_NAME")&&this.context.apps.some((t=>t.id===this.context.selectedApp)),action:()=>{this.service.codicent=this.context.selectedApp||"",localStorage.setItem("selectedApp",this.context.selectedApp||"")}}),p.addTransition(g,{condition:()=>!e.getConfigValue("APP_NAME")&&!this.context.selectedApp,action:()=>{const t=this.context.apps[0].id;this.context.selectedApp!==t&&(this.service.codicent=t,localStorage.setItem("selectedApp",t),this.updateContext({selectedApp:t}))}}),p.addTransition(g,{condition:()=>this.context.apps.some((t=>t.id===e.getConfigValue("APP_NAME"))),action:()=>{const t=e.getConfigValue("APP_NAME");this.context.selectedApp!==t&&(this.service.codicent=t,this.updateContext({selectedApp:t}))}}),p.addTransition(l,{condition:()=>!this.context.apps.some((t=>t.id===this.context.selectedApp||t.id===e.getConfigValue("APP_NAME"))),action:()=>console.log("checking access -> no access",this.context.apps,this.context.selectedApp,e.getConfigValue("APP_NAME"))}),g.addTransition(A,{condition:()=>!!localStorage.getItem("selectedApp")&&localStorage.getItem("selectedApp")!==this.context.selectedApp,action:()=>{this.service.codicent=localStorage.getItem("selectedApp")||"",this.updateContext({selectedApp:localStorage.getItem("selectedApp")||void 0})}}),o.addTransition(r,{condition:()=>!0===this.context.isRegistered}),o.addTransition(u,{condition:()=>!!this.context.error}),d.addTransition(c,{condition:()=>void 0===this.context.hasValidPurchase,action:()=>{window.history.replaceState({},document.title,window.location.pathname),this.checkPurchase()}}),[n,h,c,E,o].forEach((t=>{t.addTransition(u,{condition:()=>this.context.error?.includes("network")||this.context.error?.includes("connectivity")||!1}),t.addTransition(u,{condition:()=>!!this.context.error})})),[a,r,g,l].forEach((t=>{t.addTransition(x,{condition:()=>!1===this.context.isAuthenticated})})),r.addTransition(A,{condition:()=>!this.context.user&&!!this.context.nickname}),A.addTransition(c,{condition:()=>!!this.context.name&&e.getConfigValue("SUBSCRIPTION_NEEDED")}),A.addTransition(h,{condition:()=>!!this.context.name&&!e.getConfigValue("SUBSCRIPTION_NEEDED")}),u.addTransition(c,{condition:()=>!this.context.error&&"ErrorCheckingPurchase"!==this.context.errorType}),u.addTransition(h,{condition:()=>!this.context.error&&"ErrorGettingApps"!==this.context.errorType}),u.addTransition(p,{condition:()=>!this.context.error&&"ErrorCheckingAccess"!==this.context.errorType}),u.addTransition(A,{condition:()=>!this.context.error&&"ErrorLoadingUser"!==this.context.errorType}),u.addTransition(C,{condition:()=>!this.context.error&&"ErrorCreatingApp"!==this.context.errorType}),u.addTransition(E,{condition:()=>!this.context.error&&"CodicentLoginFailed"!==this.context.errorType}),x.addTransition(i,{condition:()=>!this.context.isAuthenticated&&!this.context.accessToken}),[i,g,s,u,x,n,a,r].forEach((t=>{t.addTransition(T,{condition:()=>!0===this.context.isAnonymous&&!!e.getConfigValue("ANONYMOUS_TOKEN")})}));const m={initial:i,authenticating:n,notAuthenticated:s,authenticated:a,checkingCodicentAccess:E,registering:o,registered:r,checkingPurchase:c,needsPurchase:d,gettingApps:h,creatingApp:C,checkingAccess:p,noAccess:l,error:u,loadingUser:A,loggingOut:x,hasAccess:g,anonymous:T,restoringFromCache:S,validatingCache:v};return this.states.push(...Object.values(m)),this.current=m.initial,m}get error(){return this.context.error}checkPurchase(){this.service.checkSubscriptionStatus().then((t=>this.updateContext({hasValidPurchase:"active"===t||"trialing"===t}))).catch((t=>this.updateContext({error:t.toString(),errorType:"ErrorCheckingPurchase"})))}getApps(){this.service.getApps().then((t=>{if(null===t)throw new Error("Failed to fetch apps.");e.getConfigValue("APP_PREFIX")&&(t=t.filter((t=>t.id.startsWith(e.getConfigValue("APP_PREFIX"))))),this.updateContext({apps:t,hasApps:!0,appsLoaded:!0}),this.context.selectedApp&&!t.some((t=>t.id===this.context.selectedApp))&&this.updateContext({selectedApp:void 0})})).catch((t=>this.updateContext({error:t.toString(),errorType:"ErrorGettingApps"})))}setUser(t){this.context.user=t}getContext(){return{...this.context}}updateContext(t){this.context={...this.context,...t}}getCurrentStateName(){const t=Object.entries(this.allStates).find((([t,e])=>e===this.current));return t?t[0]:""}logout(){e.getConfigValue("ENABLE_STATE_CACHE")&&this.cacheManager.clear(),localStorage.clear(),sessionStorage.clear(),this.resetContext()}setSelectedApp(t){localStorage.setItem("selectedApp",t),this.update()}isBusy(){return this.current===this.allStates.gettingApps||this.current===this.allStates.checkingPurchase||this.current===this.allStates.checkingAccess||this.current===this.allStates.checkingCodicentAccess||this.current===this.allStates.registering||this.current===this.allStates.loadingUser||this.current===this.allStates.creatingApp||this.current===this.allStates.loggingOut}}exports.AppStateMachine=n,exports.createAppStateMachine=(t,e)=>new n(t,e),exports.default=n;
@@ -0,0 +1 @@
1
+ var e={exports:{}};export{e as __module};
@@ -0,0 +1,112 @@
1
+ /**
2
+ * @fileoverview Simplified app bootstrap for codicent-app-sdk v2
3
+ * @module codicent-app-sdk/bootstrap
4
+ * @public
5
+ */
6
+ import { Root } from "react-dom/client";
7
+ import type { ButtonConfig, ListDefinitions, Translations, ModuleFlags } from "./types";
8
+ /**
9
+ * Complete app configuration for createCodicentApp()
10
+ * @public
11
+ */
12
+ export interface CreateAppConfig {
13
+ /** Application name */
14
+ name: string;
15
+ /** API base URL (e.g., "https://codicent.com/" or custom domain) */
16
+ apiBaseUrl: string;
17
+ /** App-specific URL prefix (used in routing and namespacing) */
18
+ appPrefix?: string;
19
+ /** User namespace prefix */
20
+ userPrefix?: string;
21
+ /** Navigation buttons */
22
+ buttons?: ButtonConfig[];
23
+ /** List view column definitions per tag */
24
+ listDefinitions?: ListDefinitions;
25
+ /** i18n translations map */
26
+ translations?: Translations;
27
+ /** Default language code (e.g., "en", "sv") */
28
+ defaultLanguage?: string;
29
+ /** Feature module flags */
30
+ modules?: ModuleFlags;
31
+ /** AI chat instructions */
32
+ chatInstructions?: string;
33
+ /** AI voice instructions */
34
+ voiceInstructions?: string;
35
+ /** Auth0 configuration */
36
+ auth0?: {
37
+ domain: string;
38
+ clientId: string;
39
+ audience?: string;
40
+ };
41
+ /** Stripe configuration */
42
+ stripe?: {
43
+ publicKey: string;
44
+ priceId?: string;
45
+ trialDays?: number;
46
+ };
47
+ /** Theme/branding configuration */
48
+ theme?: {
49
+ headerColor?: string;
50
+ footerColor?: string;
51
+ buttonColor?: string;
52
+ logoUrl?: string;
53
+ };
54
+ }
55
+ /**
56
+ * CodicentApp instance returned by createCodicentApp()
57
+ * @public
58
+ */
59
+ export interface CodicentApp {
60
+ /**
61
+ * Render the app to a DOM element
62
+ * @param container - DOM element or selector to render into
63
+ */
64
+ render(container: HTMLElement | string): Root;
65
+ /**
66
+ * Unmount the app
67
+ */
68
+ unmount(): void;
69
+ /**
70
+ * Get the current configuration
71
+ */
72
+ getConfig(): CreateAppConfig;
73
+ }
74
+ /**
75
+ * Create a Codicent app with the specified configuration.
76
+ *
77
+ * This is the recommended way to bootstrap a new Codicent vertical app.
78
+ * Pass a configuration object and call `.render()` to mount the app.
79
+ *
80
+ * @example
81
+ * ```tsx
82
+ * import { createCodicentApp } from "codicent-app-sdk";
83
+ *
84
+ * const app = createCodicentApp({
85
+ * name: "My CRM",
86
+ * apiBaseUrl: "https://codicent.com/",
87
+ * buttons: [
88
+ * { title: "Customers", url: "./#/list?tag=customer2" },
89
+ * { title: "Chat", url: "./#/chat" },
90
+ * ],
91
+ * listDefinitions: {
92
+ * customer2: [
93
+ * { key: "name", title: "Name", filterable: true },
94
+ * { key: "email", title: "Email" },
95
+ * ],
96
+ * },
97
+ * translations: {
98
+ * en: { "Kunder": "Customers" },
99
+ * sv: { "Customers": "Kunder" },
100
+ * },
101
+ * modules: { sales: true, voice: false },
102
+ * });
103
+ *
104
+ * app.render("#root");
105
+ * ```
106
+ *
107
+ * @param config - App configuration
108
+ * @returns CodicentApp instance with render() method
109
+ * @public
110
+ */
111
+ export declare function createCodicentApp(config: CreateAppConfig): CodicentApp;
112
+ //# sourceMappingURL=bootstrap.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bootstrap.d.ts","sourceRoot":"","sources":["../../src/bootstrap.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAAc,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAKpD,OAAO,KAAK,EAA6B,YAAY,EAAE,eAAe,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAwBnH;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC9B,uBAAuB;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,oEAAoE;IACpE,UAAU,EAAE,MAAM,CAAC;IACnB,gEAAgE;IAChE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,4BAA4B;IAC5B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,yBAAyB;IACzB,OAAO,CAAC,EAAE,YAAY,EAAE,CAAC;IACzB,2CAA2C;IAC3C,eAAe,CAAC,EAAE,eAAe,CAAC;IAClC,4BAA4B;IAC5B,YAAY,CAAC,EAAE,YAAY,CAAC;IAC5B,+CAA+C;IAC/C,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,2BAA2B;IAC3B,OAAO,CAAC,EAAE,WAAW,CAAC;IACtB,2BAA2B;IAC3B,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,4BAA4B;IAC5B,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,0BAA0B;IAC1B,KAAK,CAAC,EAAE;QACN,MAAM,EAAE,MAAM,CAAC;QACf,QAAQ,EAAE,MAAM,CAAC;QACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;KACnB,CAAC;IACF,2BAA2B;IAC3B,MAAM,CAAC,EAAE;QACP,SAAS,EAAE,MAAM,CAAC;QAClB,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,SAAS,CAAC,EAAE,MAAM,CAAC;KACpB,CAAC;IACF,mCAAmC;IACnC,KAAK,CAAC,EAAE;QACN,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,OAAO,CAAC,EAAE,MAAM,CAAC;KAClB,CAAC;CACH;AAED;;;GAGG;AACH,MAAM,WAAW,WAAW;IAC1B;;;OAGG;IACH,MAAM,CAAC,SAAS,EAAE,WAAW,GAAG,MAAM,GAAG,IAAI,CAAC;IAE9C;;OAEG;IACH,OAAO,IAAI,IAAI,CAAC;IAEhB;;OAEG;IACH,SAAS,IAAI,eAAe,CAAC;CAC9B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,eAAe,GAAG,WAAW,CAsKtE"}
@@ -0,0 +1 @@
1
+ import e from"react";import{createRoot as t}from"react-dom/client";import{HashRouter as r}from"react-router-dom";import{Auth0Provider as o}from"./node_modules/@auth0/auth0-react/dist/auth0-react.esm.js";import{initCodicentApp as n}from"./config/index.js";import{createLightTheme as i}from"./node_modules/@fluentui/tokens/lib/utils/createLightTheme.js";import{FluentProvider as a}from"./node_modules/@fluentui/react-provider/lib/components/FluentProvider/FluentProvider.js";const s={10:"#000000",20:"#10141C",30:"#172033",40:"#1E2E4B",50:"#233C64",60:"#284A7E",70:"#2D5A9A",80:"#3069B6",90:"#3779D1",100:"#4F89E1",110:"#6799EE",120:"#80A9F8",130:"#99BAFF",140:"#B5CBFF",150:"#CFDCFF",160:"#E7EEFF"};function l(l){let u=null,c=!1;if(!l.name)throw new Error("createCodicentApp: 'name' is required");if(!l.apiBaseUrl)throw new Error("createCodicentApp: 'apiBaseUrl' is required");const m={API_BASE_URL:l.apiBaseUrl,APP_NAME:l.name,APP_PREFIX:l.appPrefix||l.name.toLowerCase().replace(/\s+/g,"-"),USER_PREFIX:l.userPrefix||"users",DEFAULT_LANGUAGE:l.defaultLanguage||"en",TRANSLATIONS:l.translations,CHAT_INSTRUCTIONS:l.chatInstructions,REALTIME_VOICE_INSTRUCTIONS:l.voiceInstructions,MODULE_SALES:l.modules?.sales??!1,MODULE_VOICE:l.modules?.voice??!1,MODULE_FORMS:l.modules?.forms??!1,MODULE_SEARCH:l.modules?.search??!1,MODULE_QR:l.modules?.qr??!1,MODULE_SNAP:l.modules?.snap??!1,AUTH0_DOMAIN:l.auth0?.domain||"auth.codicent.com",AUTH0_CLIENT_ID:l.auth0?.clientId||"80STzWmmzN3Tgf76HgFRyv54keYmvnaw",AUTH0_AUDIENCE:l.auth0?.audience||"https://codicent.com/api",AUTH0_PROVIDER_SCOPE:"read:current_user update:current_user_metadata openid profile email",AUTH0_SCOPE:"read:current_user",STRIPE_PUBLIC_KEY:l.stripe?.publicKey||"",STRIPE_PRICE_ID:l.stripe?.priceId||"",STRIPE_TRIAL_PERIOD_DAYS:l.stripe?.trialDays||0,SUBSCRIPTION_NEEDED:!!l.stripe?.publicKey,APP_HEADER_COLOR:l.theme?.headerColor,APP_FOOTER_COLOR:l.theme?.footerColor,BUTTON_BACKGROUND_COLOR:l.theme?.buttonColor,APP_ICON_URL:l.theme?.logoUrl,APP_HEADER_ICON_URL:l.theme?.logoUrl,APP_CONFIG:{apps:{[l.appPrefix||l.name]:{buttons:l.buttons||[],tasks:[],voiceInstructions:l.voiceInstructions||"",chatInstructions:l.chatInstructions||"",listDefinitions:l.listDefinitions||{}}}}};n(m);const d={...i(s),fontFamilyBase:"'Segoe UI', Roboto, 'Helvetica Neue', sans-serif"};return{render(n){if(c)return console.warn("createCodicentApp: App is already mounted. Call unmount() first."),u;const i="string"==typeof n?document.querySelector(n):n;if(!i)throw new Error(`createCodicentApp: Could not find container: ${n}`);return u=t(i),u.render(e.createElement(e.StrictMode,null,e.createElement(o,{domain:m.AUTH0_DOMAIN,clientId:m.AUTH0_CLIENT_ID,authorizationParams:{redirect_uri:window.location.origin,audience:m.AUTH0_AUDIENCE,scope:m.AUTH0_PROVIDER_SCOPE,ui_locales:m.DEFAULT_LANGUAGE},cacheLocation:"localstorage",useRefreshTokens:!0},e.createElement(a,{theme:d},e.createElement(r,null,e.createElement((()=>e.createElement("div",{style:{padding:"20px",fontFamily:"system-ui, sans-serif",maxWidth:"600px",margin:"40px auto"}},e.createElement("h1",null,`Welcome to ${l.name}`),e.createElement("p",null,"Your Codicent app is configured and ready."),e.createElement("p",null,"To use the full app UI, import and render your App component directly."),e.createElement("h2",null,"Configuration:"),e.createElement("pre",{style:{background:"#f5f5f5",padding:"10px",borderRadius:"4px",overflow:"auto"}},JSON.stringify({name:l.name,apiBaseUrl:l.apiBaseUrl,buttons:l.buttons?.length||0,modules:l.modules},null,2)))))))))),c=!0,u},unmount(){u&&(u.unmount(),u=null,c=!1)},getConfig:()=>l}}export{l as createCodicentApp};
@@ -1 +1 @@
1
- import{jsxs as o,jsx as e,Fragment as t}from"react/jsx-runtime";import{useState as i,useEffect as r}from"react";import"./Markdown.js";import"./Textarea.js";import{Button as s}from"./Button.js";import"./CompoundButton.js";import{Text as a}from"./Text.js";import{Spinner as m}from"./Spinner.js";import"./TextHeader.js";import"./TypingIndicator.js";import"./Dialog.js";import"./ChatInput.js";import"./CombinedPlaceholderDialog.js";import"./ChatMessage.js";import"./Header.js";import"../services/codicent.js";import p from"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"../_virtual/index.js";import"../config/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import"../pages/AppFrame.js";import"../pages/Chat.js";import"../pages/Compose.js";import"../pages/Snap.js";import"../pages/Search.js";import"../pages/Login.js";import"../pages/CrmPage.js";import"../pages/CrmPagePersistent.js";import"../pages/ImageView.js";import"../pages/FormInvite.js";import"../pages/FormAccept.js";import"../pages/Sales.js";import"../pages/Purchase.js";import l from"../hooks/useLocalization.js";import"../hooks/useAppStyles.js";import"./FileThumbnail.js";import"./MessageInput.js";import"./UploadFile.js";import"./SnapFooter.js";import"./Profile.js";import"./MessageItem.js";import"./Content.js";import"./SearchBox.js";import"./HtmlView.js";import"./Footer.js";import"./Page.js";import"./QrCodeDialog.js";import{makeStyles as n}from"../node_modules/@griffel/react/makeStyles.esm.js";import{useId as c}from"../node_modules/@fluentui/react-utilities/lib/hooks/useId.js";import{Combobox as j}from"../node_modules/@fluentui/react-combobox/lib/components/Combobox/Combobox.js";import{Option as d}from"../node_modules/@fluentui/react-combobox/lib/components/Option/Option.js";const g=n({root:{display:"grid",gridTemplateRows:"repeat(1fr)",justifyItems:"start",gap:"2px",maxWidth:"400px",padding:"8px"},combo:{width:"100%"},horizonal:{display:"flex",flexDirection:"row",verticalAlign:"middle"}}),u=n=>{const{id:u,options:f,title:h,placeholder:b,onChangeValue:x,value:w="",prompt:C,service:v}=n,y=c(u+"-combo"),[S,_]=i([...f||[]]),[k,T]=i(),[z,I]=i(!1),F=g(),{t:P}=l();r((()=>{x(k)}),[k,x]);return o("div",{id:u,className:F.root,children:[o("div",{className:F.horizonal,children:[e(a,{size:400,id:y,children:h}),C&&o(t,{children:[!z&&e(s,{icon:"WandRegular",title:P("Autoskapa"),style:{fontSize:16,marginLeft:6},onClick:async()=>{I(!0),await(async o=>{if(o){const e=await v.chat(o);if(e){const o=new p(e.content).content;x(o)}}})(C),I(!1)},appearance:"transparent",size:"small"}),z&&e(m,{size:"extra-small",style:{marginLeft:12},children:P("Arbetar...")})]})]}),o(j,{className:F.combo,"aria-labelledby":y,freeform:!0,placeholder:b||P("Välj..."),onChange:o=>{const e=o.target.value;T(e);const t=(f||[]).filter((o=>0===o.toLowerCase().indexOf(e.toLowerCase())));_(t)},onOptionSelect:(o,e)=>{e.optionText&&(f||[]).includes(e.optionText);T(e.optionText)},size:"large",value:w,children:[k?e(d,{text:k,children:P("Sök efter ")+k},"freeform"):null,S.map((o=>e(d,{children:o},o)))]})]})};export{u as default};
1
+ import{jsxs as o,jsx as e,Fragment as t}from"react/jsx-runtime";import{useState as i,useEffect as r}from"react";import"./Markdown.js";import"./Textarea.js";import{Button as s}from"./Button.js";import"./CompoundButton.js";import{Text as a}from"./Text.js";import{Spinner as m}from"./Spinner.js";import"./TextHeader.js";import"./TypingIndicator.js";import"./Dialog.js";import"./ChatInput.js";import"./CombinedPlaceholderDialog.js";import"./ChatMessage.js";import"./Header.js";import"../services/codicent.js";import p from"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"../_virtual/index.js";import"../config/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import"../pages/AppFrame.js";import"../pages/Chat.js";import"../pages/Compose.js";import"../pages/Snap.js";import"../pages/Search.js";import"../pages/Login.js";import"../pages/CrmPage.js";import"../pages/CrmPagePersistent.js";import"../pages/ImageView.js";import"../pages/FormInvite.js";import"../pages/FormAccept.js";import"../pages/Sales.js";import"../pages/Purchase.js";import"./Content.js";import"./Page.js";import"../pages/QrScan.js";import l from"../hooks/useLocalization.js";import"./FileThumbnail.js";import"react-dom/client";import"react-router-dom";import"../node_modules/@auth0/auth0-react/dist/auth0-react.esm.js";import"../hooks/useAppStyles.js";import"./MessageInput.js";import"./UploadFile.js";import"./SnapFooter.js";import"./Profile.js";import"./MessageItem.js";import"./SearchBox.js";import"./HtmlView.js";import"./Footer.js";import"./QrCodeDialog.js";import"./QrScanner.js";import"./OfflineMessage.js";import"./LanguageSelector.js";import"./ListView.js";import"./RecordModal.js";import"./BulkUploadDialog.js";import{makeStyles as n}from"../node_modules/@griffel/react/makeStyles.esm.js";import{useId as c}from"../node_modules/@fluentui/react-utilities/lib/hooks/useId.js";import{Combobox as j}from"../node_modules/@fluentui/react-combobox/lib/components/Combobox/Combobox.js";import{Option as d}from"../node_modules/@fluentui/react-combobox/lib/components/Option/Option.js";const g=n({root:{display:"grid",gridTemplateRows:"repeat(1fr)",justifyItems:"start",gap:"2px",maxWidth:"400px",padding:"8px"},combo:{width:"100%"},horizonal:{display:"flex",flexDirection:"row",verticalAlign:"middle"}}),u=n=>{const{id:u,options:f,title:h,placeholder:b,onChangeValue:x,value:w="",prompt:C,service:v}=n,y=c(u+"-combo"),[S,_]=i([...f||[]]),[k,T]=i(),[z,I]=i(!1),L=g(),{t:M}=l();r((()=>{x(k)}),[k,x]);return o("div",{id:u,className:L.root,children:[o("div",{className:L.horizonal,children:[e(a,{size:400,id:y,children:h}),C&&o(t,{children:[!z&&e(s,{icon:"WandRegular",title:M("Autoskapa"),style:{fontSize:16,marginLeft:6},onClick:async()=>{I(!0),await(async o=>{if(o){const e=await v.chat(o);if(e){const o=new p(e.content).content;x(o)}}})(C),I(!1)},appearance:"transparent",size:"small"}),z&&e(m,{size:"extra-small",style:{marginLeft:12},children:M("Arbetar...")})]})]}),o(j,{className:L.combo,"aria-labelledby":y,freeform:!0,placeholder:b||M("Välj..."),onChange:o=>{const e=o.target.value;T(e);const t=(f||[]).filter((o=>0===o.toLowerCase().indexOf(e.toLowerCase())));_(t)},onOptionSelect:(o,e)=>{e.optionText&&(f||[]).includes(e.optionText);T(e.optionText)},size:"large",value:w,children:[k?e(d,{text:k,children:M("Sök efter ")+k},"freeform"):null,S.map((o=>e(d,{children:o},o)))]})]})};export{u as default};
@@ -1 +1 @@
1
- import{jsx as o}from"react/jsx-runtime";import"react";import"../services/codicent.js";import"./Markdown.js";import"./Textarea.js";import"./Button.js";import"./CompoundButton.js";import"./Spinner.js";import"./TextHeader.js";import"./TypingIndicator.js";import"./Dialog.js";import"./ChatInput.js";import"./CombinedPlaceholderDialog.js";import"./ChatMessage.js";import"./Header.js";import"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import s from"../utils/withWakeLock.js";import"../_virtual/index.js";import"../config/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import"./FileThumbnail.js";import"./MessageInput.js";import"./UploadFile.js";import"./SnapFooter.js";import"./Profile.js";import"./MessageItem.js";import"./Content.js";import"./AiInput.js";import"./SearchBox.js";import"./HtmlView.js";import"./Footer.js";import"./Page.js";import"./QrCodeDialog.js";import"../pages/AppFrame.js";import"../pages/Chat.js";import"../pages/Compose.js";import"../pages/Snap.js";import"../pages/Search.js";import"../pages/Login.js";import"../pages/CrmPage.js";import"../pages/CrmPagePersistent.js";import"../pages/ImageView.js";import"../pages/FormInvite.js";import"../pages/FormAccept.js";import"../pages/Sales.js";import"../pages/Purchase.js";import"../hooks/useLocalization.js";import i from"../hooks/useAppStyles.js";import{Mic24Regular as t,MicPulse24Filled as r,MicRecord24Filled as e}from"../node_modules/@fluentui/react-icons/lib/sizedIcons/chunk-10.js";const p=s((({isSoundCaptured:s,stopRecording:t})=>{const{pointer:p}=i();return o(s?r:e,{onClick:t,className:p})})),a=({audio:s,disabled:r})=>{const{isRecording:e,isSoundCaptured:a,startRecording:m,stopRecording:n}=s,{pointer:j}=i();return r?o(t,{}):e?o(p,{isSoundCaptured:a,stopRecording:n}):o(t,{onClick:()=>m(""),className:j})};export{a as default};
1
+ import{jsx as o}from"react/jsx-runtime";import"react";import"../services/codicent.js";import"./Markdown.js";import"./Textarea.js";import"./Button.js";import"./CompoundButton.js";import"./Spinner.js";import"./TextHeader.js";import"./TypingIndicator.js";import"./Dialog.js";import"./ChatInput.js";import"./CombinedPlaceholderDialog.js";import"./ChatMessage.js";import"./Header.js";import"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import t from"../utils/withWakeLock.js";import"../_virtual/index.js";import"../config/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import"./FileThumbnail.js";import"./MessageInput.js";import"./UploadFile.js";import"./SnapFooter.js";import"./Profile.js";import"./MessageItem.js";import"./Content.js";import"./AiInput.js";import"./SearchBox.js";import"./HtmlView.js";import"./Footer.js";import"./Page.js";import"./QrCodeDialog.js";import"./QrScanner.js";import"../hooks/useLocalization.js";import"./OfflineMessage.js";import"./LanguageSelector.js";import"./ListView.js";import"./RecordModal.js";import"./BulkUploadDialog.js";import"../pages/AppFrame.js";import"../pages/Chat.js";import"../pages/Compose.js";import"../pages/Snap.js";import"../pages/Search.js";import"../pages/Login.js";import"../pages/CrmPage.js";import"../pages/CrmPagePersistent.js";import"../pages/ImageView.js";import"../pages/FormInvite.js";import"../pages/FormAccept.js";import"../pages/Sales.js";import"../pages/Purchase.js";import"../pages/QrScan.js";import"react-dom/client";import"react-router-dom";import"../node_modules/@auth0/auth0-react/dist/auth0-react.esm.js";import s from"../hooks/useAppStyles.js";import{Mic24Regular as i,MicPulse24Filled as r,MicRecord24Filled as e}from"../node_modules/@fluentui/react-icons/lib/sizedIcons/chunk-10.js";const p=t((({isSoundCaptured:t,stopRecording:i})=>{const{pointer:p}=s();return o(t?r:e,{onClick:i,className:p})})),a=({audio:t,disabled:r})=>{const{isRecording:e,isSoundCaptured:a,startRecording:m,stopRecording:n}=t,{pointer:j}=s();return r?o(i,{}):e?o(p,{isSoundCaptured:a,stopRecording:n}):o(i,{onClick:()=>m(""),className:j})};export{a as default};
@@ -0,0 +1,16 @@
1
+ import { CodicentService } from "../services/codicent";
2
+ interface BulkUploadDialogProps {
3
+ project: string;
4
+ hidden: boolean;
5
+ onDismiss: () => void;
6
+ sendMessage: (text: string) => Promise<string | undefined>;
7
+ onUploaded?: () => void;
8
+ service: CodicentService;
9
+ tags?: string[];
10
+ title?: string;
11
+ description?: string;
12
+ dropText?: string;
13
+ }
14
+ declare const BulkUploadDialog: (props: BulkUploadDialogProps) => import("react/jsx-runtime").JSX.Element;
15
+ export default BulkUploadDialog;
16
+ //# sourceMappingURL=BulkUploadDialog.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BulkUploadDialog.d.ts","sourceRoot":"","sources":["../../../src/components/BulkUploadDialog.tsx"],"names":[],"mappings":"AAYA,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAMvD,UAAU,qBAAqB;IAC7B,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,OAAO,CAAC;IAChB,SAAS,EAAE,MAAM,IAAI,CAAC;IACtB,WAAW,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IAE3D,UAAU,CAAC,EAAE,MAAM,IAAI,CAAC;IACxB,OAAO,EAAE,eAAe,CAAC;IACzB,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAkCD,QAAA,MAAM,gBAAgB,UAAW,qBAAqB,4CAkNrD,CAAC;AAEF,eAAe,gBAAgB,CAAC"}
@@ -0,0 +1 @@
1
+ import{jsx as e,jsxs as o}from"react/jsx-runtime";import{Spinner as r}from"./Spinner.js";import n from"../hooks/useLocalization.js";import{Button as l}from"./Button.js";import{useState as i,useRef as t,useEffect as a,useCallback as s}from"react";import{makeStyles as d}from"../node_modules/@griffel/react/makeStyles.esm.js";import{shorthands as c}from"../node_modules/@griffel/core/index.esm.js";import{tokens as p}from"../node_modules/@fluentui/tokens/lib/tokens.js";import{Dialog as m}from"../node_modules/@fluentui/react-dialog/lib/components/Dialog/Dialog.js";import{DialogSurface as u}from"../node_modules/@fluentui/react-dialog/lib/components/DialogSurface/DialogSurface.js";import{DialogBody as f}from"../node_modules/@fluentui/react-dialog/lib/components/DialogBody/DialogBody.js";import{DialogTitle as g}from"../node_modules/@fluentui/react-dialog/lib/components/DialogTitle/DialogTitle.js";import{DialogContent as h}from"../node_modules/@fluentui/react-dialog/lib/components/DialogContent/DialogContent.js";import{MessageBar as D}from"../node_modules/@fluentui/react-message-bar/lib/components/MessageBar/MessageBar.js";import{DialogActions as k}from"../node_modules/@fluentui/react-dialog/lib/components/DialogActions/DialogActions.js";const b=d({dropZone:{...c.border("2px","dashed",p.colorNeutralStroke2),...c.borderRadius(p.borderRadiusMedium),...c.padding("2rem"),textAlign:"center",backgroundColor:p.colorNeutralBackground1,cursor:"pointer",transition:"all 0.2s ease-in-out","&:hover":{backgroundColor:p.colorNeutralBackground1Hover}},dropZoneActive:{...c.border("2px","dashed",p.colorBrandBackground),backgroundColor:p.colorBrandBackground2},dropZoneText:{color:p.colorNeutralForeground2,fontSize:p.fontSizeBase300,marginBottom:"1rem"},fileInput:{display:"none"},fileList:{fontSize:"0.8rem",color:p.colorNeutralForeground3,marginTop:"0.5rem"}}),j=d=>{const[c,p]=i(""),[j,v]=i(!1),[B,y]=i(""),[C,x]=i(!1),[_,N]=i([]),$=b(),S=t(null),{hidden:A,onDismiss:T,project:z,sendMessage:U,onUploaded:Z,service:E,title:P,description:F,dropText:L}=d,{t:M}=n();a((()=>{A&&(N([]),p(""),v(!1),y(""),x(!1),S.current&&(S.current.value=""))}),[A]);const w=s((async e=>{0!==e.length&&(N(e),p(""))}),[]),I=s((()=>{try{if(S.current?.files){const e=Array.from(S.current.files);w(e)}}catch{p(M("Error selecting files"))}}),[w,M]),O=s((e=>{e.preventDefault(),e.stopPropagation(),x(!0)}),[]),R=s((e=>{e.preventDefault(),e.stopPropagation(),x(!1)}),[]),H=s((e=>{e.preventDefault(),e.stopPropagation()}),[]),q=s((e=>{e.preventDefault(),e.stopPropagation(),x(!1);const o=Array.from(e.dataTransfer.files);w(o)}),[w]),G=s((()=>{S.current?.click()}),[]);return e(m,{open:!A,onOpenChange:(e,o)=>!o.open&&T(),children:e(u,{children:o(f,{children:[e(g,{children:P||M("Bulk Upload")}),o(h,{children:[e("p",{children:F||M("Drag and drop files here or click to select files")}),o("div",{className:`${$.dropZone} ${C?$.dropZoneActive:""}`,onDragEnter:O,onDragLeave:R,onDragOver:H,onDrop:q,onClick:G,children:[e("div",{className:$.dropZoneText,children:C?M("Drop files here..."):_.length>0?M(`${_.length} ${1===_.length?"file":"files"} selected`):L||M("Drag and drop files here or click to select")}),!C&&_.length>0&&e("div",{className:$.fileList,children:_.map(((o,r)=>e("div",{children:o.name},r)))})]}),e("input",{ref:S,className:$.fileInput,title:"Upload",type:"file",name:"files",multiple:!0,onChange:I}),j&&e(r,{size:"large",children:M("Uploading...")}),j&&o("p",{children:[M("Uploading")," ",B]}),""!==c&&e(D,{intent:"error",children:c})]}),o(k,{children:[e(l,{onClick:T,children:M("Cancel")}),e(l,{disabled:0===_.length||j,onClick:async()=>{if(0!==_.length){v(!0),p("");for(const e of _)try{const o=new FormData;o.append("file",e),y(e.name);const r=await E.uploadFile(e.name,o);if(!r){p(M("Error uploading file"));continue}const n=d.tags?d.tags.map((e=>`#${e}`)).join(" "):"#index #summarize",l=`@${z} ${n}\n\n${e.name}\n#file:${r}\n`;console.log("uploading file: "+l);if(!await U(l)){p(M("Error sending file"));continue}}catch(e){console.log(e),p(M("Error uploading file"))}v(!1),Z&&Z(),T()}else p(M("Please select files to upload"))},appearance:"primary",children:M("Upload")})]})]})})})};export{j as default};