@kayjs/kay 1.106.0 → 1.108.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 (254) hide show
  1. package/README.md +2 -2
  2. package/dist/eslint.js +477 -204
  3. package/editors/zed/extension.toml +2 -2
  4. package/llms/action-protection.md +1 -1
  5. package/llms/actions-from-islands.md +1 -1
  6. package/llms/actions-refused-fields.md +22 -0
  7. package/llms/actions.md +2 -22
  8. package/llms/browser-only.md +1 -1
  9. package/llms/compiler-api.md +1 -1
  10. package/llms/component-libraries.md +1 -1
  11. package/llms/components.md +1 -1
  12. package/llms/deprecated-lints.md +2 -4
  13. package/llms/island-and-form-lints.md +1 -0
  14. package/llms/islands.md +11 -2
  15. package/llms/project-new-and-add.md +1 -1
  16. package/llms/project.md +2 -2
  17. package/llms/schemas.md +6 -4
  18. package/llms/upgrading.md +25 -1
  19. package/llms/whats-new-archive.md +36 -1
  20. package/llms/whats-new.md +18 -35
  21. package/llms.txt +1 -1
  22. package/package.json +15 -6
  23. package/src/build/client.ts +23 -26
  24. package/src/build/entry-files.ts +19 -0
  25. package/src/build/icon-slots.ts +140 -0
  26. package/src/build/lazy-components.ts +130 -0
  27. package/src/build/lazy-manifest.ts +56 -0
  28. package/src/build/lazy-stubs.ts +31 -0
  29. package/src/build/libraries.ts +24 -2
  30. package/src/build/plugin.ts +13 -1
  31. package/src/build/runtime-chunk.ts +3 -3
  32. package/src/build/source-files.ts +8 -3
  33. package/src/build/transform.ts +17 -7
  34. package/src/build/variants.ts +97 -5
  35. package/src/check/action-options.ts +56 -0
  36. package/src/check/project.ts +4 -4
  37. package/src/check/renamed-packages.ts +3 -63
  38. package/src/check/schema-json.ts +226 -0
  39. package/src/check/shadow-types.ts +15 -27
  40. package/src/compiler/codegen.ts +7 -17
  41. package/src/compiler/dead-code.ts +22 -0
  42. package/src/compiler/deprecated-lints-1-105.ts +41 -0
  43. package/src/compiler/deprecated-lints-1-106.ts +1 -1
  44. package/src/compiler/deprecated-lints-1-107.ts +14 -0
  45. package/src/compiler/deprecated-lints.ts +8 -65
  46. package/src/compiler/dom-property.ts +23 -0
  47. package/src/compiler/dom.ts +15 -15
  48. package/src/compiler/import-edits.ts +15 -0
  49. package/src/compiler/index.ts +8 -3
  50. package/src/compiler/island-declaration.ts +15 -0
  51. package/src/compiler/kay-exports.ts +1 -0
  52. package/src/compiler/lazy-imports.ts +357 -0
  53. package/src/compiler/parser.ts +2 -2
  54. package/src/compiler/route-lints.ts +2 -0
  55. package/src/compiler/schema-lints.ts +13 -0
  56. package/src/compiler/script-server.ts +6 -3
  57. package/src/content/validate.ts +1 -1
  58. package/src/new.ts +6 -2
  59. package/src/package-names.ts +1 -1
  60. package/src/runtime/action-call.ts +39 -327
  61. package/src/runtime/action-run.ts +357 -0
  62. package/src/runtime/action.ts +47 -4
  63. package/src/runtime/client.ts +10 -0
  64. package/src/runtime/dom-lazy.ts +276 -0
  65. package/src/runtime/field-errors.ts +58 -0
  66. package/src/runtime/field-refusal.ts +179 -0
  67. package/src/runtime/form.ts +3 -2
  68. package/src/runtime/html.ts +6 -1
  69. package/src/runtime/index.ts +2 -0
  70. package/src/runtime/island.server.ts +36 -2
  71. package/src/runtime/schema-record.ts +2 -1
  72. package/src/runtime/schema.client.ts +104 -14
  73. package/src/runtime/schema.ts +9 -2
  74. package/src/runtime/standard-schema.ts +32 -0
  75. package/src/runtime/validate-run.client.ts +179 -0
  76. package/src/runtime/validate.client.ts +11 -0
  77. package/src/runtime/validate.ts +4 -137
  78. package/src/server/actions.ts +48 -43
  79. package/src/server/answer.ts +102 -0
  80. package/src/server/api-input.ts +166 -0
  81. package/src/server/api.ts +12 -44
  82. package/src/server/app-stages.ts +15 -8
  83. package/src/server/app.ts +5 -2
  84. package/src/server/client.ts +2 -0
  85. package/src/server/dev.ts +7 -9
  86. package/src/server/file-limit.ts +7 -1
  87. package/src/server/forms.ts +1 -1
  88. package/src/server/host-allowlist.ts +7 -7
  89. package/src/server/index.ts +2 -0
  90. package/src/server/kay-routes.ts +221 -0
  91. package/src/server/kay-server.ts +228 -0
  92. package/src/server/kept-exports.ts +1 -0
  93. package/src/server/library.ts +0 -2
  94. package/src/server/mcp.ts +1 -1
  95. package/src/server/openapi.ts +12 -3
  96. package/src/server/phases.ts +249 -0
  97. package/src/server/protection.ts +6 -6
  98. package/src/server/proxy-key.ts +8 -8
  99. package/src/server/query.ts +4 -25
  100. package/src/server/receive.ts +43 -0
  101. package/src/server/render-document.ts +13 -3
  102. package/src/server/request-context.ts +137 -0
  103. package/src/server/schema-check.ts +1 -1
  104. package/src/server/socket.ts +19 -47
  105. package/src/server/stream.ts +1 -1
  106. package/src/server/validate.ts +346 -0
  107. package/src/test/mount.ts +6 -2
  108. package/types/build/client.d.ts +3 -2
  109. package/types/build/client.d.ts.map +1 -1
  110. package/types/build/entry-files.d.ts +4 -0
  111. package/types/build/entry-files.d.ts.map +1 -0
  112. package/types/build/icon-slots.d.ts +7 -0
  113. package/types/build/icon-slots.d.ts.map +1 -0
  114. package/types/build/lazy-components.d.ts +6 -0
  115. package/types/build/lazy-components.d.ts.map +1 -0
  116. package/types/build/lazy-manifest.d.ts +19 -0
  117. package/types/build/lazy-manifest.d.ts.map +1 -0
  118. package/types/build/lazy-stubs.d.ts +5 -0
  119. package/types/build/lazy-stubs.d.ts.map +1 -0
  120. package/types/build/libraries.d.ts +2 -0
  121. package/types/build/libraries.d.ts.map +1 -1
  122. package/types/build/plugin.d.ts +2 -0
  123. package/types/build/plugin.d.ts.map +1 -1
  124. package/types/build/source-files.d.ts.map +1 -1
  125. package/types/build/transform.d.ts +3 -1
  126. package/types/build/transform.d.ts.map +1 -1
  127. package/types/build/variants.d.ts.map +1 -1
  128. package/types/check/action-options.d.ts +3 -0
  129. package/types/check/action-options.d.ts.map +1 -0
  130. package/types/check/renamed-packages.d.ts +0 -3
  131. package/types/check/renamed-packages.d.ts.map +1 -1
  132. package/types/check/schema-json.d.ts +3 -0
  133. package/types/check/schema-json.d.ts.map +1 -0
  134. package/types/check/shadow-types.d.ts.map +1 -1
  135. package/types/compiler/codegen.d.ts +2 -0
  136. package/types/compiler/codegen.d.ts.map +1 -1
  137. package/types/compiler/dead-code.d.ts +9 -0
  138. package/types/compiler/dead-code.d.ts.map +1 -0
  139. package/types/compiler/deprecated-lints-1-105.d.ts +39 -0
  140. package/types/compiler/deprecated-lints-1-105.d.ts.map +1 -0
  141. package/types/compiler/deprecated-lints-1-106.d.ts +1 -1
  142. package/types/compiler/deprecated-lints-1-106.d.ts.map +1 -1
  143. package/types/compiler/deprecated-lints-1-107.d.ts +12 -0
  144. package/types/compiler/deprecated-lints-1-107.d.ts.map +1 -0
  145. package/types/compiler/deprecated-lints.d.ts +36 -53
  146. package/types/compiler/deprecated-lints.d.ts.map +1 -1
  147. package/types/compiler/dom-property.d.ts +9 -0
  148. package/types/compiler/dom-property.d.ts.map +1 -0
  149. package/types/compiler/dom.d.ts +1 -0
  150. package/types/compiler/dom.d.ts.map +1 -1
  151. package/types/compiler/import-edits.d.ts +1 -0
  152. package/types/compiler/import-edits.d.ts.map +1 -1
  153. package/types/compiler/index.d.ts +2 -0
  154. package/types/compiler/index.d.ts.map +1 -1
  155. package/types/compiler/island-declaration.d.ts +5 -0
  156. package/types/compiler/island-declaration.d.ts.map +1 -1
  157. package/types/compiler/kay-exports.d.ts.map +1 -1
  158. package/types/compiler/lazy-imports.d.ts +33 -0
  159. package/types/compiler/lazy-imports.d.ts.map +1 -0
  160. package/types/compiler/lints.d.ts +44 -53
  161. package/types/compiler/lints.d.ts.map +1 -1
  162. package/types/compiler/route-lints.d.ts +8 -0
  163. package/types/compiler/route-lints.d.ts.map +1 -1
  164. package/types/compiler/schema-lints.d.ts +11 -0
  165. package/types/compiler/schema-lints.d.ts.map +1 -0
  166. package/types/compiler/script-server.d.ts.map +1 -1
  167. package/types/new.d.ts +1 -0
  168. package/types/new.d.ts.map +1 -1
  169. package/types/runtime/action-call.d.ts.map +1 -1
  170. package/types/runtime/action-run.d.ts +23 -0
  171. package/types/runtime/action-run.d.ts.map +1 -0
  172. package/types/runtime/action.d.ts +26 -1
  173. package/types/runtime/action.d.ts.map +1 -1
  174. package/types/runtime/client.d.ts.map +1 -1
  175. package/types/runtime/dom-lazy.d.ts +6 -0
  176. package/types/runtime/dom-lazy.d.ts.map +1 -0
  177. package/types/runtime/field-errors.d.ts +4 -0
  178. package/types/runtime/field-errors.d.ts.map +1 -0
  179. package/types/runtime/field-refusal.d.ts +37 -0
  180. package/types/runtime/field-refusal.d.ts.map +1 -0
  181. package/types/runtime/form.d.ts +1 -1
  182. package/types/runtime/form.d.ts.map +1 -1
  183. package/types/runtime/html.d.ts.map +1 -1
  184. package/types/runtime/index.d.ts +2 -0
  185. package/types/runtime/index.d.ts.map +1 -1
  186. package/types/runtime/island.server.d.ts +2 -0
  187. package/types/runtime/island.server.d.ts.map +1 -1
  188. package/types/runtime/schema-record.d.ts.map +1 -1
  189. package/types/runtime/schema.client.d.ts.map +1 -1
  190. package/types/runtime/schema.d.ts +6 -1
  191. package/types/runtime/schema.d.ts.map +1 -1
  192. package/types/runtime/standard-schema.d.ts +37 -0
  193. package/types/runtime/standard-schema.d.ts.map +1 -0
  194. package/types/runtime/validate-run.client.d.ts +4 -0
  195. package/types/runtime/validate-run.client.d.ts.map +1 -0
  196. package/types/runtime/validate.client.d.ts +4 -0
  197. package/types/runtime/validate.client.d.ts.map +1 -0
  198. package/types/runtime/validate.d.ts +1 -21
  199. package/types/runtime/validate.d.ts.map +1 -1
  200. package/types/server/actions.d.ts.map +1 -1
  201. package/types/server/answer.d.ts +6 -0
  202. package/types/server/answer.d.ts.map +1 -0
  203. package/types/server/api-input.d.ts +19 -0
  204. package/types/server/api-input.d.ts.map +1 -0
  205. package/types/server/api.d.ts.map +1 -1
  206. package/types/server/app-stages.d.ts +4 -1
  207. package/types/server/app-stages.d.ts.map +1 -1
  208. package/types/server/app.d.ts +2 -0
  209. package/types/server/app.d.ts.map +1 -1
  210. package/types/server/client.d.ts +1 -0
  211. package/types/server/client.d.ts.map +1 -1
  212. package/types/server/dev.d.ts +1 -1
  213. package/types/server/dev.d.ts.map +1 -1
  214. package/types/server/file-limit.d.ts.map +1 -1
  215. package/types/server/host-allowlist.d.ts +3 -3
  216. package/types/server/host-allowlist.d.ts.map +1 -1
  217. package/types/server/index.d.ts +2 -0
  218. package/types/server/index.d.ts.map +1 -1
  219. package/types/server/kay-routes.d.ts +47 -0
  220. package/types/server/kay-routes.d.ts.map +1 -0
  221. package/types/server/kay-server.d.ts +25 -0
  222. package/types/server/kay-server.d.ts.map +1 -0
  223. package/types/server/kept-exports.d.ts.map +1 -1
  224. package/types/server/library.d.ts +0 -1
  225. package/types/server/library.d.ts.map +1 -1
  226. package/types/server/openapi.d.ts.map +1 -1
  227. package/types/server/phases.d.ts +36 -0
  228. package/types/server/phases.d.ts.map +1 -0
  229. package/types/server/protection.d.ts +3 -2
  230. package/types/server/protection.d.ts.map +1 -1
  231. package/types/server/proxy-key.d.ts +3 -3
  232. package/types/server/proxy-key.d.ts.map +1 -1
  233. package/types/server/query.d.ts.map +1 -1
  234. package/types/server/receive.d.ts +9 -0
  235. package/types/server/receive.d.ts.map +1 -0
  236. package/types/server/render-document.d.ts.map +1 -1
  237. package/types/server/request-context.d.ts +29 -0
  238. package/types/server/request-context.d.ts.map +1 -0
  239. package/types/server/schema-check.d.ts +1 -0
  240. package/types/server/schema-check.d.ts.map +1 -1
  241. package/types/server/socket.d.ts +3 -5
  242. package/types/server/socket.d.ts.map +1 -1
  243. package/types/server/validate.d.ts +26 -0
  244. package/types/server/validate.d.ts.map +1 -0
  245. package/types/test/mount.d.ts.map +1 -1
  246. package/src/check/schema-type.ts +0 -9
  247. package/src/compiler/deprecated-script-fence.ts +0 -26
  248. package/src/server/field-errors.ts +0 -136
  249. package/types/check/schema-type.d.ts +0 -3
  250. package/types/check/schema-type.d.ts.map +0 -1
  251. package/types/compiler/deprecated-script-fence.d.ts +0 -3
  252. package/types/compiler/deprecated-script-fence.d.ts.map +0 -1
  253. package/types/server/field-errors.d.ts +0 -6
  254. package/types/server/field-errors.d.ts.map +0 -1
