@qoretechnologies/reqraft 0.10.53 → 0.10.54-pr.115.g9bc96ed

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 (283) hide show
  1. package/.claude/CLAUDE.md +25 -0
  2. package/.tasks/INDEX.md +1 -0
  3. package/.tasks/STORY_NETWORK_ISOLATION.md +98 -0
  4. package/README.md +1 -1
  5. package/design/FORM_ENGINE_EXPRESSIONS.md +110 -0
  6. package/design/FORM_ENGINE_FIELD_MIGRATION.md +56 -1
  7. package/design/RENDER_EXPRESSION_TRANSPORT.md +76 -10
  8. package/design/SMART_EDITOR_UX.md +21 -0
  9. package/dist/components/dpqlEditor/DpqlEditor.d.ts.map +1 -1
  10. package/dist/components/dpqlEditor/DpqlEditor.js +3 -3
  11. package/dist/components/dpqlEditor/DpqlEditor.js.map +1 -1
  12. package/dist/components/dpqlEditor/dpqlHelpers.d.ts +6 -0
  13. package/dist/components/dpqlEditor/dpqlHelpers.d.ts.map +1 -1
  14. package/dist/components/dpqlEditor/dpqlHelpers.js +21 -2
  15. package/dist/components/dpqlEditor/dpqlHelpers.js.map +1 -1
  16. package/dist/components/dpqlEditor/dpqlProbe.d.ts +37 -0
  17. package/dist/components/dpqlEditor/dpqlProbe.d.ts.map +1 -0
  18. package/dist/components/dpqlEditor/dpqlProbe.js +203 -0
  19. package/dist/components/dpqlEditor/dpqlProbe.js.map +1 -0
  20. package/dist/components/dpqlEditor/dpqlTags.d.ts +8 -0
  21. package/dist/components/dpqlEditor/dpqlTags.d.ts.map +1 -1
  22. package/dist/components/dpqlEditor/dpqlTags.js +5 -1
  23. package/dist/components/dpqlEditor/dpqlTags.js.map +1 -1
  24. package/dist/components/dpqlEditor/index.d.ts +4 -0
  25. package/dist/components/dpqlEditor/index.d.ts.map +1 -1
  26. package/dist/components/dpqlEditor/index.js +5 -1
  27. package/dist/components/dpqlEditor/index.js.map +1 -1
  28. package/dist/components/dpqlEditor/types.d.ts +42 -2
  29. package/dist/components/dpqlEditor/types.d.ts.map +1 -1
  30. package/dist/components/dpqlEditor/types.js +0 -4
  31. package/dist/components/dpqlEditor/types.js.map +1 -1
  32. package/dist/components/dpqlEditor/useDpqlProbe.d.ts +4 -0
  33. package/dist/components/dpqlEditor/useDpqlProbe.d.ts.map +1 -0
  34. package/dist/components/dpqlEditor/useDpqlProbe.js +29 -0
  35. package/dist/components/dpqlEditor/useDpqlProbe.js.map +1 -0
  36. package/dist/components/dpqlEditor/useDpqlSession.d.ts +5 -2
  37. package/dist/components/dpqlEditor/useDpqlSession.d.ts.map +1 -1
  38. package/dist/components/dpqlEditor/useDpqlSession.js +8 -2
  39. package/dist/components/dpqlEditor/useDpqlSession.js.map +1 -1
  40. package/dist/components/form/engine/CompactRow.d.ts.map +1 -1
  41. package/dist/components/form/engine/CompactRow.js +192 -45
  42. package/dist/components/form/engine/CompactRow.js.map +1 -1
  43. package/dist/components/form/engine/CompactToolbar.d.ts.map +1 -1
  44. package/dist/components/form/engine/CompactToolbar.js +5 -2
  45. package/dist/components/form/engine/CompactToolbar.js.map +1 -1
  46. package/dist/components/form/engine/FormEngine.d.ts +160 -12
  47. package/dist/components/form/engine/FormEngine.d.ts.map +1 -1
  48. package/dist/components/form/engine/FormEngine.js +376 -75
  49. package/dist/components/form/engine/FormEngine.js.map +1 -1
  50. package/dist/components/form/engine/FormFieldsSkeleton.d.ts +48 -0
  51. package/dist/components/form/engine/FormFieldsSkeleton.d.ts.map +1 -0
  52. package/dist/components/form/engine/FormFieldsSkeleton.js +38 -0
  53. package/dist/components/form/engine/FormFieldsSkeleton.js.map +1 -0
  54. package/dist/components/form/engine/OptionFieldMessages.d.ts +17 -2
  55. package/dist/components/form/engine/OptionFieldMessages.d.ts.map +1 -1
  56. package/dist/components/form/engine/OptionFieldMessages.js +61 -11
  57. package/dist/components/form/engine/OptionFieldMessages.js.map +1 -1
  58. package/dist/components/form/engine/_structuredData/SchemaDataView.d.ts.map +1 -1
  59. package/dist/components/form/engine/_structuredData/SchemaDataView.js +7 -1
  60. package/dist/components/form/engine/_structuredData/SchemaDataView.js.map +1 -1
  61. package/dist/components/form/engine/compactToolbarContext.d.ts +1 -0
  62. package/dist/components/form/engine/compactToolbarContext.d.ts.map +1 -1
  63. package/dist/components/form/engine/readFirst.d.ts +42 -1
  64. package/dist/components/form/engine/readFirst.d.ts.map +1 -1
  65. package/dist/components/form/engine/readFirst.js +74 -7
  66. package/dist/components/form/engine/readFirst.js.map +1 -1
  67. package/dist/components/form/engine/rendererTypes.d.ts +13 -0
  68. package/dist/components/form/engine/rendererTypes.d.ts.map +1 -1
  69. package/dist/components/form/engine/rendererTypes.js.map +1 -1
  70. package/dist/components/form/engine/rowMenuContext.d.ts +78 -0
  71. package/dist/components/form/engine/rowMenuContext.d.ts.map +1 -0
  72. package/dist/components/form/engine/rowMenuContext.js +103 -0
  73. package/dist/components/form/engine/rowMenuContext.js.map +1 -0
  74. package/dist/components/form/engine/typeChoices.d.ts +37 -0
  75. package/dist/components/form/engine/typeChoices.d.ts.map +1 -0
  76. package/dist/components/form/engine/typeChoices.js +25 -0
  77. package/dist/components/form/engine/typeChoices.js.map +1 -0
  78. package/dist/components/form/expressions/DpqlRendering.d.ts +26 -0
  79. package/dist/components/form/expressions/DpqlRendering.d.ts.map +1 -0
  80. package/dist/components/form/expressions/DpqlRendering.js +53 -0
  81. package/dist/components/form/expressions/DpqlRendering.js.map +1 -0
  82. package/dist/components/form/expressions/ExpressionField.d.ts +7 -1
  83. package/dist/components/form/expressions/ExpressionField.d.ts.map +1 -1
  84. package/dist/components/form/expressions/ExpressionField.js +202 -45
  85. package/dist/components/form/expressions/ExpressionField.js.map +1 -1
  86. package/dist/components/form/expressions/argumentPresence.d.ts +97 -0
  87. package/dist/components/form/expressions/argumentPresence.d.ts.map +1 -0
  88. package/dist/components/form/expressions/argumentPresence.js +203 -0
  89. package/dist/components/form/expressions/argumentPresence.js.map +1 -0
  90. package/dist/components/form/expressions/builder/argumentLabel.d.ts.map +1 -1
  91. package/dist/components/form/expressions/builder/argumentLabel.js +9 -4
  92. package/dist/components/form/expressions/builder/argumentLabel.js.map +1 -1
  93. package/dist/components/form/expressions/builder/index.d.ts +15 -2
  94. package/dist/components/form/expressions/builder/index.d.ts.map +1 -1
  95. package/dist/components/form/expressions/builder/index.js +20 -58
  96. package/dist/components/form/expressions/builder/index.js.map +1 -1
  97. package/dist/components/form/expressions/builder/renderTemplate.d.ts +4 -1
  98. package/dist/components/form/expressions/builder/renderTemplate.d.ts.map +1 -1
  99. package/dist/components/form/expressions/builder/renderTemplate.js +10 -67
  100. package/dist/components/form/expressions/builder/renderTemplate.js.map +1 -1
  101. package/dist/components/form/expressions/dpqlMockLanguage.d.ts +76 -0
  102. package/dist/components/form/expressions/dpqlMockLanguage.d.ts.map +1 -0
  103. package/dist/components/form/expressions/dpqlMockLanguage.js +525 -0
  104. package/dist/components/form/expressions/dpqlMockLanguage.js.map +1 -0
  105. package/dist/components/form/expressions/dpqlMockLsp.d.ts +31 -2
  106. package/dist/components/form/expressions/dpqlMockLsp.d.ts.map +1 -1
  107. package/dist/components/form/expressions/dpqlMockLsp.js +86 -80
  108. package/dist/components/form/expressions/dpqlMockLsp.js.map +1 -1
  109. package/dist/components/form/expressions/mockExpressions.d.ts.map +1 -1
  110. package/dist/components/form/expressions/mockExpressions.js +8 -4
  111. package/dist/components/form/expressions/mockExpressions.js.map +1 -1
  112. package/dist/components/form/expressions/renderExpressionToText.d.ts +1 -1
  113. package/dist/components/form/expressions/renderExpressionToText.d.ts.map +1 -1
  114. package/dist/components/form/expressions/renderExpressionToText.js +95 -19
  115. package/dist/components/form/expressions/renderExpressionToText.js.map +1 -1
  116. package/dist/components/form/expressions/types.d.ts +7 -0
  117. package/dist/components/form/expressions/types.d.ts.map +1 -1
  118. package/dist/components/form/expressions/useRenderExpression.d.ts +7 -16
  119. package/dist/components/form/expressions/useRenderExpression.d.ts.map +1 -1
  120. package/dist/components/form/expressions/useRenderExpression.js +50 -126
  121. package/dist/components/form/expressions/useRenderExpression.js.map +1 -1
  122. package/dist/components/form/fields/Field.d.ts.map +1 -1
  123. package/dist/components/form/fields/Field.js +3 -1
  124. package/dist/components/form/fields/Field.js.map +1 -1
  125. package/dist/components/form/fields/allowed-values/AllowedValues.d.ts +11 -1
  126. package/dist/components/form/fields/allowed-values/AllowedValues.d.ts.map +1 -1
  127. package/dist/components/form/fields/allowed-values/AllowedValues.js +14 -2
  128. package/dist/components/form/fields/allowed-values/AllowedValues.js.map +1 -1
  129. package/dist/components/form/fields/auto/AutoFormField.d.ts.map +1 -1
  130. package/dist/components/form/fields/auto/AutoFormField.js +32 -8
  131. package/dist/components/form/fields/auto/AutoFormField.js.map +1 -1
  132. package/dist/components/form/fields/date/Date.d.ts +1 -1
  133. package/dist/components/form/fields/date/Date.d.ts.map +1 -1
  134. package/dist/components/form/fields/date/Date.js +16 -2
  135. package/dist/components/form/fields/date/Date.js.map +1 -1
  136. package/dist/components/form/fields/rich-text/RichText.d.ts +21 -1
  137. package/dist/components/form/fields/rich-text/RichText.d.ts.map +1 -1
  138. package/dist/components/form/fields/rich-text/RichText.js +140 -8
  139. package/dist/components/form/fields/rich-text/RichText.js.map +1 -1
  140. package/dist/components/form/fields/template/ReadOnlyTemplateTag.d.ts +2 -1
  141. package/dist/components/form/fields/template/ReadOnlyTemplateTag.d.ts.map +1 -1
  142. package/dist/components/form/fields/template/ReadOnlyTemplateTag.js +3 -2
  143. package/dist/components/form/fields/template/ReadOnlyTemplateTag.js.map +1 -1
  144. package/dist/components/form/fields/template/TemplateField.d.ts +31 -1
  145. package/dist/components/form/fields/template/TemplateField.d.ts.map +1 -1
  146. package/dist/components/form/fields/template/TemplateField.js +528 -50
  147. package/dist/components/form/fields/template/TemplateField.js.map +1 -1
  148. package/dist/components/form/index.d.ts +1 -0
  149. package/dist/components/form/index.d.ts.map +1 -1
  150. package/dist/components/form/index.js +1 -0
  151. package/dist/components/form/index.js.map +1 -1
  152. package/dist/components/smartEditor/SmartEditor.d.ts.map +1 -1
  153. package/dist/components/smartEditor/SmartEditor.js +29 -8
  154. package/dist/components/smartEditor/SmartEditor.js.map +1 -1
  155. package/dist/components/smartEditor/__fixtures__/mockLspServer.d.ts +8 -0
  156. package/dist/components/smartEditor/__fixtures__/mockLspServer.d.ts.map +1 -1
  157. package/dist/components/smartEditor/__fixtures__/mockLspServer.js +53 -10
  158. package/dist/components/smartEditor/__fixtures__/mockLspServer.js.map +1 -1
  159. package/dist/components/smartEditor/useLspSession.d.ts +5 -1
  160. package/dist/components/smartEditor/useLspSession.d.ts.map +1 -1
  161. package/dist/components/smartEditor/useLspSession.js +16 -2
  162. package/dist/components/smartEditor/useLspSession.js.map +1 -1
  163. package/dist/helpers/dpqlDetection.d.ts +58 -0
  164. package/dist/helpers/dpqlDetection.d.ts.map +1 -0
  165. package/dist/helpers/dpqlDetection.js +164 -0
  166. package/dist/helpers/dpqlDetection.js.map +1 -0
  167. package/dist/helpers/optionUiTypes.d.ts +3 -3
  168. package/dist/helpers/options.d.ts +37 -0
  169. package/dist/helpers/options.d.ts.map +1 -1
  170. package/dist/helpers/options.js +78 -1
  171. package/dist/helpers/options.js.map +1 -1
  172. package/dist/helpers/templateItems.d.ts +47 -0
  173. package/dist/helpers/templateItems.d.ts.map +1 -0
  174. package/dist/helpers/templateItems.js +88 -0
  175. package/dist/helpers/templateItems.js.map +1 -0
  176. package/dist/helpers/templateText.d.ts +37 -0
  177. package/dist/helpers/templateText.d.ts.map +1 -0
  178. package/dist/helpers/templateText.js +64 -0
  179. package/dist/helpers/templateText.js.map +1 -0
  180. package/dist/helpers/templates.d.ts +19 -11
  181. package/dist/helpers/templates.d.ts.map +1 -1
  182. package/dist/helpers/templates.js +46 -29
  183. package/dist/helpers/templates.js.map +1 -1
  184. package/dist/helpers/validations.d.ts.map +1 -1
  185. package/dist/helpers/validations.js +56 -9
  186. package/dist/helpers/validations.js.map +1 -1
  187. package/dist/hooks/useArgSchema.d.ts +2 -1
  188. package/dist/hooks/useArgSchema.d.ts.map +1 -1
  189. package/dist/hooks/useFetch/useFetch.d.ts +3 -1
  190. package/dist/hooks/useFetch/useFetch.d.ts.map +1 -1
  191. package/dist/hooks/useFetch/useFetch.js +47 -9
  192. package/dist/hooks/useFetch/useFetch.js.map +1 -1
  193. package/dist/hooks/useTemplates.d.ts +20 -0
  194. package/dist/hooks/useTemplates.d.ts.map +1 -1
  195. package/dist/hooks/useTemplates.js +34 -2
  196. package/dist/hooks/useTemplates.js.map +1 -1
  197. package/dist/index.d.ts +2 -1
  198. package/dist/index.d.ts.map +1 -1
  199. package/dist/index.js +5 -1
  200. package/dist/index.js.map +1 -1
  201. package/dist/stories/storyNetwork.d.ts +36 -0
  202. package/dist/stories/storyNetwork.d.ts.map +1 -0
  203. package/dist/stories/storyNetwork.js +82 -0
  204. package/dist/stories/storyNetwork.js.map +1 -0
  205. package/dist/utils/fetch.d.ts +151 -1
  206. package/dist/utils/fetch.d.ts.map +1 -1
  207. package/dist/utils/fetch.js +256 -44
  208. package/dist/utils/fetch.js.map +1 -1
  209. package/dist/utils/lspClient.d.ts +6 -0
  210. package/dist/utils/lspClient.d.ts.map +1 -1
  211. package/dist/utils/lspClient.js +62 -11
  212. package/dist/utils/lspClient.js.map +1 -1
  213. package/dist/utils/websocket.d.ts +6 -0
  214. package/dist/utils/websocket.d.ts.map +1 -1
  215. package/dist/utils/websocket.js +15 -7
  216. package/dist/utils/websocket.js.map +1 -1
  217. package/package.json +2 -2
  218. package/src/components/dpqlEditor/DpqlEditor.stories.tsx +3 -119
  219. package/src/components/dpqlEditor/DpqlEditor.tsx +5 -2
  220. package/src/components/dpqlEditor/dpqlHelpers.ts +20 -1
  221. package/src/components/dpqlEditor/dpqlProbe.ts +165 -0
  222. package/src/components/dpqlEditor/dpqlTags.ts +13 -0
  223. package/src/components/dpqlEditor/index.ts +4 -0
  224. package/src/components/dpqlEditor/types.ts +38 -2
  225. package/src/components/dpqlEditor/useDpqlProbe.ts +33 -0
  226. package/src/components/dpqlEditor/useDpqlSession.ts +20 -4
  227. package/src/components/form/engine/CompactRow.tsx +240 -51
  228. package/src/components/form/engine/CompactToolbar.tsx +10 -3
  229. package/src/components/form/engine/FormEngine.stories.tsx +423 -120
  230. package/src/components/form/engine/FormEngine.tsx +504 -87
  231. package/src/components/form/engine/FormFieldsSkeleton.tsx +76 -0
  232. package/src/components/form/engine/OptionFieldMessages.tsx +89 -11
  233. package/src/components/form/engine/_structuredData/SchemaDataView.tsx +11 -0
  234. package/src/components/form/engine/compactToolbarContext.ts +1 -1
  235. package/src/components/form/engine/readFirst.ts +86 -7
  236. package/src/components/form/engine/rendererTypes.ts +12 -0
  237. package/src/components/form/engine/rowMenuContext.ts +159 -0
  238. package/src/components/form/engine/typeChoices.ts +55 -0
  239. package/src/components/form/expressions/DpqlRendering.tsx +85 -0
  240. package/src/components/form/expressions/ExpressionField.stories.tsx +826 -48
  241. package/src/components/form/expressions/ExpressionField.tsx +265 -54
  242. package/src/components/form/expressions/argumentPresence.ts +200 -0
  243. package/src/components/form/expressions/builder/ExpressionBuilder.stories.tsx +20 -4
  244. package/src/components/form/expressions/builder/argumentLabel.tsx +10 -4
  245. package/src/components/form/expressions/builder/index.tsx +39 -77
  246. package/src/components/form/expressions/builder/renderTemplate.tsx +23 -56
  247. package/src/components/form/expressions/dpqlMockLanguage.ts +565 -0
  248. package/src/components/form/expressions/dpqlMockLsp.ts +109 -83
  249. package/src/components/form/expressions/mockExpressions.ts +8 -4
  250. package/src/components/form/expressions/renderExpressionToText.ts +112 -22
  251. package/src/components/form/expressions/types.ts +7 -0
  252. package/src/components/form/expressions/useRenderExpression.ts +43 -127
  253. package/src/components/form/fields/Field.tsx +3 -2
  254. package/src/components/form/fields/allowed-values/AllowedValues.tsx +13 -2
  255. package/src/components/form/fields/auto/AutoFormField.stories.tsx +27 -20
  256. package/src/components/form/fields/auto/AutoFormField.tsx +33 -9
  257. package/src/components/form/fields/date/Date.tsx +17 -1
  258. package/src/components/form/fields/rich-text/RichText.tsx +199 -22
  259. package/src/components/form/fields/template/ReadOnlyTemplateTag.tsx +4 -2
  260. package/src/components/form/fields/template/TemplateField.stories.tsx +31 -9
  261. package/src/components/form/fields/template/TemplateField.tsx +714 -122
  262. package/src/components/form/index.tsx +1 -0
  263. package/src/components/log/Log.stories.tsx +2 -1
  264. package/src/components/smartEditor/SmartEditor.tsx +41 -9
  265. package/src/components/smartEditor/__fixtures__/mockLspServer.ts +52 -3
  266. package/src/components/smartEditor/useLspSession.ts +21 -3
  267. package/src/helpers/dpqlDetection.ts +209 -0
  268. package/src/helpers/options.ts +70 -0
  269. package/src/helpers/templateItems.ts +81 -0
  270. package/src/helpers/templateText.ts +92 -0
  271. package/src/helpers/templates.ts +47 -37
  272. package/src/helpers/validations.ts +59 -9
  273. package/src/hooks/useFetch/useFetch.stories.tsx +6 -5
  274. package/src/hooks/useFetch/useFetch.tsx +53 -7
  275. package/src/hooks/useStorage/useStorage.stories.tsx +2 -1
  276. package/src/hooks/useTemplates.ts +41 -0
  277. package/src/hooks/useWebSocket/useWebsocket.stories.tsx +2 -1
  278. package/src/index.tsx +14 -1
  279. package/src/stores/currentUser/currentUser.stories.tsx +2 -1
  280. package/src/stories/storyNetwork.ts +92 -0
  281. package/src/utils/fetch.ts +311 -21
  282. package/src/utils/lspClient.ts +68 -11
  283. package/src/utils/websocket.ts +20 -9
