@kayjs/kay 1.105.0 → 1.106.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 (310) hide show
  1. package/dist/eslint.js +435 -120
  2. package/editors/zed/extension.toml +2 -2
  3. package/llms/action-protection.md +1 -1
  4. package/llms/actions-from-islands.md +2 -2
  5. package/llms/actions.md +22 -19
  6. package/llms/analytics.md +1 -1
  7. package/llms/api-from-islands.md +1 -1
  8. package/llms/api-routes.md +6 -6
  9. package/llms/check-and-tools.md +1 -1
  10. package/llms/code-lints.md +2 -2
  11. package/llms/compiler-api.md +1 -1
  12. package/llms/component-libraries.md +1 -0
  13. package/llms/content-cms.md +1 -1
  14. package/llms/content-markdown-to-caching.md +1 -1
  15. package/llms/content-preview.md +2 -2
  16. package/llms/content.md +21 -21
  17. package/llms/deprecated-lints-1-105-libraries.md +2 -0
  18. package/llms/deprecated-lints-1-105.md +3 -3
  19. package/llms/deprecated-lints.md +3 -2
  20. package/llms/dev-tool.md +2 -2
  21. package/llms/environment.md +22 -22
  22. package/llms/files.md +5 -5
  23. package/llms/islands-state-to-ids.md +2 -1
  24. package/llms/local-collections.md +2 -2
  25. package/llms/mcp.md +2 -1
  26. package/llms/navigation-from-code.md +1 -1
  27. package/llms/notifications.md +4 -2
  28. package/llms/project.md +1 -1
  29. package/llms/rate-limits.md +1 -1
  30. package/llms/recipes.md +16 -16
  31. package/llms/rooms.md +4 -4
  32. package/llms/routing-endpoints-and-base.md +1 -1
  33. package/llms/routing.md +5 -5
  34. package/llms/schemas.md +10 -5
  35. package/llms/server.md +7 -7
  36. package/llms/site.md +9 -9
  37. package/llms/sitemap-search-fonts.md +2 -0
  38. package/llms/styles-and-assets.md +2 -1
  39. package/llms/templates-elements-slots-snippets.md +2 -2
  40. package/llms/testing-browser.md +20 -0
  41. package/llms/testing.md +1 -1
  42. package/llms/upgrading-1-105-config.md +2 -2
  43. package/llms/upgrading.md +18 -3
  44. package/llms/whats-new-archive.md +35 -66
  45. package/llms/whats-new.md +34 -28
  46. package/llms.txt +1 -1
  47. package/package.json +15 -11
  48. package/src/add.ts +1 -1
  49. package/src/build/class-table.ts +2 -2
  50. package/src/build/client.ts +7 -6
  51. package/src/build/plugin.ts +14 -11
  52. package/src/build/styles.ts +3 -3
  53. package/src/build/transform.ts +3 -1
  54. package/src/build/ui-layers.ts +30 -0
  55. package/src/build/ui.ts +108 -11
  56. package/src/build/variants.ts +119 -43
  57. package/src/build/worker-bundle.ts +6 -0
  58. package/src/check/boot.ts +22 -1
  59. package/src/check/call-result.ts +242 -0
  60. package/src/check/config-objects.ts +17 -2
  61. package/src/check/diagnose.ts +22 -0
  62. package/src/check/handler-events.ts +149 -0
  63. package/src/check/index.ts +6 -2
  64. package/src/check/link-flag-tests.ts +130 -0
  65. package/src/check/project.ts +4 -3
  66. package/src/check/refusal-calls.ts +2 -2
  67. package/src/check/regroup.ts +5 -3
  68. package/src/check/renamed-packages.ts +58 -14
  69. package/src/check/schema-builders.ts +256 -0
  70. package/src/check/secret-keys.ts +15 -2
  71. package/src/check/shadow-types.ts +2 -0
  72. package/src/check/template-hints.ts +1 -1
  73. package/src/check/tool-labels.ts +11 -9
  74. package/src/check/ui-types.ts +4 -3
  75. package/src/check/ui.ts +14 -11
  76. package/src/commands/env-declare.ts +18 -6
  77. package/src/commands/routes.ts +1 -1
  78. package/src/compiler/a11y.ts +8 -1
  79. package/src/compiler/ast.ts +1 -1
  80. package/src/compiler/bound-props.ts +1 -1
  81. package/src/compiler/codegen.ts +6 -6
  82. package/src/compiler/deprecated-lints-1-106.ts +14 -0
  83. package/src/compiler/deprecated-lints.ts +10 -5
  84. package/src/compiler/deprecated-typed-lints.ts +23 -0
  85. package/src/compiler/dom-here.ts +72 -0
  86. package/src/compiler/dom.ts +23 -23
  87. package/src/compiler/fence-checks.ts +12 -11
  88. package/src/compiler/field-described.ts +2 -2
  89. package/src/compiler/helper-imports.ts +1 -1
  90. package/src/compiler/html-fields.ts +92 -0
  91. package/src/compiler/html-initial.ts +5 -3
  92. package/src/compiler/html.ts +14 -31
  93. package/src/compiler/index.ts +3 -1
  94. package/src/compiler/items.ts +5 -5
  95. package/src/compiler/link-flags.ts +6 -5
  96. package/src/compiler/lints.ts +12 -12
  97. package/src/compiler/rest-omits.ts +15 -0
  98. package/src/config-loader.ts +10 -2
  99. package/src/config-resolve.ts +3 -1
  100. package/src/config-shape.ts +2 -2
  101. package/src/config.ts +20 -4
  102. package/src/content/markdown.ts +2 -3
  103. package/src/generate-resource.ts +9 -9
  104. package/src/generate.ts +1 -1
  105. package/src/mcp/guards.ts +1 -1
  106. package/src/mcp/tools.ts +1 -1
  107. package/src/migrate/content.ts +61 -55
  108. package/src/runtime/action-shared.ts +2 -2
  109. package/src/runtime/action.ts +6 -2
  110. package/src/runtime/form-types.ts +99 -0
  111. package/src/runtime/form.ts +22 -7
  112. package/src/runtime/html.ts +36 -5
  113. package/src/runtime/markdown-autolink.ts +69 -0
  114. package/src/runtime/markdown-render.client.ts +39 -3
  115. package/src/runtime/markdown.client.ts +6 -3
  116. package/src/runtime/markdown.server.ts +6 -3
  117. package/src/runtime/markdown.ts +125 -1
  118. package/src/runtime/navigate-api.ts +10 -5
  119. package/src/runtime/persist.ts +7 -7
  120. package/src/runtime/query-param.ts +1 -1
  121. package/src/runtime/reactive.ts +14 -0
  122. package/src/runtime/sanitize.ts +3 -1
  123. package/src/runtime/schema-record.ts +31 -0
  124. package/src/runtime/schema.client.ts +1 -4
  125. package/src/runtime/schema.ts +321 -26
  126. package/src/runtime/swap-focus.ts +59 -11
  127. package/src/server/action-module.ts +16 -0
  128. package/src/server/actions.ts +6 -14
  129. package/src/server/api-modules.ts +1 -1
  130. package/src/server/api.ts +13 -1
  131. package/src/server/app-stages.ts +23 -18
  132. package/src/server/dev-ui.ts +2 -2
  133. package/src/server/env-state.ts +1 -1
  134. package/src/server/env.ts +11 -3
  135. package/src/server/favicon.ts +47 -1
  136. package/src/server/image-metadata-bmff.ts +1 -1
  137. package/src/server/kept-pages.ts +3 -3
  138. package/src/server/library.ts +2 -0
  139. package/src/server/mcp.ts +13 -12
  140. package/src/server/notifications.ts +4 -2
  141. package/src/server/offline.ts +24 -7
  142. package/src/server/push-settings.ts +16 -2
  143. package/src/server/push.ts +12 -4
  144. package/src/server/query.ts +13 -6
  145. package/src/server/render.ts +1 -1
  146. package/src/server/scope.ts +20 -13
  147. package/src/server/signals.ts +4 -4
  148. package/src/template-ws.ts +1 -1
  149. package/src/test/a11y-dom.ts +70 -0
  150. package/src/test/html-snapshot.ts +103 -0
  151. package/src/test/index.ts +2 -1
  152. package/src/test/mount.ts +8 -1
  153. package/src/test/page-checks.ts +12 -0
  154. package/src/test/screenshot-match.ts +2 -2
  155. package/src/test/shared-modules.ts +27 -5
  156. package/src/test/site-types.ts +5 -1
  157. package/types/build/class-table.d.ts +1 -1
  158. package/types/build/class-table.d.ts.map +1 -1
  159. package/types/build/client.d.ts.map +1 -1
  160. package/types/build/plugin.d.ts.map +1 -1
  161. package/types/build/transform.d.ts +1 -0
  162. package/types/build/transform.d.ts.map +1 -1
  163. package/types/build/ui-layers.d.ts +5 -0
  164. package/types/build/ui-layers.d.ts.map +1 -0
  165. package/types/build/ui.d.ts +7 -0
  166. package/types/build/ui.d.ts.map +1 -1
  167. package/types/build/variants.d.ts +1 -1
  168. package/types/build/variants.d.ts.map +1 -1
  169. package/types/build/worker-bundle.d.ts +1 -0
  170. package/types/build/worker-bundle.d.ts.map +1 -1
  171. package/types/check/boot.d.ts.map +1 -1
  172. package/types/check/call-result.d.ts +7 -0
  173. package/types/check/call-result.d.ts.map +1 -0
  174. package/types/check/config-objects.d.ts.map +1 -1
  175. package/types/check/diagnose.d.ts.map +1 -1
  176. package/types/check/handler-events.d.ts +9 -0
  177. package/types/check/handler-events.d.ts.map +1 -0
  178. package/types/check/index.d.ts +1 -0
  179. package/types/check/index.d.ts.map +1 -1
  180. package/types/check/link-flag-tests.d.ts +4 -0
  181. package/types/check/link-flag-tests.d.ts.map +1 -0
  182. package/types/check/project.d.ts.map +1 -1
  183. package/types/check/regroup.d.ts +1 -1
  184. package/types/check/regroup.d.ts.map +1 -1
  185. package/types/check/renamed-packages.d.ts +1 -0
  186. package/types/check/renamed-packages.d.ts.map +1 -1
  187. package/types/check/schema-builders.d.ts +3 -0
  188. package/types/check/schema-builders.d.ts.map +1 -0
  189. package/types/check/secret-keys.d.ts.map +1 -1
  190. package/types/check/shadow-types.d.ts.map +1 -1
  191. package/types/check/template-hints.d.ts +1 -0
  192. package/types/check/template-hints.d.ts.map +1 -1
  193. package/types/check/tool-labels.d.ts.map +1 -1
  194. package/types/check/ui-types.d.ts.map +1 -1
  195. package/types/check/ui.d.ts.map +1 -1
  196. package/types/commands/env-declare.d.ts.map +1 -1
  197. package/types/compiler/a11y.d.ts.map +1 -1
  198. package/types/compiler/bound-props.d.ts +1 -0
  199. package/types/compiler/bound-props.d.ts.map +1 -1
  200. package/types/compiler/codegen.d.ts +1 -0
  201. package/types/compiler/codegen.d.ts.map +1 -1
  202. package/types/compiler/deprecated-lints-1-106.d.ts +12 -0
  203. package/types/compiler/deprecated-lints-1-106.d.ts.map +1 -0
  204. package/types/compiler/deprecated-lints.d.ts +32 -5
  205. package/types/compiler/deprecated-lints.d.ts.map +1 -1
  206. package/types/compiler/deprecated-typed-lints.d.ts +21 -0
  207. package/types/compiler/deprecated-typed-lints.d.ts.map +1 -0
  208. package/types/compiler/dom-here.d.ts +14 -0
  209. package/types/compiler/dom-here.d.ts.map +1 -0
  210. package/types/compiler/dom.d.ts +1 -0
  211. package/types/compiler/dom.d.ts.map +1 -1
  212. package/types/compiler/fence-checks.d.ts.map +1 -1
  213. package/types/compiler/field-described.d.ts +1 -1
  214. package/types/compiler/field-described.d.ts.map +1 -1
  215. package/types/compiler/html-fields.d.ts +19 -0
  216. package/types/compiler/html-fields.d.ts.map +1 -0
  217. package/types/compiler/html-initial.d.ts +3 -2
  218. package/types/compiler/html-initial.d.ts.map +1 -1
  219. package/types/compiler/html.d.ts.map +1 -1
  220. package/types/compiler/index.d.ts +1 -0
  221. package/types/compiler/index.d.ts.map +1 -1
  222. package/types/compiler/items.d.ts +4 -1
  223. package/types/compiler/items.d.ts.map +1 -1
  224. package/types/compiler/link-flags.d.ts +6 -0
  225. package/types/compiler/link-flags.d.ts.map +1 -1
  226. package/types/compiler/lints.d.ts +44 -17
  227. package/types/compiler/lints.d.ts.map +1 -1
  228. package/types/compiler/rest-omits.d.ts +4 -0
  229. package/types/compiler/rest-omits.d.ts.map +1 -0
  230. package/types/config-loader.d.ts.map +1 -1
  231. package/types/config-resolve.d.ts.map +1 -1
  232. package/types/config.d.ts +15 -2
  233. package/types/config.d.ts.map +1 -1
  234. package/types/content/markdown.d.ts.map +1 -1
  235. package/types/migrate/content.d.ts.map +1 -1
  236. package/types/runtime/action-shared.d.ts +1 -1
  237. package/types/runtime/action-shared.d.ts.map +1 -1
  238. package/types/runtime/action.d.ts +3 -0
  239. package/types/runtime/action.d.ts.map +1 -1
  240. package/types/runtime/form-types.d.ts +6 -0
  241. package/types/runtime/form-types.d.ts.map +1 -0
  242. package/types/runtime/form.d.ts +3 -1
  243. package/types/runtime/form.d.ts.map +1 -1
  244. package/types/runtime/html.d.ts +3 -0
  245. package/types/runtime/html.d.ts.map +1 -1
  246. package/types/runtime/markdown-autolink.d.ts +11 -0
  247. package/types/runtime/markdown-autolink.d.ts.map +1 -0
  248. package/types/runtime/markdown-render.client.d.ts +2 -1
  249. package/types/runtime/markdown-render.client.d.ts.map +1 -1
  250. package/types/runtime/markdown.client.d.ts +3 -1
  251. package/types/runtime/markdown.client.d.ts.map +1 -1
  252. package/types/runtime/markdown.d.ts +11 -0
  253. package/types/runtime/markdown.d.ts.map +1 -1
  254. package/types/runtime/markdown.server.d.ts +3 -1
  255. package/types/runtime/markdown.server.d.ts.map +1 -1
  256. package/types/runtime/navigate-api.d.ts +1 -1
  257. package/types/runtime/navigate-api.d.ts.map +1 -1
  258. package/types/runtime/persist.d.ts +2 -2
  259. package/types/runtime/persist.d.ts.map +1 -1
  260. package/types/runtime/reactive.d.ts +3 -0
  261. package/types/runtime/reactive.d.ts.map +1 -1
  262. package/types/runtime/sanitize.d.ts.map +1 -1
  263. package/types/runtime/schema-record.d.ts +9 -0
  264. package/types/runtime/schema-record.d.ts.map +1 -0
  265. package/types/runtime/schema.client.d.ts.map +1 -1
  266. package/types/runtime/schema.d.ts +94 -10
  267. package/types/runtime/schema.d.ts.map +1 -1
  268. package/types/runtime/swap-focus.d.ts.map +1 -1
  269. package/types/server/action-module.d.ts +2 -0
  270. package/types/server/action-module.d.ts.map +1 -0
  271. package/types/server/actions.d.ts +1 -0
  272. package/types/server/actions.d.ts.map +1 -1
  273. package/types/server/api.d.ts.map +1 -1
  274. package/types/server/app-stages.d.ts +3 -2
  275. package/types/server/app-stages.d.ts.map +1 -1
  276. package/types/server/env-state.d.ts.map +1 -1
  277. package/types/server/env.d.ts +5 -1
  278. package/types/server/env.d.ts.map +1 -1
  279. package/types/server/favicon.d.ts +3 -1
  280. package/types/server/favicon.d.ts.map +1 -1
  281. package/types/server/kept-pages.d.ts +1 -1
  282. package/types/server/kept-pages.d.ts.map +1 -1
  283. package/types/server/library.d.ts +2 -0
  284. package/types/server/library.d.ts.map +1 -1
  285. package/types/server/mcp.d.ts +1 -1
  286. package/types/server/mcp.d.ts.map +1 -1
  287. package/types/server/notifications.d.ts +2 -1
  288. package/types/server/notifications.d.ts.map +1 -1
  289. package/types/server/offline.d.ts.map +1 -1
  290. package/types/server/push-settings.d.ts +1 -1
  291. package/types/server/push-settings.d.ts.map +1 -1
  292. package/types/server/push.d.ts +1 -0
  293. package/types/server/push.d.ts.map +1 -1
  294. package/types/server/query.d.ts.map +1 -1
  295. package/types/server/scope.d.ts +1 -1
  296. package/types/server/scope.d.ts.map +1 -1
  297. package/types/test/a11y-dom.d.ts +20 -0
  298. package/types/test/a11y-dom.d.ts.map +1 -0
  299. package/types/test/html-snapshot.d.ts +4 -0
  300. package/types/test/html-snapshot.d.ts.map +1 -0
  301. package/types/test/index.d.ts.map +1 -1
  302. package/types/test/mount.d.ts +3 -0
  303. package/types/test/mount.d.ts.map +1 -1
  304. package/types/test/page-checks.d.ts +6 -0
  305. package/types/test/page-checks.d.ts.map +1 -0
  306. package/types/test/screenshot-match.d.ts +1 -1
  307. package/types/test/screenshot-match.d.ts.map +1 -1
  308. package/types/test/shared-modules.d.ts.map +1 -1
  309. package/types/test/site-types.d.ts +3 -1
  310. package/types/test/site-types.d.ts.map +1 -1