@@ -30,13 +30,17 @@ import { ASSET_PREFIX, clientDir, DEV_MAPS_DIR, MAPS_DIR, outputDir } from './as
30
30
  import { AWAIT_ALERT_FILE } from './await-alert'
31
31
  import { pruneNodes, pruneUtilityLayer } from './class-rules'
32
32
  import { buildClassTable, mergesAtRuntime } from './class-table'
33
+ import { entryFile, KAY_OUTPUT, lazyEntryKey } from './entry-files'
33
34
  import { CSS_FILE, findKayFiles, findProjectFiles, forgetSources, inWalkScope, keepSources, liftSources, readSource, readSourcePaths, readText, writeIfChanged } from './files'
35
+ import { iconSlotsOf, slotsKey } from './icon-slots'
34
36
  import { Increments, realPaths, sameEntries } from './increments'
35
37
  import { keepBundleMapCached, pruneKeptMaps } from './kept-maps'
36
38
  import { hoistLayerOrder } from './layer-order'
39
+ import { eagerKeys, lazyKey } from './lazy-components'
40
+ import { noteLazy, staticClosure } from './lazy-manifest'
41
+ import { foldStubs, inRounds } from './lazy-stubs'
37
42
  import { fileWords, importEdges, libraryOf, reachedFrom, reachingAny } from './libraries'