@@ -0,0 +1,92 @@
1
+ // Copyright 2026 Qore Technologies, s.r.o.
2
+ // Where a story's network goes: the instance its Reqraft points at, the URLs
3
+ // its mocks must intercept, and the requests every story is mocked for.
4
+ //
5
+ // `query()` and `ReqraftWebSocket` build absolute URLs from the configured
6
+ // instance, and both mock layers match on the host as well as the path —
7
+ // storybook-addon-mock keys on `host + pathname`, mock-socket on the URL minus
8
+ // its query. A mock written against a hard-coded host stops matching the moment
9
+ // the instance is overridden, and the request goes out to the real network
10
+ // instead, silently. Build mock URLs with the helpers below.
11
+ import { defaultQorusTypes } from '../hooks/useQorusTypes';
12
+ import { buildReqraftApiUrl } from '../utils/fetch';
13
+ import { buildReqraftSocketUrl } from '../utils/websocket';
14
+
15
+ /**
16
+ * What storybook-addon-mock accepts as a response. Anything else — a bare
17
+ * number or string — fails the addon's validation and the entry is kept but
18
+ * never matched, so the request goes out to the network with no warning.
19
+ */
20
+ export type TStoryMockResponse = object | ((request: unknown) => unknown);
21
+
22
+ export interface IStoryMockRequest {
23
+ url: string;
24
+ method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
25
+ status: number;
26
+ response: TStoryMockResponse;
27
+ }
28
+
29
+ /**
30
+ * The instance every story's Reqraft is initialized with. Override it with
31
+ * `REACT_APP_QORUS_INSTANCE` (or `QORUS_INSTANCE`) to run live stories against
32
+ * your own Qorus; mocks built from it follow the override.
33
+ */
34
+ export const STORY_QORUS_INSTANCE =
35
+ process.env.REACT_APP_QORUS_INSTANCE || 'https://hq.qoretechnologies.com:8092/';
36
+
37
+ /** The URL `query()` requests for `path`. */
38
+ export const storyApiUrl = (path: string): string =>
39
+ buildReqraftApiUrl(STORY_QORUS_INSTANCE, path);
40
+
41
+ /**
42
+ * The URL `ReqraftWebSocket` dials for `path`, token omitted — mock-socket
43
+ * matches servers without the query string.
44
+ */
45
+ export const storySocketUrl = (path: string): string =>
46
+ buildReqraftSocketUrl(STORY_QORUS_INSTANCE, path);
47
+
48
+ /** A GET of `path` answered with `response`. */
49
+ const mockGet = (path: string, response: TStoryMockResponse): IStoryMockRequest[] => [
50
+ { url: storyApiUrl(path), method: 'GET', status: 200, response },
51
+ ];
52
+
53
+ /**
54
+ * The type catalogue, pinned to the built-in list. `useQorusTypes` uses a
55
+ * reachable server's list *instead of* the built-in one, so an unmocked story
56
+ * renders whichever labels that server happens to have — and every FormEngine
57
+ * shows its loading skeleton until the request settles, which against an
58
+ * unreachable instance is never.
59
+ */
60
+ const QORUS_TYPE_INFO_MOCK_DATA = mockGet('system/qorus-type-info', defaultQorusTypes);
61
+
62
+ /**
63
+ * The system expression catalogue, empty. `useExpressions` fetches it whenever
64
+ * functions are allowed — even when the story passes its own list, which is
65
+ * merged in as extras — and TemplateField shows a skeleton in place of "Use
66
+ * Expression" until it arrives. Stories that need functions provide them
67
+ * (`expressions`, or their own `mockData` for this URL).
68
+ */
69
+ const EXPRESSIONS_CATALOGUE_MOCK_DATA = mockGet('system?action=expressions&context=ui', []);
70
+
71
+ /**
72
+ * `ReqraftWebSocket`'s server probe, which every reconnect attempt awaits
73
+ * before it dials. Unanswered, no attempt is ever made — a mock socket server
74
+ * that comes back is never reconnected to, and one that stays down is never
75
+ * given up on. The probe only needs an answer; its body is not read.
76
+ */
77
+ const SERVER_STATUS_MOCK_DATA = mockGet('system/pid', {});
78
+
79
+ /**
80
+ * Requests components make on their own, whatever the story is about —
81
+ * mounting a FormEngine fetches the type catalogue; allowing functions fetches
82
+ * the expression catalogue; a reconnecting socket probes the server.
83
+ * Registered for every story as storybook-addon-mock's `globalMockData`
84
+ * (`.storybook/preview.tsx`, and mirrored for the Vitest run in
85
+ * `.storybook/vitest.setup.ts`); a story's own `mockData` entry for the same
86
+ * URL takes precedence.
87
+ */
88
+ export const GLOBAL_STORY_MOCK_DATA: IStoryMockRequest[] = [
89
+ ...QORUS_TYPE_INFO_MOCK_DATA,
90
+ ...EXPRESSIONS_CATALOGUE_MOCK_DATA,
91
+ ...SERVER_STATUS_MOCK_DATA,
92
+ ];
@@ -13,6 +13,21 @@ export interface IReqraftFetchResponse<T> {
13
13
  ok: boolean;
14
14
  code?: number;
15
15
  error?: any;
16
+ /**
17
+ * The parsed error body on a non-ok response, when the server sent JSON.
18
+ *
19
+ * Qorus errors carry `{ err, desc }`; `error` above is only the HTTP reason
20
+ * phrase, which is why a caller that wanted the sentence had to reach into
21
+ * `data`. Consumers that need the code (`err`) or the message (`desc`) should
22
+ * read this rather than re-parsing.
23
+ */
24
+ errorBody?: Record<string, any>;
25
+ /**
26
+ * The response text when the body was NOT valid JSON. A non-JSON error would
27
+ * otherwise arrive as `{}` with only a reason phrase, discarding whatever the
28
+ * server actually said.
29
+ */
30
+ rawText?: string;
16
31
  response: Response;
17
32
  }
