@kayjs/kay 1.104.1 → 1.104.3

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 (116) hide show
  1. package/README.md +2 -7
  2. package/dist/eslint.js +208 -34
  3. package/editors/zed/extension.toml +2 -2
  4. package/llms/check-and-tools.md +5 -3
  5. package/llms/code-lints.md +1 -0
  6. package/llms/components.md +1 -1
  7. package/llms/islands.md +1 -1
  8. package/llms/project-new-and-add.md +5 -5
  9. package/llms/project.md +1 -2
  10. package/llms/styles-and-assets.md +1 -1
  11. package/llms/testing-browser.md +1 -0
  12. package/llms/upgrading.md +4 -0
  13. package/llms/whats-new-archive.md +17 -1
  14. package/llms/whats-new.md +20 -17
  15. package/llms.txt +1 -1
  16. package/package.json +9 -7
  17. package/src/add.ts +2 -0
  18. package/src/build/class-rules.ts +8 -0
  19. package/src/build/client.ts +9 -6
  20. package/src/build/recipe-classes.ts +11 -1
  21. package/src/build/recipe-utilities.ts +183 -0
  22. package/src/build/signals.ts +113 -14
  23. package/src/build/style-uses.ts +7 -6
  24. package/src/build/styles.ts +32 -21
  25. package/src/build/supports.ts +4 -4
  26. package/src/check/removed-ui-tokens.ts +2 -2
  27. package/src/check/shadow-types.ts +2 -0
  28. package/src/check/text-size-colour.ts +57 -0
  29. package/src/commands/new.ts +17 -7
  30. package/src/commands/upgrade-majors.ts +26 -0
  31. package/src/commands/upgrade-manifest.ts +23 -0
  32. package/src/commands/upgrade-messages.ts +16 -0
  33. package/src/commands/upgrade-peers.ts +89 -0
  34. package/src/commands/upgrade.ts +68 -36
  35. package/src/compiler/codegen.ts +1 -1
  36. package/src/compiler/dom.ts +12 -1
  37. package/src/compiler/index.ts +32 -17
  38. package/src/compiler/island-cause.ts +5 -2
  39. package/src/compiler/module-signals.ts +111 -8
  40. package/src/compiler/rewrite-reads.ts +1 -1
  41. package/src/compiler/route-lints.ts +8 -0
  42. package/src/compiler/script-props.ts +18 -1
  43. package/src/compiler/script-shared.ts +2 -0
  44. package/src/eslint/index.ts +19 -2
  45. package/src/features.ts +2 -2
  46. package/src/lsp/semantic-tokens.ts +2 -2
  47. package/src/migrate/project.ts +2 -2
  48. package/src/new.ts +6 -4
  49. package/src/runtime/dom.ts +11 -12
  50. package/src/template-config.ts +11 -4
  51. package/src/template-docker.ts +1 -1
  52. package/src/template-shared.ts +4 -1
  53. package/src/template-starter.ts +25 -4
  54. package/src/template-styles.ts +55 -43
  55. package/src/template-ws.ts +1 -1
  56. package/src/templates.ts +2 -4
  57. package/src/test/browser.ts +2 -5
  58. package/src/test/text-match.ts +44 -0
  59. package/types/add.d.ts.map +1 -1
  60. package/types/build/class-rules.d.ts +1 -0
  61. package/types/build/class-rules.d.ts.map +1 -1
  62. package/types/build/client.d.ts +1 -1
  63. package/types/build/client.d.ts.map +1 -1
  64. package/types/build/recipe-classes.d.ts +2 -0
  65. package/types/build/recipe-classes.d.ts.map +1 -1
  66. package/types/build/recipe-utilities.d.ts +4 -0
  67. package/types/build/recipe-utilities.d.ts.map +1 -0
  68. package/types/build/signals.d.ts.map +1 -1
  69. package/types/build/style-uses.d.ts +1 -0
  70. package/types/build/style-uses.d.ts.map +1 -1
  71. package/types/build/styles.d.ts +1 -1
  72. package/types/build/styles.d.ts.map +1 -1
  73. package/types/build/supports.d.ts +1 -1
  74. package/types/build/supports.d.ts.map +1 -1
  75. package/types/check/removed-ui-tokens.d.ts +2 -0
  76. package/types/check/removed-ui-tokens.d.ts.map +1 -1
  77. package/types/check/shadow-types.d.ts.map +1 -1
  78. package/types/check/text-size-colour.d.ts +3 -0
  79. package/types/check/text-size-colour.d.ts.map +1 -0
  80. package/types/commands/new.d.ts.map +1 -1
  81. package/types/commands/upgrade-majors.d.ts +7 -0
  82. package/types/commands/upgrade-majors.d.ts.map +1 -0
  83. package/types/commands/upgrade-manifest.d.ts +6 -0
  84. package/types/commands/upgrade-manifest.d.ts.map +1 -0
  85. package/types/commands/upgrade-messages.d.ts +4 -0
  86. package/types/commands/upgrade-messages.d.ts.map +1 -0
  87. package/types/commands/upgrade-peers.d.ts +23 -0
  88. package/types/commands/upgrade-peers.d.ts.map +1 -0
  89. package/types/commands/upgrade.d.ts +7 -0
  90. package/types/commands/upgrade.d.ts.map +1 -1
  91. package/types/compiler/dom.d.ts +1 -0
  92. package/types/compiler/dom.d.ts.map +1 -1
  93. package/types/compiler/index.d.ts.map +1 -1
  94. package/types/compiler/island-cause.d.ts +2 -2
  95. package/types/compiler/island-cause.d.ts.map +1 -1
  96. package/types/compiler/lints.d.ts +8 -0
  97. package/types/compiler/lints.d.ts.map +1 -1
  98. package/types/compiler/module-signals.d.ts +14 -1
  99. package/types/compiler/module-signals.d.ts.map +1 -1
  100. package/types/compiler/route-lints.d.ts +8 -0
  101. package/types/compiler/route-lints.d.ts.map +1 -1
  102. package/types/compiler/script-props.d.ts.map +1 -1
  103. package/types/compiler/script-shared.d.ts +1 -0
  104. package/types/compiler/script-shared.d.ts.map +1 -1
  105. package/types/new.d.ts.map +1 -1
  106. package/types/runtime/dom.d.ts +1 -0
  107. package/types/runtime/dom.d.ts.map +1 -1
  108. package/types/template-config.d.ts.map +1 -1
  109. package/types/template-shared.d.ts +1 -1
  110. package/types/template-shared.d.ts.map +1 -1
  111. package/types/template-starter.d.ts.map +1 -1
  112. package/types/template-styles.d.ts.map +1 -1
  113. package/types/templates.d.ts.map +1 -1
  114. package/types/test/browser.d.ts.map +1 -1
  115. package/types/test/text-match.d.ts +13 -0
  116. package/types/test/text-match.d.ts.map +1 -0
