@nuraly/lumenjs 0.1.2 → 0.1.4

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 (337) hide show
  1. package/README.md +76 -235
  2. package/dist/auth/config.d.ts +23 -0
  3. package/dist/auth/config.js +115 -0
  4. package/dist/auth/guard.d.ts +12 -0
  5. package/dist/auth/guard.js +28 -0
  6. package/dist/auth/index.d.ts +3 -0
  7. package/dist/auth/index.js +1 -0
  8. package/dist/auth/middleware.d.ts +23 -0
  9. package/dist/auth/middleware.js +89 -0
  10. package/dist/auth/native-auth.d.ts +73 -0
  11. package/dist/auth/native-auth.js +293 -0
  12. package/dist/auth/oidc-client.d.ts +17 -0
  13. package/dist/auth/oidc-client.js +123 -0
  14. package/dist/auth/providers/google.d.ts +23 -0
  15. package/dist/auth/providers/google.js +25 -0
  16. package/dist/auth/providers/index.d.ts +2 -0
  17. package/dist/auth/providers/index.js +1 -0
  18. package/dist/auth/routes/login.d.ts +8 -0
  19. package/dist/auth/routes/login.js +98 -0
  20. package/dist/auth/routes/logout.d.ts +4 -0
  21. package/dist/auth/routes/logout.js +79 -0
  22. package/dist/auth/routes/oidc-callback.d.ts +3 -0
  23. package/dist/auth/routes/oidc-callback.js +70 -0
  24. package/dist/auth/routes/password.d.ts +5 -0
  25. package/dist/auth/routes/password.js +149 -0
  26. package/dist/auth/routes/signup.d.ts +3 -0
  27. package/dist/auth/routes/signup.js +81 -0
  28. package/dist/auth/routes/token.d.ts +4 -0
  29. package/dist/auth/routes/token.js +70 -0
  30. package/dist/auth/routes/utils.d.ts +7 -0
  31. package/dist/auth/routes/utils.js +35 -0
  32. package/dist/auth/routes/verify.d.ts +3 -0
  33. package/dist/auth/routes/verify.js +26 -0
  34. package/dist/auth/routes.d.ts +8 -0
  35. package/dist/auth/routes.js +110 -0
  36. package/dist/auth/session.d.ts +8 -0
  37. package/dist/auth/session.js +54 -0
  38. package/dist/auth/token.d.ts +33 -0
  39. package/dist/auth/token.js +90 -0
  40. package/dist/auth/types.d.ts +156 -0
  41. package/dist/auth/types.js +2 -0
  42. package/dist/build/build-client.d.ts +15 -0
  43. package/dist/build/build-client.js +45 -0
  44. package/dist/build/build-prerender.d.ts +11 -0
  45. package/dist/build/build-prerender.js +159 -0
  46. package/dist/build/build-server.d.ts +17 -0
  47. package/dist/build/build-server.js +98 -0
  48. package/dist/build/build.js +52 -120
  49. package/dist/build/scan.d.ts +19 -0
  50. package/dist/build/scan.js +77 -6
  51. package/dist/build/serve-api.js +8 -2
  52. package/dist/build/serve-loaders.d.ts +4 -2
  53. package/dist/build/serve-loaders.js +128 -10
  54. package/dist/build/serve-ssr.js +38 -11
  55. package/dist/build/serve-static.js +3 -3
  56. package/dist/build/serve.js +229 -14
  57. package/dist/cli.js +37 -6
  58. package/dist/communication/encryption.d.ts +35 -0
  59. package/dist/communication/encryption.js +90 -0
  60. package/dist/communication/handlers/context.d.ts +27 -0
  61. package/dist/communication/handlers/context.js +1 -0
  62. package/dist/communication/handlers/conversation.d.ts +24 -0
  63. package/dist/communication/handlers/conversation.js +113 -0
  64. package/dist/communication/handlers/file-upload.d.ts +17 -0
  65. package/dist/communication/handlers/file-upload.js +62 -0
  66. package/dist/communication/handlers/messaging.d.ts +30 -0
  67. package/dist/communication/handlers/messaging.js +237 -0
  68. package/dist/communication/handlers/presence.d.ts +15 -0
  69. package/dist/communication/handlers/presence.js +76 -0
  70. package/dist/communication/handlers.d.ts +5 -0
  71. package/dist/communication/handlers.js +5 -0
  72. package/dist/communication/index.d.ts +9 -0
  73. package/dist/communication/index.js +7 -0
  74. package/dist/communication/link-preview.d.ts +18 -0
  75. package/dist/communication/link-preview.js +115 -0
  76. package/dist/communication/schema.d.ts +10 -0
  77. package/dist/communication/schema.js +101 -0
  78. package/dist/communication/server.d.ts +86 -0
  79. package/dist/communication/server.js +212 -0
  80. package/dist/communication/signaling.d.ts +43 -0
  81. package/dist/communication/signaling.js +271 -0
  82. package/dist/communication/store.d.ts +71 -0
  83. package/dist/communication/store.js +289 -0
  84. package/dist/communication/types.d.ts +454 -0
  85. package/dist/communication/types.js +1 -0
  86. package/dist/create.d.ts +1 -0
  87. package/dist/create.js +55 -0
  88. package/dist/db/auto-migrate.d.ts +3 -0
  89. package/dist/db/auto-migrate.js +100 -0
  90. package/dist/db/client.d.ts +3 -0
  91. package/dist/db/client.js +18 -0
  92. package/dist/db/context.d.ts +2 -0
  93. package/dist/db/context.js +9 -0
  94. package/dist/db/index.d.ts +23 -0
  95. package/dist/db/index.js +258 -0
  96. package/dist/db/seed.d.ts +12 -0
  97. package/dist/db/seed.js +88 -0
  98. package/dist/db/table.d.ts +10 -0
  99. package/dist/db/table.js +12 -0
  100. package/dist/dev-server/config.d.ts +14 -0
  101. package/dist/dev-server/config.js +26 -9
  102. package/dist/dev-server/index-html.d.ts +3 -0
  103. package/dist/dev-server/index-html.js +18 -6
  104. package/dist/dev-server/nuralyui-aliases.d.ts +0 -4
  105. package/dist/dev-server/nuralyui-aliases.js +115 -94
  106. package/dist/dev-server/plugins/vite-plugin-api-routes.js +29 -5
  107. package/dist/dev-server/plugins/vite-plugin-auth.d.ts +6 -0
  108. package/dist/dev-server/plugins/vite-plugin-auth.js +223 -0
  109. package/dist/dev-server/plugins/vite-plugin-auto-define.d.ts +16 -0
  110. package/dist/dev-server/plugins/vite-plugin-auto-define.js +111 -0
  111. package/dist/dev-server/plugins/vite-plugin-communication.d.ts +6 -0
  112. package/dist/dev-server/plugins/vite-plugin-communication.js +205 -0
  113. package/dist/dev-server/plugins/vite-plugin-editor-api.d.ts +6 -0
  114. package/dist/dev-server/plugins/vite-plugin-editor-api.js +318 -0
  115. package/dist/dev-server/plugins/vite-plugin-i18n.js +69 -2
  116. package/dist/dev-server/plugins/vite-plugin-lit-dedup.d.ts +6 -0
  117. package/dist/dev-server/plugins/vite-plugin-lit-dedup.js +78 -34
  118. package/dist/dev-server/plugins/vite-plugin-lit-hmr.js +44 -2
  119. package/dist/dev-server/plugins/vite-plugin-llms.d.ts +2 -0
  120. package/dist/dev-server/plugins/vite-plugin-llms.js +92 -0
  121. package/dist/dev-server/plugins/vite-plugin-loaders.d.ts +0 -1
  122. package/dist/dev-server/plugins/vite-plugin-loaders.js +311 -42
  123. package/dist/dev-server/plugins/vite-plugin-routes.js +18 -6
  124. package/dist/dev-server/plugins/vite-plugin-socketio.d.ts +2 -0
  125. package/dist/dev-server/plugins/vite-plugin-socketio.js +51 -0
  126. package/dist/dev-server/plugins/vite-plugin-source-annotator.d.ts +2 -0
  127. package/dist/dev-server/plugins/vite-plugin-source-annotator.js +26 -3
  128. package/dist/dev-server/plugins/vite-plugin-storage.d.ts +10 -0
  129. package/dist/dev-server/plugins/vite-plugin-storage.js +126 -0
  130. package/dist/dev-server/plugins/vite-plugin-virtual-modules.js +111 -2
  131. package/dist/dev-server/server.js +128 -12
  132. package/dist/dev-server/ssr-render.d.ts +2 -1
  133. package/dist/dev-server/ssr-render.js +107 -48
  134. package/dist/editor/ai/backend.d.ts +20 -0
  135. package/dist/editor/ai/backend.js +104 -0
  136. package/dist/editor/ai/claude-code-client.d.ts +20 -0
  137. package/dist/editor/ai/claude-code-client.js +145 -0
  138. package/dist/editor/ai/opencode-client.d.ts +14 -0
  139. package/dist/editor/ai/opencode-client.js +125 -0
  140. package/dist/editor/ai/snapshot-store.d.ts +22 -0
  141. package/dist/editor/ai/snapshot-store.js +35 -0
  142. package/dist/editor/ai/types.d.ts +30 -0
  143. package/dist/editor/ai/types.js +136 -0
  144. package/dist/editor/ai-chat-panel.d.ts +13 -0
  145. package/dist/editor/ai-chat-panel.js +587 -0
  146. package/dist/editor/ai-markdown.d.ts +10 -0
  147. package/dist/editor/ai-markdown.js +70 -0
  148. package/dist/editor/ai-project-panel.d.ts +11 -0
  149. package/dist/editor/ai-project-panel.js +332 -0
  150. package/dist/editor/ast-modification.d.ts +11 -0
  151. package/dist/editor/ast-modification.js +1 -0
  152. package/dist/editor/ast-service.d.ts +30 -0
  153. package/dist/editor/ast-service.js +180 -0
  154. package/dist/editor/css-rules.d.ts +54 -0
  155. package/dist/editor/css-rules.js +423 -0
  156. package/dist/editor/editor-api-client.d.ts +51 -0
  157. package/dist/editor/editor-api-client.js +162 -0
  158. package/dist/editor/editor-bridge.d.ts +1 -0
  159. package/dist/editor/editor-bridge.js +17 -8
  160. package/dist/editor/editor-toolbar.d.ts +14 -0
  161. package/dist/editor/editor-toolbar.js +115 -0
  162. package/dist/editor/file-editor.d.ts +9 -0
  163. package/dist/editor/file-editor.js +236 -0
  164. package/dist/editor/file-service.d.ts +16 -0
  165. package/dist/editor/file-service.js +52 -0
  166. package/dist/editor/i18n-key-gen.d.ts +1 -0
  167. package/dist/editor/i18n-key-gen.js +7 -0
  168. package/dist/editor/inline-text-edit.d.ts +5 -0
  169. package/dist/editor/inline-text-edit.js +173 -92
  170. package/dist/editor/overlay-events.d.ts +5 -0
  171. package/dist/editor/overlay-events.js +364 -0
  172. package/dist/editor/overlay-hmr.d.ts +2 -0
  173. package/dist/editor/overlay-hmr.js +75 -0
  174. package/dist/editor/overlay-selection.d.ts +29 -0
  175. package/dist/editor/overlay-selection.js +148 -0
  176. package/dist/editor/overlay-utils.d.ts +12 -0
  177. package/dist/editor/overlay-utils.js +59 -0
  178. package/dist/editor/properties-panel-persist.d.ts +14 -0
  179. package/dist/editor/properties-panel-persist.js +70 -0
  180. package/dist/editor/properties-panel-rows.d.ts +10 -0
  181. package/dist/editor/properties-panel-rows.js +349 -0
  182. package/dist/editor/properties-panel-styles.d.ts +4 -0
  183. package/dist/editor/properties-panel-styles.js +174 -0
  184. package/dist/editor/properties-panel.d.ts +4 -0
  185. package/dist/editor/properties-panel.js +148 -0
  186. package/dist/editor/property-registry.d.ts +16 -0
  187. package/dist/editor/property-registry.js +303 -0
  188. package/dist/editor/standalone-file-panel.d.ts +0 -0
  189. package/dist/editor/standalone-file-panel.js +1 -0
  190. package/dist/editor/standalone-overlay-dom.d.ts +0 -0
  191. package/dist/editor/standalone-overlay-dom.js +1 -0
  192. package/dist/editor/standalone-overlay-styles.d.ts +0 -0
  193. package/dist/editor/standalone-overlay-styles.js +1 -0
  194. package/dist/editor/standalone-overlay.d.ts +1 -0
  195. package/dist/editor/standalone-overlay.js +76 -0
  196. package/dist/editor/syntax-highlighter.d.ts +4 -0
  197. package/dist/editor/syntax-highlighter.js +81 -0
  198. package/dist/editor/text-toolbar.d.ts +11 -0
  199. package/dist/editor/text-toolbar.js +327 -0
  200. package/dist/editor/toolbar-styles.d.ts +4 -0
  201. package/dist/editor/toolbar-styles.js +198 -0
  202. package/dist/email/index.d.ts +32 -0
  203. package/dist/email/index.js +154 -0
  204. package/dist/email/providers/resend.d.ts +2 -0
  205. package/dist/email/providers/resend.js +24 -0
  206. package/dist/email/providers/sendgrid.d.ts +2 -0
  207. package/dist/email/providers/sendgrid.js +31 -0
  208. package/dist/email/providers/smtp.d.ts +13 -0
  209. package/dist/email/providers/smtp.js +125 -0
  210. package/dist/email/template-engine.d.ts +18 -0
  211. package/dist/email/template-engine.js +116 -0
  212. package/dist/email/templates/base.d.ts +9 -0
  213. package/dist/email/templates/base.js +65 -0
  214. package/dist/email/templates/password-reset.d.ts +5 -0
  215. package/dist/email/templates/password-reset.js +15 -0
  216. package/dist/email/templates/verify-email.d.ts +5 -0
  217. package/dist/email/templates/verify-email.js +15 -0
  218. package/dist/email/templates/welcome.d.ts +5 -0
  219. package/dist/email/templates/welcome.js +13 -0
  220. package/dist/email/types.d.ts +49 -0
  221. package/dist/email/types.js +1 -0
  222. package/dist/llms/generate.d.ts +46 -0
  223. package/dist/llms/generate.js +185 -0
  224. package/dist/permissions/guard.d.ts +28 -0
  225. package/dist/permissions/guard.js +30 -0
  226. package/dist/permissions/index.d.ts +6 -0
  227. package/dist/permissions/index.js +3 -0
  228. package/dist/permissions/service.d.ts +80 -0
  229. package/dist/permissions/service.js +210 -0
  230. package/dist/permissions/tables.d.ts +5 -0
  231. package/dist/permissions/tables.js +68 -0
  232. package/dist/permissions/types.d.ts +33 -0
  233. package/dist/permissions/types.js +1 -0
  234. package/dist/runtime/app-shell.js +163 -0
  235. package/dist/runtime/auth.d.ts +10 -0
  236. package/dist/runtime/auth.js +30 -0
  237. package/dist/runtime/communication.d.ts +137 -0
  238. package/dist/runtime/communication.js +228 -0
  239. package/dist/runtime/error-boundary.d.ts +23 -0
  240. package/dist/runtime/error-boundary.js +120 -0
  241. package/dist/runtime/i18n.d.ts +6 -1
  242. package/dist/runtime/i18n.js +42 -21
  243. package/dist/runtime/router-data.d.ts +5 -0
  244. package/dist/runtime/router-data.js +121 -16
  245. package/dist/runtime/router-hydration.js +25 -0
  246. package/dist/runtime/router.d.ts +21 -1
  247. package/dist/runtime/router.js +221 -39
  248. package/dist/runtime/socket-client.d.ts +2 -0
  249. package/dist/runtime/socket-client.js +30 -0
  250. package/dist/runtime/webrtc.d.ts +47 -0
  251. package/dist/runtime/webrtc.js +178 -0
  252. package/dist/shared/graceful-shutdown.d.ts +8 -0
  253. package/dist/shared/graceful-shutdown.js +36 -0
  254. package/dist/shared/health.d.ts +8 -0
  255. package/dist/shared/health.js +25 -0
  256. package/dist/shared/llms-txt.d.ts +31 -0
  257. package/dist/shared/llms-txt.js +85 -0
  258. package/dist/shared/logger.d.ts +32 -0
  259. package/dist/shared/logger.js +93 -0
  260. package/dist/shared/meta.d.ts +27 -0
  261. package/dist/shared/meta.js +71 -0
  262. package/dist/shared/middleware-runner.d.ts +9 -0
  263. package/dist/shared/middleware-runner.js +29 -0
  264. package/dist/shared/rate-limit.d.ts +18 -0
  265. package/dist/shared/rate-limit.js +71 -0
  266. package/dist/shared/request-id.d.ts +5 -0
  267. package/dist/shared/request-id.js +18 -0
  268. package/dist/shared/route-matching.js +16 -1
  269. package/dist/shared/security-headers.d.ts +18 -0
  270. package/dist/shared/security-headers.js +38 -0
  271. package/dist/shared/socket-io-setup.d.ts +11 -0
  272. package/dist/shared/socket-io-setup.js +51 -0
  273. package/dist/shared/types.d.ts +16 -0
  274. package/dist/shared/utils.d.ts +37 -7
  275. package/dist/shared/utils.js +175 -26
  276. package/dist/storage/adapters/local.d.ts +44 -0
  277. package/dist/storage/adapters/local.js +85 -0
  278. package/dist/storage/adapters/s3.d.ts +32 -0
  279. package/dist/storage/adapters/s3.js +116 -0
  280. package/dist/storage/adapters/types.d.ts +53 -0
  281. package/dist/storage/adapters/types.js +1 -0
  282. package/dist/storage/index.d.ts +76 -0
  283. package/dist/storage/index.js +83 -0
  284. package/package.json +20 -1
  285. package/templates/blog/api/posts.ts +6 -0
  286. package/templates/blog/data/migrations/001_init.sql +13 -0
  287. package/templates/blog/lumenjs.config.ts +3 -0
  288. package/templates/blog/package.json +14 -0
  289. package/templates/blog/pages/_layout.ts +25 -0
  290. package/templates/blog/pages/index.ts +65 -0
  291. package/templates/blog/pages/posts/[slug].ts +60 -0
  292. package/templates/blog/pages/tag/[tag].ts +44 -0
  293. package/templates/dashboard/api/stats.ts +10 -0
  294. package/templates/dashboard/data/migrations/001_init.sql +13 -0
  295. package/templates/dashboard/lumenjs.config.ts +3 -0
  296. package/templates/dashboard/package.json +14 -0
  297. package/templates/dashboard/pages/_layout.ts +25 -0
  298. package/templates/dashboard/pages/index.ts +72 -0
  299. package/templates/dashboard/pages/settings/index.ts +29 -0
  300. package/templates/default/lumenjs.config.ts +3 -0
  301. package/templates/default/package.json +14 -0
  302. package/templates/default/pages/index.ts +24 -0
  303. package/templates/social/api/posts/[id].ts +14 -0
  304. package/templates/social/api/posts.ts +11 -0
  305. package/templates/social/api/profile/[username].ts +10 -0
  306. package/templates/social/api/upload.ts +19 -0
  307. package/templates/social/data/migrations/001_init.sql +78 -0
  308. package/templates/social/data/migrations/002_add_image_url.sql +1 -0
  309. package/templates/social/data/migrations/003_auth.sql +7 -0
  310. package/templates/social/docs/architecture.md +76 -0
  311. package/templates/social/docs/components.md +100 -0
  312. package/templates/social/docs/data.md +89 -0
  313. package/templates/social/docs/pages.md +96 -0
  314. package/templates/social/docs/theming.md +52 -0
  315. package/templates/social/lib/media.ts +130 -0
  316. package/templates/social/lumenjs.auth.ts +21 -0
  317. package/templates/social/lumenjs.config.ts +3 -0
  318. package/templates/social/package.json +5 -0
  319. package/templates/social/pages/_layout.ts +239 -0
  320. package/templates/social/pages/apps/[id].ts +173 -0
  321. package/templates/social/pages/apps/index.ts +116 -0
  322. package/templates/social/pages/auth/login.ts +92 -0
  323. package/templates/social/pages/bookmarks.ts +57 -0
  324. package/templates/social/pages/explore.ts +73 -0
  325. package/templates/social/pages/index.ts +351 -0
  326. package/templates/social/pages/messages.ts +298 -0
  327. package/templates/social/pages/new.ts +77 -0
  328. package/templates/social/pages/notifications.ts +73 -0
  329. package/templates/social/pages/post/[id].ts +124 -0
  330. package/templates/social/pages/profile/[username].ts +100 -0
  331. package/templates/social/pages/settings/accessibility.ts +153 -0
  332. package/templates/social/pages/settings/account.ts +260 -0
  333. package/templates/social/pages/settings/help.ts +141 -0
  334. package/templates/social/pages/settings/language.ts +103 -0
  335. package/templates/social/pages/settings/privacy.ts +183 -0
  336. package/templates/social/pages/settings/security.ts +133 -0
  337. package/templates/social/pages/settings.ts +185 -0