@@ -19,7 +19,7 @@ import type { ServedPage } from './render'
19
19
  import type { RouteTable } from './route-table'
20
20
  import type { Claim, ServedPaths } from './served-paths'
21
21
  import type { PageSetup } from './setup'
22
- import { join, resolve } from 'node:path'
22
+ import { join, relative, resolve } from 'node:path'
23
23
  import process from 'node:process'
24
24
  import { MAPS_DIR } from '../build/assets'
25
25
  import { pageHooks, servedPageHooks } from '../config-extensions'
@@ -52,7 +52,7 @@ import { entryUrls } from './entry-urls'
52
52
  import { servePublicEnv } from './env'
53
53
  import { browserStackMapper, devStackMapper } from './error-maps'
54
54
  import { serveErrorReports } from './errors'
55
- import { FAVICON_DIR, faviconSource, faviconVersion, serveFavicons } from './favicon'
55
+ import { checkShareAction, FAVICON_DIR, faviconSource, faviconVersion, serveFavicons } from './favicon'
56
56
  import { loadGuard, requiredGuards } from './guards'
57
57
  import { refuseUnknownHosts } from './host-allowlist'
58
58
 
@@ -64,7 +64,7 @@ import { HEALTH_PATH, serveHealth, stopOnSignal } from './lifecycle'
64
64
  import { liveConnections, serveLive } from './live'
