akanjs 3.1.0-rc.8 → 3.1.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 (323) hide show
  1. package/CHANGELOG.md +547 -0
  2. package/README.ko.md +2 -2
  3. package/README.md +2 -2
  4. package/client/cookie.ts +5 -0
  5. package/client/csrLocation.ts +17 -72
  6. package/client/csrTypes.ts +19 -4
  7. package/client/href.ts +8 -0
  8. package/client/makePageProto.tsx +3 -2
  9. package/client/route/PageDefinition.ts +103 -10
  10. package/client/route/RouteDefinition.ts +44 -3
  11. package/client/route/RouteGuards.ts +64 -0
  12. package/client/route/index.ts +1 -0
  13. package/client/route/resolveRouteModule.ts +8 -0
  14. package/client/route/routeArgs.ts +9 -0
  15. package/client/router.ts +51 -2
  16. package/client/translator.ts +16 -0
  17. package/client/viewportMeta.ts +23 -8
  18. package/common/Logger.ts +6 -4
  19. package/common/authCookie.ts +13 -0
  20. package/common/authToken.ts +1 -12
  21. package/common/codeAgentWire.ts +8 -1
  22. package/common/index.ts +2 -8
  23. package/common/routeConvention.ts +2 -0
  24. package/constant/inputParser.ts +1 -1
  25. package/dictionary/base.dictionary.ts +11 -0
  26. package/document/database.ts +3 -0
  27. package/document/documentQuery.ts +21 -0
  28. package/document/into.ts +2 -0
  29. package/document/liveRowScope.ts +4 -8
  30. package/document/noDocumentError.ts +6 -1
  31. package/document/queryEvaluator.ts +5 -8
  32. package/fetch/appScope.ts +54 -0
  33. package/fetch/client/fetchClient.ts +46 -29
  34. package/fetch/client/httpClient.ts +38 -10
  35. package/fetch/client/sliceInitHandle.ts +2 -3
  36. package/fetch/client/wsClient.ts +3 -1
  37. package/fetch/fetchType/endpointFetch.type.ts +11 -9
  38. package/fetch/index.ts +1 -0
  39. package/index.ts +2 -0
  40. package/package.json +32 -22
  41. package/server/akanApp.ts +12 -3
  42. package/server/akanServer.ts +10 -5
  43. package/server/index.ts +1 -0
  44. package/server/mcp/McpApps.ts +44 -50
  45. package/server/mcp/McpDispatcher.ts +3 -3
  46. package/server/mcp/McpPages.ts +93 -19
  47. package/server/mcp/McpRouter.ts +14 -11
  48. package/server/memoryLimit.ts +4 -0
  49. package/server/migration/docPath.ts +121 -0
  50. package/server/migration/index.ts +15 -0
  51. package/server/migration/migrationChangeLog.ts +86 -0
  52. package/server/migration/migrationChanges.ts +70 -0
  53. package/server/migration/migrationCommand.ts +179 -0
  54. package/server/migration/migrationContext.ts +53 -0
  55. package/server/migration/migrationDefinition.ts +87 -0
  56. package/server/migration/migrationError.ts +45 -0
  57. package/server/migration/migrationLedger.ts +172 -0
  58. package/server/migration/migrationLock.ts +103 -0
  59. package/server/migration/migrationParams.ts +122 -0
  60. package/server/migration/migrationPulse.ts +39 -0
  61. package/server/migration/migrationRunner.ts +525 -0
  62. package/server/migration/migrationScope.ts +93 -0
  63. package/server/migration/migrationTable.ts +258 -0
  64. package/server/migration/migrations.ts +57 -0
  65. package/server/ops/migrateJobs.ts +145 -0
  66. package/server/ops/opsCommand.ts +30 -1
  67. package/server/ops/opsRoute.ts +39 -7
  68. package/server/ops/opsToken.ts +7 -2
  69. package/server/resolver/CascadeRunner.ts +15 -2
  70. package/server/resolver/database.resolver.ts +4 -0
  71. package/server/resolver/service.resolver.ts +3 -0
  72. package/server/resolver/signal.resolver.ts +41 -31
  73. package/server/routeElementComposer.tsx +33 -6
  74. package/server/routeState.ts +1 -0
  75. package/server/routeTreeBuilder.ts +5 -0
  76. package/server/rscClient.tsx +67 -22
  77. package/server/rscClientFetch.ts +8 -3
  78. package/server/rscNavigationState.ts +2 -2
  79. package/server/rscPagePrompts.ts +66 -16
  80. package/server/rscScrollRestoration.ts +21 -8
  81. package/server/rscWorker.tsx +79 -32
  82. package/server/rscWorkerHost.ts +12 -1
  83. package/server/tunnel/TunnelAgent.ts +2 -1
  84. package/server/webRouter.ts +33 -27
  85. package/service/agent.service.ts +21 -1
  86. package/service/endpointCacheKeys.ts +35 -0
  87. package/service/index.ts +1 -0
  88. package/service/liveSyncHub.ts +2 -1
  89. package/service/predefinedAdaptor/anthropicLlm.ts +37 -17
  90. package/service/predefinedAdaptor/database.adaptor.ts +98 -25
  91. package/service/predefinedAdaptor/documentTransfer.ts +50 -0
  92. package/service/predefinedAdaptor/endpointCacheControl.adaptor.ts +19 -0
  93. package/service/predefinedAdaptor/index.ts +1 -0
  94. package/service/predefinedAdaptor/llm.adaptor.ts +7 -0
  95. package/service/predefinedAdaptor/openaiDialect.ts +53 -17
  96. package/service/predefinedAdaptor/openaiLlm.ts +1 -1
  97. package/service/predefinedAdaptor/solidQueue.adaptor.ts +30 -9
  98. package/service/predefinedAdaptor/sql/MigrationTables.ts +90 -0
  99. package/service/predefinedAdaptor/sql/QueryCompiler.ts +16 -14
  100. package/service/predefinedAdaptor/sql/RawDocumentTable.ts +200 -0
  101. package/service/predefinedAdaptor/sql/SqlDocumentStore.ts +218 -44
  102. package/service/predefinedAdaptor/sql/SqliteInsightSession.ts +4 -1
  103. package/service/predefinedAdaptor/sql/dialect/postgres.ts +13 -3
  104. package/service/predefinedAdaptor/sql/dialect/sqlite.ts +13 -2
  105. package/service/predefinedAdaptor/sql/driver/bunSqlite.ts +4 -5
  106. package/service/predefinedAdaptor/sql/types.ts +22 -1
  107. package/service/predefinedAdaptor/sql/values.ts +19 -0
  108. package/service/predefinedAdaptor/storage.adaptor.ts +19 -0
  109. package/service/serviceModule.ts +3 -0
  110. package/service/types.ts +1 -0
  111. package/signal/TaggedJson.ts +26 -4
  112. package/signal/endpointCache.ts +16 -6
  113. package/signal/exception.ts +4 -1
  114. package/signal/mcp/mcpProtocol.ts +7 -0
  115. package/signal/mcp/pagePrompt.ts +18 -1
  116. package/signal/signalContext.ts +7 -10
  117. package/store/action.ts +181 -73
  118. package/store/agent/ScreenImage.ts +166 -0
  119. package/store/agent/StoreSurfaceSource.ts +41 -2
  120. package/store/agent/index.ts +2 -1
  121. package/store/databaseStateNames.ts +1 -0
  122. package/store/formUploadOf.ts +41 -0
  123. package/store/index.ts +1 -0
  124. package/store/liveInsert.ts +5 -1
  125. package/store/sliceKeys.ts +1 -0
  126. package/store/state.ts +15 -3
  127. package/store/stateBuilder.ts +7 -1
  128. package/store/storeInstance.ts +22 -4
  129. package/types/client/csrLocation.d.ts +3 -7
  130. package/types/client/csrTypes.d.ts +22 -3
  131. package/types/client/href.d.ts +3 -0
  132. package/types/client/route/PageDefinition.d.ts +21 -4
  133. package/types/client/route/RouteDefinition.d.ts +4 -0
  134. package/types/client/route/RouteGuards.d.ts +15 -0
  135. package/types/client/route/index.d.ts +1 -0
  136. package/types/client/route/resolveRouteModule.d.ts +2 -0
  137. package/types/client/route/routeArgs.d.ts +5 -0
  138. package/types/client/route/routeBuilders.d.ts +1 -1
  139. package/types/client/router.d.ts +9 -1
  140. package/types/client/translator.d.ts +2 -0
  141. package/types/common/authCookie.d.ts +5 -0
  142. package/types/common/authToken.d.ts +0 -5
  143. package/types/common/codeAgentWire.d.ts +7 -0
  144. package/types/common/index.d.ts +2 -1
  145. package/types/dictionary/base.dictionary.d.ts +1 -1
  146. package/types/dictionary/dictionary.d.ts +8 -8
  147. package/types/document/database.d.ts +3 -0
  148. package/types/document/documentQuery.d.ts +1 -0
  149. package/types/document/into.d.ts +2 -0
  150. package/types/document/noDocumentError.d.ts +6 -1
  151. package/types/fetch/appScope.d.ts +18 -0
  152. package/types/fetch/client/fetchClient.d.ts +1 -1
  153. package/types/fetch/fetchType/endpointFetch.type.d.ts +1 -1
  154. package/types/fetch/index.d.ts +1 -0
  155. package/types/index.d.ts +5 -0
  156. package/types/server/akanServer.d.ts +10 -5
  157. package/types/server/index.d.ts +1 -0
  158. package/types/server/mcp/McpApps.d.ts +14 -8
  159. package/types/server/mcp/McpPages.d.ts +6 -3
  160. package/types/server/migration/docPath.d.ts +20 -0
  161. package/types/server/migration/index.d.ts +15 -0
  162. package/types/server/migration/migrationChangeLog.d.ts +27 -0
  163. package/types/server/migration/migrationChanges.d.ts +27 -0
  164. package/types/server/migration/migrationCommand.d.ts +33 -0
  165. package/types/server/migration/migrationContext.d.ts +28 -0
  166. package/types/server/migration/migrationDefinition.d.ts +42 -0
  167. package/types/server/migration/migrationError.d.ts +15 -0
  168. package/types/server/migration/migrationLedger.d.ts +51 -0
  169. package/types/server/migration/migrationLock.d.ts +34 -0
  170. package/types/server/migration/migrationParams.d.ts +41 -0
  171. package/types/server/migration/migrationPulse.d.ts +15 -0
  172. package/types/server/migration/migrationRunner.d.ts +93 -0
  173. package/types/server/migration/migrationScope.d.ts +42 -0
  174. package/types/server/migration/migrationTable.d.ts +52 -0
  175. package/types/server/migration/migrations.d.ts +12 -0
  176. package/types/server/migration.d.ts +1 -0
  177. package/types/server/ops/migrateJobs.d.ts +36 -0
  178. package/types/server/ops/opsCommand.d.ts +10 -1
  179. package/types/server/ops/opsRoute.d.ts +4 -1
  180. package/types/server/ops/opsToken.d.ts +3 -0
  181. package/types/server/routeElementComposer.d.ts +10 -1
  182. package/types/server/routeState.d.ts +1 -0
  183. package/types/server/rscClientFetch.d.ts +2 -0
  184. package/types/server/rscNavigationState.d.ts +1 -1
  185. package/types/server/rscPagePrompts.d.ts +3 -1
  186. package/types/server/rscScrollRestoration.d.ts +2 -0
  187. package/types/server/rscWorkerHost.d.ts +2 -1
  188. package/types/server/webRouter.d.ts +3 -0
  189. package/types/service/agent.service.d.ts +2 -0
  190. package/types/service/endpointCacheKeys.d.ts +8 -0
  191. package/types/service/index.d.ts +1 -0
  192. package/types/service/predefinedAdaptor/anthropicLlm.d.ts +9 -4
  193. package/types/service/predefinedAdaptor/database.adaptor.d.ts +21 -2
  194. package/types/service/predefinedAdaptor/documentTransfer.d.ts +1 -0
  195. package/types/service/predefinedAdaptor/endpointCacheControl.adaptor.d.ts +9 -0
  196. package/types/service/predefinedAdaptor/index.d.ts +1 -0
  197. package/types/service/predefinedAdaptor/llm.adaptor.d.ts +7 -0
  198. package/types/service/predefinedAdaptor/openaiDialect.d.ts +20 -5
  199. package/types/service/predefinedAdaptor/solidQueue.adaptor.d.ts +1 -0
  200. package/types/service/predefinedAdaptor/sql/MigrationTables.d.ts +17 -0
  201. package/types/service/predefinedAdaptor/sql/QueryCompiler.d.ts +0 -1
  202. package/types/service/predefinedAdaptor/sql/RawDocumentTable.d.ts +38 -0
  203. package/types/service/predefinedAdaptor/sql/SqlDocumentStore.d.ts +1 -0
  204. package/types/service/predefinedAdaptor/sql/dialect/postgres.d.ts +2 -1
  205. package/types/service/predefinedAdaptor/sql/dialect/sqlite.d.ts +3 -1
  206. package/types/service/predefinedAdaptor/sql/driver/bunSqlite.d.ts +2 -2
  207. package/types/service/predefinedAdaptor/sql/types.d.ts +26 -0
  208. package/types/service/predefinedAdaptor/sql/values.d.ts +1 -0
  209. package/types/service/predefinedAdaptor/storage.adaptor.d.ts +8 -0
  210. package/types/service/types.d.ts +1 -0
  211. package/types/signal/exception.d.ts +4 -1
  212. package/types/signal/mcp/mcpProtocol.d.ts +6 -0
  213. package/types/signal/mcp/pagePrompt.d.ts +16 -0
  214. package/types/signal/signalContext.d.ts +0 -2
  215. package/types/store/action.d.ts +2 -0
  216. package/types/store/agent/ScreenImage.d.ts +27 -0
  217. package/types/store/agent/StoreSurfaceSource.d.ts +1 -1
  218. package/types/store/agent/index.d.ts +2 -1
  219. package/types/store/databaseStateNames.d.ts +1 -0
  220. package/types/store/formUploadOf.d.ts +9 -0
  221. package/types/store/index.d.ts +1 -0
  222. package/types/store/liveInsert.d.ts +3 -1
  223. package/types/store/sliceKeys.d.ts +1 -0
  224. package/types/store/state.d.ts +10 -4
  225. package/types/store/stateBuilder.d.ts +1 -0
  226. package/types/ui/Agent/Composer.d.ts +2 -0
  227. package/types/ui/Agent/Menu.d.ts +2 -0
  228. package/types/ui/CsrImage.d.ts +2 -0
  229. package/types/ui/Image.d.ts +3 -1
  230. package/types/ui/Layout/FrameSlotPortal.d.ts +1 -1
  231. package/types/ui/Load/sliceClaim.d.ts +28 -0
  232. package/types/ui/Model/Edit.d.ts +3 -2
  233. package/types/ui/Model/editSeed.d.ts +4 -0
  234. package/types/ui/System/App.d.ts +17 -0
  235. package/types/ui/System/index.d.ts +2 -0
  236. package/types/ui/recipe/badgeRecipe.d.ts +2 -2
  237. package/types/ui/recipe/buttonRecipe.d.ts +2 -2
  238. package/types/ui/sliceNamesOf.d.ts +2 -0
  239. package/types/vendor/@akanjs/native/packages/cli/src/lib/compat.d.ts +6 -0
  240. package/types/vendor/@akanjs/native/packages/cli/src/lib/toolchains.d.ts +2 -2
  241. package/types/vendor/use-agentic/Compaction.d.ts +3 -1
  242. package/types/vendor/use-agentic/Reference.d.ts +7 -2
  243. package/types/vendor/use-agentic/ToolOutput.d.ts +6 -1
  244. package/types/vendor/use-agentic/ToolReturn.d.ts +18 -0
  245. package/types/vendor/use-agentic/Transcript.d.ts +7 -0
  246. package/types/vendor/use-agentic/index.d.ts +1 -0
  247. package/types/vendor/use-agentic/types.d.ts +6 -0
  248. package/types/webkit/CsrGuards.d.ts +25 -0
  249. package/types/webkit/CsrRouteTable.d.ts +6 -0
  250. package/types/webkit/CsrStack.d.ts +7 -0
  251. package/types/webkit/McpAppBoot.d.ts +32 -0
  252. package/types/webkit/McpAppBridge.d.ts +10 -1
  253. package/types/webkit/McpAppFetchBridge.d.ts +3 -1
  254. package/types/webkit/McpAppView.d.ts +4 -1
  255. package/types/webkit/PageNotFound.d.ts +5 -0
  256. package/types/webkit/RenderLayer.d.ts +1 -3
  257. package/types/webkit/index.d.ts +1 -0
  258. package/types/webkit/useDebounce.d.ts +1 -1
  259. package/ui/Agent/Chat.tsx +1 -0
  260. package/ui/Agent/Composer.tsx +2 -0
  261. package/ui/Agent/Menu.tsx +5 -1
  262. package/ui/Agent/agentSessionOf.ts +15 -8
  263. package/ui/Agent/mentionDraft.ts +2 -3
  264. package/ui/Agent/useReferenceMenu.ts +1 -0
  265. package/ui/Agent/useSlashMenu.ts +1 -0
  266. package/ui/CsrImage.tsx +3 -1
  267. package/ui/Dialog/LegacyModal.tsx +7 -5
  268. package/ui/Dialog/Modal.tsx +7 -4
  269. package/ui/Field/Collection.tsx +2 -1
  270. package/ui/Image.tsx +4 -4
  271. package/ui/Layout/BottomInset.tsx +2 -11
  272. package/ui/Layout/FrameSlotPortal.tsx +1 -3
  273. package/ui/Layout/Navbar.tsx +7 -22
  274. package/ui/Layout/TopInset.tsx +3 -4
  275. package/ui/Load/Units.tsx +34 -12
  276. package/ui/Load/sliceClaim.ts +164 -0
  277. package/ui/Model/Edit.tsx +22 -3
  278. package/ui/Model/EditModal.tsx +22 -6
  279. package/ui/Model/LoadStore.tsx +1 -1
  280. package/ui/Model/NewWrapper_Client.tsx +1 -1
  281. package/ui/Model/ViewEditModal.tsx +9 -3
  282. package/ui/Model/editSeed.ts +28 -0
  283. package/ui/System/App.tsx +43 -0
  284. package/ui/System/CSR.tsx +1 -10
  285. package/ui/System/Client.tsx +3 -0
  286. package/ui/System/index.tsx +3 -0
  287. package/ui/Tab/Provider.tsx +6 -8
  288. package/ui/styles.css +10 -0
  289. package/vendor/@akanjs/native/native/ios/Sources/AkanNativeBridge.swift +3 -2
  290. package/vendor/@akanjs/native/packages/cli/src/lib/compat.ts +6 -2
  291. package/vendor/@akanjs/native/packages/cli/src/lib/native-plugins.ts +1 -1
  292. package/vendor/@akanjs/native/packages/cli/src/lib/toolchains.ts +1 -1
  293. package/vendor/@akanjs/native/packages/cli/src/lib/updates.ts +3 -3
  294. package/vendor/@akanjs/native/plugins/sqlite/src/desktop.ts +10 -5
  295. package/vendor/@akanjs/native/plugins/updates/src/desktop.ts +45 -15
  296. package/vendor/use-agentic/CHANGELOG.md +31 -0
  297. package/vendor/use-agentic/Compaction.ts +38 -7
  298. package/vendor/use-agentic/Reference.ts +14 -10
  299. package/vendor/use-agentic/ToolOutput.ts +25 -3
  300. package/vendor/use-agentic/ToolReturn.ts +32 -0
  301. package/vendor/use-agentic/ToolRunner.ts +15 -13
  302. package/vendor/use-agentic/Transcript.ts +38 -2
  303. package/vendor/use-agentic/WIRE.md +20 -0
  304. package/vendor/use-agentic/index.ts +1 -0
  305. package/vendor/use-agentic/types.ts +6 -0
  306. package/webkit/CsrGuards.ts +112 -0
  307. package/webkit/CsrRouteTable.ts +71 -16
  308. package/webkit/CsrStack.ts +47 -1
  309. package/webkit/McpAppAgent.ts +14 -2
  310. package/webkit/McpAppBoot.tsx +129 -0
  311. package/webkit/McpAppBridge.ts +30 -6
  312. package/webkit/McpAppFetchBridge.ts +8 -2
  313. package/webkit/McpAppView.ts +39 -28
  314. package/webkit/PageNotFound.tsx +24 -0
  315. package/webkit/RenderLayer.tsx +106 -30
  316. package/webkit/bootCsr.tsx +4 -43
  317. package/webkit/index.ts +1 -0
  318. package/webkit/useCsrValues.ts +66 -6
  319. package/webkit/useDebounce.ts +23 -14
  320. package/webkit/useEscapeKey.tsx +1 -1
  321. package/webkit/useLocation.ts +21 -19
  322. package/types/webkit/EmbeddedLayout.d.ts +0 -10
  323. package/webkit/EmbeddedLayout.tsx +0 -82