38
43
  import { packagesOf } from './licenses'
39
- import { throughLinks } from './links'
40
44
  import { isPageFile, pageDirs } from './page-dirs'
41
45
  import { kay } from './plugin'
42
46
  import { unusedLibraryClasses } from './prune'
@@ -91,6 +95,7 @@ type Outputs = Record<string, MetafileOutput>
91
95
 
92
96
  const LEADING_DOT_SLASH = /^\.\//
93
97
  const JS_OUTPUT = /\.js$/
98
+
94
99
  const COMPILES_WASM = /\bWebAssembly\./
95
100
  const STARTS_WORKER = /\bnew\s+(?:Shared)?Worker\(/
96
101
  const OBJECT_URL = /\bcreateObjectURL\(/
@@ -222,7 +227,7 @@ export function clientSession(root: string, options: ClientOptions, settings: Se
222
227
  if (previous && islandsAgain)
223
228
  await increments!.stopMaps(false)
224
229
 
225
- const [scripts, styles] = await bothBundles(islandsAgain ? bundleIslands(root, sources.islands, sources.files, sources.actionForms, sources.actionProps, options, classTable, islandTable) : undefined, stylesAgain ? bundleStyles(root, sources, options) : undefined)
230
+ const [scripts, styles] = await bothBundles(islandsAgain ? bundleIslands(root, sources.islands, sources.files, sources.actionForms, sources.actionProps, options, classTable, islandTable, await iconSlotsOf(root, [...sources.files, ...sources.islands.values()], sources.libraries, graph)) : undefined, stylesAgain ? bundleStyles(root, sources, options) : undefined)
226
231
  const styleUses = styles ? styles.uses : previous!.styleUses
227
232
  const manifest: ClientManifest = { ...scripts?.manifest ?? previous!.islands, styles: styles?.styles ?? previous!.styles, ...classTable && { classTable }, ...styleUses && { styleUses }, ...options.hot && { problems: sources.problems }, ...key !== undefined && { options: key } }
228
233
 
@@ -501,7 +506,14 @@ export async function islandClassTableOf(root: string, sources: Pick<ClientSourc
501
506
  }
502
507
 
503
508
  // `inputs` holds the modules of each chunk, `maps` the source maps written.
504
- async function bundleIslands(root: string, islands: Map<string, string>, files: string[], actionForms: boolean, actionProps: boolean, options: ClientOptions, classTable?: ClassTable, islandTable?: ClassTable): Promise<{ manifest: Omit<ClientManifest, 'styles'>, inputs: ChunkInputs, maps: string[] }> {
509
+ interface Bundled { manifest: Omit<ClientManifest, 'styles'>, inputs: ChunkInputs, maps: string[] }
510
+
511
+ async function bundleIslands(root: string, islands: Map<string, string>, files: string[], actionForms: boolean, actionProps: boolean, options: ClientOptions, classTable?: ClassTable, islandTable?: ClassTable, iconSlots?: ReadonlySet<string>): Promise<Bundled> {
512
+ return inRounds(async last => bundleRound(root, islands, files, actionForms, actionProps, options, last, classTable, islandTable, iconSlots))
513
+ }
514
+
515
+ // One build of the islands, which `foldStubs` ends when lazy components that do not pay were left.
516
+ async function bundleRound(root: string, islands: Map<string, string>, files: string[], actionForms: boolean, actionProps: boolean, options: ClientOptions, last: boolean, classTable?: ClassTable, islandTable?: ClassTable, iconSlots?: ReadonlySet<string>): Promise<Bundled> {
505
517
  const navigation = options.client?.navigation ?? true
506
518
 
507
519
  if (islands.size === 0 && !navigation)
@@ -556,13 +568,13 @@ async function bundleIslands(root: string, islands: Map<string, string>, files:
556
568
  // Bun resolves packages' `development` export condition unless NODE_ENV is defined as production, which would ship a package's dev build; a build for development, not NODE_ENV, asks for theirs.
557
569
  const define: Record<string, string> = { 'KAY_BROWSER': 'true', 'process.env.NODE_ENV': JSON.stringify(options.hot === true ? 'development' : 'production'), 'KAY_STATIC_EXPORT': options.exported === true ? 'true' : 'undefined', 'KAY_NAV_ENTRY': 'undefined', 'KAY_FRENCH': options.french === true ? 'true' : 'undefined', 'KAY_I18N': options.i18n === true ? 'true' : 'undefined', 'KAY_NO_ACTION_PROPS': options.hot !== true && !actionProps ? 'true' : 'undefined', 'KAY_VISIBLE_MARGIN': JSON.stringify(rootMargin(options.client?.hydration?.visible, '200px', 'visible')), 'KAY_NEAR_MARGIN': JSON.stringify(rootMargin(options.client?.hydration?.serverIslands, '100% 0px', 'serverIslands')) }
558
570
  const external = publicEnv !== undefined ? [publicEnv] : []
559
- const plugins = (anchor?: string, anchored?: ReadonlySet<string>, direct?: boolean) => [withoutStyles(), api, kay({ target: 'dom', root, variants, localeLinks: options.i18n === true, cacheDir: projectPaths(root).cache, settings: options.librarySettings, anchor, anchored, direct, inspect: options.inspect, api: trees, external, classTable }), ...options.plugins ?? []]
571
+ const plugins = (anchor?: string, anchored?: ReadonlySet<string>, direct?: boolean) => [withoutStyles(), api, kay({ target: 'dom', root, variants, localeLinks: options.i18n === true, cacheDir: projectPaths(root).cache, settings: options.librarySettings, iconSlots, anchor, anchored, direct, inspect: options.inspect, api: trees, external, classTable }), ...options.plugins ?? []]
560
572
 
561
573
  await Bun.write(entryFile, `import ${JSON.stringify(bootFile)}\n`)
562
574
 
563
575
  // Without the registry in the boot, each island is an entry point of its own.
564
576
  const islandFiles = options.hot ? [] : [...entries.values()]
565
- const chunk = await runtimeChunk(entryFile, { plugins: plugins(), define, external, islands: islandFiles, cache: { file: join(projectPaths(root).cache, `runtime-search-${options.hot ? 'dev' : 'build'}.json`), key: `${JSON.stringify([options.librarySettings, options.inspect, options.client?.navigation, trees, islandFiles])}\0${await Bun.file(bootFile).text()}` } })
577
+ const chunk = await runtimeChunk(entryFile, { plugins: plugins(), define, external, islands: islandFiles, cache: { file: join(projectPaths(root).cache, `runtime-search-${options.hot ? 'dev' : 'build'}.json`), key: `${JSON.stringify([options.librarySettings, slotsKey(iconSlots), options.inspect, options.client?.navigation, trees, islandFiles, eagerKeys()])}\0${await Bun.file(bootFile).text()}` } })
566
578
 
567
579
  // In development the entry keeps its own code, the islands it imports by their hashed names included: the runtime's chunk then stays as it was through an edit of an island, which swaps in alone.
568
580
  // A second entry point importing the runtime alone has Bun give it that chunk of its own, which it would otherwise merge into the entry's.
@@ -592,6 +604,8 @@ async function bundleIslands(root: string, islands: Map<string, string>, files:
592
604
  // A production page posting forms and holding no island loads navigation alone, from a build of its own: in the islands' build it would move the navigation code out of their runtime's chunk, adding a file to every page. A static export has no server to post to, and an app rendering no such form has no page loading it.
593
605
  const [build, nav] = await Promise.all([Bun.build({ ...config, outdir: clientDir(root) }), navigation && actionForms && !options.hot && options.exported !== true ? bundleNavigation(root, options, { ...config, plugins: plugins() }) : undefined])
594
606
 
607
+ await foldStubs(build, nav, last, lazyEntryKey(root, new Set(islands.values())))
608
+
595
609
  if (!build.success) {
596
610
  await refuseBuiltinImports(root, build.logs, islands.values(), config)
597
611
 
@@ -790,6 +804,10 @@ export function islandManifest(root: string, outputs: Outputs, islands: Map<stri
790
804
 
791
805
  const file = entryFile(root, meta.entryPoint, files)
792
806
 
807
+ // A `.kay` entry, an island or not, is a component another island may load lazily, which the page preloads when its server drew it.
808
+ if (KAY_OUTPUT.test(meta.entryPoint))
809
+ noteLazy(manifest, lazyKey(root, resolve(variantFile(meta.entryPoint))), meta.entryPoint, [...closure(output)].map(assetUrl))
810
+
793
811
  // Any other entry point is the entry, or a chunk some code imports dynamically, loaded when it asks for it.
794
812
  if (file === undefined)
795
813
  continue
@@ -819,20 +837,6 @@ export function islandManifest(root: string, outputs: Outputs, islands: Map<stri
819
837
  return manifest
820
838
  }
821
839
 
822
- // Every chunk a chunk needs before it can run, itself included.
823
- function staticClosure(outputs: Outputs, output: string, seen = new Set<string>()): Set<string> {
824
- if (seen.has(output))
825
- return seen
826
-
827
- seen.add(output)
828
- for (const imported of outputs[output]?.imports ?? []) {
829
- if (imported.kind === 'import-statement')
830
- staticClosure(outputs, imported.path, seen)
831
- }
832
-
833
- return seen
834
- }
835
-
836
840
  // The URL a page loads an entry by, and the chunks it imports statically, which the page preloads.
837
841
  function entryChunks(root: string, outputs: Outputs, entry: string): { entry: string, imports: string[] } | undefined {
838
842
  const entries = new Set([entry])
@@ -853,13 +857,6 @@ function islandPath(root: string, input: string): string {
853
857
  return relative(root, resolve(input)).replaceAll('\\', '/')
854
858
  }
855
859
 
856
- // Bun names entry points relative to the working directory, not the root: from a library holding a test app, its layout and the app's share a path.
857
- function entryFile(root: string, entryPoint: string, files: Set<string>): string | undefined {
858
- const point = resolve(variantFile(entryPoint))
859
-
860
- return [point, throughLinks(root, point)].find(file => files.has(file))
861
- }
862
-
863
860
  function assetUrl(output: string): string {
864
861
  return `${ASSET_PREFIX}${output.replace(LEADING_DOT_SLASH, '')}`
865
862
  }
@@ -0,0 +1,19 @@
1
+ import { resolve } from 'node:path'
2
+ import { lazyKey } from './lazy-components'
3
+ import { throughLinks } from './links'
4
+ import { variantFile } from './variants'
5
+
6
+ export const KAY_OUTPUT = /\.kay(?:\?uses=[^?]*)?$/
7
+
8
+ // Bun names entry points relative to the working directory, not the root: from a library holding a test app, its layout and the app's share a path.
9
+ // The file among `files` a build's entry point stands for, a variant or a link followed.
10
+ export function entryFile(root: string, entryPoint: string, files: Set<string>): string | undefined {
11
+ const point = resolve(variantFile(entryPoint))
12
+
13
+ return [point, throughLinks(root, point)].find(file => files.has(file))
14
+ }
15
+
16
+ // The lazy key of an entry point that is a component and no island.
17
+ export function lazyEntryKey(root: string, islandFiles: Set<string>): (entryPoint: string) => string | undefined {
18
+ return entryPoint => KAY_OUTPUT.test(entryPoint) && entryFile(root, entryPoint, islandFiles) === undefined ? lazyKey(root, resolve(variantFile(entryPoint))) : undefined
19
+ }
@@ -0,0 +1,140 @@
1
+ import type { ImportGraph, KayLibrary } from './libraries'
2
+ import { existsSync, readFileSync, realpathSync } from 'node:fs'
3
+ import { dirname, join, resolve, sep } from 'node:path'
4
+ import { importEdges, importsOf, reachedFrom } from './libraries'
5
+
6
+ // kayjs-ui draws its icons from a registry keyed by slot, `settings.icons[slot]`, which a bundler cannot shrink: an island would carry every icon of it. The build instead reads the slots the project and the modules it reaches write, and loads the registry holding those alone.
7
+ // A slot is named where the code writes it as a string, `icon="close"` or `icon: 'close'`; pages hand them to islands as props, so every `.kay` file of the build is read, not only what an island imports. One taken from a variable in the project's own code may be any slot, so the whole registry stays.
8
+ const WORD = /(["'`])(\w+)\1/g
9
+ const ICON_PROP = /\b\w*[iI]con\w*=\{((?:[^{}]|\{[^{}]*\})*)\}/g
10
+ const ICON_KEY = /\b\w*[iI]con\w*\s*:\s*([^,}\n]+)/g
11
+ const ICON_IMPORT = /^import\s+(\w+)\s+from\s+(["'])~icons\/[^"'\n]+\2/gm
12
+ const LITERAL = /^(["'])\w+\1$/
13
+ const CHOICE = /^[^'"`?]+\?\s*(["'])\w+\1\s*:\s*(["'])\w+\2$/
14
+ const IDENTIFIER = /^[\w$]+$/
15
+ const TYPE_WORD = /^(?:string|undefined|null|true|false|any|unknown|number|boolean)\b/
16
+ const LOWERCASE = /^[a-z]/
17
+ const SLOT_NAME = /^\w+/
18
+ const IN_PACKAGES = /[\\/]node_modules[\\/]/
19
+ const UI_ICON = /[\\/](?:packages[\\/]ui|node_modules[\\/]@kayjs[\\/]ui)[\\/]src[\\/]icon\.kay$/
20
+ // A component called with a spread, `Button({...opts})`: the props it takes, an icon among them, are not written here.
21
+ const SPREAD_CALL = /\b[A-Z]\w*\([^)\n]*\.\.\./
22
+ const JSON_IMPORT = /(?:from\s*|import\(\s*)((["'])\.[^"'\n]*\.json\2)/g
23
+ const SCANNED = /\.(?:kay|[cm]?[jt]sx?)$/
24
+
25
+ // The registry modules of kayjs-ui, by where the project reaches it: in a checkout or under `node_modules`.
26
+ export const REGISTRY_FILE = /[\\/](?:packages[\\/]ui|node_modules[\\/]@kayjs[\\/]ui)[\\/]src[\\/](?:defaults|added-icons)\.ts$/
27
+
28
+ // Whether a registry module belongs to kayjs-ui itself, not to an app's own `packages/ui`.
29
+ export function isUiRegistry(file: string): boolean {
30
+ try {
31
+ return (JSON.parse(readFileSync(join(dirname(file), '../package.json'), 'utf8')) as { name?: string }).name === '@kayjs/ui'
32
+ }
33
+ catch {
34
+ return false
35
+ }
36
+ }
37
+
38
+ // Whether the value written for an icon is a slot or an icon of a set, and not something computed.
39
+ function isStatic(value: string, imported: ReadonlySet<string>): boolean {
40
+ const written = value.trim()
41
+
42
+ return LITERAL.test(written) || CHOICE.test(written) || (IDENTIFIER.test(written) && imported.has(written))
43
+ }
44
+
45
+ // Whether a file belongs to kayjs-ui, by the package.json above it.
46
+ function inUi(file: string): boolean {
47
+ for (let dir = dirname(file); dir !== dirname(dir); dir = dirname(dir)) {
48
+ if (existsSync(join(dir, 'package.json')))
49
+ return isUiRegistry(join(dir, 'src/x'))
50
+ }
51
+
52
+ return false
53
+ }
54
+
55
+ // The words written as strings in the files of the build and what they import, or undefined when a slot may come from a variable.
56
+ export async function iconSlotsOf(root: string, entries: Iterable<string>, libraries: KayLibrary[], graph?: ImportGraph): Promise<ReadonlySet<string> | undefined> {
57
+ const project = realpathSync(root) + sep
58
+ const reached = await reachedFrom([...entries], importEdges(root, libraries, graph))
59
+ const slots = new Set<string>()
60
+ let dynamic = false
61
+
62
+ await Promise.all([...reached].map(async (file) => {
63
+ if (REGISTRY_FILE.test(file) || !SCANNED.test(file))
64
+ return
65
+
66
+ const text = await Bun.file(file).text()
67
+
68
+ for (const [, , word] of text.matchAll(WORD))
69
+ slots.add(word!)
70
+
71
+ // Data a file imports hands icons to components as props, which no component writes.
72
+ for (const [, written] of text.matchAll(JSON_IMPORT)) {
73
+ const data = resolve(dirname(file), JSON.parse(written!.replaceAll('\'', '"')) as string)
74
+
75
+ if (existsSync(data)) {
76
+ for (const [, , word] of readFileSync(data, 'utf8').matchAll(WORD))
77
+ slots.add(word!)
78
+ }
79
+ }
80
+
81
+ // A kayjs-ui file the file imports and the walk did not follow, which its slots would be missing from.
82
+ for (const specifier of await importsOf(file, text)) {
83
+ try {
84
+ const path = realpathSync(Bun.resolveSync(specifier, dirname(file)))
85
+
86
+ if (SCANNED.test(path) && !reached.has(path) && inUi(path))
87
+ dynamic = true
88
+ }
89
+ catch {
90
+ // Not a file of the project's: a builtin or a package.
91
+ }
92
+ }
93
+
94
+ if (!file.startsWith(project) || IN_PACKAGES.test(file.slice(project.length)))
95
+ return
96
+
97
+ if (SPREAD_CALL.test(text))
98
+ dynamic = true
99
+
100
+ const imported = new Set([...text.matchAll(ICON_IMPORT)].map(hit => hit[1]!))
101
+
102
+ for (const [, value] of text.matchAll(ICON_PROP)) {
103
+ if (!isStatic(value!, imported))
104
+ dynamic = true
105
+ }
106
+
107
+ for (const [, value] of text.matchAll(ICON_KEY)) {
108
+ const written = value!.trim()
109
+
110
+ // A type annotation, `icon: IconSlot`, writes no value.
111
+ if (!isStatic(written, imported) && (written.includes('.') || written.includes('(') || written.includes('[') || (LOWERCASE.test(written) && !TYPE_WORD.test(written))))
112
+ dynamic = true
113
+ }
114
+ }))
115
+
116
+ // Without kayjs-ui's Icon among the files read, its components were not followed (a library the project does not declare), and their slots are unknown.
117
+ return dynamic || ![...reached].some(file => UI_ICON.test(file)) ? undefined : slots
118
+ }
119
+
120
+ const REGISTRY = /^(\s*icons: |export const addedIcons\b[^=\n]*= )\{ ([^{}\n]*) \}(,?)$/m
121
+ const ICON_IMPORT_LINE = /^import (\w+) from '~icons\/[^'\n]+'\n/gm
122
+
123
+ // A registry module with the entries of `slots` only, the imports of the others dropped with them. A module whose registry is not written on one line as `{ slot, other: local }` is left as it is.
124
+ export function registryWith(source: string, slots: ReadonlySet<string>): string {
125
+ const hit = REGISTRY.exec(source)
126
+
127
+ if (hit === null)
128
+ return source
129
+
130
+ const kept = hit[2]!.split(', ').filter(entry => slots.has(SLOT_NAME.exec(entry)![0]))
131
+ const body = source.replace(REGISTRY, () => `${hit[1]}{ ${kept.join(', ')} }${hit[3]}`)
132
+ const names = new Set(kept.map(entry => entry.split(':').at(-1)!.trim()))
133
+
134
+ return body.replace(ICON_IMPORT_LINE, (line, name: string) => names.has(name) ? line : '')
135
+ }
136
+
137
+ // What a cache keyed on the slots holds of them.
138
+ export function slotsKey(slots: ReadonlySet<string> | undefined): string {
139
+ return slots === undefined ? '*' : [...slots].sort().join(',')
140
+ }
@@ -0,0 +1,130 @@
1
+ import type { ImportedComponent, ImportedComponents } from '../compiler/lazy-imports'
2
+ import type { ImportBinding } from '../compiler/script-shared'
3
+ import { readFileSync, realpathSync, statSync } from 'node:fs'
4
+ import { basename, relative } from 'node:path'
5
+ import { deferredProps, eagerReach, lazyImports } from '../compiler/lazy-imports'
6
+ import { parseKay } from '../compiler/parser'
7
+ import { resolveFrom } from './files'
8
+ import { fences } from './libraries'
9
+
10
+ // A default import of a `.kay` module, as a script writes it on a line of its own.
11
+ const KAY_IMPORT = /^[ \t]*import\s+([\w$]+)\s+from\s*(['"])([^'"]+\.kay)\2/gm
12
+
13
+ interface Facts {
14
+ // The own stamp of the module and of each module its answer reads: the facts are read again once any changes.
15
+ stamps: Map<string, string>
16
+ deferred: string[]
17
+ size: number
18
+ // The paths of the components the module loads with it, which a module importing it does not need a chunk for.
19
+ reach: string[]
20
+ }
21
+
22
+ // What a key may not hold, as the page writes keys apart by a space inside an attribute.
23
+ const UNSAFE_KEY = /[^\w.-]/g
24
+
25
+ const known = new Map<string, Facts>()
26
+
27
+ function stampOf(path: string): string | undefined {
28
+ const stats = statSync(path, { throwIfNoEntry: false })
29
+
30
+ return stats ? `${stats.mtimeMs}-${stats.size}` : undefined
31
+ }
32
+
33
+ function importsOf(source: string): ImportBinding[] {
34
+ return [...fences(source).matchAll(KAY_IMPORT)].map(([line, local, , specifier]) => ({ local: local!, imported: 'default', source: specifier!, typeOnly: false, span: { start: 0, end: 0 }, declaration: { start: source.indexOf(line), end: source.indexOf(line) + line.trimEnd().length } }))
35
+ }
36
+
37
+ // The props a component draws only where a branch may not render, which hold when each module it passes a block to says the same of that block: a wrapper of a dialog defers what the dialog does.
38
+ function factsOf(path: string, visiting: ReadonlySet<string>): Facts | undefined {
39
+ const stamp = stampOf(path)
40
+
41
+ if (stamp === undefined || visiting.has(path))
42
+ return undefined
43
+
44
+ const kept = known.get(path)
45
+
46
+ if (kept && [...kept.stamps].every(([module, expected]) => stampOf(module) === expected))
47
+ return kept
48
+
49
+ const source = readFileSync(path, 'utf8')
50
+ const stamps = new Map([[path, stamp]])
51
+ const inside = new Set([...visiting, path])
52
+ const file = parseKay(source)
53
+ const imports = importsOf(source)
54
+ const children: Record<string, ImportedComponent> = {}
55
+
56
+ for (const { source: specifier } of imports) {
57
+ const found = resolveFrom(specifier, path)
58
+ const facts = found === undefined ? undefined : factsOf(found, inside)
59
+
60
+ for (const [module, other] of facts?.stamps ?? [])
61
+ stamps.set(module, other)
62
+
63
+ if (found !== undefined && facts !== undefined)
64
+ children[specifier] = { key: found, deferred: facts.deferred, size: facts.size, reach: facts.reach }
65
+ }
66
+
67
+ const deferred = deferredProps(file, imports, specifier => children[specifier])
68
+ const reach = eagerReach(imports, children, lazyImports(file, imports, children))
69
+ const facts = { stamps, deferred, size: source.length, reach }
70
+
71
+ known.set(path, facts)
72
+
73
+ return facts
74
+ }
75
+
76
+ // What names a lazy component's chunk to the page that draws it and to the build's manifest: the file's name and a hash of its path from the root, the same wherever it is read from.
77
+ export function lazyKey(root: string, path: string): string {
78
+ const name = basename(path, '.kay').replaceAll(UNSAFE_KEY, '_')
79
+
80
+ return `${name}-${Bun.hash(relative(realOf(root), realOf(path)).replaceAll('\\', '/')).toString(36).slice(0, 6)}`
81
+ }
82
+
83
+ // The components whose lazy chunk the build found to be a stub, which then load with the code drawing them.
84
+ const eager = new Set<string>()
85
+
86
+ // Marks components as loading with their importers; whether any was not marked already.
87
+ export function keepEager(keys: Iterable<string>): boolean {
88
+ const before = eager.size
89
+
90
+ for (const key of keys)
91
+ eager.add(key)
92
+
93
+ return eager.size > before
94
+ }
95
+
96
+ // The keys marked so far, which a cache of what depends on the imports the islands make has to key on.
97
+ export function eagerKeys(): string[] {
98
+ return [...eager].sort()
99
+ }
100
+
101
+ // Its path with the links resolved, or as it is when no file is there.
102
+ function realOf(path: string): string {
103
+ try {
104
+ return realpathSync(path)
105
+ }
106
+ catch {
107
+ return path
108
+ }
109
+ }
110
+
111
+ // The `.kay` components a file imports that its templates may draw lazily: each with the key naming its chunk (its path from the root) and the props it draws only inside a branch that may not render.
112
+ export function importedComponents(file: string, source: string, root: string): ImportedComponents {
113
+ const found: Record<string, ImportedComponent> = {}
114
+ const self = realOf(file)
115
+
116
+ for (const { source: specifier } of importsOf(source)) {
117
+ const path = resolveFrom(specifier, file)
118
+
119
+ // A component drawing itself stays eager whatever its import is written as: its module is the one loading, so a chunk would only make its nested draws late.
120
+ if (path !== undefined && realOf(path) === self)
121
+ continue
122
+
123
+ const facts = path === undefined ? undefined : factsOf(path, new Set())
124
+
125
+ if (path !== undefined && facts !== undefined)
126
+ found[specifier] = { key: lazyKey(root, path), deferred: facts.deferred, size: eager.has(lazyKey(root, path)) ? 0 : facts.size, reach: facts.reach.map(other => lazyKey(root, other)) }
127
+ }
128
+
129
+ return found
130
+ }
@@ -0,0 +1,56 @@
1
+ type Outputs = Record<string, { imports: { kind: string, path: string }[] }>
2
+
3
+ // A component's chunk by its key; two files that hash to one key would load each other's code, so that is refused.
4
+ export function noteLazy(manifest: { lazies?: Record<string, string[]> | undefined }, key: string, file: string, chunks: string[]): void {
5
+ const lazies = manifest.lazies ??= {}
6
+
7
+ if (lazies[key] !== undefined && lazies[key].join() !== chunks.join())
8
+ throw new Error(`${file} and another component share the lazy key ${key}: rename one of the files`)
9
+
10
+ lazies[key] = chunks
11
+ }
12
+
13
+ // Every chunk a chunk needs before it can run, itself included.
14
+ export function staticClosure(outputs: Outputs, output: string, seen = new Set<string>()): Set<string> {
15
+ if (seen.has(output))
16
+ return seen
17
+
18
+ seen.add(output)
19
+ for (const imported of outputs[output]?.imports ?? []) {
20
+ if (imported.kind === 'import-statement')
21
+ staticClosure(outputs, imported.path, seen)
22
+ }
23
+
24
+ return seen
25
+ }
26
+
27
+ type Entries = Record<string, { entryPoint?: string | undefined, inputs?: Record<string, { bytesInOutput?: number | undefined }> | undefined }>
28
+
29
+ // What the lazy runtime and a request cost a page, minified: the lazy chunks of a build holding less than this between them leave a page heavier than the code they keep off it.
30
+ const LAZY_PAYOFF = 6000
31
+
32
+ // The keys of the lazy components that do not pay: a chunk that is only a stub, its code sitting in chunks the islands load up front, or all of them when the chunks with code of their own weigh less than `LAZY_PAYOFF` together. The build runs again with these imports eager.
33
+ export function stubKeys(outputs: Entries, keyOf: (entryPoint: string) => string | undefined): string[] {
34
+ const stubs: string[] = []
35
+ const held: string[] = []
36
+ let bytes = 0
37
+
38
+ for (const meta of Object.values(outputs)) {
39
+ const key = meta.entryPoint === undefined ? undefined : keyOf(meta.entryPoint)
40
+
41
+ if (key === undefined)
42
+ continue
43
+
44
+ const own = Object.values(meta.inputs ?? {}).reduce((sum, input) => sum + (input.bytesInOutput ?? 0), 0)
45
+
46
+ if (own === 0) {
47
+ stubs.push(key)
48
+ }
49
+ else {
50
+ held.push(key)
51
+ bytes += own
52
+ }
53
+ }
54
+
55
+ return bytes < LAZY_PAYOFF ? [...stubs, ...held] : stubs
56
+ }
@@ -0,0 +1,31 @@
1
+ import { rm } from 'node:fs/promises'
2
+ import { keepEager } from './lazy-components'
3
+ import { stubKeys } from './lazy-manifest'
4
+
5
+ // The last round builds whatever it finds.
6
+ const ROUNDS = 3
7
+
8
+ class Folded extends Error {}
9
+
10
+ // Marks the lazy components of the build that do not pay (see `stubKeys`) to load with the code drawing them, and ends the round, its files removed, when there were some: what the runtime chunk holds follows the imports the islands make, so the build is searched and run again.
11
+ export async function foldStubs(build: Bun.BuildOutput, nav: { build: Bun.BuildOutput } | undefined, last: boolean, keyOf: (entryPoint: string) => string | undefined): Promise<void> {
12
+ if (last || !build.success || !keepEager(stubKeys(build.metafile!.outputs, keyOf)))
13
+ return
14
+
15
+ await Promise.all([build, nav?.build].flatMap(each => each?.outputs ?? []).map(async output => rm(output.path, { force: true })))
16
+
17
+ throw new Folded()
18
+ }
19
+
20
+ // Runs a build, again when a round folded stubs; the run is told when it is the last.
21
+ export async function inRounds<T>(run: (last: boolean) => Promise<T>): Promise<T> {
22
+ for (let round = 0; ; round++) {
23
+ try {
24
+ return await run(round === ROUNDS - 1)
25
+ }
26
+ catch (error) {
27
+ if (!(error instanceof Folded))
28
+ throw error
29
+ }
30
+ }
31
+ }
@@ -1,7 +1,7 @@
1
1
  import type { Manifest } from './manifests'
2
2
  import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
3
3
  import { isBuiltin } from 'node:module'
4
- import { dirname, join, relative, resolve, sep } from 'node:path'
4
+ import { basename, dirname, join, relative, resolve, sep } from 'node:path'
5
5
  import { KayError } from '../compiler/errors'
6
6
  import { parseKay } from '../compiler/parser'
7
7
  import { findKayFiles, KAY_FILE, readSource, scoped, SCRIPT_FILE, scriptLoader, transpilerFor } from './files'
@@ -222,7 +222,28 @@ export function packageRoot(dir: string): string {
222
222
  }
223
223
  }
224
224
 
225
- // The library holding `file`, by its path under `node_modules` or its real one: the deepest, for a library installed inside another's `node_modules`.
225
+ // Whether `path` exists outside the project's own files and is no install: a linked library or a folder above the root, whose real path is outside any `node_modules`.
226
+ export function linkedOutside(root: string, path: string): boolean {
227
+ const own = relative(resolve(root), path)
228
+
229
+ return (own.startsWith('..') || own.split(sep).includes('node_modules')) && existsSync(path) && !realpathSync(path).split(sep).includes('node_modules')
230
+ }
231
+
232
+ // The package holding each of `extensionDirs`, an extension's routes or its editor's directory, that no kay library holds, the nearest directory above them with a package.json, as a library: its components are shadowed and reached as one's are.
233
+ export async function extensionPackages(root: string, libraries: KayLibrary[], extensionDirs: string[]): Promise<KayLibrary[]> {
234
+ const dirs = new Set(extensionDirs.filter(dir => libraryOf(libraries, join(dir, 'page.kay')) === undefined).map(packageRoot))
235
+
236
+ const realRoot = realpathSync(root)
237
+
238
+ return Promise.all([...dirs].map(async (dir) => {
239
+ // Left out: the app itself, when the package holds it as a fixture; the other projects inside it, to their own checks; a kay library's files, to the library. A package linked into `node_modules` goes by that path, as the app imports it.
240
+ const files = (await findKayFiles(dir, { project: true, ownOnly: true, ownKayOnly: true })).filter(file => !realpathSync(file).startsWith(realRoot + sep) && libraryOf(libraries, file) === undefined)
241
+
242
+ return { name: basename(dir), dir, realDir: realpathSync(dir), files, specifiers: new Map<string, string>(), exports: undefined, extension: true as const }
243
+ }))
244
+ }
245
+
246
+ // Whether the package.json at `manifest` names a package.
226
247
  function namesPackage(manifest: string): boolean {
227
248
  try {
228
249
  return typeof (JSON.parse(readFileSync(manifest, 'utf8')) as { name?: unknown }).name === 'string'
@@ -232,6 +253,7 @@ function namesPackage(manifest: string): boolean {
232
253
  }
233
254
  }
234
255
 
256
+ // The library holding `file`, by its path under `node_modules` or its real one: the deepest, for a library installed inside another's `node_modules`.
235
257
  export function libraryOf(libraries: KayLibrary[], file: string): KayLibrary | undefined {
236
258
  const holding = (dir: string) => file.startsWith(dir + sep) ? dir.length : 0
237
259
 
@@ -16,6 +16,7 @@ import { cacheIds } from './cache-ids'
16
16
  import { directImports } from './direct-imports'
17
17
  import { KAY_MODULE, SCRIPT_FILE, scriptLoader } from './files'
18
18
  import { expandGlobs } from './glob'
19
+ import { isUiRegistry, REGISTRY_FILE, registryWith } from './icon-slots'
19
20
  import { iconModule, iconNames, installedIconSets } from './icons'
20
21
  import { linkedKayCopies, settingsReplacements } from './libraries'
21
22
  import { liveIds } from './live-ids'
@@ -48,6 +49,8 @@ export interface KayPluginOptions {
48
49
  inspect?: boolean | undefined
49
50
  // The classes a later Tailwind class overrides, with which an island's literal classes resolve while compiling.
50
51
  classTable?: ClassTable | undefined
52
+ // False draws every component at once: the bundle of a component mounted by a test, which has no server markup to claim and nothing to wait for.
53
+ lazy?: boolean | undefined
51
54
  // A browser build's API trees, whose modules islands get as stubs, and the modules it leaves to the page, which a worker's bundle takes as the islands do.
52
55
  api?: RouteMount[] | undefined
53
56
  external?: string[] | undefined
@@ -65,6 +68,8 @@ export interface KayPluginOptions {
65
68
  rewrite?: ((file: string, source: string) => string) | undefined
66
69
  // What the build knows of the call sites of its components with features, shared by every bundle of it; one of its own, over the project's files, when unset.
67
70
  variants?: VariantIndex | undefined
71
+ // The icon slots of kayjs-ui the islands can draw: its registry loads with these alone. Unset, it loads whole.
72
+ iconSlots?: ReadonlySet<string> | undefined
68
73
  }
69
74
 
70
75
  // A static component imports its `?island` twin, the build of it that renders inside islands, as a module of its own.
@@ -263,7 +268,7 @@ export function kayPlugin(options: KayPluginOptions, workers: string[]): BunPlug
263
268
  const original = await Bun.file(withoutTwin(file)).text()
264
269
  const source = features === undefined ? original : specializedSource(original, features, withoutTwin(file))
265
270
 
266
- const compiled = await transformKayCached(source, file, { target, hydratable: options.hydratable ?? true, root: options.root, pages: options.pages, cacheDir: options.cacheDir, inspect: options.inspect, classTable: options.classTable, variant: features === undefined ? undefined : `${[...features].sort().join('.')}${written === undefined ? '' : `~${[...written].sort().join('.')}`}`, writtenProps: written })
271
+ const compiled = await transformKayCached(source, file, { target, hydratable: options.hydratable ?? true, root: options.root, pages: options.pages, cacheDir: options.cacheDir, inspect: options.inspect, classTable: options.classTable, lazy: options.lazy, variant: features === undefined ? undefined : `${[...features].sort().join('.')}${written === undefined ? '' : `~${[...written].sort().join('.')}`}`, writtenProps: written })
267
272
  const code = target === 'dom' ? await variantIndex.variantImports(compiled, withoutTwin(file), original) : compiled
268
273
  const contents = await pointed(await shippingFiles(expandGlobs(code, withoutTwin(file), root, 'ts'), withoutTwin(file), 'ts'))
269
274
 
@@ -300,6 +305,13 @@ export function kayPlugin(options: KayPluginOptions, workers: string[]): BunPlug
300
305
  build.onLoad({ filter: new RegExp(`^${RegExp.escape(path)}$`) }, () => ({ contents: `export * from ${JSON.stringify(replacement)}\nexport { default } from ${JSON.stringify(replacement)}\n`, loader: 'ts' }))
301
306
  }
302
307
 
308
+ // After the app's own settings, which stay whole: only kayjs-ui's default registry is cut.
309
+ if (target === 'dom' && options.iconSlots !== undefined) {
310
+ const slots = options.iconSlots
311
+
312
+ build.onLoad({ filter: REGISTRY_FILE }, async ({ path }) => isUiRegistry(path) ? { contents: registryWith(await Bun.file(path).text(), slots), loader: 'ts' } : undefined)
313
+ }
314
+
303
315
  // A linked library's own copy of kay loads as the app's: each of its modules re-exports the app's module at the same place, so the library and the app share one kay. A module the app's copy lacks, as another version may, stays the library's.
304
316
  for (const { from, to } of linkedKayCopies(root)) {
305
317
  build.onLoad({ filter: new RegExp(`^${RegExp.escape(from + sep)}(?!(?:.*[\\\\/])?node_modules[\\\\/]).*\\.[cm]?[jt]sx?$`) }, async ({ path }) => {
@@ -25,10 +25,10 @@ const DEFAULT_IMPORT = /^[\w$]+\s*(?:,|$)/
25
25
  const NAMED = /\{([^}]*)\}/
26
26
  const ALIAS = /\s+as\s+/
27
27
  const KAY_SPECIFIER = /^kay(?:\/|$)/
28
- // Lazy modules whose imports of the runtime stay with them rather than join the chunk a page loads: the code reviving an action, which only a page passing an island one loads, carries the action runtime along, the code posting an action call, which the first call loads, and the reader of a streaming action's answer, whose `ended()`, `onData()` and `retry()` a page with no such action does not carry.
29
- const STANDALONE = new Set([resolve(RUNTIME_DIR, 'action-reviver.ts'), resolve(RUNTIME_DIR, 'action-stream.ts'), resolve(RUNTIME_DIR, 'action-post.ts')])
28
+ // Lazy modules whose imports of the runtime stay with them rather than join the chunk a page loads: the code reviving an action, which only a page passing an island one loads, carries the action runtime along, the code running an action call, which the first call loads, and the reader of a streaming action's answer, whose `ended()`, `onData()` and `retry()` a page with no such action does not carry.
29
+ const STANDALONE = new Set([resolve(RUNTIME_DIR, 'action-reviver.ts'), resolve(RUNTIME_DIR, 'action-stream.ts'), resolve(RUNTIME_DIR, 'action-run.ts')])
30
30
  // Entries of the runtime that bundle a package, or that few pages use, which stay in the chunks of the islands importing them rather than weigh on every page: the `for`, `await` and `try` blocks, the spread and the localizing of the links an island writes, which most islands do without.
31
- const OWN_CHUNK = new Set(['kay/markdown', 'kay/internal/title', 'kay/dom-loop', 'kay/dom-await', 'kay/dom-try', 'kay/dom-spread', 'kay/i18n-links'])
31
+ const OWN_CHUNK = new Set(['kay/markdown', 'kay/internal/title', 'kay/dom-loop', 'kay/dom-await', 'kay/dom-try', 'kay/dom-spread', 'kay/dom-lazy', 'kay/i18n-links'])
32
32
  const RELATIVE = /^\.\.?\//
33
33
  const EXTENSIONS = ['.ts', '.tsx', '/index.ts']
34
34
  const ALL = '*'
@@ -1,9 +1,10 @@
1
1
  import type { KayExtension } from '../config'
2
2
  import type { ImportGraph, KayLibrary } from './libraries'
3
3
  import { existsSync } from 'node:fs'
4
+ import { dirname } from 'node:path'
4
5
  import { extensionEditor, routeMounts } from '../server/routes'
5
6
  import { findKayFiles } from './files'
6
- import { findKayLibraries, reachableLibraryFiles } from './libraries'
7
+ import { extensionPackages, findKayLibraries, linkedOutside, reachableLibraryFiles } from './libraries'
7
8
 
8
9
  export interface BuildFiles {
9
10
  // The project's own components, the pages of the libraries it mounts and the components of the libraries it reaches, in that order.
@@ -22,9 +23,13 @@ export async function buildFiles(root: string, extensions: KayExtension[] | unde
22
23
  const ownFiles = new Set(own)
23
24
  const editor = extensionEditor(root, extensions)
24
25
  // The pages of the libraries the app mounts, which it reaches through its config rather than an import.
25
- const mountedFiles = (await Promise.all(routeMounts(root, extensions).map(async mount => existsSync(mount.dir) ? findKayFiles(mount.dir) : []))).flat()
26
+ const mounts = routeMounts(root, extensions)
27
+ const mountedFiles = (await Promise.all(mounts.map(async mount => existsSync(mount.dir) ? findKayFiles(mount.dir) : []))).flat()
26
28
  const mounted = [...new Set([...mountedFiles, ...editor === undefined ? [] : [editor]])].filter(file => !ownFiles.has(file))
27
- const libraries = await findKayLibraries(root)
29
+ const installed = await findKayLibraries(root)
30
+ // An extension reached with no dependency on it, as a workspace link or a folder above the root, is a library whose islands the pages it wraps still render.
31
+ const mountDirs = mounts.filter(mount => mount.reaching !== 'context' && linkedOutside(root, mount.dir)).map(mount => mount.dir)
32
+ const libraries = [...installed, ...await extensionPackages(root, installed, [...mountDirs, ...editor === undefined || !linkedOutside(root, editor) ? [] : [dirname(editor)]])]
28
33
  const fromLibraries = await reachableLibraryFiles(root, libraries, [...own, ...mounted], graph)
29
34
 
30
35
  return { files: [...own, ...mounted, ...fromLibraries.components], own, mounted, editor, libraries, fromLibraries }