@@ -64,6 +64,11 @@ function tokensOf(file: string): { text: string, words: Set<string>, fragments:
64
64
  return found
65
65
  }
66
66
 
67
+ // The classes a stylesheet's `@source inline` lists.
68
+ export function inlineClasses(css: string): string[] {
69
+ return [...css.matchAll(SOURCE_INLINE)].flatMap(([, , pattern]) => pattern!.split(SPACES).flatMap(expandInline))
70
+ }
71
+
67
72
  // The class-like words of the string literals of a script, which are what it writes out as names, unlike an identifier or a comment.
68
73
  const STRING_LITERAL = /'(?:\\.|[^'\\\n])*'|"(?:\\.|[^"\\\n])*"|`(?:\\.|[^`\\])*`/g
69
74
 
@@ -239,12 +244,8 @@ function stylesheetClasses(file: string, kept: Set<string>, seen = new Set<strin
239
244
  for (const name of styledClassNames(parse(text)))
240
245
  found.add(name)
241
246
 
242
- for (const [, , pattern] of text.matchAll(SOURCE_INLINE)) {
243
- for (const word of pattern!.split(SPACES)) {
244
- for (const name of expandInline(word))
245
- kept.add(name)
246
- }
247
- }
247
+ for (const name of inlineClasses(text))
248
+ kept.add(name)
248
249
 
249
250
  for (const match of text.matchAll(CSS_IMPORT)) {
250
251
  const imported = resolve(dirname(file), match[1]!)
@@ -1,7 +1,7 @@
1
1
  import type { BunPlugin } from 'bun'
2
2
  import type { KayLibrary } from './libraries'
3
3
  import { readFileSync, statSync } from 'node:fs'
4
- import { rename } from 'node:fs/promises'
4
+ import { realpath, rename } from 'node:fs/promises'
5
5
  import { dirname, join, relative, sep } from 'node:path'
6
6
  import { islandId, withoutTwin } from '../compiler'
7
7
  import { parseKay } from '../compiler/parser'
@@ -82,6 +82,23 @@ async function keepStylesheet(file: string, contents: string): Promise<void> {
82
82
  }
83
83
  }
84
84
 
85
+ // Writes a `--- style` fence as a stylesheet of its own under the cache, its selectors scoped, and gives its path.
86
+ async function writeScopedStylesheet(root: string, path: string, css: string, reference: () => Promise<string | undefined>): Promise<string> {
87
+ const moduleId = islandId(throughLinks(root, path), root)
88
+ const file = join(cacheDir(root, 'scoped'), `${scopeHash(moduleId)}.css`)
89
+
90
+ scopedTouched = true
91
+ touchCacheFile(file)
92
+
93
+ const scoped = rebaseUrls(scopeCss(css, scopeAttribute(moduleId)), dirname(path), dirname(file))
94
+ // `@apply` in a stylesheet of its own needs the app's Tailwind entry as a reference, which kay writes so the fence needs no line of it.
95
+ const entry = THEME_USE.test(scoped) ? await reference() : undefined
96
+
97
+ await keepStylesheet(file, entry === undefined ? scoped : `@reference ${JSON.stringify(relative(dirname(file), entry).split(sep).join('/'))};\n${scoped}`)
98
+
99
+ return file
100
+ }
101
+
85
102
  // Writes the stylesheet of the classes a component's recipe lifted, undefined when it lifts none.
86
103
  async function writeRecipeStylesheet(root: string, path: string, source: string, reference: () => Promise<string | undefined>): Promise<string | undefined> {
87
104
  const rules = source.includes('recipe(') ? (await recipeLifter(root))?.lift(source, path)?.rules : undefined
@@ -99,16 +116,24 @@ async function writeRecipeStylesheet(root: string, path: string, source: string,
99
116
  return file
100
117
  }
101
118
 
102
- // Writes the stylesheets of the recipes among `files` before the bundler runs: Bun reads a folder once, so a file written into it while it bundles can fail to resolve.
103
- export async function writeRecipeStylesheets(root: string, files: string[]): Promise<void> {
119
+ // Writes the stylesheets of the `--- style` fences and recipes among `files` before the bundler runs: Bun reads a folder once, so a file written into it while it bundles can fail to resolve.
120
+ // Each is written under the file's real path, the one Bun hands the plugin, so both name and rebase it alike: a library under Bun's isolated store is reached through a link inside the root.
121
+ export async function writeComponentStylesheets(root: string, files: string[]): Promise<void> {
104
122
  const reference = tailwindEntry(root, true)
105
123
 
106
- await Promise.all(files.filter(file => KAY_FILE.test(file)).map(async (file) => {
124
+ await Promise.all(files.filter(file => KAY_FILE.test(file)).map(async (listed) => {
107
125
  try {
108
- await writeRecipeStylesheet(root, file, await Bun.file(file).text(), async () => reference)
126
+ const file = await realpath(listed)
127
+ const source = await Bun.file(file).text()
128
+ const style = source.includes('style') ? parseKay(source).style : undefined
129
+
130
+ await Promise.all([
131
+ style && writeScopedStylesheet(root, file, source.slice(style.start, style.end), async () => reference),
132
+ writeRecipeStylesheet(root, file, source, async () => reference),
133
+ ])
109
134
  }
110
135
  catch (error) {
111
- // A file deleted since the listing is no recipe to write.
136
+ // A file deleted since the listing has no stylesheet to write.
112
137
  if ((error as NodeJS.ErrnoException).code !== 'ENOENT')
113
138
  throw error
114
139
  }
@@ -179,21 +204,7 @@ export function styleImports(root: string, libraries: KayLibrary[] = [], loaded?
179
204
  // The app's Tailwind entry, looked up once per build for every fence using `@apply`.
180
205
  let tailwindReference: Promise<string | undefined> | undefined
181
206
  // A `--- style` fence reaches the bundler as a stylesheet of its own, written under the cache with its selectors scoped.
182
- const scopedStylesheet = async (path: string, css: string) => {
183
- const moduleId = islandId(throughLinks(root, path), root)
184
- const file = join(cacheDir(root, 'scoped'), `${scopeHash(moduleId)}.css`)
185
-
186
- scopedTouched = true
187
- touchCacheFile(file)
188
-
189
- const scoped = rebaseUrls(scopeCss(css, scopeAttribute(moduleId)), dirname(path), dirname(file))
190
- // `@apply` in a stylesheet of its own needs the app's Tailwind entry as a reference, which kay writes so the fence needs no line of it.
191
- const entry = THEME_USE.test(scoped) ? await (tailwindReference ??= tailwindEntry(root, true)) : undefined
192
-
193
- await keepStylesheet(file, entry === undefined ? scoped : `@reference ${JSON.stringify(relative(dirname(file), entry).split(sep).join('/'))};\n${scoped}`)
194
-
195
- return importing(note(path, [file]))
196
- }
207
+ const scopedStylesheet = async (path: string, css: string) => importing(note(path, [await writeScopedStylesheet(root, path, css, async () => tailwindReference ??= tailwindEntry(root, true))]))
197
208
  // The rules of the classes a component's recipe lifted into the stylesheet, which the pages rendering the component carry as they carry a `--- style` fence's.
198
209
  const recipeStylesheet = async (path: string, source: string) => {
199
210
  const file = await writeRecipeStylesheet(root, path, source, async () => tailwindReference ??= tailwindEntry(root, true))
@@ -171,15 +171,15 @@ async function referenced<T>(path: string, references: StyleReferences, load: ()
171
171
  }
172
172
 
173
173
  // The stylesheet build's plugins, each stylesheet one returns merged, and a last one merging those no plugin loads; `transform` runs on the parsed stylesheet first, as kay prunes a library's unused classes, so each output is parsed and printed once.
174
- export function mergingSupports(plugins: BunPlugin[], transform: (nodes: Node[]) => Node[] | Promise<Node[]> = nodes => nodes, references?: StyleReferences): BunPlugin[] {
175
- const rewrite = async (css: string) => css.includes('{') ? print(merge(await transform(parse(css)), false)) : css
174
+ export function mergingSupports(plugins: BunPlugin[], transform: (nodes: Node[], tailwind: boolean) => Node[] | Promise<Node[]> = nodes => nodes, references?: StyleReferences): BunPlugin[] {
175
+ const rewrite = async (css: string, tailwind: boolean) => css.includes('{') ? print(merge(await transform(parse(css), tailwind), false)) : css
176
176
  const wrapped = plugins.map((plugin): BunPlugin => ({
177
177
  ...plugin,
178
178
  async setup(build) {
179
179
  const onLoad: PluginBuilder['onLoad'] = (constraints, callback) => build.onLoad(constraints, async (args) => {
180
180
  const result = await (references !== undefined && references.files.length > 0 && args.namespace === 'file' && referenceable(args.path, references.root) ? referenced(args.path, references, async () => callback(args)) : callback(args))
181
181
 
182
- return result && 'contents' in result && typeof result.contents === 'string' && (result.loader === 'css' || (result.loader === undefined && CSS_FILE.test(args.path))) ? { ...result, contents: await rewrite(result.contents) } : result
182
+ return result && 'contents' in result && typeof result.contents === 'string' && (result.loader === 'css' || (result.loader === undefined && CSS_FILE.test(args.path))) ? { ...result, contents: await rewrite(result.contents, plugin.name.includes('tailwind')) } : result
183
183
  })
184
184
 
185
185
  return plugin.setup(new Proxy(build, { get: (target, key) => key === 'onLoad' ? onLoad : Reflect.get(target, key) as unknown }))
@@ -190,7 +190,7 @@ export function mergingSupports(plugins: BunPlugin[], transform: (nodes: Node[])
190
190
  setup(build) {
191
191
  build.onLoad({ filter: CSS_FILE }, async ({ path }) => {
192
192
  const css = await Bun.file(path).text()
193
- const merged = await rewrite(css)
193
+ const merged = await rewrite(css, false)
194
194
 
195
195
  return merged === css ? undefined : { contents: merged, loader: 'css' }
196
196
  })
@@ -70,12 +70,12 @@ export async function removedUiTokens(root: string, options: CheckOptions): Prom
70
70
  return found
71
71
  }
72
72
 
73
- function blank(text: string): string {
73
+ export function blank(text: string): string {
74
74
  return text.replace(/[^\n]/g, ' ')
75
75
  }
76
76
 
77
77
  // A `.kay` file or src/ui.ts with its `//` and `/* */` comments blanked, quoted strings left alone so a URL in one is not a comment. Prose in a template holds apostrophes and stray backticks, so an apostrophe after a word character (`don't`) opens nothing, a quote ends at its line, and a backtick runs on to its twin or to the next blank line; the code of a `${ }` inside one is read like any other.
78
- function blankComments(source: string): string {
78
+ export function blankComments(source: string): string {
79
79
  let out = ''
80
80
  let index = 0
81
81
  let quote = ''
@@ -53,6 +53,7 @@ import { schemaType } from './schema-type'
53
53
  import { compileShadow, guardTypes, layoutQueries, matcherSource, outerSlots, pageRoute, serializeShadowSettings, SHADOW_SETTINGS, shadowOptionsFor, shadowPath } from './shadow'
54
54
  import { untypedSockets } from './socket-routes'
55
55
  import { unusedStatusPages } from './status-pages'
56
+ import { textSizeColour } from './text-size-colour'
56
57
  import { unknownToolLabels } from './tool-labels'
57
58
  import { typingOptions } from './tsgo'
58
59
 
@@ -149,6 +150,7 @@ const PROJECT_CHECKS: ((input: ProjectCheckInput) => CheckDiagnostic[] | Promise
149
150
  async ({ root, options, served }) => largePublicImages(options, root, served),
150
151
  async ({ options, served }) => untypedSockets(options, served),
151
152
  async ({ root, options }) => removedUiTokens(root, options),
153
+ async ({ root, options }) => textSizeColour(root, options),
152
154
  async ({ root, options }) => unknownToolLabels(root, options),
153
155
  async ({ root, options }) => publicEnvOutsideSrc(root, options),
154
156
  ({ root, options }) => unmountedJobs(root, options),
@@ -0,0 +1,57 @@
1
+ import type { CheckDiagnostic, CheckOptions } from '.'
2
+ import { CSS_FILE, findProjectFiles, KAY_FILE } from '../build/files'
3
+ import { lintLevel, lintLevels } from '../compiler/lints'
4
+ import { positionAt } from '../compiler/mapping'
5
+ import { blank, blankComments } from './removed-ui-tokens'
6
+
7
+ const COMMENT = /\/\*[\s\S]*?\*\//g
8
+ const SIZE = 'xs|sm|base|lg|xl|[2-9]xl'
9
+ const THEME = /@theme\b[^{]*\{([^}]*)\}/g
10
+ // A colour of the app's theme named like a size of Tailwind's `text-` utility: `--color-base`.
11
+ const DECLARED = new RegExp(`(?<![\\w-])--color-(${SIZE})\\s*:`, 'g')
12
+
13
+ // A `--color-base` makes `text-base` the text colour as well as the font size, so every use of the size also paints the text that colour: the page background, in a palette where `base` is the ground.
14
+ export async function textSizeColour(root: string, options: CheckOptions): Promise<CheckDiagnostic[]> {
15
+ const level = lintLevel('text-size-colour', options.lints)
16
+
17
+ if (level === 'allow')
18
+ return []
19
+
20
+ const files = [...await findProjectFiles(root, CSS_FILE, { project: true, ownOnly: true }), ...await findProjectFiles(root, KAY_FILE, { project: true, ownOnly: true })]
21
+ const sources = await Promise.all(files.map(async (file) => {
22
+ const source = await Bun.file(file).text()
23
+
24
+ return { file, source, code: CSS_FILE.test(file) ? source.replace(COMMENT, blank) : blankComments(source) }
25
+ }))
26
+ const names = new Set(sources.flatMap(({ code, file }) => CSS_FILE.test(file) ? [...code.matchAll(THEME)].flatMap(theme => [...theme[1]!.matchAll(DECLARED)]).map(match => match[1]!) : []))
27
+
28
+ if (names.size === 0)
29
+ return []
30
+
31
+ const use = new RegExp(`(?<![\\w-])text-(${[...names].join('|')})(?![\\w-])`, 'g')
32
+ const found: CheckDiagnostic[] = []
33
+
34
+ for (const { file, source, code } of sources) {
35
+ const levelAt = lintLevels(source, options.lints)
36
+
37
+ for (const match of code.matchAll(use)) {
38
+ const at = levelAt('text-size-colour', match.index)
39
+ const name = match[1]!
40
+
41
+ if (at === 'allow')
42
+ continue
43
+
44
+ found.push({
45
+ file,
46
+ ...positionAt(source, match.index),
47
+ end: match.index + match[0].length,
48
+ message: `\`text-${name}\` sets the font size and, as \`--color-${name}\` is a colour of the theme, the text colour too`,
49
+ help: `rename the colour (\`--color-${name}\` to \`--color-background\`, say) and write \`text-background\` where the colour was meant, or keep \`text-${name}\` for the size alone: \`text-[1rem]\` is the size without the colour`,
50
+ code: 'text-size-colour',
51
+ severity: at === 'warn' ? 'warning' : 'error',
52
+ })
53
+ }
54
+ }
55
+
56
+ return found
57
+ }
@@ -18,6 +18,22 @@ function printMissing(features: readonly Feature[], quiet: boolean): void {
18
18
  console.log(`\n Add ${missing.map(feature => ADDABLE[feature]).join(' and ')} later with ${colors.cyan(missing.map(feature => `kay add ${feature}`).join(' and '))}.`)
19
19
  }
20
20
 
21
+ // The preset with what --with adds and --without drops. kayjs-ui is in the presets to style the starter, so a project without Tailwind leaves it out unless it was asked for.
22
+ function chosenFeatures(template: Preset, added: readonly Feature[], removed: readonly Feature[]): Set<Feature> {
23
+ const chosen = new Set(PRESETS[template].features)
24
+
25
+ for (const name of added)
26
+ chosen.add(name)
27
+
28
+ for (const name of removed)
29
+ chosen.delete(name)
30
+
31
+ if (removed.includes('tailwind') && !added.includes('ui'))
32
+ chosen.delete('ui')
33
+
34
+ return chosen
35
+ }
36
+
21
37
  export const scaffold: Command = {
22
38
  usage: 'new <dir> [--kay <dependency>] [--template blank|server|site|app] [--with <features>] [--without <features>] [--editor helix,zed|none] [--forge forgejo|github] [--agents none] [--runner <label>] [-y] [--dry-run] [--format text|json] [--quiet]',
23
39
  options: { 'kay': { type: 'string' }, 'template': { type: 'string' }, 'with': { type: 'string' }, 'forge': { type: 'string' }, 'agents': { type: 'string' }, 'editor': { type: 'string' }, 'runner': { type: 'string' }, 'without': { type: 'string' }, 'yes': { type: 'boolean', short: 'y' }, 'dry-run': { type: 'boolean' }, 'format': { type: 'string' }, 'quiet': { type: 'boolean' } },
@@ -85,13 +101,7 @@ export const scaffold: Command = {
85
101
 
86
102
  // With no option saying what to scaffold, a terminal asks; anything else takes the preset, the server's by default, with what --with and --without change.
87
103
  const ask = template === undefined && added === undefined && removed === undefined && yes !== true && isInteractive()
88
- const chosen = new Set(PRESETS[(template as Preset | undefined) ?? 'server'].features)
89
-
90
- for (const name of listed(added))
91
- chosen.add(name as Feature)
92
-
93
- for (const name of listed(removed))
94
- chosen.delete(name as Feature)
104
+ const chosen = chosenFeatures((template as Preset | undefined) ?? 'server', listed(added) as Feature[], listed(removed) as Feature[])
95
105
 
96
106
  const features = ask ? await pickFeatures() : [...chosen]
97
107
 
@@ -0,0 +1,26 @@
1
+ import { existsSync } from 'node:fs'
2
+ import { join, relative } from 'node:path'
3
+
4
+ const GIT_PREFIX = /^git\+/
5
+ const CHANGE_FILES = ['MIGRATION.md', 'UPGRADING.md', 'CHANGELOG.md']
6
+
7
+ // Whether going from `from` to `to` is a major, a 0.x minor counting as one.
8
+ function crossesMajor(from: string, to: string): boolean {
9
+ const [fromMajor, fromMinor] = from.split('.').map(Number)
10
+ const [toMajor, toMinor] = to.split('.').map(Number)
11
+
12
+ return fromMajor !== toMajor || (fromMajor === 0 && fromMinor !== toMinor)
13
+ }
14
+
15
+ // The warning for a package raised from `held` to `wanted` across a major, pointing at its installed migration file (path from the app) or else its repository; undefined when it stayed within a major.
16
+ export function majorWarning(root: string, name: string, held: string, wanted: string, installed: { dir: string, repository?: string | { url?: string } } | undefined): string | undefined {
17
+ if (!crossesMajor(held, wanted))
18
+ return undefined
19
+
20
+ const file = installed === undefined ? undefined : CHANGE_FILES.map(file => join(installed.dir, file)).find(path => existsSync(path))
21
+ const repository = typeof installed?.repository === 'string' ? installed.repository : installed?.repository?.url
22
+ const where = file === undefined ? repository?.replace(GIT_PREFIX, '') : relative(root, file)
23
+ const notes = where === undefined ? '' : `: what changed is ${file === undefined ? 'at' : 'in'} ${where}`
24
+
25
+ return `${name} was raised from ${held} to ${wanted}, across a major, so its API may have changed${notes}`
26
+ }
@@ -0,0 +1,23 @@
1
+ import type { ProblemFormat } from './command'
2
+ import { existsSync } from 'node:fs'
3
+ import { printFailure } from './command'
4
+
5
+ // The text and the parsed content of the project's package.json; undefined after printing why there is none to upgrade.
6
+ export async function readManifest(manifest: string, root: string, format: ProblemFormat): Promise<{ original: string, packageJson: Record<string, unknown> } | undefined> {
7
+ if (!existsSync(manifest)) {
8
+ printFailure('upgrade', `${root} has no package.json`, format)
9
+
10
+ return undefined
11
+ }
12
+
13
+ const original = await Bun.file(manifest).text()
14
+
15
+ try {
16
+ return { original, packageJson: JSON.parse(original) }
17
+ }
18
+ catch (error) {
19
+ printFailure('upgrade', `package.json does not parse: ${error instanceof Error ? error.message : String(error)}`, format)
20
+
21
+ return undefined
22
+ }
23
+ }
@@ -0,0 +1,16 @@
1
+ import type { Phase } from './upgrade'
2
+
3
+ // Says each package a dry run would move in `phase`, and that its kay still rewrites forms when the phase is a stop on the way.
4
+ export function wouldMove({ version, changes, stone }: Phase, say: (verb: string, rest: string) => void): void {
5
+ for (const { name, spec } of changes)
6
+ say('would move', `${name} to ${spec.slice(spec.lastIndexOf('~'))}${stone ? ` (kay ${version} still rewrites forms the next minors drop)` : ''}`)
7
+ }
8
+
9
+ // Why a phase's install failed and where that left the app: back as it was when nothing had been rewritten, else at the version `behind` that the rewrites reached.
10
+ export function installFailed(version: string, behind: string, from: string): string {
11
+ const left = behind === from
12
+ ? 'so package.json and the lockfile are back as they were and nothing was rewritten; node_modules may still hold what the install did'
13
+ : `after the forms of the minors up to ${behind} were rewritten on the way; package.json and the lockfile are back at kay ${behind}`
14
+
15
+ return `the install of kay ${version} failed or left no kay in node_modules, ${left}, so run \`bun install\` once the install is fixed, then \`kay upgrade\` again`
16
+ }
@@ -0,0 +1,89 @@
1
+ import type { DependencyChange } from './upgrade'
2
+
3
+ // What `kay upgrade` reads of an installed kay: its peers and which of them are optional.
4
+ export interface PeerManifest {
5
+ peerDependencies?: Record<string, string>
6
+ peerDependenciesMeta?: Record<string, { optional?: boolean }>
7
+ }
8
+
9
+ const SECTIONS = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies']
10
+ const INDENT = /^\n?([ \t]+)"/m
11
+
12
+ // The optional peers an app installs itself (`typescript7`, `axe-core`, `@happy-dom/global-registrator`, `@kaynooo/pg-orm`), which kay no longer pulls in.
13
+ function optionalPeers(kay: PeerManifest | undefined): string[] {
14
+ return Object.entries(kay?.peerDependenciesMeta ?? {}).filter(([, meta]) => meta.optional === true).map(([name]) => name)
15
+ }
16
+
17
+ // The optional peers of `kay` the app has installed (from its folder up) without declaring them: the ones it uses today only because an older kay installed them for it.
18
+ export async function undeclaredPeers(kay: PeerManifest | undefined, packageJson: Record<string, unknown>, installed: (name: string) => Promise<boolean>): Promise<string[]> {
19
+ const declared = new Set(SECTIONS.flatMap(section => Object.keys((packageJson[section] ?? {}))))
20
+ const found: string[] = []
21
+
22
+ for (const name of optionalPeers(kay)) {
23
+ if (!declared.has(name) && await installed(name))
24
+ found.push(name)
25
+ }
26
+
27
+ return found
28
+ }
29
+
30
+ // What `addPeers` needs of the upgrade; `snapshot` and `restore` keep and put back package.json and the lockfile.
31
+ export interface PeerHooks<Saved> {
32
+ dryRun: boolean
33
+ manifest: string
34
+ install: (changes: DependencyChange[]) => Promise<boolean>
35
+ moved: (changes: DependencyChange[]) => void
36
+ say: (verb: string, rest: string) => void
37
+ snapshot: () => Promise<Saved & { source: string }>
38
+ restore: (saved: Saved) => Promise<void>
39
+ fail: (message: string) => void
40
+ }
41
+
42
+ // Adds the peers `had` to the app's devDependencies at the range `kay` (the one now installed) asks for, one it no longer lists left out; only says so on a dry run, and puts package.json and the lockfile back when the install fails. False when it did.
43
+ export async function addPeers<Saved>(kay: PeerManifest | undefined, had: string[], hooks: PeerHooks<Saved>): Promise<boolean> {
44
+ const changes = had.flatMap((name) => {
45
+ const spec = kay?.peerDependencies?.[name]
46
+
47
+ return spec === undefined ? [] : [{ name, spec, section: 'devDependencies' }]
48
+ })
49
+
50
+ if (changes.length === 0)
51
+ return true
52
+
53
+ hooks.moved(changes)
54
+
55
+ const list = changes.map(({ name, spec }) => `${name}@${spec}`).join(', ')
56
+ const why = 'to devDependencies, which the app uses and kay no longer installs for it'
57
+
58
+ if (hooks.dryRun) {
59
+ hooks.say('would add', `${list} ${why}`)
60
+
61
+ return true
62
+ }
63
+
64
+ const saved = await hooks.snapshot()
65
+
66
+ await Bun.write(hooks.manifest, withDevDependencies(saved.source, changes))
67
+ hooks.say('added', `${list} ${why}`)
68
+
69
+ if (await hooks.install(changes))
70
+ return true
71
+
72
+ await hooks.restore(saved)
73
+ hooks.fail(`the install of ${changes.map(({ name }) => name).join(', ')} failed, so package.json and the lockfile are back as they were; run \`bun add -d ${list}\``)
74
+
75
+ return false
76
+ }
77
+
78
+ // `source` with `changes` added to its devDependencies, sorted as `bun add` leaves them, in the indent the file has.
79
+ export function withDevDependencies(source: string, changes: DependencyChange[]): string {
80
+ const packageJson = JSON.parse(source) as Record<string, unknown>
81
+ const dev = { ...(packageJson.devDependencies as Record<string, string> | undefined) }
82
+
83
+ for (const { name, spec } of changes)
84
+ dev[name] = spec
85
+
86
+ packageJson.devDependencies = Object.fromEntries(Object.entries(dev).sort(([left], [right]) => left < right ? -1 : 1))
87
+
88
+ return `${JSON.stringify(packageJson, null, INDENT.exec(source)?.[1] ?? ' ')}${source.endsWith('\n') ? '\n' : ''}`
89
+ }
@@ -1,4 +1,5 @@
1
1
  import type { Command, ProblemFormat } from './command'
2
+ import type { PeerManifest } from './upgrade-peers'
2
3
  import { existsSync } from 'node:fs'
3
4
  import { rm } from 'node:fs/promises'
4
5
  import { dirname, join } from 'node:path'
@@ -8,6 +9,10 @@ import { renameProjectFiles } from '../check/renamed-packages'
8
9
  import { DEPRECATION_MINORS, minorAfter, minorOf, UPGRADE_FROM } from '../compiler/lints'
9
10
  import { isKayPackage, RENAMED_IN, renamePackages } from '../package-names'
10
11
  import { done, formatOption, printDocument, printFailure, projectRoot } from './command'
12
+ import { majorWarning } from './upgrade-majors'
13
+ import { readManifest } from './upgrade-manifest'
14
+ import { installFailed, wouldMove } from './upgrade-messages'
15
+ import { addPeers, undeclaredPeers } from './upgrade-peers'
11
16
 
12
17
  // What an upgrade asks of the outside: the registry, the package manager and the project's own kay, which a test replaces so none of them is reached.
13
18
  export interface UpgradeDeps {
@@ -188,11 +193,13 @@ export const upgrade: Command = {
188
193
  export interface UpgradeResult {
189
194
  steps: { verb: string, rest: string }[]
190
195
  changed: DependencyChange[]
196
+ // A shared dependency that crossed a major (a 0.x minor counts) on the way, with the file or the repository to read what changed.
197
+ warnings: string[]
191
198
  }
192
199
 
193
200
  // With `dryRun`, lists the packages that would move and touches nothing: no write, no install, no rewrite.
194
201
  export async function upgradeProject(root: string, deps: UpgradeDeps, { dryRun = false, quiet = false, format = 'text' }: { dryRun?: boolean, quiet?: boolean, format?: ProblemFormat } = {}): Promise<number> {
195
- const result: UpgradeResult = { steps: [], changed: [] }
202
+ const result: UpgradeResult = { steps: [], changed: [], warnings: [] }
196
203
  // Said in text, or kept in the document under json; quiet, the steps are not announced: what would move, and how it ended, still are.
197
204
  const say = (verb: string, rest: string, always: boolean) => {
198
205
  result.steps.push({ verb, rest })
@@ -210,30 +217,14 @@ export async function upgradeProject(root: string, deps: UpgradeDeps, { dryRun =
210
217
 
211
218
  return code
212
219
  }
213
- const moved = (changes: DependencyChange[]) => {
214
- for (const change of changes)
215
- result.changed = [...result.changed.filter(({ name }) => name !== change.name), change]
216
- }
217
220
  const manifest = join(root, 'package.json')
218
221
 
219
- if (!existsSync(manifest)) {
220
- printFailure('upgrade', `${root} has no package.json`, format)
222
+ const read = await readManifest(manifest, root, format)
221
223
 
224
+ if (read === undefined)
222
225
  return 1
223
- }
224
-
225
- const original = await Bun.file(manifest).text()
226
- let packageJson: Record<string, unknown>
227
-
228
- try {
229
- packageJson = JSON.parse(original)
230
- }
231
- catch (error) {
232
- printFailure('upgrade', `package.json does not parse: ${error instanceof Error ? error.message : String(error)}`, format)
233
-
234
- return 1
235
- }
236
226
 
227
+ const { original, packageJson } = read
237
228
  const found = kayDependencies(packageJson)
238
229
  const kay = found.find(isKay)
239
230
 
@@ -243,6 +234,8 @@ export async function upgradeProject(root: string, deps: UpgradeDeps, { dryRun =
243
234
  return 1
244
235
  }
245
236
 
237
+ // The optional peers the app has installed without declaring them, which an older kay installed for it and the new one no longer does.
238
+ const hadPeers = await undeclaredPeers(await findInstalled(root, 'kay'), packageJson, async name => await findInstalled(root, name) !== undefined)
246
239
  const latest = await latestVersions(root, kay, found, deps)
247
240
 
248
241
  if (typeof latest === 'string') {
@@ -268,19 +261,24 @@ export async function upgradeProject(root: string, deps: UpgradeDeps, { dryRun =
268
261
  if (raised.length === 0)
269
262
  return true
270
263
 
271
- moved(raised.map(({ change }) => change))
264
+ moved(result, raised.map(({ change }) => change))
272
265
 
273
266
  if (dryRun) {
274
267
  for (const one of raised)
275
268
  say(one.rewritten ? 'would raise' : 'would install', describeRaise(one, 'the installed kay'), true)
276
269
 
270
+ await warnAcrossMajors(root, raised, result, format)
271
+
277
272
  return true
278
273
  }
279
274
 
280
275
  step('raised', raised.map(one => describeRaise(one, `kay ${latestKay}`)).join(', '))
281
276
 
282
- if (await deps.install(root, raised.map(({ change }) => change)))
277
+ if (await deps.install(root, raised.map(({ change }) => change))) {
278
+ await warnAcrossMajors(root, raised, result, format)
279
+
283
280
  return true
281
+ }
284
282
 
285
283
  await restore(manifest, settled)
286
284
  printFailure('upgrade', `the install of ${raised.map(({ change }) => change.name).join(', ')} failed, so package.json and the lockfile are back as they were; raise them by hand to what kay asks for, then run \`bun install\``, format)
@@ -288,8 +286,20 @@ export async function upgradeProject(root: string, deps: UpgradeDeps, { dryRun =
288
286
  return false
289
287
  }
290
288
 
289
+ // Adds the peers the app had to its devDependencies, or only says so on a dry run; false when that failed.
290
+ const keepPeers = async () => addPeers(await findInstalled(root, 'kay'), hadPeers, {
291
+ dryRun,
292
+ manifest,
293
+ install: async changes => deps.install(root, changes),
294
+ moved: changes => moved(result, changes),
295
+ say: (verb, rest) => say(verb, rest, dryRun),
296
+ snapshot: async () => ({ source: await Bun.file(manifest).text(), locks: await readLocks(root) }),
297
+ restore: async settled => restore(manifest, settled),
298
+ fail: message => printFailure('upgrade', message, format),
299
+ })
300
+
291
301
  if (phases.every(phase => phase.changes.length === 0)) {
292
- if (!await raiseAndInstall({ source: original, locks: await readLocks(root) }))
302
+ if (!await raiseAndInstall({ source: original, locks: await readLocks(root) }) || !await keepPeers())
293
303
  return finish(1)
294
304
 
295
305
  say('upgraded', `nothing: kay ${from} is the latest, run \`kay check --fix\` for the rest`, true)
@@ -298,13 +308,14 @@ export async function upgradeProject(root: string, deps: UpgradeDeps, { dryRun =
298
308
  }
299
309
 
300
310
  if (dryRun) {
301
- for (const { version, changes, stone } of phases) {
302
- moved(changes)
303
-
304
- for (const { name, spec } of changes)
305
- say('would move', `${name} to ${spec.slice(spec.lastIndexOf('~'))}${stone ? ` (kay ${version} still rewrites forms the next minors drop)` : ''}`, true)
311
+ for (const phase of phases) {
312
+ moved(result, phase.changes)
313
+ wouldMove(phase, (verb, rest) => say(verb, rest, true))
306
314
  }
307
315
 
316
+ if (!await keepPeers())
317
+ return finish(1)
318
+
308
319
  say('dry run', 'nothing written; run `kay upgrade` to install them and rewrite the old forms', true)
309
320
 
310
321
  return finish(0)
@@ -324,7 +335,7 @@ export async function upgradeProject(root: string, deps: UpgradeDeps, { dryRun =
324
335
  await Bun.write(manifest, phase.source)
325
336
 
326
337
  if (await deps.install(root, phase.changes) && existsSync(join(root, 'node_modules/kay/src/cli.ts'))) {
327
- moved(phase.changes)
338
+ moved(result, phase.changes)
328
339
  step('moved', phase.changes.map(({ name, spec }) => `${name} to ${spec.slice(spec.lastIndexOf('~'))}`).join(', '))
329
340
 
330
341
  return true
@@ -373,9 +384,7 @@ export async function upgradeProject(root: string, deps: UpgradeDeps, { dryRun =
373
384
  }
374
385
 
375
386
  if (outcome === 'failed') {
376
- printFailure('upgrade', behind === from
377
- ? `the install of kay ${phase.version} failed or left no kay in node_modules, so package.json and the lockfile are back as they were and nothing was rewritten; node_modules may still hold what the install did, so run \`bun install\` once the install is fixed, then \`kay upgrade\` again`
378
- : `the install of kay ${phase.version} failed or left no kay in node_modules, after the forms of the minors up to ${behind} were rewritten on the way; package.json and the lockfile are back at kay ${behind}, so run \`bun install\` once the install is fixed, then \`kay upgrade\` again`, format)
387
+ printFailure('upgrade', installFailed(phase.version, behind, from), format)
379
388
 
380
389
  return 1
381
390
  }
@@ -393,7 +402,7 @@ export async function upgradeProject(root: string, deps: UpgradeDeps, { dryRun =
393
402
  settled = { source: phase.source, locks: await readLocks(root) }
394
403
  }
395
404
 
396
- if (!await raiseAndInstall(settled))
405
+ if (!await raiseAndInstall(settled) || !await keepPeers())
397
406
  return finish(1)
398
407
 
399
408
  step('checking', 'what is left')
@@ -490,6 +499,27 @@ async function raiseShared(root: string, manifest: string, source: string, write
490
499
  return raised
491
500
  }
492
501
 
502
+ // Records the packages that moved, the last range of each.
503
+ function moved(result: UpgradeResult, changes: DependencyChange[]): void {
504
+ for (const change of changes)
505
+ result.changed = [...result.changed.filter(({ name }) => name !== change.name), change]
506
+ }
507
+
508
+ // Names each raise that crossed a major, on stderr in text and in the document under json.
509
+ async function warnAcrossMajors(root: string, raised: Raise[], result: UpgradeResult, format: ProblemFormat): Promise<void> {
510
+ for (const one of raised) {
511
+ const message = majorWarning(root, one.change.name, one.held, one.wanted, await findInstalled(root, one.change.name))
512
+
513
+ if (message === undefined)
514
+ continue
515
+
516
+ result.warnings.push(message)
517
+
518
+ if (format === 'text')
519
+ console.error(`warning: ${message}`)
520
+ }
521
+ }
522
+
493
523
  interface Raise {
494
524
  change: DependencyChange
495
525
  // What the app had: the version of its range when that was below kay's, else of its installed copy.
@@ -505,10 +535,12 @@ function describeRaise({ change, held, wanted, rewritten }: Raise, kay: string):
505
535
  }
506
536
 
507
537
  // The manifest of a package as `node_modules` holds it from the app's folder up, as a hoisted install or a workspace puts it, never above the project: the first folder with `workspaces`, a lockfile or `.git`. Undefined when none is found.
508
- async function findInstalled(root: string, name: string): Promise<{ version?: string, dependencies?: Record<string, string> } | undefined> {
538
+ async function findInstalled(root: string, name: string): Promise<({ dir: string, version?: string, dependencies?: Record<string, string>, repository?: string | { url?: string } } & PeerManifest) | undefined> {
509
539
  for (let dir = root; ; dir = dirname(dir)) {
510
540
  try {
511
- return (await Bun.file(join(dir, 'node_modules', name, 'package.json')).json()) as { version?: string, dependencies?: Record<string, string> }
541
+ const folder = join(dir, 'node_modules', name)
542
+
543
+ return { dir: folder, ...(await Bun.file(join(folder, 'package.json')).json()) as object }
512
544
  }
513
545
  catch {
514
546
  // Not here, or unreadable: look in the folder above.
@@ -557,7 +589,7 @@ async function readLocks(root: string): Promise<{ path: string, content: Uint8Ar
557
589
  }
558
590
 
559
591
  // One install of the upgrade: the ranges `source` holds once its `changes` are written, and the version of kay then installed.
560
- interface Phase {
592
+ export interface Phase {
561
593
  version: string
562
594
  source: string
563
595
  changes: DependencyChange[]