@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
@@ -5,11 +5,11 @@ import { parseProgram, positionOf } from '../compiler/estree'
5
5
  // An Astro content config, `defineCollection` with a zod schema, as kay's: `collection(folder, { schema })` with the schema in `s`.
6
6
 
7
7
  // zod's types and the `s` builder each becomes, for those that take their arguments the same way.
8
- const SAME: Record<string, string> = { string: 'String', number: 'Number', boolean: 'Boolean', date: 'Date', array: 'Array', object: 'Object', literal: 'Literal', any: 'Any', unknown: 'Unknown', null: 'Null' }
9
- // zod's string checks and the `s.String` option each becomes.
10
- const STRING_CHECKS: Record<string, string> = { min: 'minLength', max: 'maxLength', email: 'format', url: 'format', regex: 'pattern' }
8
+ const SAME: Record<string, string> = { string: 'string', number: 'number', boolean: 'boolean', date: 'date', literal: 'literal' }
9
+ // zod's string checks and the `s.string` option each becomes.
10
+ const STRING_CHECKS: Record<string, string> = { min: 'min', max: 'max', email: 'format', url: 'format', regex: 'pattern' }
11
11
  const LEADING_DOT_SLASH = /^\.\//
12
- const NUMBER_CHECKS: Record<string, string> = { min: 'minimum', max: 'maximum', gte: 'minimum', lte: 'maximum' }
12
+ const NUMBER_CHECKS: Record<string, string> = { min: 'min', max: 'max', gte: 'min', lte: 'max' }
13
13
  const CHECKS_BY_KIND = new Map([['string', STRING_CHECKS], ['number', NUMBER_CHECKS]])
14
14
 
