@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,123 @@
1
+ import { getRequestEvent, isServer } from '@solidjs/web';
2
+ export { normalizePathname, resolveRoute } from '../logic/path.js';
3
+ /**
4
+ * The kit router. Navigation is app state: a route model (`.model.ts`) turns
5
+ * a `Navigated` Message into the new route plus the kit's `Navigate`
6
+ * Command. This file holds the only URL side effects:
7
+ *
8
+ * - `currentUrl()` seeds the route model (`init`). On the server it reads
9
+ * the request URL (`getRequestEvent()`), so a deep link with params
10
+ * renders the right route on first byte; in the browser it reads
11
+ * `location`, so hydration sees the same route.
12
+ * - `navigateTo` runs the `Navigate` kit Command: a full page load (pages
13
+ * are static HTML + islands), or, between routes of one client section,
14
+ * the kit's client navigation (`nav-client.ts`). Any model can navigate
15
+ * (a form that signed in goes to `/account`).
16
+ * - `subscribeUrlChanges` feeds same-document history changes (Back /
17
+ * Forward between entries of this document) to models as a Message;
18
+ * `createModel({ urlChanged })` wires it.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * const [nav, sendNav] = createModel({
23
+ * init: () => initRouteModel(routePathsOf(routes), currentUrl()),
24
+ * update: updateRoute,
25
+ * urlChanged,
26
+ * });
27
+ * ```
28
+ */
29
+ /** DOM event a same-document URL change dispatches on `window` (kit-internal). */
30
+ const NAVIGATED_EVENT = 'kit:navigated';
31
+ /**
32
+ * The path + query of the page being rendered: the request URL during SSR,
33
+ * `location` in the browser, `/` otherwise.
34
+ *
35
+ * @example
36
+ * ```ts
37
+ * currentUrl(); // "/plans/voltar-main?tab=stats"
38
+ * ```
39
+ */
40
+ export function currentUrl() {
41
+ if (isServer) {
42
+ const event = getRequestEvent();
43
+ if (!event)
44
+ return '/';
45
+ const url = new URL(event.request.url);
46
+ return `${url.pathname}${url.search}`;
47
+ }
48
+ return typeof window !== 'undefined'
49
+ ? `${window.location.pathname}${window.location.search}`
50
+ : '/';
51
+ }
52
+ /** @deprecated Use `currentUrl()` (it keeps the query string for search params). */
53
+ export function currentPathname() {
54
+ return currentUrl().split('?')[0] ?? '/';
55
+ }
56
+ /** Set on `window` while a kit navigation is leaving this document (reset on `pageshow`). */
57
+ const LEAVING = '__kitLeaving';
58
+ /** Set on `window` by the client navigation runtime (`nav-client.ts`) on pages in a client-navigation section. */
59
+ const CLIENT_NAVIGATOR = '__kitClientNavigator';
60
+ /**
61
+ * Kit-internal: the client navigation runtime registers itself, so the
62
+ * `Navigate` Command takes the same path a link click does.
63
+ */
64
+ export function setClientNavigator(navigator) {
65
+ if (typeof window === 'undefined')
66
+ return;
67
+ window[CLIENT_NAVIGATOR] =
68
+ navigator;
69
+ }
70
+ /**
71
+ * Runs the `Navigate` kit Command: a full document navigation
72
+ * (`location.assign`, or `location.replace` with `replace`). Pages are
73
+ * static server HTML plus islands, so a new page is a new document: the
74
+ * Worker renders (or the CDN serves) it, and its islands hydrate. There is
75
+ * no client-side page swap (see `docs/guides/ui-kit-architecture.md`, Navigation).
76
+ *
77
+ * The first `Navigate` of a page wins: once the document is leaving, later
78
+ * ones are dropped (a sign-out navigates home, then the refetch its
79
+ * invalidation started fails `Unauthorized` and the auth guard would send
80
+ * the visitor to sign-in instead). Same URL: no-op. No-op on the server.
81
+ */
82
+ export function navigateTo(cmd) {
83
+ if (typeof window === 'undefined')
84
+ return;
85
+ const host = window;
86
+ if (host[LEAVING] === true)
87
+ return;
88
+ // A page in a client-navigation section: the kit's runtime follows hrefs in its
89
+ // section without a full load (it answers false for anything else).
90
+ const client = host[CLIENT_NAVIGATOR];
91
+ if (client?.(cmd.href, cmd.replace === true))
92
+ return;
93
+ const here = `${window.location.pathname}${window.location.search}`;
94
+ if (here === cmd.href)
95
+ return;
96
+ host[LEAVING] = true;
97
+ // Back to this document from the back/forward cache: navigable again.
98
+ window.addEventListener('pageshow', () => {
99
+ host[LEAVING] = false;
100
+ }, { once: true });
101
+ if (cmd.replace)
102
+ window.location.replace(cmd.href);
103
+ else
104
+ window.location.assign(cmd.href);
105
+ }
106
+ /**
107
+ * Calls `onChange(url)` (path + query) on Back / Forward and after every
108
+ * `Navigate` Command. Kit-internal: used by `createModel({ urlChanged })`
109
+ * after hydration settles.
110
+ *
111
+ * @returns Unsubscribe function.
112
+ */
113
+ export function subscribeUrlChanges(onChange) {
114
+ if (typeof window === 'undefined')
115
+ return () => { };
116
+ const notify = () => onChange(`${window.location.pathname}${window.location.search}`);
117
+ window.addEventListener('popstate', notify);
118
+ window.addEventListener(NAVIGATED_EVENT, notify);
119
+ return () => {
120
+ window.removeEventListener('popstate', notify);
121
+ window.removeEventListener(NAVIGATED_EVENT, notify);
122
+ };
123
+ }
@@ -0,0 +1,12 @@
1
+ import type { StartMiddleware } from '@solidjs/vite-plugin';
2
+ /**
3
+ * Dev only (`vite dev`; the kit's Vite plugin sets it as the Solid plugin's
4
+ * `start.middleware`). `vite dev` runs pages and server functions in Node,
5
+ * not workerd, so there is no Worker `env`: this gives each request the
6
+ * local platform's bindings (`devPlatform`) on `locals.env` / `locals.ctx`,
7
+ * and runs the same request prelude, page status probe and 404 split as
8
+ * the Worker (`prepareAppRequest`), so `vite dev` and workerd answer alike.
9
+ * Vite serves real modules and `public/` files before this runs.
10
+ */
11
+ declare const devMiddleware: StartMiddleware;
12
+ export default devMiddleware;
@@ -0,0 +1,39 @@
1
+ import config from 'virtual:ui-kit/dev-config';
2
+ import { serverApp } from 'virtual:ui-kit/server-app';
3
+ import { devPlatform } from './dev-platform.js';
4
+ import { renderModeFor } from '../worker/page-routes.js';
5
+ import { finishPage } from '../worker/request-prelude.js';
6
+ import { notFoundResponse, withStatus } from '../worker/security.js';
7
+ import { prepareAppRequest } from '../worker/server-app.js';
8
+ /**
9
+ * Dev only (`vite dev`; the kit's Vite plugin sets it as the Solid plugin's
10
+ * `start.middleware`). `vite dev` runs pages and server functions in Node,
11
+ * not workerd, so there is no Worker `env`: this gives each request the
12
+ * local platform's bindings (`devPlatform`) on `locals.env` / `locals.ctx`,
13
+ * and runs the same request prelude, page status probe and 404 split as
14
+ * the Worker (`prepareAppRequest`), so `vite dev` and workerd answer alike.
15
+ * Vite serves real modules and `public/` files before this runs.
16
+ */
17
+ const devMiddleware = async (event, next) => {
18
+ const { env, ctx } = await devPlatform(config.local, config.names);
19
+ const { kind, prelude, status } = await prepareAppRequest(serverApp, event.request, env);
20
+ if (kind._tag === 'NotFoundStatic')
21
+ return notFoundResponse();
22
+ if (prelude._tag === 'Respond')
23
+ return prelude.response;
24
+ event.locals.env = env;
25
+ event.locals.ctx = ctx;
26
+ event.locals.session = prelude.session;
27
+ event.locals.formFlash = prelude.formFlash;
28
+ // Like the Worker: whole pages render whole (`renderMode: "async"`).
29
+ if (kind._tag === 'Page')
30
+ event.renderMode = renderModeFor(kind);
31
+ const response = await next();
32
+ if (kind._tag === 'ServerFunction')
33
+ return response;
34
+ const page = finishPage(new Response(response.body, response), prelude);
35
+ return kind._tag === 'NotFoundPage' || status === 404
36
+ ? withStatus(page, 404)
37
+ : page;
38
+ };
39
+ export default devMiddleware;
@@ -0,0 +1,25 @@
1
+ import { type Logger, type Plugin } from 'vite';
2
+ import type { LocalConfig } from './local-config.ts';
3
+ import type { ResourcesDecl } from '../logic/resources.ts';
4
+ /** A socket error that only means the other end went away. */
5
+ export declare function isPeerGone(error: unknown): boolean;
6
+ /**
7
+ * The dev server's logger, minus the live proxy's ECONNRESET / EPIPE
8
+ * reports (closing a tab resets its socket every time). Every other proxy
9
+ * error still logs.
10
+ */
11
+ export declare function devProxyLogger(): Logger;
12
+ /** The `vite dev` proxy entries for the live paths. */
13
+ export declare function devObjectsProxy(livePrefix: string, port: number): {
14
+ [livePrefix]: {
15
+ target: string;
16
+ ws: boolean;
17
+ };
18
+ };
19
+ export declare function devObjects({ resources, local, objects, live, port, }: {
20
+ resources: ResourcesDecl;
21
+ local: () => LocalConfig;
22
+ objects: string;
23
+ live: string;
24
+ port: number;
25
+ }): Plugin;
@@ -0,0 +1,127 @@
1
+ import { mkdirSync, writeFileSync } from 'node:fs';
2
+ import { join, relative, resolve } from 'node:path';
3
+ import { createLogger, } from 'vite';
4
+ import { unstable_dev } from 'wrangler';
5
+ import { GENERATED_DIR } from '../alchemy/migrations.js';
6
+ import { wranglerConfig } from '../alchemy/wrangler-config.js';
7
+ /**
8
+ * Dev only (`vite dev`): the app's Durable Objects in a local Worker of
9
+ * their own (wrangler's `getPlatformProxy` can't run a Durable Object that
10
+ * lives in the main Worker), started with `unstable_dev` in workerd (the
11
+ * hibernation API and alarms), persisted in the same `.wrangler/state`.
12
+ * The kit writes its entry and wrangler config from the resource
13
+ * declaration (`.ui-kit/dev-objects/`), and Vite proxies the live paths
14
+ * (WebSocket upgrades included) to it, so sockets work on the dev server
15
+ * as on the deployed Worker.
16
+ *
17
+ * The entry re-exports the app's Durable Object classes (`objects`) and
18
+ * answers with its live router (`live`'s `routeLive(request, env,
19
+ * extraOrigins)`), given the dev server's origins (Vite's proxy forwards
20
+ * the page's `Origin`, which isn't the side Worker's own port).
21
+ */
22
+ /** Socket error codes that only mean the other end went away (a tab closed). */
23
+ const PEER_GONE_CODES = new Set(['ECONNRESET', 'EPIPE']);
24
+ /** A socket error that only means the other end went away. */
25
+ export function isPeerGone(error) {
26
+ return (typeof error === 'object' &&
27
+ error !== null &&
28
+ PEER_GONE_CODES.has(Reflect.get(error, 'code')));
29
+ }
30
+ /**
31
+ * The dev server's logger, minus the live proxy's ECONNRESET / EPIPE
32
+ * reports (closing a tab resets its socket every time). Every other proxy
33
+ * error still logs.
34
+ */
35
+ export function devProxyLogger() {
36
+ const logger = createLogger();
37
+ const logError = logger.error.bind(logger);
38
+ logger.error = (message, options) => {
39
+ if (message.includes('ws proxy') && isPeerGone(options?.error))
40
+ return;
41
+ logError(message, options);
42
+ };
43
+ return logger;
44
+ }
45
+ /** The generated side Worker: entry source and config, written under `.ui-kit/dev-objects/`. */
46
+ function writeDevObjects({ appDir, resources, local, objects, live, origins, }) {
47
+ const dir = resolve(appDir, GENERATED_DIR, 'dev-objects');
48
+ mkdirSync(dir, { recursive: true });
49
+ const rel = (path) => {
50
+ const r = relative(dir, resolve(appDir, path));
51
+ return r.startsWith('.') ? r : `./${r}`;
52
+ };
53
+ const entry = join(dir, 'entry.ts');
54
+ writeFileSync(entry, [
55
+ '// Generated by the ui-kit Vite plugin (dev only). Do not edit.',
56
+ `export * from '${rel(objects)}'`,
57
+ `import { routeLive } from '${rel(live)}'`,
58
+ `const ORIGINS = ${JSON.stringify(origins)}`,
59
+ 'export default {',
60
+ ' fetch(request: Request, env: unknown): Promise<Response> {',
61
+ ' return routeLive(request, env, ORIGINS) ?? Promise.resolve(new Response("Not found", { status: 404 }))',
62
+ ' },',
63
+ '}',
64
+ '',
65
+ ].join('\n'));
66
+ const migrations = Object.fromEntries(local.d1.map((binding) => [
67
+ binding,
68
+ relative(dir, resolve(appDir, GENERATED_DIR, 'migrations', binding)),
69
+ ]));
70
+ const config = join(dir, 'wrangler.json');
71
+ writeFileSync(config, `${JSON.stringify(wranglerConfig({
72
+ resources,
73
+ name: `${resources.name}-dev-objects`,
74
+ main: 'entry.ts',
75
+ migrations,
76
+ crons: false,
77
+ }), null, 4)}\n`);
78
+ return { entry, config };
79
+ }
80
+ /** The `vite dev` proxy entries for the live paths. */
81
+ export function devObjectsProxy(livePrefix, port) {
82
+ return {
83
+ [livePrefix]: { target: `ws://127.0.0.1:${port}`, ws: true },
84
+ };
85
+ }
86
+ export function devObjects({ resources, local, objects, live, port, }) {
87
+ return {
88
+ name: 'ui-kit:dev-objects',
89
+ apply: 'serve',
90
+ configureServer(server) {
91
+ // Not awaited: the dev server comes up while the objects start.
92
+ void start(server);
93
+ },
94
+ };
95
+ async function start(server) {
96
+ const devPort = server.config.server.port ?? 5173;
97
+ const origins = [
98
+ `http://127.0.0.1:${devPort}`,
99
+ `http://localhost:${devPort}`,
100
+ ];
101
+ try {
102
+ const files = writeDevObjects({
103
+ appDir: server.config.root,
104
+ resources,
105
+ local: local(),
106
+ objects,
107
+ live,
108
+ origins,
109
+ });
110
+ const worker = await unstable_dev(files.entry, {
111
+ config: files.config,
112
+ ip: '127.0.0.1',
113
+ port,
114
+ persistTo: local().stateDir,
115
+ logLevel: 'warn',
116
+ experimental: { disableExperimentalWarning: true },
117
+ });
118
+ server.httpServer?.once('close', () => {
119
+ void worker.stop();
120
+ });
121
+ server.config.logger.info(` Durable Objects (dev): ws://127.0.0.1:${port}`);
122
+ }
123
+ catch (error) {
124
+ server.config.logger.error(`[ui-kit dev-objects] could not start the Durable Object Worker: ${error instanceof Error ? error.message : String(error)}`);
125
+ }
126
+ }
127
+ }
@@ -0,0 +1,19 @@
1
+ import { getPlatformProxy } from 'wrangler';
2
+ import { type LocalConfig } from './local-config.ts';
3
+ /**
4
+ * Dev only: the local platform `vite dev` gives each request (wrangler's
5
+ * `getPlatformProxy`: Miniflare D1, R2 and rate limits over the same
6
+ * `.wrangler/state` `ui-kit preview` uses). On first use it applies the D1
7
+ * migrations locally, so a fresh `vite dev` needs no setup step.
8
+ *
9
+ * Its state (one platform per dev server process, on `globalThis`) is dev
10
+ * tooling, never in a build: Vite's server-module reloads reuse it instead
11
+ * of starting another Miniflare on the same state directory.
12
+ */
13
+ type Proxy = Awaited<ReturnType<typeof getPlatformProxy>>;
14
+ /**
15
+ * The platform for this request: starts one if none, replaces a dead one
16
+ * once per request. A second failure goes to the request as an error.
17
+ */
18
+ export declare function devPlatform(config: LocalConfig, names: readonly string[]): Promise<Proxy>;
19
+ export {};
@@ -0,0 +1,77 @@
1
+ import { getPlatformProxy } from 'wrangler';
2
+ import { migrateLocalD1 } from './local-config.js';
3
+ const holder = globalThis;
4
+ async function startPlatform(config) {
5
+ await migrateLocalD1(config);
6
+ return getPlatformProxy({
7
+ configPath: config.platformPath,
8
+ persist: { path: `${config.stateDir}/v3` },
9
+ });
10
+ }
11
+ async function resetPlatform() {
12
+ const current = holder.__uiKitDevPlatform;
13
+ holder.__uiKitDevPlatform = undefined;
14
+ if (!current)
15
+ return;
16
+ try {
17
+ await (await current).dispose();
18
+ }
19
+ catch {
20
+ // Already dead or never started: nothing left to release.
21
+ }
22
+ }
23
+ /**
24
+ * Whether a platform still answers, with every binding the app needs (a
25
+ * platform started from an older declaration is replaced, so a config
26
+ * change needs no restart). Catches Miniflare's "poisoned stub" errors
27
+ * after an HMR reload too.
28
+ */
29
+ async function isAlive(proxy, names) {
30
+ const env = proxy.env;
31
+ const bindingOf = (name) => typeof env === 'object' && env !== null
32
+ ? Reflect.get(env, name)
33
+ : undefined;
34
+ const missing = names.filter((name) => bindingOf(name) === undefined);
35
+ if (missing.length > 0) {
36
+ console.warn(`[ui-kit dev] local platform lacks ${missing.join(', ')}; restarting it`);
37
+ return false;
38
+ }
39
+ try {
40
+ await Promise.all(names.map((name) => {
41
+ const binding = bindingOf(name);
42
+ if (typeof binding !== 'object' || binding === null)
43
+ return;
44
+ const prepare = Reflect.get(binding, 'prepare');
45
+ if (typeof prepare === 'function') {
46
+ // A D1 database: one trivial read.
47
+ return Reflect.apply(prepare, binding, ['SELECT 1']).first();
48
+ }
49
+ return undefined;
50
+ }));
51
+ return true;
52
+ }
53
+ catch {
54
+ return false;
55
+ }
56
+ }
57
+ /**
58
+ * The platform for this request: starts one if none, replaces a dead one
59
+ * once per request. A second failure goes to the request as an error.
60
+ */
61
+ export async function devPlatform(config, names) {
62
+ for (let attempt = 0; attempt < 2; attempt += 1) {
63
+ holder.__uiKitDevPlatform ??= startPlatform(config);
64
+ try {
65
+ const proxy = await holder.__uiKitDevPlatform;
66
+ if (await isAlive(proxy, names))
67
+ return proxy;
68
+ console.warn('[ui-kit dev] local platform stopped answering; restarting it');
69
+ }
70
+ catch (error) {
71
+ console.warn(`[ui-kit dev] local platform failed to start: ${String(error)}`);
72
+ }
73
+ await resetPlatform();
74
+ }
75
+ holder.__uiKitDevPlatform ??= startPlatform(config);
76
+ return holder.__uiKitDevPlatform;
77
+ }
@@ -0,0 +1,11 @@
1
+ import type { Plugin } from 'vite';
2
+ /**
3
+ * Dev only: answers `/sitemap.xml` and `/robots.txt` from the route table
4
+ * (`seoFiles`, loaded through Vite's SSR module graph so edits to
5
+ * `routes.ts` show up without a restart), the same bodies the build writes.
6
+ */
7
+ export declare function devSeoFiles(tables: {
8
+ readonly routes: string;
9
+ readonly site: string;
10
+ readonly sitemapSources: string;
11
+ }): Plugin;
@@ -0,0 +1,40 @@
1
+ import { SEO_FILES } from '../build/seo-files.js';
2
+ /**
3
+ * Dev only: answers `/sitemap.xml` and `/robots.txt` from the route table
4
+ * (`seoFiles`, loaded through Vite's SSR module graph so edits to
5
+ * `routes.ts` show up without a restart), the same bodies the build writes.
6
+ */
7
+ export function devSeoFiles(tables) {
8
+ return {
9
+ name: 'ui-kit:dev-seo-files',
10
+ apply: 'serve',
11
+ configureServer(server) {
12
+ server.middlewares.use((req, res, next) => {
13
+ const file = SEO_FILES[(req.url ?? '').split('?')[0] ?? ''];
14
+ if (!file)
15
+ return next();
16
+ const load = async () => {
17
+ const [kit, routes, site, sources] = await Promise.all([
18
+ server.ssrLoadModule(new URL('../build/seo-files', import.meta.url)
19
+ .pathname +
20
+ (import.meta.url.endsWith('.ts')
21
+ ? '.ts'
22
+ : '.js')),
23
+ server.ssrLoadModule(tables.routes),
24
+ server.ssrLoadModule(tables.site),
25
+ server.ssrLoadModule(tables.sitemapSources),
26
+ ]);
27
+ const files = await kit.seoFiles({
28
+ routes: routes.routes,
29
+ siteHead: site.siteHead,
30
+ sitemapSources: sources.sitemapSources,
31
+ });
32
+ res.setHeader('Content-Type', file.type);
33
+ res.setHeader('Cache-Control', 'no-store');
34
+ res.end(files[file.key]);
35
+ };
36
+ load().catch(next);
37
+ });
38
+ },
39
+ };
40
+ }
@@ -0,0 +1,53 @@
1
+ import type { Plugin } from 'vite';
2
+ import { type ResourcesDecl } from '../logic/resources.ts';
3
+ /**
4
+ * `@alecsibilia/ui-kit/vite`: the app's whole Vite setup in one plugin.
5
+ *
6
+ * - Solid (`@solidjs/vite-plugin`): SSR, server functions, and the kit's
7
+ * no-JS form protocol installed on every surface;
8
+ * - the Worker build (one self-contained `dist/server/server.js`) and the
9
+ * prerender build `ui-kit prerender` runs, with client-only modules
10
+ * stubbed out of the server bundle;
11
+ * - `vite dev`: local bindings from the resource declaration (Miniflare
12
+ * D1, R2, rate limits, migrated on first use), the Worker's request
13
+ * prelude and 404 split, the app's Durable Objects in a side Worker with
14
+ * the live paths proxied to it, and `sitemap.xml` / `robots.txt`.
15
+ *
16
+ * Writes `.ui-kit/` (local wrangler config and assembled migrations) at
17
+ * startup: keep it out of git.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * // vite.config.ts
22
+ * import { uiKit } from '@alecsibilia/ui-kit/vite'
23
+ * import { resources } from './src/resources.ts'
24
+ *
25
+ * export default defineConfig({ plugins: [uiKit({ resources })] })
26
+ * ```
27
+ */
28
+ export interface UiKitOptions {
29
+ readonly resources: ResourcesDecl;
30
+ /** The module exporting `serverApp` (`defineServerApp`). */
31
+ readonly serverApp?: string;
32
+ /** The Worker entry (`createWorker`). */
33
+ readonly worker?: string;
34
+ /** The module exporting the app's Durable Object classes (and nothing else). */
35
+ readonly objects?: string;
36
+ /** The module exporting `routeLive(request, env, extraOrigins)`. */
37
+ readonly live?: string;
38
+ /** URL prefix of every Durable Object route (proxied to the dev side Worker). */
39
+ readonly livePrefix?: string;
40
+ /** Modules only prerendered pages use: stubbed out of the deployed Worker. */
41
+ readonly prerenderOnly?: RegExp;
42
+ /** Port of the dev Durable Object Worker. */
43
+ readonly devObjectsPort?: number;
44
+ /** The route table, site head and sitemap sources (for the dev SEO files). */
45
+ readonly tables?: {
46
+ readonly routes: string;
47
+ readonly site: string;
48
+ readonly sitemapSources: string;
49
+ };
50
+ }
51
+ export declare function uiKit(options: UiKitOptions): Plugin[];
52
+ export { PRERENDER_BUILD_ENV } from './worker-build.ts';
53
+ export { LOCAL_STATE_DIR, migrateLocalD1, writeLocalConfig, type LocalConfig, } from './local-config.ts';