@@ -1,7 +1,7 @@
1
1
  import path from 'path';
2
2
  import fs from 'fs';
3
3
  import { resolvePageFile, extractRouteParams } from './plugins/vite-plugin-loaders.js';
4
- import { stripOuterLitMarkers, dirToLayoutTagName, filePathToTagName } from '../shared/utils.js';
4
+ import { stripOuterLitMarkers, dirToLayoutTagName, filePathToTagName, patchLoaderDataSpread } from '../shared/utils.js';
5
5
  import { installDomShims } from '../shared/dom-shims.js';
6
6
  import { loadTranslationsFromDisk } from './plugins/vite-plugin-i18n.js';
7
7
  /**
@@ -10,7 +10,7 @@ import { loadTranslationsFromDisk } from './plugins/vite-plugin-i18n.js';
10
10
  *
11
11
  * Returns pre-rendered HTML and loader data, or null on failure (falls back to CSR).
12
12
  */
13
- export async function ssrRenderPage(server, pagesDir, pathname, headers, locale) {
13
+ export async function ssrRenderPage(server, pagesDir, pathname, headers, locale, user) {
14
14
  try {
15
15
  const filePath = resolvePageFile(pagesDir, pathname);
16
16
  if (!filePath)
@@ -20,32 +20,27 @@ export async function ssrRenderPage(server, pagesDir, pathname, headers, locale)
20
20
  await server.ssrLoadModule('@lit-labs/ssr/lib/install-global-dom-shim.js');
21
21
  // Patch missing DOM APIs that NuralyUI components may use during SSR
22
22
  installDomShims();
23
- // Initialize i18n in the SSR context so t() works during render
24
- if (locale) {
25
- const projectDir = path.resolve(pagesDir, '..');
26
- const translations = loadTranslationsFromDisk(projectDir, locale);
27
- try {
28
- // Load the same i18n module the page will import (via resolve.alias)
29
- const i18nMod = await server.ssrLoadModule('@lumenjs/i18n');
30
- if (i18nMod?.initI18n) {
31
- i18nMod.initI18n({ locales: [], defaultLocale: locale, prefixDefault: false }, locale, translations);
32
- }
33
- }
34
- catch {
35
- // i18n module not available — translations will show keys
36
- }
37
- }
38
23
  // Invalidate SSR module cache so we always get fresh content after file edits.
39
24
  // Also clear the custom element from the SSR registry so the new class is used.
25
+ // IMPORTANT: This must happen BEFORE i18n/auth init, because invalidation
26
+ // recursively clears all SSR-imported modules (including @lumenjs/i18n).
27
+ // If we init i18n first, then invalidate, the page reload gets a fresh i18n
28
+ // module instance with empty translations.
40
29
  const g = globalThis;
41
30
  invalidateSsrModule(server, filePath);
42
31
  clearSsrCustomElement(g);
43
32
  // Load the page module via Vite (registers the custom element, applies transforms)
33
+ // Bypass get() so auto-define re-registers fresh classes
34
+ const registry = g.customElements;
35
+ if (registry)
36
+ registry.__nk_bypass_get = true;
44
37
  const mod = await server.ssrLoadModule(filePath);
38
+ if (registry)
39
+ registry.__nk_bypass_get = false;
45
40
  // Run loader if present
46
41
  let loaderData = undefined;
47
42
  if (mod.loader && typeof mod.loader === 'function') {
48
- loaderData = await mod.loader({ params, query: {}, url: pathname, headers: headers || {}, locale });
43
+ loaderData = await mod.loader({ params, query: {}, url: pathname, headers: headers || {}, locale, user: user ?? null });
49
44
  if (loaderData && typeof loaderData === 'object' && loaderData.__nk_redirect) {
50
45
  return { html: '', loaderData: null, redirect: { location: loaderData.location, status: loaderData.status || 302 } };
51
46
  }
@@ -53,8 +48,8 @@ export async function ssrRenderPage(server, pagesDir, pathname, headers, locale)
53
48
  // Determine the custom element tag name from file path (matches client router)
54
49
  const relPath = path.relative(pagesDir, filePath).replace(/\\/g, '/');
55
50
  const tagName = filePathToTagName(relPath);
56
- // Discover layout chain for this page
57
- const layoutChain = discoverLayoutChain(pagesDir, filePath);
51
+ // Standalone pages skip all layouts
52
+ const layoutChain = mod.standalone ? [] : discoverLayoutChain(pagesDir, filePath);
58
53
  const layoutsData = [];
59
54
  // Load layout modules and run their loaders
60
55
  const layoutModules = [];
@@ -62,10 +57,14 @@ export async function ssrRenderPage(server, pagesDir, pathname, headers, locale)
62
57
  // Invalidate layout module cache and clear SSR element registry
63
58
  invalidateSsrModule(server, layout.filePath);
64
59
  clearSsrCustomElement(g);
60
+ if (registry)
61
+ registry.__nk_bypass_get = true;
65
62
  const layoutMod = await server.ssrLoadModule(layout.filePath);
63
+ if (registry)
64
+ registry.__nk_bypass_get = false;
66
65
  let layoutLoaderData = undefined;
67
66
  if (layoutMod.loader && typeof layoutMod.loader === 'function') {
68
- layoutLoaderData = await layoutMod.loader({ params: {}, query: {}, url: pathname, headers: headers || {}, locale });
67
+ layoutLoaderData = await layoutMod.loader({ params: {}, query: {}, url: pathname, headers: headers || {}, locale, user: user ?? null });
69
68
  if (layoutLoaderData && typeof layoutLoaderData === 'object' && layoutLoaderData.__nk_redirect) {
70
69
  return { html: '', loaderData: null, redirect: { location: layoutLoaderData.location, status: layoutLoaderData.status || 302 } };
71
70
  }
@@ -74,6 +73,38 @@ export async function ssrRenderPage(server, pagesDir, pathname, headers, locale)
74
73
  layoutModules.push({ tagName: layoutTagName, loaderData: layoutLoaderData });
75
74
  layoutsData.push({ loaderPath: layout.dir, data: layoutLoaderData });
76
75
  }
76
+ // Patch element classes to spread loaderData into individual properties
77
+ for (const lm of layoutModules) {
78
+ patchLoaderDataSpread(lm.tagName);
79
+ }
80
+ patchLoaderDataSpread(tagName);
81
+ // Initialize i18n in the SSR context AFTER all page/layout modules are loaded.
82
+ // This ensures t() uses the same module instance the components imported.
83
+ // Must happen after invalidation + module loading, because invalidateSsrModule
84
+ // recursively clears cached modules — if i18n was initialized before, the
85
+ // reloaded page/layout would get a fresh i18n instance with empty translations.
86
+ if (locale) {
87
+ const projectDir = path.resolve(pagesDir, '..');
88
+ const translations = loadTranslationsFromDisk(projectDir, locale);
89
+ try {
90
+ const i18nMod = await server.ssrLoadModule('@lumenjs/i18n');
91
+ if (i18nMod?.initI18n) {
92
+ i18nMod.initI18n({ locales: [], defaultLocale: locale, prefixDefault: false }, locale, translations);
93
+ }
94
+ }
95
+ catch {
96
+ // i18n module not available — translations will show keys
97
+ }
98
+ }
99
+ // Initialize auth in the SSR context (same reason — after module loading)
100
+ if (user) {
101
+ try {
102
+ const authMod = await server.ssrLoadModule('@nuraly/lumenjs-auth');
103
+ if (authMod?.initAuth)
104
+ authMod.initAuth(user);
105
+ }
106
+ catch { }
107
+ }
77
108
  // Load SSR render + lit/static-html.js through Vite (same module registry as page)
78
109
  const { render } = await server.ssrLoadModule('@lit-labs/ssr');
79
110
  const { html, unsafeStatic } = await server.ssrLoadModule('lit/static-html.js');
@@ -106,7 +137,7 @@ export async function ssrRenderPage(server, pagesDir, pathname, headers, locale)
106
137
  htmlStr = layoutHtml + htmlStr;
107
138
  }
108
139
  }
109
- return { html: htmlStr, loaderData, layoutsData: layoutsData.length > 0 ? layoutsData : undefined };
140
+ return { html: htmlStr, loaderData, layoutsData: layoutsData.length > 0 ? layoutsData : undefined, authUser: user ?? undefined };
110
141
  }
111
142
  catch (err) {
112
143
  console.error('[LumenJS] SSR render failed, falling back to CSR:', err);
@@ -145,41 +176,69 @@ function findLayoutFile(dir) {
145
176
  return null;
146
177
  }
147
178
  /**
148
- * Aggressively invalidate a module for SSR re-execution.
179
+ * Aggressively invalidate a module and all its SSR-imported dependencies.
180
+ * Without this, editing a component imported by a page/layout serves stale SSR.
149
181
  */
150
182
  function invalidateSsrModule(server, filePath) {
151
- const byFile = server.moduleGraph.getModulesByFile(filePath);
152
- if (byFile) {
153
- for (const m of byFile) {
154
- server.moduleGraph.invalidateModule(m);
155
- m.ssrModule = null;
156
- m.ssrTransformResult = null;
183
+ const visited = new Set();
184
+ function invalidateRecursive(id) {
185
+ if (visited.has(id))
186
+ return;
187
+ visited.add(id);
188
+ const mods = server.moduleGraph.getModulesByFile(id);
189
+ if (mods) {
190
+ for (const m of mods) {
191
+ server.moduleGraph.invalidateModule(m);
192
+ m.ssrModule = null;
193
+ m.ssrTransformResult = null;
194
+ // Recurse into SSR-imported modules
195
+ if (m.ssrImportedModules) {
196
+ for (const dep of m.ssrImportedModules) {
197
+ if (dep.file)
198
+ invalidateRecursive(dep.file);
199
+ }
200
+ }
201
+ }
202
+ }
203
+ const urlMod = server.moduleGraph.getModuleById(id);
204
+ if (urlMod) {
205
+ server.moduleGraph.invalidateModule(urlMod);
206
+ urlMod.ssrModule = null;
207
+ urlMod.ssrTransformResult = null;
157
208
  }
158
209
  }
159
- const urlMod = server.moduleGraph.getModuleById(filePath);
160
- if (urlMod) {
161
- server.moduleGraph.invalidateModule(urlMod);
162
- urlMod.ssrModule = null;
163
- urlMod.ssrTransformResult = null;
164
- }
210
+ invalidateRecursive(filePath);
165
211
  }
166
212
  /**
167
- * Patch the SSR customElements registry to allow re-registration.
213
+ * Patch the SSR customElements registry to allow re-registration,
214
+ * and proactively clear all definitions so auto-define guards pass.
168
215
  */
169
216
  function clearSsrCustomElement(g) {
170
217
  const registry = g.customElements;
171
- if (!registry || registry.__nk_patched)
218
+ if (!registry)
172
219
  return;
173
- registry.__nk_patched = true;
174
- const origDefine = registry.define.bind(registry);
175
- registry.define = (name, ctor) => {
176
- if (registry.__definitions && registry.__definitions.has(name)) {
177
- const oldCtor = registry.__definitions.get(name)?.ctor;
178
- registry.__definitions.delete(name);
179
- if (oldCtor && registry.__reverseDefinitions) {
180
- registry.__reverseDefinitions.delete(oldCtor);
220
+ // Patch define() to allow re-registration and get() to bypass
221
+ // auto-define guards (one-time)
222
+ if (!registry.__nk_patched) {
223
+ registry.__nk_patched = true;
224
+ const origDefine = registry.define.bind(registry);
225
+ registry.define = (name, ctor) => {
226
+ if (registry.__definitions && registry.__definitions.has(name)) {
227
+ const oldCtor = registry.__definitions.get(name)?.ctor;
228
+ registry.__definitions.delete(name);
229
+ if (oldCtor && registry.__reverseDefinitions) {
230
+ registry.__reverseDefinitions.delete(oldCtor);
231
+ }
181
232
  }
182
- }
183
- return origDefine(name, ctor);
184
- };
233
+ return origDefine(name, ctor);
234
+ };
235
+ // Patch get() so auto-define's `if (!customElements.get('tag'))` guard
236
+ // always passes, allowing define() to re-register the fresh class.
237
+ const origGet = registry.get.bind(registry);
238
+ registry.get = (name) => {
239
+ if (registry.__nk_bypass_get)
240
+ return undefined;
241
+ return origGet(name);
242
+ };
243
+ }
185
244
  }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * AI backend router — selects between Claude Code and OpenCode based on:
3
+ * 1. AI_BACKEND env var ('claude-code' | 'opencode')
4
+ * 2. Auto-detection: Claude Code CLI first, then OpenCode server
5
+ */
6
+ import type { AiChatOptions, AiChatResult, AiStatusResult } from './types.js';
7
+ export type { AiChatOptions, AiChatResult, AiStatusResult } from './types.js';
8
+ /**
9
+ * Stream an AI chat message using the configured backend.
10
+ */
11
+ export declare function streamAiChat(projectDir: string, options: AiChatOptions): AiChatResult;
12
+ /**
13
+ * Warm up the AI backend session in the background.
14
+ * Call on editor startup so the first user request is fast.
15
+ */
16
+ export declare function warmUpAiSession(projectDir: string): Promise<void>;
17
+ /**
18
+ * Check if any AI backend is available.
19
+ */
20
+ export declare function checkAiStatus(): Promise<AiStatusResult>;
@@ -0,0 +1,104 @@
1
+ /**
2
+ * AI backend router — selects between Claude Code and OpenCode based on:
3
+ * 1. AI_BACKEND env var ('claude-code' | 'opencode')
4
+ * 2. Auto-detection: Claude Code CLI first, then OpenCode server
5
+ */
6
+ let resolvedBackend = null;
7
+ async function detectBackend() {
8
+ if (resolvedBackend)
9
+ return resolvedBackend;
10
+ const explicit = process.env.AI_BACKEND;
11
+ if (explicit === 'claude-code' || explicit === 'opencode') {
12
+ resolvedBackend = explicit;
13
+ console.log(`[LumenJS] AI backend: ${explicit} (from AI_BACKEND env)`);
14
+ return resolvedBackend;
15
+ }
16
+ // Auto-detect: try Claude Code first (subscription-based, no server needed)
17
+ try {
18
+ const cc = await import('./claude-code-client.js');
19
+ const status = await cc.checkAiStatus();
20
+ if (status.configured) {
21
+ resolvedBackend = 'claude-code';
22
+ console.log('[LumenJS] AI backend: claude-code (auto-detected)');
23
+ return resolvedBackend;
24
+ }
25
+ }
26
+ catch {
27
+ // SDK not installed or CLI not found
28
+ }
29
+ // Fall back to OpenCode
30
+ resolvedBackend = 'opencode';
31
+ console.log('[LumenJS] AI backend: opencode (fallback)');
32
+ return resolvedBackend;
33
+ }
34
+ async function getClient() {
35
+ const backend = await detectBackend();
36
+ if (backend === 'claude-code') {
37
+ return import('./claude-code-client.js');
38
+ }
39
+ return import('./opencode-client.js');
40
+ }
41
+ /**
42
+ * Stream an AI chat message using the configured backend.
43
+ */
44
+ export function streamAiChat(projectDir, options) {
45
+ const tokenCallbacks = [];
46
+ const doneCallbacks = [];
47
+ const errorCallbacks = [];
48
+ let innerResult = null;
49
+ const run = async () => {
50
+ try {
51
+ const client = await getClient();
52
+ innerResult = client.streamAiChat(projectDir, options);
53
+ // Forward callbacks registered before the client loaded
54
+ for (const cb of tokenCallbacks)
55
+ innerResult.onToken(cb);
56
+ for (const cb of doneCallbacks)
57
+ innerResult.onDone(cb);
58
+ for (const cb of errorCallbacks)
59
+ innerResult.onError(cb);
60
+ }
61
+ catch (err) {
62
+ const error = err instanceof Error ? err : new Error(String(err));
63
+ for (const cb of errorCallbacks)
64
+ cb(error);
65
+ }
66
+ };
67
+ run();
68
+ return {
69
+ get sessionId() { return innerResult?.sessionId || options.sessionId || ''; },
70
+ onToken: (cb) => { tokenCallbacks.push(cb); innerResult?.onToken(cb); },
71
+ onDone: (cb) => { doneCallbacks.push(cb); innerResult?.onDone(cb); },
72
+ onError: (cb) => { errorCallbacks.push(cb); innerResult?.onError(cb); },
73
+ abort: () => innerResult?.abort(),
74
+ };
75
+ }
76
+ /**
77
+ * Warm up the AI backend session in the background.
78
+ * Call on editor startup so the first user request is fast.
79
+ */
80
+ export async function warmUpAiSession(projectDir) {
81
+ const backend = await detectBackend();
82
+ if (backend === 'claude-code') {
83
+ try {
84
+ const cc = await import('./claude-code-client.js');
85
+ await cc.warmUpSession(projectDir);
86
+ console.log('[LumenJS] AI session warmed up');
87
+ }
88
+ catch {
89
+ // Non-fatal
90
+ }
91
+ }
92
+ }
93
+ /**
94
+ * Check if any AI backend is available.
95
+ */
96
+ export async function checkAiStatus() {
97
+ try {
98
+ const client = await getClient();
99
+ return client.checkAiStatus();
100
+ }
101
+ catch {
102
+ return { configured: false, backend: 'opencode' };
103
+ }
104
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Claude Code AI client — uses the Claude Agent SDK (@anthropic-ai/claude-agent-sdk).
3
+ * Spawns the `claude` CLI as a subprocess. Requires Claude Code CLI installed and logged in.
4
+ * Works with Pro/Max subscription — no API key needed.
5
+ */
6
+ import type { AiChatOptions, AiChatResult, AiStatusResult } from './types.js';
7
+ /**
8
+ * Warm up by pre-spawning a Claude Code session. The first real request
9
+ * will resume this session, skipping CLI cold-start entirely.
10
+ */
11
+ export declare function warmUpSession(projectDir: string): Promise<void>;
12
+ /**
13
+ * Stream an AI chat message via Claude Code Agent SDK.
14
+ */
15
+ export declare function streamAiChat(projectDir: string, options: AiChatOptions): AiChatResult;
16
+ /**
17
+ * Check if Claude Code CLI is installed and the Agent SDK is importable.
18
+ * Both are required — the CLI alone isn't enough.
19
+ */
20
+ export declare function checkAiStatus(): Promise<AiStatusResult>;
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Claude Code AI client — uses the Claude Agent SDK (@anthropic-ai/claude-agent-sdk).
3
+ * Spawns the `claude` CLI as a subprocess. Requires Claude Code CLI installed and logged in.
4
+ * Works with Pro/Max subscription — no API key needed.
5
+ */
6
+ import { SYSTEM_PROMPT, buildPrompt } from './types.js';
7
+ import { execSync } from 'child_process';
8
+ // ── SDK Cache & Session Warm-up ──────────────────────────────────
9
+ let _sdkCache = null;
10
+ let _warmSessionId = null;
11
+ async function getSdk() {
12
+ if (_sdkCache)
13
+ return _sdkCache;
14
+ const sdk = await import('@anthropic-ai/claude-agent-sdk');
15
+ const query = sdk.query || sdk.default?.query;
16
+ if (!query)
17
+ throw new Error('Claude Agent SDK loaded but query() not found');
18
+ _sdkCache = { query };
19
+ return _sdkCache;
20
+ }
21
+ /**
22
+ * Warm up by pre-spawning a Claude Code session. The first real request
23
+ * will resume this session, skipping CLI cold-start entirely.
24
+ */
25
+ export async function warmUpSession(projectDir) {
26
+ try {
27
+ const { query } = await getSdk();
28
+ const stream = query({
29
+ prompt: 'Ready.',
30
+ options: {
31
+ cwd: projectDir,
32
+ systemPrompt: SYSTEM_PROMPT,
33
+ allowedTools: ['Read', 'Edit', 'Write', 'Glob', 'Grep', 'Bash'],
34
+ maxTurns: 1,
35
+ model: 'sonnet',
36
+ effort: 'low',
37
+ persistSession: true,
38
+ },
39
+ });
40
+ for await (const msg of stream) {
41
+ if (msg.session_id) {
42
+ _warmSessionId = msg.session_id;
43
+ break;
44
+ }
45
+ }
46
+ }
47
+ catch {
48
+ // Non-fatal — first request will just be slower
49
+ }
50
+ }
51
+ /**
52
+ * Stream an AI chat message via Claude Code Agent SDK.
53
+ */
54
+ export function streamAiChat(projectDir, options) {
55
+ const tokenCallbacks = [];
56
+ const doneCallbacks = [];
57
+ const errorCallbacks = [];
58
+ let aborted = false;
59
+ let sessionId = options.sessionId || '';
60
+ const enrichedPrompt = buildPrompt(options);
61
+ const run = async () => {
62
+ try {
63
+ const { query } = await getSdk();
64
+ let fullText = '';
65
+ const queryOptions = {
66
+ cwd: projectDir,
67
+ systemPrompt: SYSTEM_PROMPT,
68
+ allowedTools: ['Read', 'Edit', 'Write', 'Glob', 'Grep', 'Bash'],
69
+ maxTurns: 10,
70
+ persistSession: true,
71
+ model: 'sonnet',
72
+ };
73
+ // Use Sonnet + low effort for fast mode (quick actions like text improvement, spacing)
74
+ if (options.model === 'fast') {
75
+ queryOptions.model = 'sonnet';
76
+ queryOptions.effort = 'low';
77
+ queryOptions.maxTurns = 5;
78
+ }
79
+ // Resume existing session, or use pre-warmed session for instant first request
80
+ if (sessionId) {
81
+ queryOptions.resume = sessionId;
82
+ }
83
+ else if (_warmSessionId) {
84
+ queryOptions.resume = _warmSessionId;
85
+ sessionId = _warmSessionId;
86
+ _warmSessionId = null;
87
+ }
88
+ const stream = query({
89
+ prompt: enrichedPrompt,
90
+ options: queryOptions,
91
+ });
92
+ for await (const msg of stream) {
93
+ if (aborted)
94
+ break;
95
+ // Capture session ID from any message
96
+ if (msg.session_id && !sessionId) {
97
+ sessionId = msg.session_id;
98
+ }
99
+ if (msg.type === 'assistant' && msg.message?.content) {
100
+ for (const block of msg.message.content) {
101
+ if (block.type === 'text' && block.text) {
102
+ fullText += block.text;
103
+ for (const cb of tokenCallbacks)
104
+ cb(block.text);
105
+ }
106
+ }
107
+ }
108
+ }
109
+ if (!aborted) {
110
+ for (const cb of doneCallbacks)
111
+ cb(fullText);
112
+ }
113
+ }
114
+ catch (err) {
115
+ if (aborted)
116
+ return;
117
+ for (const cb of errorCallbacks)
118
+ cb(err instanceof Error ? err : new Error(String(err)));
119
+ }
120
+ };
121
+ // Start the async flow
122
+ run();
123
+ return {
124
+ get sessionId() { return sessionId; },
125
+ onToken: (cb) => { tokenCallbacks.push(cb); },
126
+ onDone: (cb) => { doneCallbacks.push(cb); },
127
+ onError: (cb) => { errorCallbacks.push(cb); },
128
+ abort: () => { aborted = true; },
129
+ };
130
+ }
131
+ /**
132
+ * Check if Claude Code CLI is installed and the Agent SDK is importable.
133
+ * Both are required — the CLI alone isn't enough.
134
+ */
135
+ export async function checkAiStatus() {
136
+ try {
137
+ execSync('claude --version', { timeout: 5000, stdio: 'pipe' });
138
+ // Verify the SDK is actually importable (it's an optional dependency)
139
+ await import('@anthropic-ai/claude-agent-sdk');
140
+ return { configured: true, backend: 'claude-code' };
141
+ }
142
+ catch {
143
+ return { configured: false, backend: 'claude-code' };
144
+ }
145
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * OpenCode AI client — wraps the OpenCode REST API for AI coding agent integration.
3
+ * Connects to an OpenCode server (`opencode serve`) that handles LLM calls and file editing.
4
+ */
5
+ import type { AiChatOptions, AiChatResult, AiStatusResult } from './types.js';
6
+ /**
7
+ * Stream an AI chat message via OpenCode's REST API.
8
+ * Uses the /api/session and /api/message endpoints.
9
+ */
10
+ export declare function streamAiChat(projectDir: string, options: AiChatOptions): AiChatResult;
11
+ /**
12
+ * Check if OpenCode server is reachable.
13
+ */
14
+ export declare function checkAiStatus(): Promise<AiStatusResult>;
@@ -0,0 +1,125 @@
1
+ /**
2
+ * OpenCode AI client — wraps the OpenCode REST API for AI coding agent integration.
3
+ * Connects to an OpenCode server (`opencode serve`) that handles LLM calls and file editing.
4
+ */
5
+ import { SYSTEM_PROMPT, buildPrompt } from './types.js';
6
+ const OPENCODE_URL = process.env.OPENCODE_URL || 'http://localhost:3500';
7
+ const OPENCODE_PASSWORD = process.env.OPENCODE_SERVER_PASSWORD || '';
8
+ function buildHeaders() {
9
+ const headers = { 'Content-Type': 'application/json' };
10
+ if (OPENCODE_PASSWORD) {
11
+ headers['Authorization'] = `Bearer ${OPENCODE_PASSWORD}`;
12
+ }
13
+ return headers;
14
+ }
15
+ /**
16
+ * Stream an AI chat message via OpenCode's REST API.
17
+ * Uses the /api/session and /api/message endpoints.
18
+ */
19
+ export function streamAiChat(projectDir, options) {
20
+ const tokenCallbacks = [];
21
+ const doneCallbacks = [];
22
+ const errorCallbacks = [];
23
+ const controller = new AbortController();
24
+ let sessionId = options.sessionId || '';
25
+ const enrichedPrompt = buildPrompt(options);
26
+ const run = async () => {
27
+ try {
28
+ // Create a new session if we don't have one
29
+ if (!sessionId) {
30
+ const createRes = await fetch(`${OPENCODE_URL}/api/session`, {
31
+ method: 'POST',
32
+ headers: buildHeaders(),
33
+ body: JSON.stringify({ path: projectDir, system: SYSTEM_PROMPT }),
34
+ signal: controller.signal,
35
+ });
36
+ if (!createRes.ok) {
37
+ throw new Error(`Failed to create OpenCode session: ${createRes.status}`);
38
+ }
39
+ const sessionData = await createRes.json();
40
+ sessionId = sessionData.id || sessionData.sessionId || '';
41
+ }
42
+ // Send message and stream response
43
+ const msgRes = await fetch(`${OPENCODE_URL}/api/session/${sessionId}/message`, {
44
+ method: 'POST',
45
+ headers: { ...buildHeaders(), 'Accept': 'text/event-stream' },
46
+ body: JSON.stringify({ content: enrichedPrompt }),
47
+ signal: controller.signal,
48
+ });
49
+ if (!msgRes.ok) {
50
+ throw new Error(`OpenCode message failed: ${msgRes.status}`);
51
+ }
52
+ const reader = msgRes.body?.getReader();
53
+ if (!reader)
54
+ throw new Error('No response body from OpenCode');
55
+ const decoder = new TextDecoder();
56
+ let fullText = '';
57
+ let buffer = '';
58
+ while (true) {
59
+ const { done, value } = await reader.read();
60
+ if (done)
61
+ break;
62
+ buffer += decoder.decode(value, { stream: true });
63
+ const lines = buffer.split('\n');
64
+ buffer = lines.pop() || '';
65
+ for (const line of lines) {
66
+ if (line.startsWith('data: ')) {
67
+ const data = line.slice(6).trim();
68
+ if (data === '[DONE]')
69
+ continue;
70
+ try {
71
+ const parsed = JSON.parse(data);
72
+ // Handle different event formats from OpenCode
73
+ const text = parsed.content || parsed.text || parsed.delta || '';
74
+ if (text) {
75
+ fullText += text;
76
+ for (const cb of tokenCallbacks)
77
+ cb(text);
78
+ }
79
+ }
80
+ catch {
81
+ // Non-JSON data line, treat as raw text
82
+ if (data) {
83
+ fullText += data;
84
+ for (const cb of tokenCallbacks)
85
+ cb(data);
86
+ }
87
+ }
88
+ }
89
+ }
90
+ }
91
+ for (const cb of doneCallbacks)
92
+ cb(fullText);
93
+ }
94
+ catch (err) {
95
+ if (err?.name === 'AbortError')
96
+ return;
97
+ for (const cb of errorCallbacks)
98
+ cb(err instanceof Error ? err : new Error(String(err)));
99
+ }
100
+ };
101
+ // Start the async flow
102
+ run();
103
+ return {
104
+ get sessionId() { return sessionId; },
105
+ onToken: (cb) => { tokenCallbacks.push(cb); },
106
+ onDone: (cb) => { doneCallbacks.push(cb); },
107
+ onError: (cb) => { errorCallbacks.push(cb); },
108
+ abort: () => controller.abort(),
109
+ };
110
+ }
111
+ /**
112
+ * Check if OpenCode server is reachable.
113
+ */
114
+ export async function checkAiStatus() {
115
+ try {
116
+ const res = await fetch(`${OPENCODE_URL}/api/status`, {
117
+ headers: buildHeaders(),
118
+ signal: AbortSignal.timeout(3000),
119
+ });
120
+ return { configured: res.ok, backend: 'opencode' };
121
+ }
122
+ catch {
123
+ return { configured: false, backend: 'opencode' };
124
+ }
125
+ }