15
15
  class SchemaTranslator {
@@ -39,7 +39,7 @@ class SchemaTranslator {
39
39
 
40
40
  // The schema helper Astro passes, `schema: ({ image }) => z.object(...)`.
41
41
  if (current.type === 'CallExpression' && current.callee.type === 'Identifier' && current.callee.name === 'image')
42
- return chain.length === 0 ? 's.String()' : this.modifiers('s.String()', chain, node)
42
+ return this.image(chain, node)
43
43
 
44
44
  const base = chain.shift()
45
45
 
@@ -48,74 +48,80 @@ class SchemaTranslator {
48
48
 
49
49
  const kind = base.callee.property.name
50
50
  const args = base.arguments
51
- let built: string
52
- let integer = false
53
- const options: string[] = []
54
- const checks = CHECKS_BY_KIND.get(kind)
55
- const rest: CallExpression[] = []
56
-
57
- for (const call of chain) {
58
- const name = call.callee.type === 'MemberExpression' && call.callee.property.type === 'Identifier' ? call.callee.property.name : ''
59
- const option = checks?.[name]
51
+ const { options, integer, rest } = this.chain(kind, chain)
60
52
 
61
- if (option === 'format')
62
- options.push(`format: '${name === 'url' ? 'uri' : 'email'}'`)
63
- else if (option === 'pattern' && call.arguments[0]?.type === 'Literal' && 'regex' in call.arguments[0])
64
- options.push(`pattern: ${JSON.stringify((call.arguments[0] as { regex: { pattern: string } }).regex.pattern)}`)
65
- else if (option !== undefined && call.arguments[0])
66
- options.push(`${option}: ${this.text(call.arguments[0])}`)
67
- else if (kind === 'number' && name === 'int')
68
- integer = true
69
- else
70
- rest.push(call)
71
- }
53
+ if (rest[0])
54
+ return this.untranslated(node, `.${methodName(rest[0])}() has no \`s\` counterpart kay migrate knows`)
72
55
 
73
56
  if (kind === 'object' && args[0]?.type === 'ObjectExpression') {
74
57
  const fields = args[0].properties.map(property => isPlain(property) ? `${this.text(property.key)}: ${this.schema(property.value)}` : this.untranslated(property, 'a spread in an object schema'))
75
58
 
76
- built = `s.Object({ ${fields.join(', ')} })`
77
- }
78
- else if (kind === 'array' && args[0]) {
79
- built = `s.Array(${this.schema(args[0])}${options.length > 0 ? `, { ${options.join(', ')} }` : ''})`
59
+ return this.call('s.object', [`{ ${fields.join(', ')} }`], options)
80
60
  }
81
- else if (kind === 'enum' && args[0]?.type === 'ArrayExpression') {
82
- built = `s.Union([${args[0].elements.map(element => element ? `s.Literal(${this.text(element)})` : '').join(', ')}])`
83
- }
84
- else if (kind === 'union' && args[0]?.type === 'ArrayExpression') {
85
- built = `s.Union([${args[0].elements.map(element => element ? this.schema(element) : '').join(', ')}])`
86
- }
87
- else if (kind === 'coerce' || !(kind in SAME)) {
61
+
62
+ if (kind === 'array' && args[0])
63
+ return this.call('s.list', [this.schema(args[0])], options)
64
+
65
+ if (kind === 'enum' && args[0]?.type === 'ArrayExpression')
66
+ return this.call('s.enum', [this.text(args[0])], options)
67
+
68
+ if (kind === 'union' && args[0]?.type === 'ArrayExpression')
69
+ return this.call('s.union', [`[${args[0].elements.map(element => element ? this.schema(element) : '').join(', ')}]`], options)
70
+
71
+ if (kind === 'coerce' || !(kind in SAME))
88
72
  return this.untranslated(node, `z.${kind} has no \`s\` counterpart kay migrate knows`)
89
- }
90
- else {
91
- const builder = integer ? 's.Integer' : `s.${SAME[kind]}`
92
73
 
93
- built = `${builder}(${[...args.map(arg => this.text(arg)), ...options.length > 0 ? [`{ ${options.join(', ')} }`] : []].join(', ')})`
94
- }
74
+ return this.call(integer ? 's.int' : `s.${SAME[kind]}`, args.map(arg => this.text(arg)), options)
75
+ }
76
+
77
+ // The `image()` helper: a string, whatever follows it in the chain.
78
+ private image(chain: CallExpression[], node: Node): string {
79
+ const { options, rest } = this.chain('image', chain)
95
80
 
96
- return this.modifiers(built, rest, node)
81
+ return rest[0] ? this.untranslated(node, `.${methodName(rest[0])}() has no \`s\` counterpart kay migrate knows`) : this.call('s.string', [], options)
97
82
  }
98
83
 
99
- private modifiers(built: string, calls: CallExpression[], node: Node): string {
100
- let result = built
84
+ // `s.string({ min: 1 })`: the builder, its arguments, then the options when there are any.
85
+ private call(builder: string, args: string[], options: string[]): string {
86
+ return `${builder}(${[...args, ...options.length > 0 ? [`{ ${options.join(', ')} }`] : []].join(', ')})`
87
+ }
88
+
89
+ // The calls after a zod type: the checks that are options of the builder, `.optional()` and `.default()`, and what has no counterpart.
90
+ private chain(kind: string, chain: CallExpression[]): { options: string[], integer: boolean, rest: CallExpression[] } {
91
+ const checks = CHECKS_BY_KIND.get(kind)
92
+ const options: string[] = []
93
+ const rest: CallExpression[] = []
94
+ let integer = false
101
95
 
102
- for (const call of calls) {
103
- const name = call.callee.type === 'MemberExpression' && call.callee.property.type === 'Identifier' ? call.callee.property.name : ''
96
+ for (const call of chain) {
97
+ const name = methodName(call)
98
+ const option = checks?.[name]
99
+ const first = call.arguments[0]
104
100
 
105
- if (name === 'optional' || name === 'nullish')
106
- result = `s.Optional(${result})`
107
- else if (name === 'nullable')
108
- result = `s.Nullable(${result})`
109
- else if (name === 'default' && call.arguments[0])
110
- result = result.endsWith(')') && !result.startsWith('s.Optional(') ? `${result.slice(0, -1)}${result.endsWith('()') ? '' : ', '}{ default: ${this.text(call.arguments[0])} })` : this.untranslated(node, '`.default` on a schema already given options')
101
+ if (option === 'format')
102
+ options.push(`format: '${name === 'url' ? 'uri' : 'email'}'`)
103
+ else if (option === 'pattern' && first?.type === 'Literal' && 'regex' in first)
104
+ options.push(`pattern: ${JSON.stringify((first as { regex: { pattern: string } }).regex.pattern)}`)
105
+ else if (option !== undefined && first)
106
+ options.push(`${option}: ${this.text(first)}`)
107
+ else if (kind === 'number' && name === 'int')
108
+ integer = true
109
+ else if (name === 'optional' || name === 'nullish')
110
+ options.push('optional: true')
111
+ else if (name === 'default' && first)
112
+ options.push(`default: ${this.text(first)}`)
111
113
  else
112
- return this.untranslated(node, `.${name}() has no \`s\` counterpart kay migrate knows`)
114
+ rest.push(call)
113
115
  }
114
116
 
115
- return result
117
+ return { options, integer, rest }
116
118
  }
117
119
  }
118
120
 
121
+ function methodName(call: CallExpression): string {
122
+ return call.callee.type === 'MemberExpression' && call.callee.property.type === 'Identifier' ? call.callee.property.name : ''
123
+ }
124
+
119
125
  function literalKey(key: Node): string | undefined {
120
126
  if (key.type === 'Identifier')
121
127
  return key.name
@@ -235,7 +241,7 @@ function collectionsOf(object: ObjectExpression, declared: Map<string, CallExpre
235
241
  if (folder === undefined)
236
242
  notes.push({ line: positionOf(source, call.start).line, message: `the collection ${name} uses a loader other than \`glob({ base })\`: kay reads a folder of files, so give it the folder` })
237
243
 
238
- result.push(`export const ${name} = collection('${folder ?? `content/${name}`}', {\n schema: ${schema ? translator.schema(schema) : 's.Object({})'},\n})`)
244
+ result.push(`export const ${name} = collection('${folder ?? `content/${name}`}', {\n schema: ${schema ? translator.schema(schema) : 's.object({})'},\n})`)
239
245
  }
240
246
 
241
247
  return result
@@ -242,9 +242,9 @@ export interface ActionContext<Params extends Readonly<Record<string, unknown>>
242
242
  fail: <const Data = undefined, const Status extends number = number>(status: Status & ErrorStatus<Status>, data?: Data, errors?: FieldErrors<Field>) => Failure<Data>
243
243
  }
244
244
 
245
- // `ctx.deny` of an action: a refusal with `data` or `errors` is typed as a `Failure`, one with a message alone (or none) is `never`, so it narrows what follows as a guard's does.
245
+ // `ctx.deny` of an action: a refusal with a `message`, `data` or `errors` is typed as a `Failure`, one with no options is `never`, so it narrows what follows as a guard's does.
246
246
  export interface ActionDeny<Field extends string = string> {
247
- <const Status extends number = number>(status?: Status & ErrorStatus<Status>, options?: { message?: string | undefined, errors?: undefined, data?: undefined }): never
247
+ <const Status extends number = number>(status?: Status & ErrorStatus<Status>, options?: { message?: undefined, errors?: undefined, data?: undefined }): never
248
248
  <const Data = undefined, const Status extends number = number>(status: Status & ErrorStatus<Status>, options: DenyOptions<Data, Field>): Failure<Data>
249
249
  // What a helper taking the guard's `deny` sees: an action's context passes as one.
250
250
  <const Status extends number = number>(status?: Status & ErrorStatus<Status>, options?: DenyOptions<ErrorData>): never
@@ -2,11 +2,13 @@ import type { t } from 'elysia'
2
2
  import type { ActionContext, ActionProtection, Answer, Called, CallOptions, OutputSchema, ServerAction, Settled, Success } from './action-shared'
3
3
  import type { RouteParams } from './checks'
4
4
  import type { Schema, Static } from './schema'
5
+ import type { ObjectOf, SchemaShape } from './schema-record'
5
6
  import { callable } from './action-call'
6
7
  import { minTimeOf, resolveProtection, workOf } from './action-protection'
7
8
  import { ACTION, isAction } from './action-shared'
8
9
  import { durationSeconds } from './duration'
9
10
  import { KayError } from './kay-error'
11
+ import { schemaOf } from './schema-record'
10
12
  import { ACTION_PREFIX } from './wire'
11
13
 
12
14
  export { actionStub, OUTCOME_SCRIPT, setRequestOutcome } from './action-call'
@@ -44,13 +46,15 @@ const emptySchema = () => ({ [Symbol.for('TypeBox.Kind')]: 'Object', type: 'obje
44
46
  export interface ActionFor<Params extends Readonly<Record<string, unknown>>, Guarded extends object = object> {
45
47
  <Output, const Honeypot extends string = never, Shape extends OutputSchema = OutputSchema>(handler: (ctx: ActionContext<Params, string, Guarded>) => Output | Promise<Output>, protection?: ActionProtection<Honeypot, Success<Settled<Output>>, Shape>): NoInputAction<Settled<Output>, Honeypot>
46
48
  <Spec extends Schema, Output, const Honeypot extends string = never, Shape extends OutputSchema = OutputSchema>(schema: Spec, handler: (input: Static<Spec>, ctx: ActionContext<Params, Extract<keyof Static<Spec>, string>, Guarded>) => Output | Promise<Output>, protection?: ActionProtection<Honeypot, Success<Settled<Output>>, Shape>): ServerAction<Spec, Settled<Output>, Honeypot>
49
+ <const Fields extends SchemaShape, Output, const Honeypot extends string = never, Shape extends OutputSchema = OutputSchema>(fields: Fields, handler: (input: Static<ObjectOf<Fields>>, ctx: ActionContext<Params, Extract<keyof Static<ObjectOf<Fields>>, string>, Guarded>) => Output | Promise<Output>, protection?: ActionProtection<Honeypot, Success<Settled<Output>>, Shape>): ServerAction<ObjectOf<Fields>, Settled<Output>, Honeypot>
47
50
  }
48
51
 
49
- // Declares a server action in a page's `--- server` fence: Elysia validates the input against `schema` before `handler` runs.
52
+ // Declares a server action in a page's `--- server` fence: Elysia validates the input against `schema` before `handler` runs, `schema` a plain record of fields as well as a schema.
50
53
  // Without a schema the action takes no input, as with an empty object schema, and its handler gets the context alone.
51
54
  // kept: free, it registers a route answering a POST, which the page's own render never runs, and a kept page is refreshed after the first request that can write.
52
55
  export function action<Output, const Honeypot extends string = never, Shape extends OutputSchema = OutputSchema>(handler: (ctx: ActionContext) => Output | Promise<Output>, protection?: ActionProtection<Honeypot, Success<Settled<Output>>, Shape>): NoInputAction<Settled<Output>, Honeypot>
53
56
  export function action<Spec extends Schema, Output, const Honeypot extends string = never, Shape extends OutputSchema = OutputSchema>(schema: Spec, handler: (input: Static<Spec>, ctx: ActionContext<RouteParams, Extract<keyof Static<Spec>, string>>) => Output | Promise<Output>, protection?: ActionProtection<Honeypot, Success<Settled<Output>>, Shape>): ServerAction<Spec, Settled<Output>, Honeypot>
57
+ export function action<const Fields extends SchemaShape, Output, const Honeypot extends string = never, Shape extends OutputSchema = OutputSchema>(fields: Fields, handler: (input: Static<ObjectOf<Fields>>, ctx: ActionContext<RouteParams, Extract<keyof Static<ObjectOf<Fields>>, string>>) => Output | Promise<Output>, protection?: ActionProtection<Honeypot, Success<Settled<Output>>, Shape>): ServerAction<ObjectOf<Fields>, Settled<Output>, Honeypot>
54
58
  export function action(first: unknown, second?: unknown, third?: ActionProtection<string>): unknown {
55
59
  if (typeof first === 'function') {
56
60
  const handler = first as (ctx: ActionContext) => unknown
@@ -58,7 +62,7 @@ export function action(first: unknown, second?: unknown, third?: ActionProtectio
58
62
  return declare(emptySchema(), (_input, ctx) => handler(ctx), second as ActionProtection<string> | undefined)
59
63
  }
60
64
 
61
- return declare(first as Schema, second as (input: unknown, ctx: ActionContext) => unknown, third)
65
+ return declare(schemaOf(first as Schema | SchemaShape), second as (input: unknown, ctx: ActionContext) => unknown, third)
62
66
  }
63
67
 
64
68
  export function declare(schema: Schema, handler: (input: unknown, ctx: ActionContext) => unknown, options: ActionProtection<string> | undefined): ServerAction<Schema, unknown> {
@@ -0,0 +1,99 @@
1
+ import type { FieldSchema } from './form'
2
+ import { escape, escapeAttribute } from './escape'
3
+
4
+ // The `autocomplete` token a field name asks for, as the HTML spec words it: `firstName`, `first_name` and `given-name` are the one field.
5
+ const NAMED_AUTOCOMPLETE = new Map([
6
+ ['firstname', 'given-name'],
7
+ ['givenname', 'given-name'],
8
+ ['lastname', 'family-name'],
9
+ ['familyname', 'family-name'],
10
+ ['surname', 'family-name'],
11
+ ['username', 'username'],
12
+ ['email', 'email'],
13
+ ['phone', 'tel'],
14
+ ['tel', 'tel'],
15
+ ['telephone', 'tel'],
16
+ ['zip', 'postal-code'],
17
+ ['postalcode', 'postal-code'],
18
+ ['postcode', 'postal-code'],
19
+ ['currentpassword', 'current-password'],
20
+ ['newpassword', 'new-password'],
21
+ ['otp', 'one-time-code'],
22
+ ['birthday', 'bday'],
23
+ ])
24
+ const NAME_SEPARATORS = /[\s_-]+/g
25
+
26
+ // The input type a field's schema asks for: `email` and `url` for their formats, `number` for a number, `date` for a date, `checkbox` for a boolean and `file` for an upload, which also takes the `accept` of its media types and `multiple` for a list of files.
27
+ export function typeAttributes(field: FieldSchema, numeric: boolean, boolean: boolean): [name: string, value: string][] {
28
+ if (field.type === 'string' && field.format === 'binary')
29
+ return fileAttributes(field, false)
30
+
31
+ if (field.type === 'array' && field.items?.format === 'binary')
32
+ return fileAttributes(field, true)
33
+
34
+ if (field.type === 'string' && (field.format === 'email' || field.format === 'url'))
35
+ return [['type', field.format]]
36
+
37
+ if (boolean)
38
+ return [['type', 'checkbox']]
39
+
40
+ if (numeric)
41
+ return [['type', 'number'], ...integral(field) ? [] : [['step', 'any'] as [string, string]]]
42
+
43
+ return isDate(field) ? [['type', 'date']] : []
44
+ }
45
+
46
+ function fileAttributes(field: FieldSchema, multiple: boolean): [string, string][] {
47
+ const accepted = (field as { extension?: unknown }).extension
48
+ const accept = Array.isArray(accepted) ? accepted.filter(type => typeof type === 'string').join(',') : accepted
49
+
50
+ return [['type', 'file'], ...typeof accept === 'string' && accept !== '' ? [['accept', accept] as [string, string]] : [], ...multiple ? [['multiple', ''] as [string, string]] : []]
51
+ }
52
+
53
+ // A whole number takes the browser's own step of 1; any other number needs `any`, or the browser refuses a decimal.
54
+ function integral(field: FieldSchema): boolean {
55
+ return field.type === 'integer' || (field.anyOf?.some(member => member.type === 'integer' || member.format === 'integer') ?? false)
56
+ }
57
+
58
+ function isDate(field: FieldSchema): boolean {
59
+ return field.type === 'Date' || (field.anyOf?.some(member => member.type === 'Date') ?? false)
60
+ }
61
+
62
+ // What the field says itself with `autocomplete`, else what its format or its name asks for.
63
+ export function autocompleteOf(field: FieldSchema, name: string): string | undefined {
64
+ const own = (field as { autocomplete?: unknown }).autocomplete
65
+
66
+ if (typeof own === 'string')
67
+ return own
68
+
69
+ if (field.type !== 'string' || field.format === 'binary')
70
+ return undefined
71
+
72
+ return field.format === 'email' || field.format === 'url' ? field.format : autocompleteByName(name)
73
+ }
74
+
75
+ // The token a field name asks for, whatever its schema says.
76
+ export function autocompleteByName(name: string): string | undefined {
77
+ return NAMED_AUTOCOMPLETE.get(name.replace(NAME_SEPARATORS, '').toLowerCase())
78
+ }
79
+
80
+ // The options of a `select(field=...)` that writes none: one per value of the field's enum, worded by the `x-labels` an `s.enum` of a record keeps, and a blank first one for a field the form may leave out.
81
+ export function optionsOf(field: FieldSchema | undefined, required: boolean): string {
82
+ // An `s.enum`, or an `s.union` of `s.literal`s.
83
+ const values = (field as { enum?: unknown } | undefined)?.enum ?? (field?.anyOf?.every(member => member.const !== undefined) ? field.anyOf.map(member => member.const) : undefined)
84
+
85
+ if (!Array.isArray(values))
86
+ return ''
87
+
88
+ const labels = (field as { 'x-labels'?: Record<string, unknown> })['x-labels']
89
+ let markup = required ? '' : '<option value=""></option>'
90
+
91
+ for (const value of values) {
92
+ const text = String(value)
93
+ const label = labels?.[text]
94
+
95
+ markup += `<option value="${escapeAttribute(text).replaceAll('>', '&gt;')}">${escape(typeof label === 'string' ? label : text)}</option>`
96
+ }
97
+
98
+ return markup
99
+ }
@@ -1,4 +1,5 @@
1
1
  import type { TSchema } from 'elysia'
2
+ import { autocompleteOf, typeAttributes } from './form-types'
2
3
 
3
4
  // What a top-level field's JSON schema says about the text a form posts for it.
4
5
  export interface FieldSchema {
@@ -51,7 +52,7 @@ export function formInput(schema: TSchema, body: unknown, form = true): unknown
51
52
 
52
53
  if (value === undefined) {
53
54
  // A required list may well be empty, and an unticked checkbox posts nothing; a required file list is no file chosen, refused as missing.
54
- if (form && !optional && ((field.type === 'array' && field.items?.format !== 'binary') || field.type === 'boolean'))
55
+ if (form && !optional && ((field.type === 'array' && field.items?.format !== 'binary') || isBoolean(field)))
55
56
  fields[name] = field.type === 'array' ? [] : false
56
57
 
57
58
  continue
@@ -92,26 +93,31 @@ function fromText(field: FieldSchema | undefined, value: unknown): unknown {
92
93
  if (field !== undefined && isNumeric(field))
93
94
  return DECIMAL.test(value) ? Number(value) : Number.NaN
94
95
 
95
- if (field?.type === 'boolean')
96
+ if (field !== undefined && isBoolean(field))
96
97
  return BOOLEAN_TEXT.get(value) ?? value
97
98
 
98
99
  // A form posts a line break as CRLF, where the textarea the visitor typed in holds and counts it as one character: read as LF, a `maxLength` matches what the browser allowed and the text is stored as it was written.
99
100
  return value.includes('\r') ? value.replaceAll(CRLF, '\n') : value
100
101
  }
101
102
 
103
+ // A boolean, or the text of one as `s.boolean()` reads it.
104
+ export function isBoolean(field: FieldSchema): boolean {
105
+ return field.type === 'boolean' || (field.anyOf?.some(member => member.type === 'boolean') ?? false)
106
+ }
107
+
102
108
  // `s.Number()`, or `s.Integer()` and `s.Numeric()`, which Elysia writes as a number or a numeric string; `s.Date()` takes a number too, but not only.
103
109
  function isNumeric(field: FieldSchema): boolean {
104
110
  return field.type === 'number' || field.type === 'integer' || (field.anyOf?.every(member => isNumeric(member) || NUMERIC_FORMATS.has(member.format)) ?? false)
105
111
  }
106
112
 
107
113
  // The attributes a browser checks a field against without JavaScript, where a keyword of its schema has one; `required` only where the server would refuse the field left blank, as it never does an unticked checkbox.
108
- export function nativeConstraints(field: FieldSchema, required: boolean): [name: string, value: string][] {
114
+ export function nativeConstraints(field: FieldSchema, required: boolean, name?: string): [name: string, value: string][] {
109
115
  const found: [string, string][] = []
110
116
 
111
117
  if (required && refusesBlank(field))
112
118
  found.push(['required', ''])
113
119
 
114
- if (field.type === 'string') {
120
+ if (field.type === 'string' && field.format !== 'binary') {
115
121
  if (typeof field.minLength === 'number' && field.minLength > 0)
116
122
  found.push(['minlength', String(field.minLength)])
117
123
 
@@ -122,9 +128,6 @@ export function nativeConstraints(field: FieldSchema, required: boolean): [name:
122
128
 
123
129
  if (pattern !== undefined)
124
130
  found.push(['pattern', pattern])
125
-
126
- if (field.format === 'email')
127
- found.push(['type', 'email'])
128
131
  }
129
132
 
130
133
  if (isNumeric(field)) {
@@ -135,9 +138,21 @@ export function nativeConstraints(field: FieldSchema, required: boolean): [name:
135
138
  found.push(['max', String(field.maximum)])
136
139
  }
137
140
 
141
+ found.push(...typeAttributes(field, isNumeric(field), isBoolean(field)))
142
+
143
+ const autocomplete = name === undefined ? undefined : autocompleteOf(field, name)
144
+
145
+ if (autocomplete !== undefined)
146
+ found.push(['autocomplete', autocomplete])
147
+
138
148
  return found
139
149
  }
140
150
 
151
+ // The `type` an input takes from the field's schema, none for a field with no particular one.
152
+ export function schemaInputType(field: FieldSchema): string | undefined {
153
+ return typeAttributes(field, isNumeric(field), isBoolean(field)).find(([name]) => name === 'type')?.[1]
154
+ }
155
+
141
156
  function refusesBlank(field: FieldSchema): boolean {
142
157
  if (field.const !== undefined)
143
158
  return field.const !== ''
@@ -9,7 +9,8 @@ import { NON_ROOT_TRAILING_SLASH } from './base'
9
9
  import { fieldDescription, fieldInvalid, fieldRequired } from './described'
10
10
  import { escape, escapeAttribute } from './escape'
11
11
  import { fieldMarks, markedAttribute, markedList, markedText, withFieldMarks } from './fields'
12
- import { nativeConstraints } from './form'
12
+ import { isBoolean, nativeConstraints, schemaInputType } from './form'
13
+ import { optionsOf } from './form-types'
13
14
  import { DATA_SCRIPT, headCheckpoint, LEADING_NEWLINE, restoreHead } from './head'
14
15
  import { localizedLink } from './i18n'
15
16
  import { imageSource } from './image'
@@ -639,20 +640,50 @@ export function refillOptions(posted: string | undefined, markup: string, value?
639
640
  return initial === undefined ? markup : selectOptions(initial, markup, true)
640
641
  }
641
642
 
642
- // The constraints a `field` checks in the browser without JavaScript, read off the schema of the action its form posts to; those the template writes itself are left to it.
643
+ interface ActionSchema { properties?: Record<string, FieldSchema>, required?: string[] }
644
+
645
+ function schemaOf(target: unknown): ActionSchema | undefined {
646
+ return isAction(target) ? (target as { schema?: ActionSchema }).schema : undefined
647
+ }
648
+
649
+ // The attributes that only mean something with the `type` the schema gave, so a template writing its own leaves them out.
650
+ const TYPED = new Set(['accept', 'multiple', 'step'])
651
+
652
+ // The constraints and the `type` and `autocomplete` a `field` takes in the browser without JavaScript, read off the schema of the action its form posts to; those the template writes itself are left to it.
643
653
  export function formConstraints(target: unknown, name: string, written: readonly string[]): string {
644
- const schema = isAction(target) ? (target as { schema?: { properties?: Record<string, FieldSchema>, required?: string[] } }).schema : undefined
654
+ const schema = schemaOf(target)
645
655
  const field = schema?.properties?.[name]
646
656
 
647
657
  if (!field)
648
658
  return ''
649
659
 
650
- return nativeConstraints(field, schema.required?.includes(name) === true)
651
- .filter(([attribute]) => !written.includes(attribute))
660
+ return nativeConstraints(field, schema.required?.includes(name) === true, name)
661
+ .filter(([attribute]) => !written.includes(attribute) && !(TYPED.has(attribute) && written.includes('type')))
652
662
  .map(([attribute, value]) => value === '' ? ` ${attribute}` : ` ${attribute}="${escapeAttribute(value)}"`)
653
663
  .join('')
654
664
  }
655
665
 
666
+ // The options of a `select(field=...)` written with none, from the enum of the field in the schema of the action its form posts to.
667
+ export function formOptions(target: unknown, name: string): string {
668
+ const schema = schemaOf(target)
669
+
670
+ return optionsOf(schema?.properties?.[name], schema?.required?.includes(name) === true)
671
+ }
672
+
673
+ // The `type` the schema gives an input that writes none, which a component requiring the field reads to know a file or a checkbox.
674
+ export function formType(target: unknown, name: string): string | undefined {
675
+ const field = schemaOf(target)?.properties?.[name]
676
+
677
+ return field && schemaInputType(field)
678
+ }
679
+
680
+ // Which of two fills an `input(field=...)` with no `type` takes: a ticked box for a boolean of the schema, else a value.
681
+ export function schemaFill(target: unknown, name: string, value: (type: string | undefined) => string, checked: () => string): string {
682
+ const field = schemaOf(target)?.properties?.[name]
683
+
684
+ return field && isBoolean(field) ? checked() : value(field && schemaInputType(field) === 'date' ? 'date' : undefined)
685
+ }
686
+
656
687
  // The `p` an `error` line shows a refused form's message in, nothing while there is none.
657
688
  export function errorParagraph(message: string | undefined, id: string, classes: string): string {
658
689
  return message === undefined ? '' : `<p${id === '' ? '' : ` id="${escapeAttribute(id)}"`} class="${escapeAttribute(classes)}">${escape(message)}</p>`
@@ -0,0 +1,69 @@
1
+ // Where Bun.markdown (md4c) ends a bare URL, which marked's own rule does not match: a URL starts after a space, a line start or an opening bracket, its host has a dot, and each of its path, query and fragment takes the characters below. A trailing `.`, a `&` before an entity or a closing bracket stays out of the link, and one ending in `_`, `-`, `~`, `=` or any other mark is not a link at all.
2
+ const SCHEME = /(?:https?|ftp):\/\/|www\./iy
3
+ const HOST = /[a-z\d](?:[\w-]|\.(?=[\w-]))*/iy
4
+ const ALNUM_END = /[a-z\d]$/i
5
+ const NEXT = /[\s.,!?;&)\]<}]|$/y
6
+ const LABEL = /(?:https?|ftp):\/\/[\w.-]*|www\.[\w.-]*/iy
7
+ // How far a URL is read: a scan that fails runs to the end of its path, which hostile text repeats, and a longer URL stays text.
8
+ const REACH = 2000
9
+ const OPENERS = /[\s([{]$/
10
+ // Each part, what it may end with and the closers its last character may be followed by instead.
11
+ const PARTS: [RegExp, RegExp, RegExp][] = [
12
+ [/\/(?:[\w~%+*/-]|\.(?=[\w~%+*/.-]))*/y, /[a-z\d/]$/i, /\./],
13
+ [/\?[a-z\d](?:[\w~%+*=-]|\.(?=[\w~%+*=.&()-])|&(?!#?[a-z\d]+;)(?=[\w~%+*=.&()-])|\([\w~%+*=.-]*\)|[()](?=[\w~%+*=.&()-]))*/iy, /[a-z\d)]$/i, /[.&)]/],
14
+ [/#[a-z\d](?:[\w~%+*-]|\.(?=[\w~%+*.-]))*/iy, ALNUM_END, /\./],
15
+ ]
16
+
17
+ function match(pattern: RegExp, text: string, at: number): string | undefined {
18
+ pattern.lastIndex = at
19
+
20
+ return pattern.exec(text)?.[0]
21
+ }
22
+
23
+ /** The length of the bare URL `text` starts with, 0 when it is not one. */
24
+ export function autolinkLength(whole: string): number {
25
+ const text = whole.slice(0, REACH)
26
+ const scheme = match(SCHEME, text, 0)
27
+ const host = scheme === undefined ? undefined : match(HOST, text, scheme.length)
28
+
29
+ if (scheme === undefined || host === undefined || (!ALNUM_END.test(host) && text[scheme.length + host.length] !== '.') || (scheme.length !== 4 && !host.includes('.')))
30
+ return 0
31
+
32
+ let end = scheme.length + host.length
33
+
34
+ for (const [pattern, last, closer] of PARTS) {
35
+ const found = match(pattern, text, end)
36
+
37
+ if (found === undefined)
38
+ continue
39
+
40
+ if (!last.test(found) && !closer.test(text[end + found.length] ?? ''))
41
+ return 0
42
+
43
+ end += found.length
44
+ }
45
+
46
+ return endsAutolink(text, end) && (end < REACH || whole.length === REACH) ? end : 0
47
+ }
48
+
49
+ /** The start of a URL that `text` starts with: the part marked leaves as text when a word is stuck to it. */
50
+ export function gluedLength(text: string): number {
51
+ return match(LABEL, text, 0)?.length ?? 0
52
+ }
53
+
54
+ /** Whether `text` starts like a bare URL, which may still not be one. */
55
+ export function startsAutolink(text: string): boolean {
56
+ return match(SCHEME, text, 0) !== undefined
57
+ }
58
+
59
+ /** Whether `text` goes on after a link of `length` characters the way Bun.markdown lets one end. */
60
+ export function endsAutolink(text: string, length: number): boolean {
61
+ NEXT.lastIndex = length
62
+
63
+ return NEXT.test(text)
64
+ }
65
+
66
+ /** Whether a URL may start after `before`, the text it follows in its line. */
67
+ export function opensAutolink(before: string): boolean {
68
+ return before === '' || OPENERS.test(before)
69
+ }
@@ -1,8 +1,10 @@
1
1
  import type { RendererObject, Token, TokenizerObject, Tokens } from 'marked'
2
2
  import type { SafeHtml } from './checks'
3
+ import type { MarkdownOptions } from './markdown'
3
4
  import { Marked, Tokenizer } from 'marked'
4
5
  import { escapeMarkdownText as escape } from './escape'
5
- import { sanitizedMarkdown } from './markdown'
6
+ import { sanitizedMarkdown, withInline } from './markdown'
7
+ import { autolinkLength, endsAutolink, gluedLength, opensAutolink, startsAutolink } from './markdown-autolink'
6
8
  import { vouch } from './safe-html'
7
9
 
8
10
  const TEXT_ESCAPED = /&(?![a-z][a-z\d]{1,31};)|[<>"]/gi
@@ -10,6 +12,7 @@ const ESCAPES: Record<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;'
10
12
  const REFERENCE = /&(?:#(\d{1,7})|#x([\da-f]{1,6})|(amp|lt|gt|quot|apos|nbsp));/gi
11
13
  const NAMED: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '"', apos: '\'', nbsp: '\u00A0' }
12
14
  const FIRST_WORD = /^\S*/
15
+ const PROTOCOL = /^(?:mailto|xmpp):/i
13
16
  const BARE_TASK = /^\[([ x])\]$/i
14
17
  const TRAILING_LINES = /\n+$/
15
18
  const LINE_INDENT = /^[ \t]+/gm
@@ -135,7 +138,35 @@ function within(src: string, maskedSrc: string): [string, string] {
135
138
  return [src.slice(0, DELIMITER_REACH), maskedSrc.slice(0, maskedSrc.length - src.length + Math.min(src.length, DELIMITER_REACH))]
136
139
  }
137
140
 
141
+ // marked's address autolink where Bun.markdown ends it too.
142
+ function emailToken(tokenizer: Tokenizer, src: string): Tokens.Link | undefined {
143
+ const token = DEFAULTS.url.call(tokenizer, src)
144
+
145
+ return token && endsAutolink(src, token.raw.length) ? token : undefined
146
+ }
147
+
148
+ // The tokens Bun.markdown writes for a bare URL: it links where md4c does, and a URL stuck to the text before it stays text.
138
149
  const tokenizer: TokenizerObject = {
150
+ url(src) {
151
+ if (!startsAutolink(src))
152
+ return PROTOCOL.test(src) ? undefined : emailToken(this, src)
153
+
154
+ const length = autolinkLength(src)
155
+ const raw = src.slice(0, length)
156
+
157
+ return length === 0 ? undefined : { type: 'link', raw, text: raw, href: raw.toLowerCase().startsWith('www.') ? `http://${raw}` : raw, autolink: true, tokens: [{ type: 'text', raw, text: raw }] }
158
+ },
159
+ inlineText(src) {
160
+ const token = DEFAULTS.inlineText.call(this, src)
161
+
162
+ if (token === undefined || opensAutolink(token.raw))
163
+ return token
164
+
165
+ const rest = src.slice(token.raw.length)
166
+ const glued = startsAutolink(rest) ? rest.slice(0, gluedLength(rest)) : emailToken(this, rest)?.raw
167
+
168
+ return glued === undefined ? token : { ...token, raw: token.raw + glued, text: token.text + glued }
169
+ },
139
170
  emStrong(src, maskedSrc, prevChar) {
140
171
  return src.length > DELIMITER_REACH && DEFAULTS.emStrong.call(this, ...within(src, maskedSrc), prevChar)
141
172
  },
@@ -149,15 +180,20 @@ const marked = new Marked({ gfm: true, async: false, renderer, tokenizer })
149
180
  const asWritten = (markdown: string) => vouch(`<p>${escape(markdown)}</p>\n`)
150
181
 
151
182
  // Markdown rendered as `renderMarkdown` renders it, headings without anchors, then sanitized for `innerHTML`: formatted text, tables, images and task lists, a link leaving the site opening in a new tab, sync so it renders again on each chunk of a stream.
152
- export function markdownHtml(markdown: string): SafeHtml {
183
+ export function markdownHtml(markdown: string, options?: MarkdownOptions): SafeHtml {
153
184
  if (markdown.length > MAX_LENGTH)
154
185
  return asWritten(markdown)
155
186
 
187
+ let html: SafeHtml
188
+
156
189
  try {
157
- return sanitizedMarkdown(marked.parse(markdown) as string)
190
+ html = sanitizedMarkdown(marked.parse(markdown) as string)
158
191
  }
159
192
  // Thousands of nested quotes overflow marked's stack.
160
193
  catch {
161
194
  return asWritten(markdown)
162
195
  }
196
+
197
+ // Outside the guard above: a hook of the app's that throws is its bug, as it is on the server.
198
+ return withInline(html, options?.inline)
163
199
  }