@alecsibilia/ui-kit 0.0.0-stage → 0.1.0-alpha.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 (283) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/LICENSE +201 -0
  3. package/README.md +233 -2
  4. package/bin/ui-kit.js +12 -0
  5. package/dist/alchemy/app.d.ts +34 -0
  6. package/dist/alchemy/app.js +88 -0
  7. package/dist/alchemy/index.d.ts +11 -0
  8. package/dist/alchemy/index.js +11 -0
  9. package/dist/alchemy/live-rooms.d.ts +21 -0
  10. package/dist/alchemy/live-rooms.js +31 -0
  11. package/dist/alchemy/migrations.d.ts +28 -0
  12. package/dist/alchemy/migrations.js +56 -0
  13. package/dist/alchemy/stage.d.ts +20 -0
  14. package/dist/alchemy/stage.js +20 -0
  15. package/dist/alchemy/wrangler-config.d.ts +76 -0
  16. package/dist/alchemy/wrangler-config.js +82 -0
  17. package/dist/build/app-modules.d.ts +11 -0
  18. package/dist/build/app-modules.js +40 -0
  19. package/dist/build/check.d.ts +4 -0
  20. package/dist/build/check.js +170 -0
  21. package/dist/build/cli.d.ts +1 -0
  22. package/dist/build/cli.js +79 -0
  23. package/dist/build/feature.d.ts +8 -0
  24. package/dist/build/feature.js +24 -0
  25. package/dist/build/index.d.ts +13 -0
  26. package/dist/build/index.js +13 -0
  27. package/dist/build/measure-cpu.d.ts +2 -0
  28. package/dist/build/measure-cpu.js +196 -0
  29. package/dist/build/prerender.d.ts +5 -0
  30. package/dist/build/prerender.js +109 -0
  31. package/dist/build/preview.d.ts +7 -0
  32. package/dist/build/preview.js +41 -0
  33. package/dist/build/seo-files.d.ts +27 -0
  34. package/dist/build/seo-files.js +24 -0
  35. package/dist/client/head-swap.d.ts +45 -0
  36. package/dist/client/head-swap.js +183 -0
  37. package/dist/client/hydration-pass.d.ts +56 -0
  38. package/dist/client/hydration-pass.js +186 -0
  39. package/dist/client/hydration-reset.d.ts +82 -0
  40. package/dist/client/hydration-reset.js +154 -0
  41. package/dist/client/index.d.ts +37 -0
  42. package/dist/client/index.js +65 -0
  43. package/dist/client/nav-client.d.ts +35 -0
  44. package/dist/client/nav-client.js +371 -0
  45. package/dist/live/collab/doc-provider.d.ts +74 -0
  46. package/dist/live/collab/doc-provider.js +412 -0
  47. package/dist/live/collab/index.d.ts +51 -0
  48. package/dist/live/collab/index.jsx +142 -0
  49. package/dist/live/collab-status.d.ts +25 -0
  50. package/dist/live/collab-status.js +17 -0
  51. package/dist/live/cursors/cursor-engine.d.ts +57 -0
  52. package/dist/live/cursors/cursor-engine.js +243 -0
  53. package/dist/live/cursors/index.d.ts +46 -0
  54. package/dist/live/cursors/index.jsx +110 -0
  55. package/dist/live/declaration.d.ts +113 -0
  56. package/dist/live/declaration.js +94 -0
  57. package/dist/live/index.d.ts +8 -0
  58. package/dist/live/index.js +8 -0
  59. package/dist/live/protocol.d.ts +224 -0
  60. package/dist/live/protocol.js +272 -0
  61. package/dist/live/server/doc-store.d.ts +68 -0
  62. package/dist/live/server/doc-store.js +187 -0
  63. package/dist/live/server/index.d.ts +60 -0
  64. package/dist/live/server/index.js +77 -0
  65. package/dist/live/server/room-presence.d.ts +24 -0
  66. package/dist/live/server/room-presence.js +123 -0
  67. package/dist/live/server/room-sockets.d.ts +65 -0
  68. package/dist/live/server/room-sockets.js +97 -0
  69. package/dist/live/server/room.d.ts +20 -0
  70. package/dist/live/server/room.js +348 -0
  71. package/dist/live/server/route.d.ts +56 -0
  72. package/dist/live/server/route.js +159 -0
  73. package/dist/live/server/types.d.ts +163 -0
  74. package/dist/live/server/types.js +2 -0
  75. package/dist/logic/agent-actions.d.ts +133 -0
  76. package/dist/logic/agent-actions.js +150 -0
  77. package/dist/logic/command-types.d.ts +53 -0
  78. package/dist/logic/command-types.js +0 -0
  79. package/dist/logic/dev.d.ts +9 -0
  80. package/dist/logic/dev.js +10 -0
  81. package/dist/logic/draft-rebase.d.ts +59 -0
  82. package/dist/logic/draft-rebase.js +71 -0
  83. package/dist/logic/form-state.d.ts +105 -0
  84. package/dist/logic/form-state.js +93 -0
  85. package/dist/logic/head.d.ts +145 -0
  86. package/dist/logic/head.js +140 -0
  87. package/dist/logic/index.d.ts +27 -0
  88. package/dist/logic/index.js +25 -0
  89. package/dist/logic/island-def.d.ts +89 -0
  90. package/dist/logic/island-def.js +59 -0
  91. package/dist/logic/kit-commands.d.ts +104 -0
  92. package/dist/logic/kit-commands.js +72 -0
  93. package/dist/logic/kit-errors.d.ts +25 -0
  94. package/dist/logic/kit-errors.js +6 -0
  95. package/dist/logic/listen.d.ts +99 -0
  96. package/dist/logic/listen.js +92 -0
  97. package/dist/logic/mutation-def.d.ts +65 -0
  98. package/dist/logic/mutation-def.js +43 -0
  99. package/dist/logic/navigation-data.d.ts +50 -0
  100. package/dist/logic/navigation-data.js +55 -0
  101. package/dist/logic/navigation-policy.d.ts +74 -0
  102. package/dist/logic/navigation-policy.js +127 -0
  103. package/dist/logic/page-model-def.d.ts +108 -0
  104. package/dist/logic/page-model-def.js +31 -0
  105. package/dist/logic/path.d.ts +31 -0
  106. package/dist/logic/path.js +48 -0
  107. package/dist/logic/query-def.d.ts +56 -0
  108. package/dist/logic/query-def.js +37 -0
  109. package/dist/logic/query-key.d.ts +24 -0
  110. package/dist/logic/query-key.js +35 -0
  111. package/dist/logic/query-types.d.ts +28 -0
  112. package/dist/logic/query-types.js +2 -0
  113. package/dist/logic/resources.d.ts +163 -0
  114. package/dist/logic/resources.js +62 -0
  115. package/dist/logic/result.d.ts +30 -0
  116. package/dist/logic/result.js +23 -0
  117. package/dist/logic/route-model.d.ts +139 -0
  118. package/dist/logic/route-model.js +207 -0
  119. package/dist/logic/route-params.d.ts +80 -0
  120. package/dist/logic/route-params.js +114 -0
  121. package/dist/logic/route-table.d.ts +308 -0
  122. package/dist/logic/route-table.js +206 -0
  123. package/dist/logic/seo.d.ts +61 -0
  124. package/dist/logic/seo.js +101 -0
  125. package/dist/logic/site.d.ts +12 -0
  126. package/dist/logic/site.js +0 -0
  127. package/dist/logic/subscriptions.d.ts +177 -0
  128. package/dist/logic/subscriptions.js +152 -0
  129. package/dist/render/index.d.ts +32 -0
  130. package/dist/render/index.js +52 -0
  131. package/dist/runtime/island-wake.d.ts +38 -0
  132. package/dist/runtime/island-wake.js +147 -0
  133. package/dist/runtime/query-scope.d.ts +224 -0
  134. package/dist/runtime/query-scope.js +222 -0
  135. package/dist/runtime/room-hub.d.ts +107 -0
  136. package/dist/runtime/room-hub.js +307 -0
  137. package/dist/runtime/subscription-runner.d.ts +71 -0
  138. package/dist/runtime/subscription-runner.js +240 -0
  139. package/dist/server/bindings.d.ts +41 -0
  140. package/dist/server/bindings.js +74 -0
  141. package/dist/server/browser.d.ts +9 -0
  142. package/dist/server/browser.js +9 -0
  143. package/dist/server/edge-cache.d.ts +28 -0
  144. package/dist/server/edge-cache.js +35 -0
  145. package/dist/server/errors.d.ts +45 -0
  146. package/dist/server/errors.js +36 -0
  147. package/dist/server/form-actions-setup.d.ts +1 -0
  148. package/dist/server/form-actions-setup.js +15 -0
  149. package/dist/server/form-actions.d.ts +121 -0
  150. package/dist/server/form-actions.js +211 -0
  151. package/dist/server/index.d.ts +36 -0
  152. package/dist/server/index.js +35 -0
  153. package/dist/server/inputs.d.ts +45 -0
  154. package/dist/server/inputs.js +77 -0
  155. package/dist/server/rate-limit.d.ts +29 -0
  156. package/dist/server/rate-limit.js +32 -0
  157. package/dist/server/read-cache.d.ts +74 -0
  158. package/dist/server/read-cache.js +58 -0
  159. package/dist/server/request-info.d.ts +17 -0
  160. package/dist/server/request-info.js +11 -0
  161. package/dist/server/request.d.ts +52 -0
  162. package/dist/server/request.js +73 -0
  163. package/dist/server/response-cookies.d.ts +23 -0
  164. package/dist/server/response-cookies.js +24 -0
  165. package/dist/server/run-effect.d.ts +42 -0
  166. package/dist/server/run-effect.js +92 -0
  167. package/dist/server/run.d.ts +63 -0
  168. package/dist/server/run.js +66 -0
  169. package/dist/server/session.d.ts +125 -0
  170. package/dist/server/session.js +247 -0
  171. package/dist/test/fake-bindings.d.ts +32 -0
  172. package/dist/test/fake-bindings.js +108 -0
  173. package/dist/test/fake-room.d.ts +66 -0
  174. package/dist/test/fake-room.js +216 -0
  175. package/dist/test/index.d.ts +19 -0
  176. package/dist/test/index.js +44 -0
  177. package/dist/test/probe.d.ts +11 -0
  178. package/dist/test/probe.js +11 -0
  179. package/dist/test/solid-jsx.d.ts +23 -0
  180. package/dist/test/solid-jsx.js +28 -0
  181. package/dist/test/solid-preload.d.ts +1 -0
  182. package/dist/test/solid-preload.js +29 -0
  183. package/dist/ui/code-editor/index.d.ts +21 -0
  184. package/dist/ui/code-editor/index.jsx +286 -0
  185. package/dist/ui/collab-text/index.d.ts +29 -0
  186. package/dist/ui/collab-text/index.jsx +96 -0
  187. package/dist/ui/components/controls.d.ts +69 -0
  188. package/dist/ui/components/controls.jsx +81 -0
  189. package/dist/ui/components/feedback.d.ts +26 -0
  190. package/dist/ui/components/feedback.jsx +80 -0
  191. package/dist/ui/components/layout.d.ts +74 -0
  192. package/dist/ui/components/layout.jsx +146 -0
  193. package/dist/ui/components/lists.d.ts +69 -0
  194. package/dist/ui/components/lists.jsx +133 -0
  195. package/dist/ui/components/navigation.d.ts +73 -0
  196. package/dist/ui/components/navigation.jsx +112 -0
  197. package/dist/ui/components/text.d.ts +34 -0
  198. package/dist/ui/components/text.jsx +163 -0
  199. package/dist/ui/index.d.ts +7 -0
  200. package/dist/ui/index.js +7 -0
  201. package/dist/ui/jsx-runtime.d.ts +19 -0
  202. package/dist/ui/jsx-runtime.js +0 -0
  203. package/dist/ui/list-keys.d.ts +31 -0
  204. package/dist/ui/list-keys.js +45 -0
  205. package/dist/ui/styles/base.css +38 -0
  206. package/dist/ui/styles/components.css +608 -0
  207. package/dist/ui/styles/tokens.css +27 -0
  208. package/dist/ui/styles/transitions.css +23 -0
  209. package/dist/ui/styles/workbench.css +428 -0
  210. package/dist/ui/styles.css +9 -0
  211. package/dist/view/agent-actions-view.d.ts +30 -0
  212. package/dist/view/agent-actions-view.js +27 -0
  213. package/dist/view/agent-surface.d.ts +42 -0
  214. package/dist/view/agent-surface.js +123 -0
  215. package/dist/view/app-scope.d.ts +51 -0
  216. package/dist/view/app-scope.js +75 -0
  217. package/dist/view/boundary.d.ts +18 -0
  218. package/dist/view/boundary.jsx +26 -0
  219. package/dist/view/command-runner.d.ts +16 -0
  220. package/dist/view/command-runner.js +245 -0
  221. package/dist/view/form.d.ts +82 -0
  222. package/dist/view/form.jsx +109 -0
  223. package/dist/view/head-view.d.ts +31 -0
  224. package/dist/view/head-view.js +46 -0
  225. package/dist/view/index.d.ts +41 -0
  226. package/dist/view/index.js +40 -0
  227. package/dist/view/island-root.d.ts +30 -0
  228. package/dist/view/island-root.js +36 -0
  229. package/dist/view/island.d.ts +102 -0
  230. package/dist/view/island.jsx +154 -0
  231. package/dist/view/match.d.ts +41 -0
  232. package/dist/view/match.js +111 -0
  233. package/dist/view/model.d.ts +92 -0
  234. package/dist/view/model.js +162 -0
  235. package/dist/view/navigation-head.d.ts +29 -0
  236. package/dist/view/navigation-head.jsx +38 -0
  237. package/dist/view/page-model.d.ts +46 -0
  238. package/dist/view/page-model.js +146 -0
  239. package/dist/view/query-effects.d.ts +87 -0
  240. package/dist/view/query-effects.js +147 -0
  241. package/dist/view/query-ok.d.ts +45 -0
  242. package/dist/view/query-ok.js +96 -0
  243. package/dist/view/query.d.ts +115 -0
  244. package/dist/view/query.jsx +179 -0
  245. package/dist/view/result-view.d.ts +14 -0
  246. package/dist/view/result-view.jsx +15 -0
  247. package/dist/view/route-pages.d.ts +43 -0
  248. package/dist/view/route-pages.js +59 -0
  249. package/dist/view/router.d.ts +44 -0
  250. package/dist/view/router.js +123 -0
  251. package/dist/vite/dev-middleware.d.ts +12 -0
  252. package/dist/vite/dev-middleware.js +39 -0
  253. package/dist/vite/dev-objects.d.ts +25 -0
  254. package/dist/vite/dev-objects.js +127 -0
  255. package/dist/vite/dev-platform.d.ts +19 -0
  256. package/dist/vite/dev-platform.js +77 -0
  257. package/dist/vite/dev-seo-files.d.ts +11 -0
  258. package/dist/vite/dev-seo-files.js +40 -0
  259. package/dist/vite/index.d.ts +53 -0
  260. package/dist/vite/index.js +148 -0
  261. package/dist/vite/local-config.d.ts +34 -0
  262. package/dist/vite/local-config.js +72 -0
  263. package/dist/vite/worker-build.d.ts +24 -0
  264. package/dist/vite/worker-build.js +84 -0
  265. package/dist/worker/create-worker.d.ts +52 -0
  266. package/dist/worker/create-worker.js +90 -0
  267. package/dist/worker/index.d.ts +12 -0
  268. package/dist/worker/index.js +12 -0
  269. package/dist/worker/page-routes.d.ts +88 -0
  270. package/dist/worker/page-routes.js +100 -0
  271. package/dist/worker/page-status.d.ts +41 -0
  272. package/dist/worker/page-status.js +23 -0
  273. package/dist/worker/request-prelude.d.ts +69 -0
  274. package/dist/worker/request-prelude.js +107 -0
  275. package/dist/worker/security.d.ts +76 -0
  276. package/dist/worker/security.js +137 -0
  277. package/dist/worker/server-app.d.ts +54 -0
  278. package/dist/worker/server-app.js +76 -0
  279. package/guards/browser-only.js +5 -0
  280. package/guards/node-only.js +6 -0
  281. package/guards/server-only.js +5 -0
  282. package/migrations/0001-sessions.sql +22 -0
  283. package/package.json +233 -5