package/client/router.ts CHANGED
@@ -12,6 +12,9 @@ export interface RouteOptions {
12
12
  * navigation.
13
13
  */
14
14
  shallow?: boolean;
15
+ /** Lets an absolute URL on another origin through; without it the router refuses one, so a `?redirect=` handed on
16
+ * unchecked cannot send a visitor off-site. */
17
+ external?: boolean;
15
18
  }
16
19
  export interface RouteManifest {
17
20
  routes: string[];
@@ -55,6 +58,8 @@ export type RedirectStatus = 303 | 307 | 308;
55
58
  export interface RedirectOptions {
56
59
  method?: RedirectMethod;
57
60
  status?: RedirectStatus;
61
+ /** As `RouteOptions.external`; a target it refuses redirects to the index path instead. */
62
+ external?: boolean;
58
63
  }
59
64
 
60
65
  export class AkanRedirectError extends Error {
@@ -85,6 +90,16 @@ function getServerRequestContext() {
85
90
  };
86
91
  }
87
92
 
93
+ const getServerPublicOrigin = () => {
94
+ const { getRequest, headers } = getServerRequestContext();
95
+ const h = headers();
96
+ const url = getRequest()?.url;
97
+ const host = h.get("x-forwarded-host")?.split(",")[0]?.trim() ?? h.get("host");
98
+ const proto = h.get("x-forwarded-proto")?.split(",")[0]?.trim();
99
+ if (!host) return url;
100
+ return `${proto ?? (url ? new URL(url).protocol.replace(":", "") : "https")}://${host}`;
101
+ };
102
+
88
103
  const getConfiguredBasePaths = () => new Set(parseBasePaths(process.env.AKAN_PUBLIC_BASE_PATHS));
89
104
 
90
105
  const shouldExposeBasePath = () => getEnv().operationMode === "local";
@@ -177,6 +192,7 @@ class Router {
177
192
  #listensToPopstate: boolean = false;
178
193
  #backsAwaitingPopstate = 0;
179
194
  #redirects = 0;
195
+ #navigations = 0;
180
196
  #instance: RouterInstance = {
181
197
  push: (href: string) => {
182
198
  const { href: fullHref } = this.#getPathInfo(href);
@@ -305,7 +321,7 @@ class Router {
305
321
  }
306
322
  #withCsrRuntimeSearchParams(href: string) {
307
323
  const currentSearch = new URLSearchParams(csrLocation.search);
308
- if (currentSearch.get("csr") !== "true") return href;
324
+ if (currentSearch.get("csr") !== "true" || Href.hasWebScheme(href)) return href;
309
325
 
310
326
  const [hrefWithoutHash, hash = ""] = href.split("#");
311
327
  const [pathname, search = ""] = hrefWithoutHash.split("?");
@@ -390,6 +406,8 @@ class Router {
390
406
  }
391
407
  push(href: string, routeOptions?: RouteOptions) {
392
408
  this.#checkInitialized();
409
+ if (this.#refusesOffsite("push", href, routeOptions)) return undefined as never;
410
+ this.#navigations += 1;
393
411
  this.#track(this.#instance.push(href, routeOptions));
394
412
  this.#rememberHistoryState("push");
395
413
  this.#postDevSyncNavigation("push", href);
@@ -397,6 +415,8 @@ class Router {
397
415
  }
398
416
  replace(href: string, routeOptions?: RouteOptions) {
399
417
  this.#checkInitialized();
418
+ if (this.#refusesOffsite("replace", href, routeOptions)) return undefined as never;
419
+ this.#navigations += 1;
400
420
  this.#track(this.#instance.replace(href, routeOptions));
401
421
  this.#rememberHistoryState("replace");
402
422
  this.#postDevSyncNavigation("replace", href);
@@ -407,6 +427,20 @@ class Router {
407
427
  navigation(): Promise<void> {
408
428
  return this.#navigation;
409
429
  }
430
+ #leavesOrigin(href: string, external?: boolean) {
431
+ if (external || !Href.hasWebScheme(href)) return false;
432
+ return Href.leavesOrigin(
433
+ href,
434
+ getEnv().side === "server" ? getServerPublicOrigin() : globalThis.window?.location?.href,
435
+ );
436
+ }
437
+ #refusesOffsite(method: "push" | "replace", href: string, routeOptions?: RouteOptions) {
438
+ if (!this.#leavesOrigin(href, routeOptions?.external)) return false;
439
+ const message = `router.${method}(${href}) leaves this origin and was refused; pass { external: true } to leave on purpose`;
440
+ Logger.warn(message);
441
+ this.#track(Promise.reject(new Error(message)));
442
+ return true;
443
+ }
410
444
  #track(result: void | Promise<void>) {
411
445
  this.#navigation = Promise.resolve(result);
412
446
 
@@ -433,6 +467,7 @@ class Router {
433
467
  back(routeOptions?: RouteOptions) {
434
468
  if (getEnv().side === "server") throw new Error("back is only available in client side");
435
469
  this.#checkInitialized();
470
+ this.#navigations += 1;
436
471
  this.#instance.back(routeOptions);
437
472
  return undefined as never;
438
473
  }
@@ -447,9 +482,21 @@ class Router {
447
482
  redirectCount(): number {
448
483
  return this.#redirects;
449
484
  }
450
- redirect(href: string, options: RedirectOptions = {}): never {
485
+ /** Client-side moves so far — push, replace, back, redirect, notFound: a route guard that saw this change sent the
486
+ * visitor elsewhere, so its page does not draw. */
487
+ navigationCount(): number {
488
+ return this.#navigations;
489
+ }
490
+ redirect(target: string, options: RedirectOptions = {}): never {
451
491
  const method = options.method ?? "replace";
452
492
  const status = options.status ?? 307;
493
+
494
+ const offsite = this.#leavesOrigin(target, options.external);
495
+ if (offsite)
496
+ Logger.warn(
497
+ `router.redirect(${target}) leaves this origin, so it redirects to ${this.#indexPath} instead; pass { external: true } to leave on purpose`,
498
+ );
499
+ const href = offsite ? this.#indexPath : target;
453
500
  if (getEnv().side === "server") {
454
501
  const { getRequest, headers: requestHeaders } = getServerRequestContext();
455
502
  const h = requestHeaders();
@@ -463,6 +510,7 @@ class Router {
463
510
  throw new AkanRedirectError(fullHref, method, status);
464
511
  } else {
465
512
  this.#redirects += 1;
513
+ this.#navigations += 1;
466
514
  this.#instance[method](href);
467
515
  }
468
516
  return undefined as never;
@@ -474,6 +522,7 @@ class Router {
474
522
  }
475
523
  this.#checkInitialized();
476
524
  this.#redirects += 1;
525
+ this.#navigations += 1;
477
526
  this.#instance.replace("/404");
478
527
  return undefined as never;
479
528
  }
@@ -18,6 +18,8 @@ interface TranslatorState {
18
18
  activeLocale?: string;
19
19
 
20
20
  activePath?: string;
21
+
22
+ renderPath?: string;
21
23
  }
22
24
 
23
25
  const TRANSLATOR_STATE_KEY = "__AKAN_TRANSLATOR_STATE__";
@@ -57,6 +59,20 @@ export class Translator {
57
59
  static getActivePath(): string | undefined {
58
60
  return getTranslatorState().activePath;
59
61
  }
62
+ static renderAt<T>(path: string | undefined, render: () => T): T {
63
+ if (!path) return render();
64
+ const state = getTranslatorState();
65
+ const outer = state.renderPath;
66
+ state.renderPath = path;
67
+ try {
68
+ return render();
69
+ } finally {
70
+ state.renderPath = outer;
71
+ }
72
+ }
73
+ static getRenderPath(): string | undefined {
74
+ return getTranslatorState().renderPath;
75
+ }
60
76
  static markHydrated() {
61
77
  delete getTranslatorState().activePath;
62
78
  }
@@ -7,6 +7,9 @@ export interface ThemeColorTag {
7
7
 
8
8
  /** Turns a root layout's `.viewport()` into the `viewport` and `theme-color` meta tags every document shell writes. */
9
9
  export class ViewportMeta {
10
+ static readonly #offMedia = "not all";
11
+ static readonly #ownAttr = "data-akan-theme-color";
12
+
10
13
  static content(viewport: RouteViewport | undefined, { native = false }: { native?: boolean } = {}): string {
11
14
  const parts = ["width=device-width", "initial-scale=1"];
12
15
  if (viewport?.fitCover ?? native) parts.push("viewport-fit=cover");
@@ -39,18 +42,30 @@ export class ViewportMeta {
39
42
  const tags = ViewportMeta.themeColors(viewport, theme);
40
43
  if (!tags.length) return;
41
44
  const existing = [...document.head.querySelectorAll<HTMLMetaElement>('meta[name="theme-color"]')];
42
-
43
- for (const meta of existing.slice(tags.length)) meta.setAttribute("media", "not all");
44
- tags.forEach((tag, idx) => {
45
- const meta = existing[idx] ?? ViewportMeta.#ensureMeta("theme-color", true);
45
+ const live = existing.filter((meta) => meta.getAttribute("media") !== ViewportMeta.#offMedia);
46
+ const isCurrent =
47
+ live.length === tags.length &&
48
+ tags.every(
49
+ (tag, idx) => live[idx]?.content === tag.content && live[idx]?.getAttribute("media") === (tag.media ?? null),
50
+ );
51
+ if (isCurrent) return;
52
+
53
+ for (const meta of existing) {
54
+ if (meta.hasAttribute(ViewportMeta.#ownAttr)) meta.remove();
55
+ else meta.setAttribute("media", ViewportMeta.#offMedia);
56
+ }
57
+ for (const tag of tags) {
58
+ const meta = document.createElement("meta");
59
+ meta.name = "theme-color";
46
60
  meta.content = tag.content;
47
61
  if (tag.media) meta.setAttribute("media", tag.media);
48
- else meta.removeAttribute("media");
49
- });
62
+ meta.setAttribute(ViewportMeta.#ownAttr, "");
63
+ document.head.appendChild(meta);
64
+ }
50
65
  }
51
66
 
52
- static #ensureMeta(name: string, fresh = false): HTMLMetaElement {
53
- const found = fresh ? null : document.head.querySelector<HTMLMetaElement>(`meta[name="${name}"]`);
67
+ static #ensureMeta(name: string): HTMLMetaElement {
68
+ const found = document.head.querySelector<HTMLMetaElement>(`meta[name="${name}"]`);
54
69
  if (found) return found;
55
70
  const meta = document.createElement("meta");
56
71
  meta.name = name;
package/common/Logger.ts CHANGED
@@ -89,7 +89,9 @@ const consoleMethodMap = {
89
89
  const ansiPattern = new RegExp(`${String.fromCharCode(27)}\\[[0-?]*[ -/]*[@-~]`, "g");
90
90
 
91
91
  const secretKey =
92
- /password|passwd|passphrase|^pass$|pwd|token|jwt|authorization|cookie|secret|api[-_]?key|private[-_]?key|access[-_]?key|auth[-_]?key|hash[-_]?key|(?:signing|encryption|master|session)[-_]?key|webhook|cred|dsn$|connection[-_]?string|iap[-_]?verify|service[-_]?account/i;
92
+ /password|passwd|passphrase|^pass$|pwd|token|jwt|authorization|cookie|secret|api[-_]?key|private[-_]?key|access[-_]?key|auth[-_]?key|hash[-_]?key|(?:signing|encryption|master|session)[-_]?key|webhook|credential|dsn$|connection[-_]?string|iap[-_]?verify|service[-_]?account/i;
93
+
94
+ const credWord = /[cC]reds?(?![a-z])|CREDS?(?![A-Z])/;
93
95
 
94
96
  const envValue = (key: string): string | undefined => (typeof process === "undefined" ? undefined : process.env?.[key]);
95
97
 
@@ -174,19 +176,19 @@ export class Logger {
174
176
  static inlineData(value: unknown, max = 500): string {
175
177
  let text: string;
176
178
  try {
177
- text = JSON.stringify(value, (key, val) => (key && secretKey.test(key) ? "[redacted]" : val)) ?? "";
179
+ text = JSON.stringify(value, (key, val) => (key && Logger.isSecretKey(key) ? "[redacted]" : val)) ?? "";
178
180
  } catch {
179
181
  text = "[unserializable]";
180
182
  }
181
183
  return text.length > max ? `${text.slice(0, max)}…` : text;
182
184
  }
183
185
  static isSecretKey(name: string) {
184
- return secretKey.test(name);
186
+ return secretKey.test(name) || credWord.test(name);
185
187
  }
186
188
  static redactAttrs(attrs: LogAttrs): LogAttrs {
187
189
  let redacted: LogAttrs | null = null;
188
190
  for (const key of Object.keys(attrs)) {
189
- if (!secretKey.test(key)) continue;
191
+ if (!Logger.isSecretKey(key)) continue;
190
192
  redacted ??= { ...attrs };
191
193
  redacted[key] = "[redacted]";
192
194
  }
@@ -0,0 +1,13 @@
1
+
2
+
3
+ /** The pre-scoping key. Read as a fallback, never written; drop it once deployments have rotated past it. */
4
+ export const legacyAuthTokenKey = "jwt";
5
+
6
+ /** Matches both spellings so a signout can sweep a jar written before and after the key was scoped. */
7
+ export const isAuthTokenKey = (key: string): boolean =>
8
+ key === legacyAuthTokenKey || key.startsWith(`${legacyAuthTokenKey}:`);
9
+
10
+ const authCookiePattern = new RegExp(`(?:^|;\\s*)${legacyAuthTokenKey}(?::[^=\\s;]+)?=`);
11
+
12
+ export const cookieHeaderHasAuthToken = (cookieHeader: string | null | undefined): boolean =>
13
+ !!cookieHeader && authCookiePattern.test(cookieHeader);
@@ -1,20 +1,9 @@
1
1
  import { getEnv } from "akanjs/base";
2
+ import { legacyAuthTokenKey } from "./authCookie";
2
3
  import { decodeJwtPayload } from "./jwtDecode";
3
4
 
4
- /** The pre-scoping key. Read as a fallback, never written; drop it once deployments have rotated past it. */
5
- export const legacyAuthTokenKey = "jwt";
6
-
7
5
  export const authTokenKey = (): string => `${legacyAuthTokenKey}:${getEnv().appName}`;
8
6
 
9
- /** Matches both spellings so a signout can sweep a jar written before and after the key was scoped. */
10
- export const isAuthTokenKey = (key: string): boolean =>
11
- key === legacyAuthTokenKey || key.startsWith(`${legacyAuthTokenKey}:`);
12
-
13
- const authCookiePattern = new RegExp(`(?:^|;\\s*)${legacyAuthTokenKey}(?::[^=\\s;]+)?=`);
14
-
15
- export const cookieHeaderHasAuthToken = (cookieHeader: string | null | undefined): boolean =>
16
- !!cookieHeader && authCookiePattern.test(cookieHeader);
17
-
18
7
  export const isOwnAuthToken = (jwt: string): boolean => {
19
8
  const { appName, environment } = getEnv();
20
9
  try {
@@ -18,6 +18,8 @@ export interface CodeAgentSessionInfo {
18
18
  contextTokens: number | undefined;
19
19
  /** Absent when the model does no reasoning at all, which is not reasoning turned `off`. */
20
20
  effort: CodeAgentEffort | undefined;
21
+ /** Percent of the window that starts a compaction; absent leaves the engine's own, later threshold. */
22
+ autoCompactAt: number | undefined;
21
23
  /** Absent until the session has been asked something. */
22
24
  name: string | undefined;
23
25
  /** `await` keeps a question inside its turn; `suspend` ends the turn (`awaiting`) and the answer opens a new one. */
@@ -186,6 +188,8 @@ export type CodeAgentCommand =
186
188
  | { type: "abort" }
187
189
  | { type: "compact"; instructions?: string }
188
190
  | { type: "set_model"; provider: string; modelId: string }
191
+ /** `percent` in steps of 10; absent, or 100, restores the default. */
192
+ | { type: "set_auto_compact"; percent?: number }
189
193
  | { type: "fork"; entryId: string }
190
194
  | { type: "new_session" }
191
195
  /** Current state, plus every frame after `sinceSeq` when one is given. */
@@ -231,8 +235,11 @@ export const codeAgentEventLabel = (event: CodeAgentEventBody): string => {
231
235
  `session ${event.info.sessionId}`,
232
236
  event.info.model?.name ?? "no model",
233
237
  event.info.contextTokens ? `${Math.round(event.info.contextTokens / 1000)}k ctx` : "unknown ctx",
238
+ event.info.autoCompactAt ? `compacts at ${event.info.autoCompactAt}%` : "",
234
239
  event.info.profile,
235
- ].join(" · ");
240
+ ]
241
+ .filter((part) => !!part)
242
+ .join(" · ");
236
243
  case "turn_start":
237
244
  return "turn start";
238
245
  case "turn_end":
package/common/index.ts CHANGED
@@ -1,12 +1,6 @@
1
1
  export { applyMixins, getAllPropertyDescriptors } from "./applyMixins";
2
- export {
3
- authTokenKey,
4
- cookieHeaderHasAuthToken,
5
- isAuthTokenKey,
6
- isOwnAuthToken,
7
- legacyAuthTokenKey,
8
- readAuthToken,
9
- } from "./authToken";
2
+ export { cookieHeaderHasAuthToken, isAuthTokenKey, legacyAuthTokenKey } from "./authCookie";
3
+ export { authTokenKey, isOwnAuthToken, readAuthToken } from "./authToken";
10
4
  export { Backoff, type BackoffPolicy } from "./backoff";
11
5
  export { bearerTokenOf } from "./bearerTokenOf";
12
6
  export { CodeAgentClient, type CodeAgentTransport } from "./CodeAgentClient";
@@ -16,6 +16,7 @@ export const PAGE_ROUTE_EXPORTS: ReadonlySet<string> = new Set([
16
16
  "head",
17
17
  "generateHead",
18
18
  "Loading",
19
+ "guard",
19
20
  ]);
20
21
  export const LAYOUT_ROUTE_EXPORTS: ReadonlySet<string> = new Set([...PAGE_ROUTE_EXPORTS, "NotFound", "Error"]);
21
22
  export const ROOT_LAYOUT_ROUTE_EXPORTS: ReadonlySet<string> = new Set([
@@ -27,6 +28,7 @@ export const ROOT_LAYOUT_ROUTE_EXPORTS: ReadonlySet<string> = new Set([
27
28
  "wsConnect",
28
29
  "layoutStyle",
29
30
  "viewport",
31
+ "McpAppRoot",
30
32
  ]);
31
33
  /** Root-layout exports that are plain config rather than components, so a PascalCase check cannot allow them. */
32
34
  export const RESERVED_ROUTE_CONFIG_EXPORTS: ReadonlySet<string> = new Set(
@@ -45,12 +45,12 @@ export class InputParser {
45
45
  ]);
46
46
 
47
47
  static parse(argRef: Cls, arrDepth: number, value: unknown, option: ParseOption) {
48
- if (PrimitiveRegistry.has(argRef)) return deserialize(argRef, arrDepth, value, option);
49
48
  const { key, nullable = false } = option;
50
49
  if (value === null || value === undefined) {
51
50
  if (nullable) return null;
52
51
  throw new InvalidInputError(key, null);
53
52
  }
53
+ if (PrimitiveRegistry.has(argRef)) return deserialize(argRef, arrDepth, value, option);
54
54
  return InputParser.#walk(value, arrDepth, key, (item, path) => InputParser.#value(argRef, item, path));
55
55
  }
56
56
 
@@ -52,6 +52,7 @@ export const baseDictionary = serviceDictionary(["en", "ko"])
52
52
  invalidArgument: ["{name} has an invalid value.", "{name} 값이 올바르지 않습니다."],
53
53
  requiredArgument: ["{name} is required.", "{name}은(는) 필수 값입니다."],
54
54
  invalidField: ["{field} has an invalid value.", "{field} 값이 올바르지 않습니다."],
55
+ documentNotFound: ["The requested item does not exist.", "요청한 항목을 찾을 수 없습니다."],
55
56
  relationNotFound: [
56
57
  "The {model} that {field} refers to no longer exists.",
57
58
  "{field}이(가) 가리키는 {model}을(를) 찾을 수 없습니다.",
@@ -64,6 +65,14 @@ export const baseDictionary = serviceDictionary(["en", "ko"])
64
65
  "{endpoint} is closed: the slice's guards name none that allows it.",
65
66
  "{endpoint}이(가) 닫혀 있습니다. 슬라이스 guards에 이 동작을 허용하는 guard를 지정해야 합니다.",
66
67
  ],
68
+ mutationInApp: [
69
+ "The {app} app called {endpoint} while it loads, and an app may load with queries only.",
70
+ "{app} 앱이 불러오는 중에 {endpoint}을(를) 호출했습니다. 앱은 쿼리로만 불러올 수 있습니다.",
71
+ ],
72
+ readOnlyDeployment: [
73
+ "This server is read-only, so {endpoint} cannot run here.",
74
+ "읽기 전용 서버라 {endpoint}을(를) 실행할 수 없습니다.",
75
+ ],
67
76
  })
68
77
  .translate({
69
78
  somethingWrong: ["Something's wrong!", "문제가 생겼어요!"],
@@ -91,6 +100,8 @@ export const baseDictionary = serviceDictionary(["en", "ko"])
91
100
  cancel: ["Cancel", "취소"],
92
101
  retry: ["Try again", "다시 시도"],
93
102
  pageLoadFailed: ["This page could not be loaded.", "이 화면을 불러오지 못했습니다."],
103
+ pageNotFound: ["This page does not exist.", "없는 화면입니다."],
104
+ goBack: ["Go back", "돌아가기"],
94
105
  unauthorized: ["Unauthorized", "권한 없음"],
95
106
  agent: ["Agent", "에이전트"],
96
107
  agentIntro: ["Ask about this page or tell the agent what to do.", "이 화면에 대해 묻거나 할 일을 지시해 보세요."],
@@ -96,6 +96,8 @@ type QueryMethodOfKey<
96
96
  [K in `remove${CapitalizedK}`]: (...args: _Args) => Promise<UpdateResult>;
97
97
  } & {
98
98
  [K in `removeOne${CapitalizedK}`]: (...args: _Args) => Promise<UpdateResult>;
99
+ } & {
100
+ [K in `purge${CapitalizedK}`]: (...args: _Args) => Promise<number>;
99
101
  } & {
100
102
  [K in `update${CapitalizedK}`]: (...args: _Args) => UpdateChain<Doc>;
101
103
  } & {
@@ -154,6 +156,7 @@ export type DatabaseInstanceWithQuerySort<
154
156
  __remove: (id: string) => Promise<Doc>;
155
157
  __removeMany: (query: _QueryOfDoc) => Promise<UpdateResult>;
156
158
  __removeOne: (query: _QueryOfDoc) => Promise<UpdateResult>;
159
+ __purgeMany: (query: _QueryOfDoc) => Promise<number>;
157
160
  __updateMany: (query: _QueryOfDoc, update: DocumentUpdateInput<Doc>) => Promise<UpdateResult>;
158
161
  __updateOne: (query: _QueryOfDoc, update: DocumentUpdateInput<Doc>) => Promise<UpdateResult>;
159
162
  __list(query: _QueryOfDoc, queryOption?: _ListQueryOption): Promise<Doc[]>;
@@ -144,6 +144,27 @@ export type DocumentQuery<T = any> =
144
144
  [K in DocumentPath<T>]?: DocumentQueryValue;
145
145
  };
146
146
 
147
+ export const isDocumentQueryNode = (value: unknown): value is DocumentQueryNode => {
148
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
149
+ const node = value as Record<string, unknown>;
150
+ const fits = (...keys: string[]) => Object.keys(node).every((key) => key === "kind" || keys.includes(key));
151
+ switch (node.kind) {
152
+ case "all":
153
+ case "any":
154
+ return Array.isArray(node.queries) && fits("queries");
155
+ case "not":
156
+ return !!node.query && typeof node.query === "object" && fits("query");
157
+ case "op":
158
+ return typeof node.op === "string" && queryOperatorKeys.has(node.op) && fits("op", "value");
159
+ case "raw":
160
+ return typeof node.sql === "string" && Array.isArray(node.params) && fits("sql", "params");
161
+ case "search":
162
+ return typeof node.text === "string" && fits("text", "columns", "prefix", "weights");
163
+ default:
164
+ return false;
165
+ }
166
+ };
167
+
147
168
  export interface SqlFragment {
148
169
  sql: string;
149
170
  params: unknown[];
package/document/into.ts CHANGED
@@ -83,6 +83,8 @@ export type Mdl<
83
83
  ): Promise<UpdateResult>;
84
84
  removeOne(query: _RawQuery): Promise<UpdateResult>;
85
85
  removeMany(query: _RawQuery): Promise<UpdateResult>;
86
+ /** Deletes every row the query matches, removed ones too, and answers how many: no hook, cascade or undo. */
87
+ purgeMany(query: _RawQuery): Promise<number>;
86
88
  updateById(id: string, update: DocumentUpdateInput<_RawDoc>, options?: DocumentUpdateOptions): Promise<UpdateResult>;
87
89
  removeById(id: string): Promise<UpdateResult>;
88
90
  /**
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  type DocumentQuery,
3
- type DocumentQueryNode,
4
3
  type DocumentQueryOperator,
4
+ isDocumentQueryNode,
5
5
  queryOperatorKeys,
6
6
  } from "./documentQuery";
7
7
 
@@ -14,7 +14,7 @@ type RemovedAtTest = "isNull" | "isNotNull" | "value";
14
14
  export class LiveRowScope {
15
15
  static conflictOf(query: DocumentQuery | undefined, negated = false): string | null {
16
16
  if (!query || typeof query !== "object") return null;
17
- if (LiveRowScope.#isNode(query)) {
17
+ if (isDocumentQueryNode(query)) {
18
18
  if (query.kind === "all" || query.kind === "any")
19
19
  return query.queries.reduce<string | null>(
20
20
  (found, sub) => found ?? LiveRowScope.conflictOf(sub, negated),
@@ -30,7 +30,7 @@ export class LiveRowScope {
30
30
  }
31
31
 
32
32
  static #fieldConflict(path: string, value: unknown, negated: boolean): string | null {
33
- if (LiveRowScope.#isNode(value) && value.kind !== "op") return LiveRowScope.conflictOf(value, negated);
33
+ if (isDocumentQueryNode(value) && value.kind !== "op") return LiveRowScope.conflictOf(value, negated);
34
34
  if (path !== "removedAt") return null;
35
35
  for (const [test, spelled] of LiveRowScope.#testsOf(value)) {
36
36
  const named = negated ? `not(removedAt ${spelled})` : `removedAt ${spelled}`;
@@ -44,7 +44,7 @@ export class LiveRowScope {
44
44
  static #testsOf(value: unknown): [RemovedAtTest, string][] {
45
45
  if (value === undefined) return [];
46
46
  if (value === null) return [["isNull", "null"]];
47
- if (LiveRowScope.#isNode(value) && value.kind === "op") {
47
+ if (isDocumentQueryNode(value) && value.kind === "op") {
48
48
  const test = LiveRowScope.#testOf(value.op, value.value);
49
49
  return test ? [test] : [];
50
50
  }
@@ -72,8 +72,4 @@ export class LiveRowScope {
72
72
  if ((op === "oneOf" || op === "notOneOf") && !(operand as unknown[] | undefined)?.length) return null;
73
73
  return ["value", op];
74
74
  }
75
-
76
- static #isNode(value: unknown): value is DocumentQueryNode {
77
- return !!value && typeof value === "object" && "kind" in value;
78
- }
79
75
  }
@@ -1,7 +1,12 @@
1
1
  /**
2
2
  * A `pick` or `get` that matched nothing, so a caller can tell a missing document from a failure. Callers match on
3
- * the message; `statusCode` does not reach HTTP (`isExceptionLike` also wants a `toJSON`), where it stays a 500.
3
+ * the message, which names the table and the id or query; the wire carries only the dictionary key, as a 404.
4
4
  */
5
5
  export class NoDocumentError extends Error {
6
6
  readonly statusCode = 404;
7
+ readonly error = "base.error.documentNotFound";
8
+
9
+ toJSON() {
10
+ return { error: this.error, statusCode: this.statusCode };
11
+ }
7
12
  }
@@ -4,6 +4,7 @@ import {
4
4
  type DocumentQueryNode,
5
5
  type DocumentQueryOperator,
6
6
  encodeDocumentValue,
7
+ isDocumentQueryNode,
7
8
  queryOperatorKeys,
8
9
  sanitizeJson,
9
10
  } from "./documentQuery";
@@ -49,7 +50,7 @@ export class DocumentQueryEvaluator {
49
50
  */
50
51
  static unevaluableReason(query: DocumentQuery | undefined): string | null {
51
52
  if (!query || typeof query !== "object") return null;
52
- if (DocumentQueryEvaluator.#isNode(query)) {
53
+ if (isDocumentQueryNode(query)) {
53
54
  if (query.kind === "raw") return "q.raw() carries SQL that only the database can run";
54
55
  if (query.kind === "search") return "q.search() compiles to a full-text JOIN with no in-memory equivalent";
55
56
  if (query.kind === "all" || query.kind === "any")
@@ -70,7 +71,7 @@ export class DocumentQueryEvaluator {
70
71
  if (!value || typeof value !== "object") return null;
71
72
  if (baseDocumentColumns.has(path)) return null;
72
73
  const keyAbsence = `${path}: exists/missing asks whether the key is in the stored JSON, which a document in hand cannot answer — use q.empty()`;
73
- if (DocumentQueryEvaluator.#isNode(value)) {
74
+ if (isDocumentQueryNode(value)) {
74
75
  if (value.kind === "op") return value.op === "exists" || value.op === "missing" ? keyAbsence : null;
75
76
  return DocumentQueryEvaluator.unevaluableReason(value as DocumentQuery);
76
77
  }
@@ -94,7 +95,7 @@ export class DocumentQueryEvaluator {
94
95
 
95
96
  evaluate(query: DocumentQuery | undefined, row: DocumentRowView): boolean {
96
97
  if (!query || typeof query !== "object") return true;
97
- if (DocumentQueryEvaluator.#isNode(query)) return this.#node(query, row);
98
+ if (isDocumentQueryNode(query)) return this.#node(query, row);
98
99
  const entries = Object.entries(query);
99
100
  if (!entries.length) return true;
100
101
  return entries.every(([path, value]) => this.#field(path, value, row));
@@ -118,7 +119,7 @@ export class DocumentQueryEvaluator {
118
119
  }
119
120
 
120
121
  #field(path: string, value: unknown, row: DocumentRowView): boolean {
121
- if (DocumentQueryEvaluator.#isNode(value)) {
122
+ if (isDocumentQueryNode(value)) {
122
123
  if (value.kind !== "op") return this.evaluate({ [path]: value } as DocumentQuery, row);
123
124
  return this.#operator(path, value.op, value.value, row);
124
125
  }
@@ -290,8 +291,4 @@ export class DocumentQueryEvaluator {
290
291
  static #foldAscii(text: string) {
291
292
  return text.replace(/[A-Z]/g, (char) => char.toLowerCase());
292
293
  }
293
-
294
- static #isNode(value: unknown): value is DocumentQueryNode {
295
- return !!value && typeof value === "object" && "kind" in value;
296
- }
297
294
  }
@@ -0,0 +1,54 @@
1
+ interface AppScopeStorage {
2
+ run<T>(app: string, load: () => T): T;
3
+ getStore(): string | undefined;
4
+ }
5
+
6
+ declare global {
7
+ var __AKAN_APP_SCOPE__: AppScopeStorage | undefined;
8
+ }
9
+
10
+ /**
11
+ * Marks the run of a page's `.app()` load, which may only query: an MCP view replays those queries from the tool
12
+ * result's snapshot, so a write in the load would run once for the tool call and again when the view draws.
13
+ */
14
+ export class AppScope {
15
+ static readonly #storage: AppScopeStorage = AppScope.#shared();
16
+
17
+ static run<T>(app: string, load: () => T): T {
18
+ return AppScope.#storage.run(app, load);
19
+ }
20
+
21
+ /** The app whose load is running here, if any. */
22
+ static current(): string | undefined {
23
+ return AppScope.#storage.getStore();
24
+ }
25
+
26
+ static #shared(): AppScopeStorage {
27
+ globalThis.__AKAN_APP_SCOPE__ ??= AppScope.#createStorage();
28
+ return globalThis.__AKAN_APP_SCOPE__;
29
+ }
30
+
31
+ static #createStorage(): AppScopeStorage {
32
+ if (typeof window === "undefined") {
33
+ try {
34
+ const { AsyncLocalStorage } = require("node:async_hooks") as typeof import("node:async_hooks");
35
+ const als = new AsyncLocalStorage<string>();
36
+ return { run: (app, load) => als.run(app, load), getStore: () => als.getStore() };
37
+ } catch {}
38
+ }
39
+
40
+ let current: string | undefined;
41
+ return {
42
+ run(app, load) {
43
+ const previous = current;
44
+ current = app;
45
+ try {
46
+ return load();
47
+ } finally {
48
+ current = previous;
49
+ }
50
+ },
51
+ getStore: () => current,
52
+ };
53
+ }
54
+ }