65
65
  import { warnOfLocalFiles } from './local-files'
66
66
  import { announceStart, loggerOf, logRequests, pathOf, requestRefusalLogger, useLogger } from './log'
67
- import { mcpBodyLimit, receiveDispatched, redirectFormerMcp, serveMcp, serveToolCallsThrough } from './mcp'
67
+ import { mcpBodyLimit, receiveDispatched, serveMcp, serveToolCallsThrough } from './mcp'
68
68
  import { FORMER_METRICS_PATH, METRICS_PATH, metricsOf, serveMetrics } from './metrics'
69
69
  import { newTabStyles } from './new-tab'
70
70
  import { countMissing, knowRedirects } from './not-found'
@@ -195,8 +195,9 @@ export function bootOf(input: BootInput) {
195
195
  // Offered, so an app file at the path keeps it; only a running server counts, as `kay dev` restarts on every change and an export serves nothing.
196
196
  const metricsConfig = env.serving ? metricsOf(options.ops?.metrics) : undefined
197
197
  const metrics: Claim | undefined = metricsConfig && { path: options.endpoints?.metrics ?? METRICS_PATH, owner: 'the metrics route', kind: 'kay' }
198
- // Where the metrics were served before 1.105, answered as well until 1.108 by an app that did not move them, unless an app file serves something there.
198
+ // Where the MCP endpoint was served before 1.105, answered in place until 2.0 by an app that did not move it, unless an app file serves something there.
199
199
  const formerMcp: Claim | undefined = input.mcpAt !== undefined && options.endpoints?.mcp === undefined ? { path: FORMER_MCP_PATH, owner: '`mcp`', kind: 'kay', method: 'ALL' } : undefined
200
+ // Where the metrics were served before 1.105, answered as well until 1.108 by an app that did not move them, unless an app file serves something there.
200
201
  const formerMetrics: Claim | undefined = metrics && options.endpoints?.metrics === undefined ? { path: FORMER_METRICS_PATH, owner: 'the metrics route', kind: 'kay' } : undefined
201
202
  // Offered, so an app file at the path keeps it; the check is served once every claim is in, and only where it still holds the path.
202
203
  const health: Claim | undefined = options.ops?.health === false ? undefined : { path: options.endpoints?.health ?? HEALTH_PATH, owner: 'the health check', kind: 'kay' }
@@ -218,7 +219,7 @@ export function bootOf(input: BootInput) {
218
219
  hasPreview: options.preview !== undefined && options.preview !== false,
219
220
  metrics,
220
221
  formerMetrics,
221
- // Where the MCP endpoint was served before 1.105, redirected to its path now until 1.108 by an app that did not move it, unless an app file serves something there.
222
+ // Where the MCP endpoint was served before 1.105, answered as the endpoint is until 2.0 by an app that did not move it, unless an app file serves something there.
222
223
  formerMcp,
223
224
  health,
224
225
  registered,
@@ -265,8 +266,11 @@ export function knowPages({ app, env, options, setup: { matchers }, routes, tabl
265
266
  }
266
267
 
267
268
  // Only a kept page reads the count, so a build keeping none registers no hook for it.
268
- export function keptPageWrites({ app, setup: { client }, mcpAt }: Boot): Writes {
269
- return [...client.pages.values()].some(page => page.kept === true) ? countWrites(app, [mcpAt].filter(path => path !== undefined)) : NO_WRITES
269
+ export function keptPageWrites({ app, setup: { client }, mcpAt, formerMcp, served }: Boot): Writes {
270
+ // The former path is exempt only where kay serves it: a route of the app at `/mcp` keeps counting.
271
+ const own = () => [...mcpAt === undefined ? [] : [mcpAt], ...formerMcp !== undefined && served.holds(formerMcp) ? [formerMcp.path] : []]
272
+
273
+ return [...client.pages.values()].some(page => page.kept === true) ? countWrites(app, own) : NO_WRITES
270
274
  }
271
275
 
272
276
  // The routes under `/_kay/files/` carry the security headers themselves, as the build's files and the image route do.
@@ -557,10 +561,13 @@ export function hookLifecycleOf({ app, options }: Boot): void {
557
561
  // The actions, the API modules and the endpoints, then the jobs page, after the extensions whose derived values the guards read through `ctx.locals`.
558
562
  export async function appRoutes(boot: Boot, actionOptions: ActionOptions, jobsPage: ReturnType<typeof kayEndpoints>, apiMountsServed: string[]) {
559
563
  const { app, routes, table, setup } = boot
560
- const [{ limits: actionLimits, tools: toolActions }, apiModules] = await Promise.all([registerActionRoutes(app, routes, routeMatch(table, setup.matchers, boot.env.trailingSlash), actionOptions), setup.api])
564
+ const [{ limits: actionLimits, tools: toolActions, broken }, apiModules] = await Promise.all([registerActionRoutes(app, routes, routeMatch(table, setup.matchers, boot.env.trailingSlash), actionOptions), setup.api])
561
565
  const api = await serveApi(app, apiModules, actionOptions, setup.extensionApp)
562
566
 
563
567
  apiMountsServed.push(...apiModules.map(module => module.mount))
568
+ const rooted = (file: string) => relative(boot.project.root, file).replaceAll('\\', '/')
569
+
570
+ checkShareAction(boot.options.assets?.manifest?.shareTarget, new Set(actionLimits.keys()), new Set(routes.flatMap(route => [...route.layouts, ...route.actionModules ?? [], route.file]).map(rooted)), new Map([...broken].map(([file, message]) => [rooted(file), message])))
564
571
  boot.registered.actions = actionLimits.size > 0
565
572
  boot.registered.api = api.mounted
566
573
 
@@ -577,7 +584,7 @@ type Served = Awaited<ReturnType<typeof appRoutes>>
577
584
  // The rules a redirect added while the site runs is checked against, the API's claims and the body limits of every route. Returns where the OpenAPI document and the MCP metadata go.
578
585
  // Not async, as the closures the runtime redirects keep past the app would hold an async function's parameters, the app among them.
579
586
  export function limitBodiesAndClaimApi(boot: Boot, { actionLimits, api, endpointLimits }: Served, servers: unknown[]) {
580
- const { app, env, options, served, setup: { client }, table, hasPreview, mcpAt } = boot
587
+ const { app, env, options, served, setup: { client }, table, hasPreview, mcpAt, formerMcp } = boot
581
588
  // Claimed before kay's own files, which give way to them.
582
589
  const openapi = openApiSettings(options.openapi)
583
590
  const apiAt = apiPathOf(options.endpoints?.api)
@@ -604,14 +611,16 @@ export function limitBodiesAndClaimApi(boot: Boot, { actionLimits, api, endpoint
604
611
  }
605
612
  }
606
613
 
607
- limitBodies(app, options.limits?.body ?? DEFAULT_BODY_LIMIT, new Map([...actionLimits, ...hasPreview ? [[DRAFT_ROUTE, DRAFT_BODY_LIMIT] as const] : [], ...mcpAt === undefined ? [] : [[mcpAt, mcpBodyLimit] as const]]), mountLimits(api.limits, options.extensions, options.limits?.byPath, servers), [...api.routeLimits, ...endpointLimits])
614
+ const formerAt = formerMcp && served.offer(formerMcp) ? formerMcp.path : undefined
615
+
616
+ limitBodies(app, options.limits?.body ?? DEFAULT_BODY_LIMIT, new Map([...actionLimits, ...hasPreview ? [[DRAFT_ROUTE, DRAFT_BODY_LIMIT] as const] : [], ...mcpAt === undefined ? [] : [[mcpAt, mcpBodyLimit] as const], ...formerAt === undefined ? [] : [[formerAt, mcpBodyLimit] as const]]), mountLimits(api.limits, options.extensions, options.limits?.byPath, servers), [...api.routeLimits, ...endpointLimits])
608
617
 
609
- return { openapi, apiAt, servesOpenApi, metadataPaths }
618
+ return { openapi, apiAt, servesOpenApi, metadataPaths, formerAt }
610
619
  }
611
620
 
612
621
  // The OpenAPI document and the MCP endpoint, registered last before the pages.
613
- export async function apiDocuments(boot: Boot, { toolActions, apiModules, api }: Served, actionOptions: ActionOptions, { openapi, apiAt, servesOpenApi, metadataPaths }: ReturnType<typeof limitBodiesAndClaimApi>): Promise<void> {
614
- const { app, env, options, required, served, formerMcp, setup: { locales }, project: { paths }, mcpAt, mcpKey } = boot
622
+ export async function apiDocuments(boot: Boot, { toolActions, apiModules, api }: Served, actionOptions: ActionOptions, { openapi, apiAt, servesOpenApi, metadataPaths, formerAt }: ReturnType<typeof limitBodiesAndClaimApi>): Promise<void> {
623
+ const { app, env, options, required, setup: { locales }, project: { paths }, mcpAt, mcpKey } = boot
615
624
 
616
625
  // The actions that opted in to being tools are in the document beside the routes, and the MCP endpoint reads its tools from it.
617
626
  const document = servesOpenApi || mcpAt !== undefined
@@ -626,11 +635,7 @@ export async function apiDocuments(boot: Boot, { toolActions, apiModules, api }:
626
635
  serveOpenApi(app, document, openapi, await covering(false), actionOptions, apiAt, options.endpoints?.openapi)
627
636
 
628
637
  if (mcpAt !== undefined && document) {
629
- serveMcp(app, document, { title: (document.info as { title: string }).title, version: (document.info as { version: string }).version, base: env.base, guards: await covering(true), actions: actionOptions, metadataPaths, path: mcpAt, rateLimit: mcpRateLimit(options.mcp), instructions: mcpInstructions(options.mcp), key: mcpKey, dev: env.dev, outputs: actionOptions.toolOutputs })
630
-
631
- // Where the endpoint was served before 1.105, sent to the new path with a 308 until 1.108 by an app that did not move it, unless the app serves something there.
632
- if (formerMcp && served.offer(formerMcp))
633
- redirectFormerMcp(app, mcpAt)
638
+ serveMcp(app, document, { title: (document.info as { title: string }).title, version: (document.info as { version: string }).version, base: env.base, guards: await covering(true), actions: actionOptions, metadataPaths, path: mcpAt, former: formerAt, rateLimit: mcpRateLimit(options.mcp), instructions: mcpInstructions(options.mcp), key: mcpKey, dev: env.dev, outputs: actionOptions.toolOutputs })
634
639
  }
635
640
  }
636
641
 
@@ -6,7 +6,7 @@ import { existsSync, realpathSync } from 'node:fs'
6
6
  import { mkdir } from 'node:fs/promises'
7
7
  import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
8
8
  import { findKayLibraries } from '../build/libraries'
9
- import { classesOf, componentFile, componentsNamed, exported, forgetNames, isComponentName, keyOf, UI_FILE, uiOf } from '../build/ui'
9
+ import { classesOf, componentFile, componentsNamed, exported, forgetNames, isComponentName, keyOf, UI_FILE, uiEntryOf, uiOf } from '../build/ui'
10
10
  import { appSpecifier, styleInfo, themeTokens, tokensNamedBy } from '../build/ui-info'
11
11
  import { parseProgram } from '../compiler/estree'
12
12
  import { unwrapped } from '../compiler/object-literal'
@@ -221,7 +221,7 @@ export async function devUi(root: string, request: Request): Promise<Response> {
221
221
 
222
222
  const { info, libraries } = found
223
223
  const ui = uiOf(root)
224
- const set = ui?.components.findLast(component => componentFile(ui, component) === info.file)?.entry
224
+ const set = uiEntryOf(root, info.file)
225
225
  const own = (part: string): string | undefined => {
226
226
  if (typeof set?.parts === 'string')
227
227
  return part === 'root' ? set.parts : undefined
@@ -100,7 +100,7 @@ export function building(): boolean {
100
100
  // The module the island entry imports the public variables from, served from the environment the server runs in, so an executable or a prerendered page reads today's values rather than those of the build.
101
101
  export const PUBLIC_ENV_PATH = '/_kay/env.js'
102
102
 
103
- export const PUBLIC_FIELD = /\bs\.Public\s*\(/
103
+ export const PUBLIC_FIELD = /\bs\.[Pp]ublic\s*\(/
104
104
  export const TEST_FILE = /\.(?:test|spec)\.[cm]?[jt]sx?$/
105
105
  // What each file read last held, by its size and time, so a command asking for the files several times reads each one once.
106
106
  const scanned = new Map<string, { stamp: string, declares: boolean }>()
package/src/server/env.ts CHANGED
@@ -1,12 +1,14 @@
1
1
  import type { Elysia } from 'elysia'
2
2
  import type { PublicFieldsOf, WithPublicFields } from '../runtime/env'
3
3
  import type { Schema, Static } from '../runtime/schema'
4
+ import type { ObjectOf, SchemaShape } from '../runtime/schema-record'
4
5
  import type { EnvSchemaRecord } from './env-state'
5
6
  import { readFileSync } from 'node:fs'
6
7
  import process from 'node:process'
7
8
  import { t } from 'elysia'
8
9
  import { KayError } from '../compiler/errors'
9
10
  import { PUBLIC_ENV } from '../runtime/env'
11
+ import { schemaOf } from '../runtime/schema-record'
10
12
  import { bundled } from './bundle'
11
13
  import { fixedReply } from './compress'
12
14
  import { devSecret } from './dev-secret'
@@ -44,6 +46,8 @@ function loadSamples(length: number, pattern: unknown): string[] {
44
46
  // A `s.Object` of the variables, each read on its own.
45
47
  export type EnvSchema = Schema & { properties: Record<string, Schema> }
46
48
 
49
+ type EnvValues<Spec extends EnvSchema> = Static<Spec> & (keyof PublicFieldsOf<Spec> extends never ? unknown : WithPublicFields<Spec>)
50
+
47
51
  // The text of the file `<NAME>_FILE` names, trimmed and read once, as the server boots; a file that cannot be read or holds nothing is an error naming the variable and the path, never the content.
48
52
  function readSecretFile(name: string, file: string, path: string): string {
49
53
  try {
@@ -64,7 +68,11 @@ function readSecretFile(name: string, file: string, path: string): string {
64
68
  // A field marked `s.Public` reaches islands as `publicEnv` from `kay`, with no config key; a name such as `STRIPE_SECRET` or `DATABASE_URL` is refused.
65
69
  // A string field, `s.Public` ones apart, also reads `<NAME>_FILE`, the path of a file holding the value, trimmed and read once, as a compose secret hands it; both set, or a file that cannot be read or is empty, stops the boot naming them, unless the field is `s.Optional`, which is left unset with one warning naming the file.
66
70
  // A field with `requiredInProduction: true` is required in production with its default dropped, and outside production takes its default, stays `undefined` under `s.Optional`, or is `''` when it has neither; `s.Secret()` is one that development and tests give a value derived from the project path; `kay env` lists each as required in production.
67
- export function defineEnv<Spec extends EnvSchema>(declared: Spec, source: Record<string, string | undefined> = process.env): Static<Spec> & (keyof PublicFieldsOf<Spec> extends never ? unknown : WithPublicFields<Spec>) {
71
+ export function defineEnv<Spec extends EnvSchema>(declared: Spec, source?: Record<string, string | undefined>): EnvValues<Spec>
72
+ export function defineEnv<const Shape extends SchemaShape>(declared: Shape, source?: Record<string, string | undefined>): EnvValues<ObjectOf<Shape>>
73
+ export function defineEnv(given: EnvSchema | SchemaShape, source: Record<string, string | undefined> = process.env): unknown {
74
+ const declared = schemaOf(given) as EnvSchema
75
+
68
76
  recordEnv(declared, defineEnv)
69
77
 
70
78
  const production = source.NODE_ENV === 'production'
@@ -114,7 +122,7 @@ export function defineEnv<Spec extends EnvSchema>(declared: Spec, source: Record
114
122
 
115
123
  registerPublic(declared, values)
116
124
 
117
- return values as ReturnType<typeof defineEnv<Spec>>
125
+ return values
118
126
  }
119
127
 
120
128
  if (!building())
@@ -144,7 +152,7 @@ export function defineEnv<Spec extends EnvSchema>(declared: Spec, source: Record
144
152
 
145
153
  registerPublic(declared, env)
146
154
 
147
- return env as ReturnType<typeof defineEnv<Spec>>
155
+ return env
148
156
  }
149
157
 
150
158
  // What `--load` gives a variable the build lacks or refuses: a fixed string of 32 characters or its `minLength`, which a session secret's own check accepts and writes nothing to disk; `undefined` for a field of another type.
@@ -1,5 +1,5 @@
1
1
  import type { Elysia } from 'elysia'
2
- import type { FaviconConfig, ManifestConfig } from '../config'
2
+ import type { FaviconConfig, ManifestConfig, ManifestShareTarget } from '../config'
3
3
  import type { HeadTag } from '../runtime/head'
4
4
  import type { Localized } from '../runtime/localized'
5
5
  import type { ServedPaths } from './served-paths'
@@ -7,6 +7,7 @@ import { mkdir } from 'node:fs/promises'
7
7
  import { join, resolve } from 'node:path'
8
8
  import { SVG_FILE } from '../build/files'
9
9
  import { KayError } from '../compiler/errors'
10
+ import { actionUrl } from '../runtime/action'
10
11
  import { localizedText } from '../runtime/localized'
11
12
  import { kayLog } from '../runtime/log'
12
13
  import { revalidated } from './public'
@@ -316,9 +317,54 @@ export function manifestJson(name: string | undefined, description: string | und
316
317
  theme_color: typeof manifest.themeColor === 'object' ? manifest.themeColor.light : manifest.themeColor,
317
318
  background_color: manifest.backgroundColor,
318
319
  shortcuts: manifest.shortcuts?.map((shortcut, index) => ({ name: shortcut.name, short_name: shortcut.shortName, description: shortcut.description, url: page(shortcut.url, `shortcuts[${index}].url`) })),
320
+ share_target: manifest.shareTarget === undefined ? undefined : shareTargetJson(manifest.shareTarget, page),
319
321
  })
320
322
  }
321
323
 
324
+ // An action written as its page file and export name is served at the URL `actionUrl` gives it; a path is a route of the site.
325
+ const ACTION_REFERENCE = /^(?:\.\/)?([^#\\]+\.kay)#([A-Z_a-z$][\w$]*)$/
326
+
327
+ // What is wrong with a share target naming a page file that is no route or layout of the app, or an export of it that is no action: `actions` holds the URLs the app serves, `files` the page files relative to the root, and `broken` those that failed to compile, with the failure.
328
+ export function shareActionProblem(share: ManifestShareTarget | undefined, actions: ReadonlySet<string>, files: ReadonlySet<string>, broken: ReadonlyMap<string, string> = new Map()): string | undefined {
329
+ const reference = share === undefined || share.action.startsWith('/') ? null : ACTION_REFERENCE.exec(share.action)
330
+
331
+ if (reference === null || actions.has(actionUrl(reference[1]!, reference[2]!)))
332
+ return undefined
333
+
334
+ const [, file, name] = reference
335
+ const start = `kay: the manifest's shareTarget.action, ${share!.action}, `
336
+
337
+ if (broken.has(file!))
338
+ return `${start}names an action of ${file}, which failed to compile: ${broken.get(file!)}`
339
+
340
+ return files.has(file!) ? `${start}names no action: ${file} exports no action called ${name}` : `${start}names a file that is no page or layout of the app`
341
+ }
342
+
343
+ // Stops the boot on a share target naming an action the app does not have.
344
+ export function checkShareAction(share: ManifestShareTarget | undefined, actions: ReadonlySet<string>, files: ReadonlySet<string>, broken?: ReadonlyMap<string, string>): void {
345
+ const problem = shareActionProblem(share, actions, files, broken)
346
+
347
+ if (problem !== undefined)
348
+ throw new KayError('favicon-invalid', problem)
349
+ }
350
+
351
+ function shareTargetJson(share: ManifestShareTarget, page: (path: string, what: string) => string): object {
352
+ const reference = share.action.startsWith('/') ? null : ACTION_REFERENCE.exec(share.action)
353
+
354
+ if (reference === null && !SITE_PATH.test(share.action))
355
+ throw new KayError('favicon-invalid', `kay: the manifest's shareTarget.action is an action as 'src/routes/share.kay#receive' or a path of the site such as '/share', not ${JSON.stringify(share.action)}`)
356
+
357
+ const files = share.files ?? []
358
+ const { title = 'title', text = 'text', url = 'url', files: field = 'files' } = share.params ?? {}
359
+
360
+ return {
361
+ action: page(reference === null ? share.action : actionUrl(reference[1]!, reference[2]!), 'shareTarget.action'),
362
+ method: 'POST',
363
+ enctype: files.length > 0 ? 'multipart/form-data' : 'application/x-www-form-urlencoded',
364
+ params: { title, text, url, ...files.length > 0 && { files: [{ name: field, accept: files }] } },
365
+ }
366
+ }
367
+
322
368
  function sitePath(path: string, what: string): string {
323
369
  if (!SITE_PATH.test(path))
324
370
  throw new KayError('favicon-invalid', `kay: the manifest's ${what} is a path of the site, starting with a single /, not ${path}`)
@@ -144,7 +144,7 @@ function locations(view: DataView, iloc: Box, wanted: Set<number>): Map<number,
144
144
  const value = unsigned(view, at, size)
145
145
 
146
146
  if (!Number.isSafeInteger(value))
147
- throw new Error('a size it cannot read')
147
+ throw new TypeError('a size it cannot read')
148
148
 
149
149
  at += size
150
150
 
@@ -39,18 +39,18 @@ function withoutTrailingSlashes(path: string): string {
39
39
  // A request that is not a GET, a HEAD or an OPTIONS can change what a page renders, an action as much as a route of the app, once a route answers it: one to no route, and kay's own routes in `own` (the MCP endpoint among them, whose tool calls reach the app's actions and count there), write nothing, so no visitor can force a page to render again by sending them.
40
40
  // Counted when its route is matched and again as its response is made, so a visit between the two is checked once more, and the visit that follows the response sees the finished write; one a guard or the validation refuses (a 400, 401, 403, 405, 413, 415, 422 or 429) is counted by neither, so no visitor can make a page render again by sending those.
41
41
  // The end count is a `mapResponse` and an `afterResponse`, never an `afterHandle` or `onError`, which would change how an API module answers; called before any route is added, as a hook reaches only the routes added after it.
42
- export function countWrites(app: Elysia, own: string[] = []): Writes {
42
+ export function countWrites(app: Elysia, own: () => string[] = () => []): Writes {
43
43
  let done = 0
44
44
  let active = 0
45
45
  const writes: Writes = { get count() {
46
46
  // A write in flight counts half a step, so a visit during it is checked once more after it, and a refused one leaves the count where it was.
47
47
  return active > 0 ? done + 0.5 : done
48
48
  } }
49
- const kay = new Set([...KAY_ROUTES, ...own])
49
+ const kay = new Set(KAY_ROUTES)
50
50
  const started = new WeakSet<Request>()
51
51
 
52
52
  app.onTransform({ as: 'global' }, ({ request }) => {
53
- if (request.method !== 'GET' && request.method !== 'HEAD' && request.method !== 'OPTIONS' && !kay.has(withoutTrailingSlashes(pathOf(request.url)))) {
53
+ if (request.method !== 'GET' && request.method !== 'HEAD' && request.method !== 'OPTIONS' && !kay.has(withoutTrailingSlashes(pathOf(request.url))) && !own().includes(withoutTrailingSlashes(pathOf(request.url)))) {
54
54
  started.add(request)
55
55
  active++
56
56
  }
@@ -42,7 +42,9 @@ export type { DenyOptions, RefuseOptions } from '../runtime/refuse'
42
42
  export { refuse } from '../runtime/refuse'
43
43
  export { safeCode } from '../runtime/safe-code'
44
44
  export { isUrlAttribute, UNSAFE_ATTRIBUTE, UNSAFE_TAGS } from '../runtime/sanitize'
45
+ export { DEFAULT_MAX_ITEMS } from '../runtime/schema'
45
46
  export type { Schema, Static } from '../runtime/schema'
47
+ export { DEFAULT_MAX_LENGTH } from '../runtime/schema-bounds'
46
48
  export { configuredSite, setSite } from '../runtime/site'
47
49
  export { openSqlite } from '../runtime/sqlite.server'
48
50
  export { parseEvents } from '../runtime/sse'
package/src/server/mcp.ts CHANGED
@@ -16,7 +16,7 @@ import { configuredSite } from '../runtime/site'
16
16
  import { FAILURE_HEADER, PAGE_HEADER, REDIRECT_HEADER } from '../runtime/swap'
17
17
  import { decodeServerValue, encodeValue } from '../runtime/wire'
18
18
  import { boundToPage } from './actions'
19
- import { FORMER_MCP_PATH, RESOURCE_METADATA } from './api-modules'
19
+ import { RESOURCE_METADATA } from './api-modules'
20
20
  import { isCrossSite, postedFrom, unadmittedCrossSite } from './cross-site'
21
21
  import { answeredAsPage, currentRequest } from './log'
22
22
  import { bearsMcpKey } from './mcp-key'
@@ -403,6 +403,8 @@ export interface McpOptions {
403
403
  metadataPaths: string[]
404
404
  // Where the endpoint is served, `/mcp` by default.
405
405
  path: string
406
+ // The path before 1.105, answered as `path` is until 2.0, for an app that did not move the endpoint and serves nothing there.
407
+ former?: string | undefined
406
408
  // The requests a client may send it in a window, or undefined for no limit.
407
409
  rateLimit: RateWindowMs | undefined
408
410
  // Sent as `instructions` of `initialize`, from `mcp.instructions`.
@@ -566,7 +568,7 @@ function serveResourceMetadata(app: Elysia, name: string, paths: string[], endpo
566
568
  }
567
569
  }
568
570
 
569
- // Serves the tools of `document` at `/mcp` over Streamable HTTP: one JSON-RPC message per POST, answered with JSON.
571
+ // Serves the tools of `document` at its path over Streamable HTTP: one JSON-RPC message per POST, answered with JSON; `former`, where it was before 1.105, answers POST in place until 2.0.
570
572
  export function serveMcp(app: Elysia, document: Schema, options: McpOptions): void {
571
573
  const calls = new AsyncLocalStorage<CallContext>()
572
574
  const build = () => {
@@ -587,7 +589,7 @@ export function serveMcp(app: Elysia, document: Schema, options: McpOptions): vo
587
589
  }
588
590
  const notAllowed = () => new Response(null, { status: 405, headers: { allow: 'POST' } })
589
591
 
590
- app.post(options.path, async (served) => {
592
+ const answer = async (served: { request: Request, server: Server | null }) => {
591
593
  const { request, server } = served
592
594
 
593
595
  // A browser page of another site posting here would act with the visitor's cookies.
@@ -637,18 +639,17 @@ export function serveMcp(app: Elysia, document: Schema, options: McpOptions): vo
637
639
  status = 401
638
640
 
639
641
  return new Response(JSON.stringify(reply), { status, headers })
640
- }, { parse: 'none' })
642
+ }
643
+
644
+ app.post(options.path, answer, { parse: 'none' })
641
645
  app.get(options.path, notAllowed)
642
646
  app.delete(options.path, notAllowed)
643
- serveResourceMetadata(app, options.title, options.metadataPaths, options.path)
644
- }
645
647
 
646
- // Sends a request for `/mcp`, where the endpoint was served before 1.105, to its path now, with the method, the body and the query kept by a 308; removed in 1.108.
647
- export function redirectFormerMcp(app: Elysia, to: string): void {
648
- app.all(FORMER_MCP_PATH, ({ request }) => {
649
- // The base goes in front of the location as it does for every redirect.
650
- return new Response(null, { status: 308, headers: { 'location': `${to}${requestUrl(request).search}`, 'cache-control': 'no-store' } })
651
- })
648
+ // Only the POST is taken at the former path, so a catch-all or parameter route of the app keeps its GET and DELETE.
649
+ if (options.former !== undefined)
650
+ app.post(options.former, answer, { parse: 'none' })
651
+
652
+ serveResourceMetadata(app, options.title, options.metadataPaths, options.path)
652
653
  }
653
654
 
654
655
  // An action a library offers a model: what the model reads of it, and the call it makes.
@@ -63,6 +63,8 @@ export interface NotifyOptions {
63
63
  ttl?: Duration | undefined
64
64
  // `false` keeps the notification in the inbox alone, without the push a person who opted in would get with `push()` listed.
65
65
  push?: boolean | undefined
66
+ // `false` leaves the installed app's badge alone: the push otherwise carries the person's unread count, which the worker shows as the app badge.
67
+ badge?: boolean | undefined
66
68
  }
67
69
 
68
70
  export const MAX_TITLE = 200
@@ -278,7 +280,7 @@ function changed(user: string): void {
278
280
 
279
281
  // Puts a notification in a person's inbox, which the `Bell` of kayjs-ui shows with its unread count and updates in every open tab. `user` is the id kayjs-auth, or whatever names the request's user, gives.
280
282
  // The store is the app's `store.notifications`, which `sqliteData` and `pgData` fill; with none it is this process's memory. A notification is dropped after `ttl`, 90 days by default.
281
- export async function notify(user: string, { title, url, ttl, push }: NotifyOptions): Promise<Notification> {
283
+ export async function notify(user: string, { title, url, ttl, push, badge }: NotifyOptions): Promise<Notification> {
282
284
  const id = checkedUser(user)
283
285
  const text = typeof title === 'string' ? title.replaceAll('\0', '').trim() : ''
284
286
 
@@ -297,7 +299,7 @@ export async function notify(user: string, { title, url, ttl, push }: NotifyOpti
297
299
  changed(id)
298
300
 
299
301
  if (push !== false)
300
- pushAlongside(id, { title: text, url: link })
302
+ pushAlongside(id, { title: text, url: link }, badge === false ? undefined : async () => notificationStore().unread(id, Date.now()))
301
303
 
302
304
  return { id: note.id, title: note.title, ...link === undefined ? {} : { url: link }, createdAt: new Date(createdAt), read: false }
303
305
  }
@@ -30,7 +30,7 @@ const BACKSLASH = /\\/g
30
30
  // A rule of the fonts' stylesheet naming its file and the range of characters it holds.
31
31
  const FACE_RANGE = /url\("([^"]+)"\)[^}]*?unicode-range:([^;}]+)/g
32
32
  // Bumped whenever the worker's own code changes, so every site installs it again.
33
- const WORKER_VERSION = 8
33
+ const WORKER_VERSION = 9
34
34
  // Past this many pages kept by default, the boot says to list the ones worth it.
35
35
  const MANY_PAGES = 100
36
36
 
@@ -195,14 +195,31 @@ self.addEventListener('push', (event) => {
195
195
  }
196
196
  catch {}
197
197
 
198
- event.waitUntil(self.registration.showNotification(typeof data.title === 'string' && data.title !== '' ? data.title : location.hostname, {
199
- body: typeof data.body === 'string' ? data.body : undefined,
200
- tag: typeof data.tag === 'string' ? data.tag : undefined,
201
- icon: typeof data.icon === 'string' ? linkOf(data.icon) : undefined,
202
- data: { url: typeof data.url === 'string' ? linkOf(data.url) : linkOf('/') },
203
- }))
198
+ event.waitUntil(Promise.all([
199
+ self.registration.showNotification(typeof data.title === 'string' && data.title !== '' ? data.title : location.hostname, {
200
+ body: typeof data.body === 'string' ? data.body : undefined,
201
+ tag: typeof data.tag === 'string' ? data.tag : undefined,
202
+ icon: typeof data.icon === 'string' ? linkOf(data.icon) : undefined,
203
+ data: { url: typeof data.url === 'string' ? linkOf(data.url) : linkOf('/') },
204
+ }),
205
+ badge(data.badge),
206
+ ]))
204
207
  })
205
208
 
209
+ // The app badge a push carries the unread count of: a count sets it, 0 clears it, and a browser without the Badging API leaves it.
210
+ async function badge(count) {
211
+ if (!Number.isSafeInteger(count) || count < 0)
212
+ return
213
+
214
+ try {
215
+ if (count > 0 && self.navigator.setAppBadge)
216
+ await self.navigator.setAppBadge(count)
217
+ else if (count === 0 && self.navigator.clearAppBadge)
218
+ await self.navigator.clearAppBadge()
219
+ }
220
+ catch {}
221
+ }
222
+
206
223
  self.addEventListener('notificationclick', (event) => {
207
224
  event.notification.close()
208
225
 
@@ -37,10 +37,12 @@ export function pushLoose(): boolean {
37
37
  return underKayDev() || looseForTest
38
38
  }
39
39
 
40
+ const MOST_BADGE = 999_999
40
41
  const pending = new Set<Promise<void>>()
41
42
 
42
43
  // Pushes what `notify()` stored to the person's devices without making `notify` wait for the push services, and never fails it.
43
- export function pushAlongside(user: string, message: { title: string, url?: string | undefined }): void {
44
+ // `badge` reads the unread count the app badge shows, once a device is known to be listening.
45
+ export function pushAlongside(user: string, message: { title: string, url?: string | undefined }, badge?: () => Promise<number> | number): void {
44
46
  if (current === undefined)
45
47
  return
46
48
 
@@ -49,7 +51,7 @@ export function pushAlongside(user: string, message: { title: string, url?: stri
49
51
  const { sendPush } = await import('./push')
50
52
 
51
53
  if ((await pushStore().list(user)).length > 0)
52
- await sendPush(user, message)
54
+ await sendPush(user, badge === undefined ? message : { ...message, badge: await countOf(badge) })
53
55
  }
54
56
  catch (error) {
55
57
  kayLog('warn', `notify() could not push a notification to ${user}`, error)
@@ -61,6 +63,18 @@ export function pushAlongside(user: string, message: { title: string, url?: stri
61
63
  void job.finally(() => pending.delete(job))
62
64
  }
63
65
 
66
+ // The badge is a courtesy: a count that cannot be read leaves it out, and one past what a push carries is cut to it.
67
+ async function countOf(badge: () => Promise<number> | number): Promise<number | undefined> {
68
+ try {
69
+ return Math.min(await badge(), MOST_BADGE)
70
+ }
71
+ catch (error) {
72
+ kayLog('warn', 'notify() could not read the unread count for the app badge', error)
73
+
74
+ return undefined
75
+ }
76
+ }
77
+
64
78
  // Resolves once every push `notify()` started has been answered, for a test reading what a push service got.
65
79
  export async function pushesSettled(): Promise<void> {
66
80
  await Promise.all(pending)
@@ -42,6 +42,8 @@ export interface PushMessage {
42
42
  tag?: string | undefined
43
43
  // A path of the site or an http(s) URL of an image.
44
44
  icon?: string | undefined
45
+ // The unread count the installed app's badge shows, set by the worker (`navigator.setAppBadge`) when the push arrives, `0` clearing it; a whole number from 0 to 999999. `notify()` sends the person's unread count.
46
+ badge?: number | undefined
45
47
  }
46
48
 
47
49
  export interface PushSendOptions {
@@ -61,6 +63,7 @@ export interface PushResult {
61
63
 
62
64
  const MAX_BODY = 500
63
65
  const MAX_TAG = 64
66
+ const MAX_BADGE = 999_999
64
67
 
65
68
  export const MOST_DEVICES = 10
66
69
  const MAX_ENDPOINT = 2000
@@ -73,9 +76,9 @@ const DEFAULT_TTL = '1d'
73
76
  const URGENCIES = new Set(['very-low', 'low', 'normal', 'high'])
74
77
  const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]'])
75
78
 
76
- const PUSH_ENV = s.Object({
77
- VAPID_PUBLIC_KEY: s.String({ requiredInProduction: true, description: 'the VAPID public key push services check a push against, a base64url P-256 point; `kay push keys` prints a pair' }),
78
- VAPID_PRIVATE_KEY: s.Secret({ minLength: 43, description: 'the VAPID private key signing pushes, base64url; `kay push keys` prints a pair' }),
79
+ const PUSH_ENV = s.object({
80
+ VAPID_PUBLIC_KEY: s.string({ requiredInProduction: true, description: 'the VAPID public key push services check a push against, a base64url P-256 point; `kay push keys` prints a pair' }),
81
+ VAPID_PRIVATE_KEY: s.secret({ min: 43, description: 'the VAPID private key signing pushes, base64url; `kay push keys` prints a pair' }),
79
82
  })
80
83
 
81
84
  // Lets the site push to the devices of the people who opted in: `sendPush` sends, an island's `webPush.subscribe()` opts in, `notify()` pushes beside the inbox, and kay's service worker shows the notification and opens its link on a click.
@@ -258,7 +261,12 @@ function payloadOf(message: PushMessage): Uint8Array<ArrayBuffer> {
258
261
  const tag = text(message.tag, MAX_TAG, 'tag')
259
262
  const url = linked(message.url, 'url')
260
263
  const icon = linked(message.icon, 'icon')
261
- const bytes = new TextEncoder().encode(JSON.stringify({ title, ...body === undefined ? {} : { body }, ...url === undefined ? {} : { url }, ...tag === undefined ? {} : { tag }, ...icon === undefined ? {} : { icon } }))
264
+ const { badge } = message
265
+
266
+ if (badge !== undefined && (!Number.isSafeInteger(badge) || badge < 0 || badge > MAX_BADGE))
267
+ throw new KayError('argument-invalid', `kay: a push's badge is a whole number from 0 to ${MAX_BADGE}; got ${JSON.stringify(badge)}`)
268
+
269
+ const bytes = new TextEncoder().encode(JSON.stringify({ title, ...body === undefined ? {} : { body }, ...url === undefined ? {} : { url }, ...tag === undefined ? {} : { tag }, ...icon === undefined ? {} : { icon }, ...badge === undefined ? {} : { badge } }))
262
270
 
263
271
  if (bytes.length > MAX_PAYLOAD_BYTES)
264
272
  throw new KayError('argument-invalid', `kay: a push payload is at most ${MAX_PAYLOAD_BYTES} bytes; got ${bytes.length}`)
@@ -97,13 +97,20 @@ function layoutDeclares(modules: object[]): boolean {
97
97
  return false
98
98
  }
99
99
 
100
+ // A search parameter the schema does not name is no one's to refuse: a link carries `utm_source`, a proxy adds its own. The schema reads the ones it declares, whatever its `extra`.
101
+ function declaredOnly(schema: TSchema, input: Record<string, unknown>): Record<string, unknown> {
102
+ const { properties } = schema as ObjectSchema
103
+
104
+ return properties === undefined ? input : Object.fromEntries(Object.entries(input).filter(([name]) => Object.hasOwn(properties, name)))
105
+ }
106
+
100
107
  // `ctx.query`: the search params read against the page's `query` schema, a refusal answering 400, except for a field marked `lenient`, which a value it refuses leaves to its default.
101
108
  // Without a schema, each parameter's text, a repeated one as a list.
102
109
  export function readQuery(schema: unknown, url: URL): Readonly<Record<string, unknown>> {
103
- const input = searchInput(url)
104
-
105
110
  if (!isSchema(schema))
106
- return input
111
+ return searchInput(url)
112
+
113
+ const input = declaredOnly(schema, searchInput(url))
107
114
 
108
115
  let read = readFields(schema, input)
109
116
 
@@ -124,10 +131,10 @@ export function readQuery(schema: unknown, url: URL): Readonly<Record<string, un
124
131
 
125
132
  // `ctx.query` for a page that answers a failure, where a layout's load runs although the route's own query was refused, or never read: a field the schema refuses reads as its default, or is left out, so a layout still gets what its types promise.
126
133
  export function readQueryLeniently(schema: unknown, url: URL): Readonly<Record<string, unknown>> {
127
- const input = searchInput(url)
128
-
129
134
  if (!isSchema(schema))
130
- return input
135
+ return searchInput(url)
136
+
137
+ const input = declaredOnly(schema, searchInput(url))
131
138
 
132
139
  const read = readFields(schema, input)
133
140
 
@@ -495,7 +495,7 @@ async function runLoad(file: string, module: PageModule, ctx: PageContext<Record
495
495
  return {}
496
496
 
497
497
  const load = module.load
498
- const run = async () => traced(() => `kay.load ${projectPath(file)}`, {}, async () => inLoad(ctx.url, async () => await load(ctx) ?? {}))
498
+ const run = async () => traced(() => `kay.load ${projectPath(file)}`, {}, async () => inLoad(ctx.url, ctx.request, () => ctx.headers.append('vary', 'cookie'), async () => await load(ctx) ?? {}))
499
499
 
500
500
  if (!timings)
501
501
  return run()