@@ -0,0 +1,75 @@
1
+ import { createComponent, createContext, NoHydration, useContext, } from 'solid-js';
2
+ import { createKitScope } from '../runtime/query-scope.js';
3
+ const KitScopeContext = createContext(null, {
4
+ name: 'KitScope',
5
+ });
6
+ const SiteContext = createContext(null, { name: 'Site' });
7
+ /**
8
+ * The page root. Wrap the app once (inside the root component, so it is
9
+ * created per SSR request — never shared across requests through module
10
+ * state). Everything inside renders as static server HTML
11
+ * (`<NoHydration>`): only `<Island of={...}>` roots ship JS and hydrate
12
+ * (see `island.tsx`); the browser never renders the app root itself.
13
+ *
14
+ * Provides:
15
+ * - the site's head defaults and agent-surface flag (`site`), read by the
16
+ * route pages' head, `<Head>` and `<AgentActions>`;
17
+ * - Way 1 shared reads: `<Query>`s with the same registry query, input and
18
+ * revision share one execution (one server call) while any of them holds it.
19
+ * - Way 2 outcome channel: `<Query>` publishes each settled outcome by
20
+ * registry query name; `createModel({ listens })` turns them into Messages.
21
+ * - page models (`usePageModel`): one instance per definition per page.
22
+ *
23
+ * In the browser the island client entry (`startIslands`) creates one
24
+ * scope per page and gives it to every island root, so islands share
25
+ * reads, outcomes, invalidations and page models.
26
+ *
27
+ * @example
28
+ * ```tsx
29
+ * export default function App() {
30
+ * return <AppScope site={siteSettings}><Page>...</Page></AppScope>;
31
+ * }
32
+ * ```
33
+ */
34
+ export function AppScope(props) {
35
+ const scope = createKitScope();
36
+ return createComponent(ScopeProviders, {
37
+ scope,
38
+ // Read once: site settings are constant for the app instance.
39
+ site: props.site ?? null,
40
+ get children() {
41
+ return createComponent(NoHydration, {
42
+ get children() {
43
+ return props.children;
44
+ },
45
+ });
46
+ },
47
+ });
48
+ }
49
+ /**
50
+ * Kit-internal: the scope and site contexts, without `<NoHydration>`. The
51
+ * page root (`AppScope`) and every island root (`IslandBody`, on the server
52
+ * inside `<Hydration>`, in the browser under `hydrate`) render it, so both
53
+ * sides create the same owners.
54
+ */
55
+ export function ScopeProviders(props) {
56
+ return createComponent(SiteContext, {
57
+ value: props.site,
58
+ get children() {
59
+ return createComponent(KitScopeContext, {
60
+ value: props.scope,
61
+ get children() {
62
+ return props.children;
63
+ },
64
+ });
65
+ },
66
+ });
67
+ }
68
+ /** The nearest `<AppScope site>`'s settings, or `null`. Kit-internal. */
69
+ export function useSite() {
70
+ return useContext(SiteContext) ?? null;
71
+ }
72
+ /** The nearest `<AppScope>`'s scope, or `null` outside one. Kit-internal. */
73
+ export function useKitScope() {
74
+ return useContext(KitScopeContext) ?? null;
75
+ }
@@ -0,0 +1,18 @@
1
+ /** @jsxImportSource @solidjs/web */
2
+ import { type Element as SolidElement } from 'solid-js';
3
+ /**
4
+ * Page-level error boundary with the kit's default notice. Replaces raw
5
+ * `<Errored>` in app code: the "Reset" action is kit-internal (no raw
6
+ * `reset()` callback in app code), and the thrown value is logged, never
7
+ * shown (only a fixed message reaches the page).
8
+ *
9
+ * @example
10
+ * ```tsx
11
+ * <PageBoundary>
12
+ * <Match on={nav().route}>{{ Home: () => <Home />, About: () => <About /> }}</Match>
13
+ * </PageBoundary>
14
+ * ```
15
+ */
16
+ export declare function PageBoundary(props: {
17
+ readonly children: SolidElement;
18
+ }): SolidElement;
@@ -0,0 +1,26 @@
1
+ /** @jsxImportSource @solidjs/web */
2
+ import { Errored } from 'solid-js';
3
+ import { Button, Notice } from '../ui/index.js';
4
+ /**
5
+ * Page-level error boundary with the kit's default notice. Replaces raw
6
+ * `<Errored>` in app code: the "Reset" action is kit-internal (no raw
7
+ * `reset()` callback in app code), and the thrown value is logged, never
8
+ * shown (only a fixed message reaches the page).
9
+ *
10
+ * @example
11
+ * ```tsx
12
+ * <PageBoundary>
13
+ * <Match on={nav().route}>{{ Home: () => <Home />, About: () => <About /> }}</Match>
14
+ * </PageBoundary>
15
+ * ```
16
+ */
17
+ export function PageBoundary(props) {
18
+ return (<Errored fallback={(error, reset) => {
19
+ console.error('[PageBoundary] Unexpected error:', error());
20
+ return (<Notice tone="danger" title="Unexpected Error" description="Something went wrong while rendering this page." action={<Button size="sm" variant="primary" onClick={() => reset()}>
21
+ Reset
22
+ </Button>}/>);
23
+ }}>
24
+ {props.children}
25
+ </Errored>);
26
+ }
@@ -0,0 +1,16 @@
1
+ import type { CommandHandlers } from '../logic/command-types.ts';
2
+ import { type Tagged } from '../logic/result.ts';
3
+ import type { KitScope } from '../runtime/query-scope.ts';
4
+ export type { CommandContext, CommandHandlers, TraceEntry, } from '../logic/command-types.ts';
5
+ export declare function isPlainObject(value: unknown): value is Record<string, unknown>;
6
+ export declare function isCommandTuple<Model, Cmd>(result: unknown): result is readonly [Model, readonly Cmd[]];
7
+ /**
8
+ * The Command runner. Async work runs as plain promises (never inside a
9
+ * Solid `action`), so the model's writes commit immediately: the model's
10
+ * state IS the pending UI. Timers and result Messages are dropped once the
11
+ * owner is disposed; a mutation's invalidation is not.
12
+ */
13
+ export declare function createCommandRunner<Msg, Cmd extends Tagged>(handlers: CommandHandlers<Cmd, Msg>, send: (msg: Msg) => void, scope: KitScope | null): {
14
+ run: (commands: readonly Cmd[]) => void;
15
+ clearAll: () => void;
16
+ };
@@ -0,0 +1,245 @@
1
+ import { isServer } from '@solidjs/web';
2
+ import { getOwner, onCleanup } from 'solid-js';
3
+ import { navigateTo } from './router.js';
4
+ import { KIT_COMMAND_TAGS } from '../logic/kit-commands.js';
5
+ import { UNEXPECTED_QUERY_MESSAGE, } from '../logic/query-types.js';
6
+ import { err } from '../logic/result.js';
7
+ export function isPlainObject(value) {
8
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
9
+ return false;
10
+ }
11
+ const proto = Object.getPrototypeOf(value);
12
+ return proto === Object.prototype || proto === null;
13
+ }
14
+ export function isCommandTuple(result) {
15
+ return (Array.isArray(result) && result.length === 2 && Array.isArray(result[1]));
16
+ }
17
+ const UNEXPECTED = {
18
+ _tag: 'Unexpected',
19
+ message: UNEXPECTED_QUERY_MESSAGE,
20
+ };
21
+ function requireScope(scope, what) {
22
+ if (!scope) {
23
+ throw new Error(`${what} needs <AppScope> (create the model inside it).`);
24
+ }
25
+ return scope;
26
+ }
27
+ /**
28
+ * Invalidations run on a microtask, after the batch that holds the model's
29
+ * own writes has committed (Solid flushes on an earlier-queued microtask).
30
+ * In the same batch, the refetch's pending read would entangle and hold
31
+ * those writes ("Saved", the new version) until the refetch lands.
32
+ */
33
+ function invalidateAfterCommit(target, queryId, inputKey) {
34
+ queueMicrotask(() => target.invalidations.invalidate(queryId, inputKey));
35
+ }
36
+ /** Runs `fn`, logging (never rethrowing) what it throws. */
37
+ function logThrown(label, fn) {
38
+ try {
39
+ fn();
40
+ }
41
+ catch (error) {
42
+ console.error(`[${label}] error handler threw:`, error);
43
+ }
44
+ }
45
+ /**
46
+ * Kit-internal async step: runs `work` as a plain promise (never inside a
47
+ * Solid `action`, so the model's own writes commit at once) and hands the
48
+ * outcome to `onDone` / `onError`. If `onDone` throws (a throwing
49
+ * `toMessage`, or an `update` that throws on the result Message), the error
50
+ * is logged and routed to `onError`, so a result never vanishes silently.
51
+ */
52
+ function settle(label, work, onDone, onError) {
53
+ let pending;
54
+ try {
55
+ pending = Promise.resolve(work());
56
+ }
57
+ catch (error) {
58
+ pending = Promise.reject(error);
59
+ }
60
+ void pending.then((value) => {
61
+ try {
62
+ onDone(value);
63
+ }
64
+ catch (error) {
65
+ console.error(`[${label}] result handler threw:`, error);
66
+ logThrown(label, () => onError(error));
67
+ }
68
+ }, (error) => logThrown(label, () => onError(error)));
69
+ }
70
+ function browserStorage() {
71
+ if (typeof window === 'undefined')
72
+ return undefined;
73
+ try {
74
+ return window.localStorage;
75
+ }
76
+ catch {
77
+ // Storage blocked (sandboxed iframe, privacy settings).
78
+ return undefined;
79
+ }
80
+ }
81
+ function readStorageKeys(wanted, prefixes = []) {
82
+ const storage = browserStorage();
83
+ const values = {};
84
+ if (!storage)
85
+ return values;
86
+ const keys = [...wanted];
87
+ if (prefixes.length > 0) {
88
+ try {
89
+ for (let i = 0; i < storage.length; i += 1) {
90
+ const key = storage.key(i);
91
+ if (key !== null && prefixes.some((p) => key.startsWith(p)))
92
+ keys.push(key);
93
+ }
94
+ }
95
+ catch (error) {
96
+ console.error('[StorageRead] listing keys:', error);
97
+ }
98
+ }
99
+ for (const key of keys) {
100
+ try {
101
+ const value = storage.getItem(key);
102
+ if (value !== null)
103
+ values[key] = value;
104
+ }
105
+ catch (error) {
106
+ console.error(`[StorageRead] ${key}:`, error);
107
+ }
108
+ }
109
+ return values;
110
+ }
111
+ function writeStorageKey(key, value) {
112
+ const storage = browserStorage();
113
+ if (!storage)
114
+ return;
115
+ try {
116
+ if (value === null)
117
+ storage.removeItem(key);
118
+ else
119
+ storage.setItem(key, value);
120
+ }
121
+ catch (error) {
122
+ // Quota exceeded / blocked: the model keeps its state; nothing persists.
123
+ console.error(`[StorageWrite] ${key}:`, error);
124
+ }
125
+ }
126
+ /**
127
+ * The Command runner. Async work runs as plain promises (never inside a
128
+ * Solid `action`), so the model's writes commit immediately: the model's
129
+ * state IS the pending UI. Timers and result Messages are dropped once the
130
+ * owner is disposed; a mutation's invalidation is not.
131
+ */
132
+ export function createCommandRunner(handlers, send, scope) {
133
+ const timeouts = new Map();
134
+ let disposed = false;
135
+ const cancel = (key) => {
136
+ const t = timeouts.get(key);
137
+ if (t !== undefined) {
138
+ clearTimeout(t);
139
+ timeouts.delete(key);
140
+ }
141
+ };
142
+ const clearAll = () => {
143
+ disposed = true;
144
+ for (const t of timeouts.values())
145
+ clearTimeout(t);
146
+ timeouts.clear();
147
+ };
148
+ if (getOwner()) {
149
+ onCleanup(clearAll);
150
+ }
151
+ const sendIfLive = (msg) => {
152
+ if (!disposed)
153
+ send(msg);
154
+ };
155
+ const mutate = (mutation, input, toMessage) => {
156
+ const label = `mutation:${mutation.id}`;
157
+ settle(label,
158
+ // No input = no argument (`undefined` is not a JSON argument).
159
+ () => input === undefined
160
+ ? mutation.run()
161
+ : mutation.run(input), (result) => {
162
+ try {
163
+ // The result Message first: its writes must be queued before the
164
+ // invalidation microtask (see invalidateAfterCommit).
165
+ if (!disposed)
166
+ send(toMessage(result));
167
+ }
168
+ finally {
169
+ // The write happened: refetch what it made stale even if this
170
+ // model is gone or its result handling threw.
171
+ if (result._tag === 'Ok' &&
172
+ mutation.invalidates.length > 0) {
173
+ const target = requireScope(scope, `Mutation ${mutation.id}`);
174
+ for (const query of mutation.invalidates) {
175
+ invalidateAfterCommit(target, query.id);
176
+ }
177
+ }
178
+ // Who is looking changed: live rooms must see the new identity.
179
+ if (result._tag === 'Ok' && mutation.changesAccess)
180
+ scope?.viewerChanged();
181
+ }
182
+ }, (error) => {
183
+ console.error(`[${label}] Unexpected failure:`, error);
184
+ if (!disposed)
185
+ send(toMessage(err(UNEXPECTED)));
186
+ });
187
+ };
188
+ const ctx = {
189
+ send: sendIfLive,
190
+ mutate,
191
+ debounce: (key, ms, fn) => {
192
+ cancel(key);
193
+ if (disposed)
194
+ return;
195
+ timeouts.set(key, setTimeout(() => {
196
+ timeouts.delete(key);
197
+ if (!disposed)
198
+ fn();
199
+ }, ms));
200
+ },
201
+ cancel,
202
+ };
203
+ const kitHandlers = {
204
+ Refetch: (cmd) => {
205
+ invalidateAfterCommit(requireScope(scope, 'The Refetch Command'), cmd.queryId, cmd.inputKey);
206
+ },
207
+ StorageRead: (cmd) => {
208
+ if (isServer || typeof window === 'undefined')
209
+ return;
210
+ sendIfLive(cmd.toMessage(readStorageKeys(cmd.keys, cmd.prefixes)));
211
+ },
212
+ StorageWrite: (cmd) => {
213
+ if (isServer)
214
+ return;
215
+ writeStorageKey(cmd.key, cmd.value);
216
+ },
217
+ ScrollToTop: () => {
218
+ if (isServer || typeof window === 'undefined')
219
+ return;
220
+ window.scrollTo({ top: 0, behavior: 'instant' });
221
+ },
222
+ Navigate: (cmd) => {
223
+ if (isServer)
224
+ return;
225
+ navigateTo(cmd);
226
+ },
227
+ };
228
+ const run = (commands) => {
229
+ for (const cmd of commands) {
230
+ if (disposed)
231
+ break;
232
+ if (KIT_COMMAND_TAGS.has(cmd._tag)) {
233
+ const runKit = kitHandlers[cmd._tag];
234
+ runKit(cmd);
235
+ continue;
236
+ }
237
+ const handler = handlers[cmd._tag];
238
+ if (!handler) {
239
+ throw new Error(`Unhandled command: ${String(cmd._tag)}`);
240
+ }
241
+ handler(cmd, ctx);
242
+ }
243
+ };
244
+ return { run, clearAll };
245
+ }
@@ -0,0 +1,82 @@
1
+ /** @jsxImportSource @solidjs/web */
2
+ import { type Element as SolidElement } from 'solid-js';
3
+ import { type FormFields, type FormStatus } from '../logic/form-state.ts';
4
+ import type { MutationDef } from '../logic/mutation-def.ts';
5
+ import type { Tagged } from '../logic/result.ts';
6
+ export interface FormProps<Input, T, E extends Tagged> {
7
+ /** The registered mutation this form runs (`featureMutations.key`). */
8
+ readonly mutation: MutationDef<Input, T, E>;
9
+ /** The form's status from its model (`formSubmitting`, `formStatusOf(result)`). */
10
+ readonly status: FormStatus;
11
+ /** With JS: the form's fields; send a Message (`(fields) => send({ _tag: "Submitted", fields })`). */
12
+ readonly onSubmit: (fields: FormFields) => void;
13
+ /**
14
+ * Where a no-JS submission goes after success (the `_next` hidden field
15
+ * the server's `formActionHandler` reads; built with `hrefFor`). Without
16
+ * it, success comes back to this page (`_return`). With JS, `update`
17
+ * decides (a `navigate` Command).
18
+ */
19
+ readonly next?: string;
20
+ /**
21
+ * Shown while the form's status is `Succeeded`: after a JS submit (the
22
+ * model's status) and after a no-JS post that came back to this page
23
+ * (the flash outcome), so both ways show the same confirmation.
24
+ */
25
+ readonly success?: SolidElement;
26
+ readonly testId?: string;
27
+ readonly children: SolidElement;
28
+ }
29
+ /**
30
+ * A form bound to a registered mutation. Works without JS and is enhanced
31
+ * when JS runs:
32
+ *
33
+ * - **Without JS**, it is a real `<form method="post" action={mutation.url}>`:
34
+ * the browser posts the fields to the server function; the server's
35
+ * `formActionHandler` answers 303 to `_next` on success, else back to
36
+ * this page (`_return`), with the outcome in a one-shot flash
37
+ * (`locals.formFlash`), and this form renders that outcome:
38
+ * field errors from `ValidationFailed.field_errors` at their fields, other
39
+ * failures as a notice, the typed values back in their inputs, and
40
+ * `success` after a success that came back to this page.
41
+ * - **With JS**, a submit sends `onSubmit(fields)` (a Message). The model
42
+ * returns a Command that runs the mutation (`ctx.mutate`), and its result
43
+ * comes back as a Message whose `update` sets `status`
44
+ * (`formStatusOf(result)`): pending, field errors and the notice all
45
+ * come from `status`, as data, and so does `success`.
46
+ *
47
+ * Fields are `<FormField name label />`; the button is `<FormSubmit>`.
48
+ * Both read this form's status (closed parts: no error props to wire).
49
+ *
50
+ * @example
51
+ * ```tsx
52
+ * <Form mutation={accountMutations.signIn} status={signIn().form}
53
+ * onSubmit={(fields) => send({ _tag: "SignInSubmitted", fields })} next={nextHref(signIn())}>
54
+ * <FormField name="displayName" label="Display name" autocomplete="nickname" />
55
+ * <FormSubmit pendingLabel="Signing in...">Sign in</FormSubmit>
56
+ * </Form>
57
+ * ```
58
+ */
59
+ export declare function Form<Input, T, E extends Tagged>(props: FormProps<Input, T, E>): SolidElement;
60
+ /**
61
+ * A labelled text field of the enclosing `<Form>`: its error (from the
62
+ * form's status) shows under it, and a no-JS re-render keeps what was typed
63
+ * (never for `type="password"`).
64
+ */
65
+ export declare function FormField(props: {
66
+ readonly name: string;
67
+ readonly label: string;
68
+ readonly type?: 'text' | 'email' | 'password' | 'search';
69
+ readonly autocomplete?: string;
70
+ readonly hint?: string;
71
+ readonly required?: boolean;
72
+ /** Prefilled value when the form has nothing typed (e.g. the current display name). */
73
+ readonly initial?: string;
74
+ readonly testId?: string;
75
+ }): SolidElement;
76
+ /** The enclosing `<Form>`'s submit button: disabled, with `pendingLabel`, while it submits. */
77
+ export declare function FormSubmit(props: {
78
+ readonly pendingLabel: string;
79
+ readonly variant?: 'primary' | 'default' | 'danger';
80
+ readonly testId?: string;
81
+ readonly children: SolidElement;
82
+ }): SolidElement;
@@ -0,0 +1,109 @@
1
+ /** @jsxImportSource @solidjs/web */
2
+ import { getRequestEvent, isServer } from '@solidjs/web';
3
+ import { createContext, createMemo, useContext, } from 'solid-js';
4
+ import { currentUrl } from './router.js';
5
+ import { fieldErrorOf, flashViewFor, formFieldsOf, formMessageOf, isFormPending, } from '../logic/form-state.js';
6
+ import { Field, FormFrame, HiddenInput, Notice, SubmitButton, TextInput, } from '../ui/index.js';
7
+ const FormContext = createContext(null, {
8
+ name: 'KitForm',
9
+ });
10
+ function useForm(part) {
11
+ const form = useContext(FormContext);
12
+ if (!form)
13
+ throw new Error(`<${part}> must be inside a kit <Form>.`);
14
+ return form;
15
+ }
16
+ /**
17
+ * This request's no-JS form outcome (`locals.flash`, decoded from Solid's
18
+ * flash cookie by the Worker / dev middleware). Server only.
19
+ */
20
+ function requestFlash() {
21
+ if (!isServer)
22
+ return undefined;
23
+ const flash = getRequestEvent()?.locals?.formFlash;
24
+ return flash && typeof flash === 'object' ? flash : undefined;
25
+ }
26
+ /**
27
+ * A form bound to a registered mutation. Works without JS and is enhanced
28
+ * when JS runs:
29
+ *
30
+ * - **Without JS**, it is a real `<form method="post" action={mutation.url}>`:
31
+ * the browser posts the fields to the server function; the server's
32
+ * `formActionHandler` answers 303 to `_next` on success, else back to
33
+ * this page (`_return`), with the outcome in a one-shot flash
34
+ * (`locals.formFlash`), and this form renders that outcome:
35
+ * field errors from `ValidationFailed.field_errors` at their fields, other
36
+ * failures as a notice, the typed values back in their inputs, and
37
+ * `success` after a success that came back to this page.
38
+ * - **With JS**, a submit sends `onSubmit(fields)` (a Message). The model
39
+ * returns a Command that runs the mutation (`ctx.mutate`), and its result
40
+ * comes back as a Message whose `update` sets `status`
41
+ * (`formStatusOf(result)`): pending, field errors and the notice all
42
+ * come from `status`, as data, and so does `success`.
43
+ *
44
+ * Fields are `<FormField name label />`; the button is `<FormSubmit>`.
45
+ * Both read this form's status (closed parts: no error props to wire).
46
+ *
47
+ * @example
48
+ * ```tsx
49
+ * <Form mutation={accountMutations.signIn} status={signIn().form}
50
+ * onSubmit={(fields) => send({ _tag: "SignInSubmitted", fields })} next={nextHref(signIn())}>
51
+ * <FormField name="displayName" label="Display name" autocomplete="nickname" />
52
+ * <FormSubmit pendingLabel="Signing in...">Sign in</FormSubmit>
53
+ * </Form>
54
+ * ```
55
+ */
56
+ export function Form(props) {
57
+ const url = props.mutation.url;
58
+ // Serialized into the hydration payload: the browser adopts what the
59
+ // server rendered (a no-JS outcome), so hydration matches.
60
+ const flash = createMemo(async () => flashViewFor(requestFlash(), url), {
61
+ ssrSource: 'server',
62
+ });
63
+ const status = createMemo(() => props.status._tag === 'Idle' ? flash().status : props.status);
64
+ // Stable for the form's life (the flash never changes after render), so
65
+ // an input's server value never resets what the user typed since.
66
+ const value = (name) => flash().values[name];
67
+ const context = {
68
+ status,
69
+ value,
70
+ idPrefix: `form-${props.mutation.id.replace(/[^A-Za-z0-9_-]/g, '-')}`,
71
+ };
72
+ const message = () => formMessageOf(status());
73
+ // Where the server's form handler sends a no-JS post back to (pages send
74
+ // no Referer: `Referrer-Policy: no-referrer`).
75
+ const returnTo = currentUrl();
76
+ return (<FormContext value={context}>
77
+ <FormFrame action={url} testId={props.testId} busy={isFormPending(status())} onSubmit={(data) => props.onSubmit(formFieldsOf(data))}>
78
+ {message() ? (<Notice tone="danger" title="Couldn't submit" description={message()}/>) : null}
79
+ {status()._tag === 'Succeeded' ? props.success : null}
80
+ <HiddenInput name="_return" value={returnTo}/>
81
+ {props.next ? (<HiddenInput name="_next" value={props.next}/>) : null}
82
+ {props.children}
83
+ </FormFrame>
84
+ </FormContext>);
85
+ }
86
+ /**
87
+ * A labelled text field of the enclosing `<Form>`: its error (from the
88
+ * form's status) shows under it, and a no-JS re-render keeps what was typed
89
+ * (never for `type="password"`).
90
+ */
91
+ export function FormField(props) {
92
+ const form = useForm('FormField');
93
+ const id = `${form.idPrefix}-${props.name}`;
94
+ const error = () => fieldErrorOf(form.status(), props.name);
95
+ const typed = () => props.type === 'password'
96
+ ? undefined
97
+ : (form.value(props.name) ?? props.initial);
98
+ return (<Field label={props.label} for={id} hint={props.hint} error={error()}>
99
+ <TextInput id={id} name={props.name} type={props.type} autocomplete={props.autocomplete} required={props.required} defaultValue={typed()} invalid={error() !== undefined} testId={props.testId}/>
100
+ </Field>);
101
+ }
102
+ /** The enclosing `<Form>`'s submit button: disabled, with `pendingLabel`, while it submits. */
103
+ export function FormSubmit(props) {
104
+ const form = useForm('FormSubmit');
105
+ const pending = () => isFormPending(form.status());
106
+ return (<SubmitButton variant={props.variant} disabled={pending()} testId={props.testId}>
107
+ {pending() ? props.pendingLabel : props.children}
108
+ </SubmitButton>);
109
+ }
@@ -0,0 +1,31 @@
1
+ import type { Element as SolidElement } from 'solid-js';
2
+ import { type HeadSpec, type RouteHead } from '../logic/head.ts';
3
+ /**
4
+ * The current route's head (rendered by `createRoutePages` next to each
5
+ * page). Solid's `useHead` puts the tags in the SSR / prerendered `<head>`
6
+ * and, in the browser, replaces them when the route (or its params)
7
+ * changes; the getter only reads plain data (no reactive owners), as
8
+ * `useHead` requires for hydration.
9
+ */
10
+ export declare function RouteHeadTags(props: {
11
+ readonly path: string | null;
12
+ readonly head: RouteHead | undefined;
13
+ readonly route: {
14
+ readonly params: Readonly<Record<string, string>>;
15
+ readonly search: Readonly<Record<string, string | number>>;
16
+ };
17
+ }): SolidElement;
18
+ /**
19
+ * A page's head from its data, inside the page (typically in a `<Query ok>`):
20
+ * registered after the route's head, so its title, description, image and
21
+ * JSON-LD win tag by tag; canonical stays the route's unless `head.canonical`
22
+ * is given. Build the spec in a `.model.ts` selector.
23
+ *
24
+ * @example
25
+ * ```tsx
26
+ * <Query query={plannerQueries.plan} input={id} ok={(plan) => <Head head={planHead(props.route, plan)} />} />
27
+ * ```
28
+ */
29
+ export declare function Head(props: {
30
+ readonly head: HeadSpec;
31
+ }): SolidElement;
@@ -0,0 +1,46 @@
1
+ import { useHead } from '@solidjs/web';
2
+ import { useSite } from './app-scope.js';
3
+ import { fillPath, headTagsFor, resolveRouteHead, } from '../logic/head.js';
4
+ import { normalizePathname } from '../logic/path.js';
5
+ /** Used when an app has no `<AppScope site>` (tests, probes): a title and nothing absolute that lies. */
6
+ const FALLBACK_SITE = {
7
+ name: 'App',
8
+ origin: 'http://localhost',
9
+ lang: 'en',
10
+ locale: 'en_US',
11
+ titleTemplate: '%s',
12
+ description: '',
13
+ };
14
+ function siteHead() {
15
+ return useSite()?.head ?? FALLBACK_SITE;
16
+ }
17
+ /**
18
+ * The current route's head (rendered by `createRoutePages` next to each
19
+ * page). Solid's `useHead` puts the tags in the SSR / prerendered `<head>`
20
+ * and, in the browser, replaces them when the route (or its params)
21
+ * changes; the getter only reads plain data (no reactive owners), as
22
+ * `useHead` requires for hydration.
23
+ */
24
+ export function RouteHeadTags(props) {
25
+ const site = siteHead();
26
+ useHead(() => headTagsFor(resolveRouteHead(props.head, props.route, site), site, props.path === null
27
+ ? undefined
28
+ : fillPath(normalizePathname(props.path), props.route.params)));
29
+ return undefined;
30
+ }
31
+ /**
32
+ * A page's head from its data, inside the page (typically in a `<Query ok>`):
33
+ * registered after the route's head, so its title, description, image and
34
+ * JSON-LD win tag by tag; canonical stays the route's unless `head.canonical`
35
+ * is given. Build the spec in a `.model.ts` selector.
36
+ *
37
+ * @example
38
+ * ```tsx
39
+ * <Query query={plannerQueries.plan} input={id} ok={(plan) => <Head head={planHead(props.route, plan)} />} />
40
+ * ```
41
+ */
42
+ export function Head(props) {
43
+ const site = siteHead();
44
+ useHead(() => headTagsFor(props.head, site, undefined));
45
+ return undefined;
46
+ }