18
33
 
@@ -39,26 +54,104 @@ export const setupFetch = ({
39
54
  }
40
55
  };
41
56
 
57
+ /**
58
+ * The API path a caller asked for, without the leading slash the prefix already
59
+ * carries.
60
+ *
61
+ * `doFetchData` builds `${instance}api/latest/${url}`, and that prefix ENDS in a
62
+ * slash — so a caller writing `/dataprovider/arg_schemas/x` produced
63
+ * `api/latest//dataprovider/arg_schemas/x`. Qorus serves it, which is how both
64
+ * spellings survived side by side (`useArgSchema` writes one, `CompactRow` and
65
+ * `AutoFormField` the other), but it is not harmless: the query cache is keyed
66
+ * on the url, so `/x` and `x` were two cache entries and two requests for one
67
+ * resource.
68
+ *
69
+ * Normalised here, once, rather than at each call site — the convention is
70
+ * invisible from a caller's point of view and the next one would get it wrong
71
+ * again. Only applied when the prefix is added: a caller that opts out of the
72
+ * prefix owns its whole path, leading slash included.
73
+ */
74
+ export const reqraftApiPath = (url: string, noApiPrefix: boolean = false): string =>
75
+ noApiPrefix ? url : url.replace(/^\/+/, '');
76
+
77
+ /**
78
+ * A cheap, stable, non-reversible marker for a bearer token.
79
+ *
80
+ * Two callers holding DIFFERENT tokens are two identities and must not share a
81
+ * cached response, so the token has to take part in the cache key — but a raw
82
+ * token in a key is a credential sitting in devtools' query inspector. djb2 is
83
+ * enough to tell two tokens apart, which is all the key needs.
84
+ */
85
+ const tokenMarker = (token?: string): string => {
86
+ if (!token) {
87
+ return '';
88
+ }
89
+ let hash = 5381;
90
+ for (let index = 0; index < token.length; index++) {
91
+ hash = ((hash << 5) + hash + token.charCodeAt(index)) | 0;
92
+ }
93
+ return `:t${(hash >>> 0).toString(36)}`;
94
+ };
95
+
96
+ /**
97
+ * The one cache key for a request, used by every caller in every downstream
98
+ * project so that one resource is one entry and one in-flight request.
99
+ *
100
+ * `instance` and the token take part because both change WHICH server and WHOSE
101
+ * data answers: a call that overrides the instance, or that carries an explicit
102
+ * token, is a different resource that happens to share a path.
103
+ */
104
+ export const reqraftCacheKey = ({
105
+ url,
106
+ method = 'GET',
107
+ body,
108
+ noApiPrefix,
109
+ instance,
110
+ token,
111
+ }: Pick<IReqraftQueryConfig, 'url' | 'method' | 'body' | 'noApiPrefix' | 'instance' | 'token'>) =>
112
+ `${reqraftApiPath(url, noApiPrefix)}:${method}:${JSON.stringify(body || {})}${
113
+ instance && instance !== fetchConfig.instance ? `:@${instance}` : ''
114
+ }${tokenMarker(token)}`;
115
+
116
+ /**
117
+ * The URL `query()` requests for `url` on `instance` — the single definition.
118
+ * Story mocks build their URLs with it too, so they cannot drift from what the
119
+ * code actually dials.
120
+ *
121
+ * `noApiPrefix` means the caller owns the WHOLE url — an absolute address for
122
+ * another service, which is the only thing reqraft itself uses it for
123
+ * (`useExpressions` sets it exactly when `expressionsUrl` is `http(s)://…`).
124
+ * Prepending the instance there built `https://instance:8011/https://other/…`.
125
+ */
126
+ export const buildReqraftApiUrl = (instance: string, url: string, noApiPrefix = false): string =>
127
+ noApiPrefix ? url : `${instance}api/latest/${reqraftApiPath(url)}`;
128
+
42
129
  async function doFetchData(
43
130
  url: string,
44
131
  method = 'GET',
45
132
  body?: { [key: string]: any },
46
133
  noApiPrefix = false,
47
- instance = fetchConfig.instance
134
+ instance = fetchConfig.instance,
135
+ headers?: Record<string, string>,
136
+ token?: string
48
137
  ): Promise<Response> {
49
138
  // We do not check for token because Qorus now handles auth automatically via cookies
50
139
  // token is only supplied in a dev environment
51
- const headers = {
140
+ const finalHeaders: Record<string, string> = {
52
141
  'Content-Type': 'application/json',
142
+ ...(headers ?? {}),
53
143
  };
54
144
 
55
- if (fetchConfig.instanceToken && !fetchConfig.instanceRbacDisabled) {
56
- headers['Authorization'] = `Bearer ${fetchConfig.instanceToken}`;
145
+ const finalToken =
146
+ token ?? (fetchConfig.instanceRbacDisabled ? undefined : fetchConfig.instanceToken);
147
+
148
+ if (finalToken && !finalHeaders['Authorization']) {
149
+ finalHeaders['Authorization'] = `Bearer ${finalToken}`;
57
150
  }
58
151
 
59
- return fetch(`${instance}${noApiPrefix ? '' : 'api/latest/'}${url}`, {
152
+ return fetch(buildReqraftApiUrl(instance, url, noApiPrefix), {
60
153
  method,
61
- headers,
154
+ headers: finalHeaders,
62
155
  body: JSON.stringify(body),
63
156
  credentials: 'include',
64
157
  }).catch((error) => {
@@ -75,11 +168,123 @@ export interface IReqraftQueryConfig {
75
168
  body?: Record<string | number, any>;
76
169
  cache?: boolean;
77
170
  queryClient?: QueryClient;
171
+ /**
172
+ * The `url` is a complete address and is used verbatim — neither the instance
173
+ * nor `api/latest/` is prepended, and its leading slash is left alone. For
174
+ * reaching a service that is not this Qorus instance.
175
+ */
78
176
  noApiPrefix?: boolean;
79
177
  /** Override the global instance URL for this single call (e.g. to target a different port). */
80
178
  instance?: string;
179
+ /** Extra request headers, merged over the default `Content-Type`. */
180
+ headers?: Record<string, string>;
181
+ /**
182
+ * A bearer token for THIS call, instead of the configured instance token —
183
+ * for a route that is authenticated as somebody other than the current app
184
+ * session. Takes part in the cache key.
185
+ */
186
+ token?: string;
187
+ /**
188
+ * An explicit cache key, for a caller that must group or separate requests
189
+ * differently from the default `path:method:body` identity.
190
+ */
191
+ cacheKey?: string;
192
+ /**
193
+ * How long a cached response counts as fresh, in ms. Defaults to 5 minutes
194
+ * when `cache` is on. `Infinity` keeps it for the life of the page — what a
195
+ * caller wants for a catalogue that cannot change without a server restart.
196
+ */
197
+ staleTime?: number;
198
+ /**
199
+ * Whether a 401 on this request should send the page to
200
+ * `fetchConfig.unauthorizedRedirect`. Defaults to `true`.
201
+ *
202
+ * A 401 only means "this app's session expired" when the request actually
203
+ * carried this app's credential. A call that targets another service, or that
204
+ * hands over an explicit token, proves nothing about the session — signing the
205
+ * user out because an unrelated credential was refused is wrong. Callers that
206
+ * own their own auth policy (or that must never navigate, such as a test
207
+ * runner or a Storybook preview) pass `false`.
208
+ */
209
+ redirectOnUnauthorized?: boolean;
81
210
  }
82
211
 
212
+ /**
213
+ * Reads a response body without consuming it, and says whether it was JSON.
214
+ *
215
+ * `data` stays `{}` for a body that is empty or not JSON, which is the contract
216
+ * reqraft's consumers have always been given. The text is handed back separately
217
+ * as `rawText` so an error that was not JSON still carries whatever the server
218
+ * said, instead of being flattened to a bare reason phrase.
219
+ */
220
+ const readBody = async (response: Response): Promise<{ data: any; rawText?: string }> => {
221
+ const rawText = await response.clone().text();
222
+
223
+ try {
224
+ return { data: JSON.parse(rawText) };
225
+ } catch (_error) {
226
+ return { data: {}, rawText };
227
+ }
228
+ };
229
+
230
+ /**
231
+ * The single request mechanism.
232
+ *
233
+ * Every request in reqraft AND in the projects built on it goes through here,
234
+ * so that one resource has one cache entry and one in-flight request no matter
235
+ * which library, hook or component asked for it. A downstream project that
236
+ * keeps its own fetch helper (qorus-ide's `fetchData` is the one this was
237
+ * written for) should adapt onto this rather than hold a second cache: two
238
+ * caches over one API cannot see each other's in-flight requests, so any
239
+ * resource both libraries want is fetched twice by construction.
240
+ */
241
+ /**
242
+ * Put a resource the HOST already has into the cache `query` reads.
243
+ *
244
+ * The comment on `query` states the problem: two caches over one API cannot see
245
+ * each other's in-flight requests, so any resource both libraries want is
246
+ * fetched twice by construction. This is the seam that lets a host settle it
247
+ * without either side giving up its own loader.
248
+ *
249
+ * The case it was written for: the Qorus IDE warm-starts
250
+ * `/system/qorus-type-info` from `index.html`, before the bundle has even
251
+ * parsed, because its whole boot gates on it — and then reqraft's own
252
+ * `useQorusTypes` asked for it again on the first form's mount. Measured on the
253
+ * live IDE at 419ms and 2777ms, the same URL, the same answer.
254
+ *
255
+ * Seeding is enough to stop the second request: `query` goes through
256
+ * `fetchQuery` with a `staleTime`, and a fresh entry is returned without the
257
+ * query function ever running. `useFetch` reads the same cache directly, so it
258
+ * also skips its loading state and renders the answer on its first paint.
259
+ *
260
+ * Only for a resource the host has genuinely FETCHED. Seeding a guess would
261
+ * make every consumer believe a request had succeeded.
262
+ */
263
+ export const seedQueryCache = <T>({
264
+ url,
265
+ method = 'GET',
266
+ body,
267
+ noApiPrefix,
268
+ instance,
269
+ token,
270
+ data,
271
+ queryClient = ReqraftQueryClient,
272
+ }: Pick<
273
+ IReqraftQueryConfig,
274
+ 'url' | 'method' | 'body' | 'noApiPrefix' | 'instance' | 'token' | 'queryClient'
275
+ > & { data: T }): void => {
276
+ const key = reqraftCacheKey({ url, method, body, noApiPrefix, instance, token });
277
+
278
+ queryClient.setQueryData([key], {
279
+ data,
280
+ rawText: undefined,
281
+ ok: true,
282
+ status: 200,
283
+ statusText: 'OK',
284
+ response: undefined,
285
+ });
286
+ };
287
+
83
288
  export async function query<T>({
84
289
  url,
85
290
  method = 'GET',
@@ -88,47 +293,54 @@ export async function query<T>({
88
293
  queryClient = ReqraftQueryClient,
89
294
  noApiPrefix = false,
90
295
  instance,
296
+ headers,
297
+ token,
298
+ cacheKey,
299
+ staleTime,
300
+ redirectOnUnauthorized = true,
91
301
  }: IReqraftQueryConfig): Promise<IReqraftFetchResponse<T>> {
92
302
  const shouldCache = method === 'DELETE' || method === 'POST' ? false : cache;
93
- const cacheKey = `${url}:${method}:${JSON.stringify(body || {})}`;
303
+ const key = cacheKey ?? reqraftCacheKey({ url, method, body, noApiPrefix, instance, token });
94
304
 
95
305
  const requestData = await queryClient.fetchQuery({
96
- queryKey: [cacheKey],
306
+ queryKey: [key],
97
307
  queryFn: async () => {
98
- const response = await doFetchData(url, method, body, noApiPrefix, instance);
308
+ const response = await doFetchData(url, method, body, noApiPrefix, instance, headers, token);
99
309
 
100
- if (response.status === 401 && fetchConfig.unauthorizedRedirect) {
101
- window.location.href = fetchConfig.unauthorizedRedirect(window.location);
310
+ if (response.status === 401 && redirectOnUnauthorized && fetchConfig.unauthorizedRedirect) {
311
+ // `replace`, not an assignment: the page being left is dead, and a
312
+ // history entry for it means Back lands on a view that can only 401
313
+ // again.
314
+ window.location.replace(fetchConfig.unauthorizedRedirect(window.location));
102
315
  }
103
316
 
104
- const clone = response.clone();
105
- let data: any;
106
-
107
- try {
108
- data = await clone.json();
109
- } catch (error) {
110
- data = {};
111
- }
317
+ const { data, rawText } = await readBody(response);
112
318
 
113
319
  return {
114
320
  data,
321
+ rawText,
115
322
  ok: response.ok,
116
323
  status: response.status,
117
324
  statusText: response.statusText,
118
325
  response,
119
326
  };
120
327
  },
121
- staleTime: shouldCache ? CACHE_EXPIRATION_TIME : 0,
328
+ staleTime: shouldCache ? (staleTime ?? CACHE_EXPIRATION_TIME) : 0,
122
329
  });
123
330
 
124
331
  if (!requestData.ok) {
125
- queryClient.invalidateQueries({ queryKey: [cacheKey] });
332
+ queryClient.invalidateQueries({ queryKey: [key] });
126
333
 
127
334
  return {
128
335
  data: requestData.data,
129
336
  ok: false,
130
337
  code: requestData.status,
131
338
  error: requestData.statusText,
339
+ // Only when the body really was JSON: `data` is `{}` for a non-JSON body,
340
+ // and an empty object masquerading as a parsed error tells a caller
341
+ // nothing while looking like it did.
342
+ errorBody: requestData.rawText === undefined ? requestData.data : undefined,
343
+ rawText: requestData.rawText,
132
344
  response: requestData.response,
133
345
  };
134
346
  }
@@ -137,6 +349,84 @@ export async function query<T>({
137
349
  data: requestData.data,
138
350
  ok: true,
139
351
  code: requestData.status,
352
+ rawText: requestData.rawText,
140
353
  response: requestData.response,
141
354
  };
142
355
  }
356
+
357
+ export interface IReqraftRawResponse {
358
+ ok: boolean;
359
+ code?: number;
360
+ error?: string;
361
+ /** The response bytes. Undefined on a non-ok response. */
362
+ blob?: Blob;
363
+ /** The `Content-Type` the bytes were served with, without parameters. */
364
+ mime?: string;
365
+ }
366
+
367
+ /**
368
+ * Fetch a resource whose body is NOT JSON — a file, an export, a log.
369
+ *
370
+ * Shares `doFetchData` with `query`, which owns the API prefix, the bearer token
371
+ * and `credentials: 'include'`. The point is that raw responses do not become a
372
+ * second, drifting copy of that auth handling.
373
+ *
374
+ * Nothing is cached: these payloads are large and read once.
375
+ *
376
+ * @param accept the `Accept` header. Endpoints that negotiate on the file's own
377
+ * MIME type answer **406** unless the caller accepts that type, and the caller
378
+ * usually cannot know it ahead of time, so this accepts anything by default.
379
+ */
380
+ export async function queryRaw({
381
+ url,
382
+ method = 'GET',
383
+ body,
384
+ noApiPrefix = false,
385
+ instance,
386
+ headers,
387
+ token,
388
+ accept = '*/*',
389
+ redirectOnUnauthorized = true,
390
+ }: Omit<IReqraftQueryConfig, 'cache' | 'queryClient' | 'cacheKey' | 'staleTime'> & {
391
+ accept?: string;
392
+ }): Promise<IReqraftRawResponse> {
393
+ try {
394
+ const response = await doFetchData(
395
+ url,
396
+ method,
397
+ body,
398
+ noApiPrefix,
399
+ instance,
400
+ {
401
+ Accept: accept,
402
+ ...(headers ?? {}),
403
+ },
404
+ token
405
+ );
406
+
407
+ if (response.status === 401 && redirectOnUnauthorized && fetchConfig.unauthorizedRedirect) {
408
+ window.location.replace(fetchConfig.unauthorizedRedirect(window.location));
409
+ }
410
+
411
+ if (!response.ok) {
412
+ let error: string;
413
+ try {
414
+ // an error body is still JSON even when the success body is not
415
+ error = (await response.json()).desc ?? response.statusText;
416
+ } catch (_error) {
417
+ error = response.statusText;
418
+ }
419
+
420
+ return { ok: false, code: response.status, error };
421
+ }
422
+
423
+ return {
424
+ ok: true,
425
+ code: response.status,
426
+ blob: await response.blob(),
427
+ mime: (response.headers.get('content-type') ?? '').split(';')[0].trim() || undefined,
428
+ };
429
+ } catch (error) {
430
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
431
+ }
432
+ }
@@ -90,6 +90,12 @@ class LspSharedConnection {
90
90
  private pending = new Map<number, IPendingRequest>();
91
91
  private readonly clients = new Set<ReqraftLspClient>();
92
92
  private initPromise: Promise<void> | null = null;
93
+ /**
94
+ * Fails the handshake in flight, if there is one. Every way this connection
95
+ * stops — released, reset, or given up by its socket — goes through it, so
96
+ * no `connect()` caller is ever left waiting on a socket that is gone.
97
+ */
98
+ private failHandshake: ((err: Error) => void) | null = null;
93
99
 
94
100
  connected = false;
95
101
  capabilities: ILspServerCapabilities | null = null;
@@ -106,9 +112,16 @@ class LspSharedConnection {
106
112
  return this.initPromise;
107
113
  }
108
114
 
109
- this.initPromise = new Promise<void>((resolve, reject) => {
115
+ const attempt = new Promise<void>((resolve, reject) => {
110
116
  let initialConnect = true;
111
117
 
118
+ this.failHandshake = (err) => {
119
+ if (initialConnect) {
120
+ initialConnect = false;
121
+ reject(err);
122
+ }
123
+ };
124
+
112
125
  this.rws = new ReqraftWebSocket({
113
126
  url: this.url,
114
127
  pooled: false,
@@ -144,6 +157,7 @@ class LspSharedConnection {
144
157
  }
145
158
  if (initialConnect) {
146
159
  initialConnect = false;
160
+ this.failHandshake = null;
147
161
  // Awaiting clients self-notify ready in their connect().
148
162
  resolve();
149
163
  } else {
@@ -219,17 +233,42 @@ class LspSharedConnection {
219
233
  onError: () => {
220
234
  // onClose fires after onError; rejection happens there.
221
235
  },
236
+ onReconnectFailed: () => {
237
+ this.giveUp();
238
+ },
222
239
  });
223
240
  });
241
+ this.initPromise = attempt;
224
242
 
225
243
  // Reset on failure so connect() can be retried with a clean slate —
226
244
  // close() also drops the dead socket, which would otherwise leak when
227
- // a retry stacks a fresh ReqraftWebSocket on top of it.
228
- this.initPromise.catch(() => {
229
- this.close();
245
+ // a retry stacks a fresh ReqraftWebSocket on top of it. Only for THIS
246
+ // attempt: by the time the rejection lands a client may already have
247
+ // started the next one, and closing that would kill a live socket.
248
+ attempt.catch(() => {
249
+ if (this.initPromise === attempt) {
250
+ this.close();
251
+ }
230
252
  });
231
253
 
232
- return this.initPromise;
254
+ return attempt;
255
+ }
256
+
257
+ /**
258
+ * The socket has stopped reconnecting. Without this the connection would
259
+ * stay registered around a dead socket for as long as any client holds it —
260
+ * which, for the page-lifetime render client, is forever: a first handshake
261
+ * that never completed kept every later `connect()` waiting on it, and one
262
+ * that had completed kept reporting the dead socket as ready. Fail whatever
263
+ * is waiting and forget the socket, so the next `connect()` dials afresh.
264
+ */
265
+ private giveUp(): void {
266
+ this.clients.forEach((c) => c._forgetConnect());
267
+ this.close(
268
+ new Error(
269
+ `LSP connection to ${this.url} gave up after ${this.config.maxReconnectTries} reconnect attempts`
270
+ )
271
+ );
233
272
  }
234
273
 
235
274
  /** @internal Test hook — close and forget every shared connection. */
@@ -242,13 +281,19 @@ class LspSharedConnection {
242
281
  release(client: ReqraftLspClient): void {
243
282
  this.clients.delete(client);
244
283
  if (this.clients.size === 0) {
245
- LspSharedConnection.registry.delete(this.url);
284
+ // A reset may already have replaced this connection for the url.
285
+ if (LspSharedConnection.registry.get(this.url) === this) {
286
+ LspSharedConnection.registry.delete(this.url);
287
+ }
246
288
  this.close();
247
289
  }
248
290
  }
249
291
 
250
- private close(): void {
292
+ private close(reason: Error = new Error('Client disconnected')): void {
251
293
  this.initPromise = null;
294
+ const failHandshake = this.failHandshake;
295
+ this.failHandshake = null;
296
+ failHandshake?.(reason);
252
297
  if (this.rws) {
253
298
  // Disable reconnect before cleanup to prevent zombie reconnect timers.
254
299
  this.rws.options.reconnect = false;
@@ -374,18 +419,30 @@ export class ReqraftLspClient {
374
419
  this
375
420
  );
376
421
  }
377
- this.connectPromise = this.conn
422
+ const attempt: Promise<void> = this.conn
378
423
  .connect()
379
424
  .then(() => {
380
425
  this.readyCallback?.(true);
381
426
  })
382
427
  .catch((err) => {
383
- // Allow a retry after failure.
384
- this.connectPromise = null;
428
+ // Allow a retry after failure — unless one has already started.
429
+ if (this.connectPromise === attempt) {
430
+ this.connectPromise = null;
431
+ }
385
432
  this.readyCallback?.(false);
386
433
  throw err;
387
434
  });
388
- return this.connectPromise;
435
+ this.connectPromise = attempt;
436
+ return attempt;
437
+ }
438
+
439
+ /**
440
+ * @internal The shared connection gave up on its socket. Drop the cached
441
+ * handshake so the next `connect()` dials again instead of resolving from
442
+ * a socket that no longer exists.
443
+ */
444
+ _forgetConnect(): void {
445
+ this.connectPromise = null;
389
446
  }
390
447
 
391
448
  /**
@@ -18,6 +18,21 @@ export interface IReqraftWebSocketConfig {
18
18
  tokenOverride?: string;
19
19
  }
20
20
 
21
+ /**
22
+ * The URL a socket for `path` dials on `instance`: `http(s)` becomes `ws(s)`,
23
+ * and the token, when there is one, rides in the query. The single definition —
24
+ * story mocks build their URLs with it too, so they cannot drift from it.
25
+ */
26
+ export const buildReqraftSocketUrl = (instance: string, path: string, token?: string): string => {
27
+ let wsUrl = instance.replace('http', 'ws');
28
+
29
+ if (wsUrl.endsWith('/')) {
30
+ wsUrl = wsUrl.slice(0, -1);
31
+ }
32
+
33
+ return `${wsUrl}/${path}${token ? `?token=${token}` : ''}`;
34
+ };
35
+
21
36
  export class ReqraftWebSocketsManager {
22
37
  public static defaultConfig: IReqraftWebSocketConfig = {
23
38
  reconnect: true,
@@ -108,15 +123,11 @@ export class ReqraftWebSocket {
108
123
  }
109
124
 
110
125
  private getSocketUrl() {
111
- let wsUrl = fetchConfig.instance.replace('http', 'ws');
112
-
113
- if (wsUrl.endsWith('/')) {
114
- wsUrl = wsUrl.slice(0, -1);
115
- }
116
-
117
- const token = this.options.tokenOverride || fetchConfig.instanceToken;
118
-
119
- return `${wsUrl}/${this.options.url}${token ? `?token=${token}` : ''}`;
126
+ return buildReqraftSocketUrl(
127
+ fetchConfig.instance,
128
+ this.options.url,
129
+ this.options.tokenOverride || fetchConfig.instanceToken
130
+ );
120
131
  }
121
132
 
122
133
  public connect() {