@mun-ui/ui 0.0.0-stage → 0.2.1

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 (176) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +114 -2
  3. package/bin/compile.mjs +38 -0
  4. package/bin/desktop.mjs +143 -0
  5. package/bin/dev-protocol.mjs +94 -0
  6. package/bin/formatter.mjs +109 -0
  7. package/bin/hot-reload.mjs +38 -0
  8. package/bin/mun.mjs +538 -0
  9. package/bin/native.mjs +133 -0
  10. package/bin/pnpm-workspace.mjs +58 -0
  11. package/bin/program-patch.mjs +104 -0
  12. package/bin/project.mjs +322 -0
  13. package/bin/watch.mjs +316 -0
  14. package/bin/workflow.mjs +261 -0
  15. package/dist/astro.d.ts +3 -0
  16. package/dist/astro.d.ts.map +1 -0
  17. package/dist/astro.js +3 -0
  18. package/dist/astro.js.map +1 -0
  19. package/dist/closures.d.ts +2 -0
  20. package/dist/closures.d.ts.map +1 -0
  21. package/dist/closures.js +2 -0
  22. package/dist/closures.js.map +1 -0
  23. package/dist/compiler/index.d.ts +2 -0
  24. package/dist/compiler/index.d.ts.map +1 -0
  25. package/dist/compiler/index.js +2 -0
  26. package/dist/compiler/index.js.map +1 -0
  27. package/dist/core.d.ts +3 -0
  28. package/dist/core.d.ts.map +1 -0
  29. package/dist/core.js +3 -0
  30. package/dist/core.js.map +1 -0
  31. package/dist/experimental.d.ts +2 -0
  32. package/dist/experimental.d.ts.map +1 -0
  33. package/dist/experimental.js +2 -0
  34. package/dist/experimental.js.map +1 -0
  35. package/dist/index.d.ts +3 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +3 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/jsx-dev-runtime.d.ts +2 -0
  40. package/dist/jsx-dev-runtime.d.ts.map +1 -0
  41. package/dist/jsx-dev-runtime.js +2 -0
  42. package/dist/jsx-dev-runtime.js.map +1 -0
  43. package/dist/jsx-runtime.d.ts +2 -0
  44. package/dist/jsx-runtime.d.ts.map +1 -0
  45. package/dist/jsx-runtime.js +2 -0
  46. package/dist/jsx-runtime.js.map +1 -0
  47. package/dist/legacy.d.ts +3 -0
  48. package/dist/legacy.d.ts.map +1 -0
  49. package/dist/legacy.js +3 -0
  50. package/dist/legacy.js.map +1 -0
  51. package/dist/mun.d.ts +5 -0
  52. package/dist/mun.d.ts.map +1 -0
  53. package/dist/mun.js +4 -0
  54. package/dist/mun.js.map +1 -0
  55. package/dist/progressive-blur/index.d.ts +8 -0
  56. package/dist/progressive-blur/index.d.ts.map +1 -0
  57. package/dist/progressive-blur/index.js +8 -0
  58. package/dist/progressive-blur/index.js.map +1 -0
  59. package/dist/progressive-blur/plan.d.ts +3 -0
  60. package/dist/progressive-blur/plan.d.ts.map +1 -0
  61. package/dist/progressive-blur/plan.js +3 -0
  62. package/dist/progressive-blur/plan.js.map +1 -0
  63. package/dist/react-types.d.ts +2 -0
  64. package/dist/react-types.d.ts.map +1 -0
  65. package/dist/react-types.js +2 -0
  66. package/dist/react-types.js.map +1 -0
  67. package/dist/rendering-quality.d.ts +4 -0
  68. package/dist/rendering-quality.d.ts.map +1 -0
  69. package/dist/rendering-quality.js +4 -0
  70. package/dist/rendering-quality.js.map +1 -0
  71. package/dist/state.d.ts +2 -0
  72. package/dist/state.d.ts.map +1 -0
  73. package/dist/state.js +2 -0
  74. package/dist/state.js.map +1 -0
  75. package/dist/types.d.ts +2 -0
  76. package/dist/types.d.ts.map +1 -0
  77. package/dist/types.js +2 -0
  78. package/dist/types.js.map +1 -0
  79. package/dist/vite.d.ts +2 -0
  80. package/dist/vite.d.ts.map +1 -0
  81. package/dist/vite.js +2 -0
  82. package/dist/vite.js.map +1 -0
  83. package/editors/install.mjs +102 -0
  84. package/editors/lsp/mun-lsp.mjs +123 -0
  85. package/editors/lsp/service.mjs +306 -0
  86. package/editors/lsp/source.mjs +58 -0
  87. package/editors/vscode/client.mjs +40 -0
  88. package/editors/vscode/dev-client.mjs +83 -0
  89. package/editors/vscode/discovery.mjs +46 -0
  90. package/editors/vscode/export.mjs +42 -0
  91. package/editors/vscode/extension.cjs +226 -0
  92. package/editors/vscode/language-configuration.json +15 -0
  93. package/editors/vscode/package.json +119 -0
  94. package/editors/vscode/protocol.mjs +29 -0
  95. package/editors/vscode/syntaxes/mun.tmLanguage.json +130 -0
  96. package/native/Cargo.lock +3581 -0
  97. package/native/Cargo.toml +21 -0
  98. package/native/README.md +21 -0
  99. package/native/mun-native/Cargo.toml +23 -0
  100. package/native/mun-native/src/accessibility.rs +738 -0
  101. package/native/mun-native/src/dev.rs +604 -0
  102. package/native/mun-native/src/host_services.rs +202 -0
  103. package/native/mun-native/src/lib.rs +2843 -0
  104. package/native/mun-native/src/main.rs +204 -0
  105. package/native/mun-native/src/offscreen.rs +393 -0
  106. package/native/mun-native/src/rect.wgsl +63 -0
  107. package/native/mun-native/src/text.rs +401 -0
  108. package/native/mun-native/tests/offscreen_rendering.rs +161 -0
  109. package/native/mun-native/tests/stress.rs +408 -0
  110. package/native/mun-native/tests/window_lifecycle.rs +183 -0
  111. package/native/mun-runtime/Cargo.toml +13 -0
  112. package/native/mun-runtime/src/accessibility.rs +193 -0
  113. package/native/mun-runtime/src/collection.rs +1090 -0
  114. package/native/mun-runtime/src/gesture.rs +1070 -0
  115. package/native/mun-runtime/src/input.rs +325 -0
  116. package/native/mun-runtime/src/ir.rs +852 -0
  117. package/native/mun-runtime/src/kinetics.rs +500 -0
  118. package/native/mun-runtime/src/layout.rs +258 -0
  119. package/native/mun-runtime/src/layout_cache.rs +209 -0
  120. package/native/mun-runtime/src/lib.rs +52 -0
  121. package/native/mun-runtime/src/motion.rs +1162 -0
  122. package/native/mun-runtime/src/retained.rs +574 -0
  123. package/native/mun-runtime/src/runtime.rs +7449 -0
  124. package/native/mun-runtime/src/scene.rs +567 -0
  125. package/native/mun-runtime/src/scroll.rs +521 -0
  126. package/native/mun-runtime/src/scroll_view.rs +220 -0
  127. package/native/mun-runtime/src/text_edit.rs +670 -0
  128. package/native/mun-runtime/src/timeline.rs +1534 -0
  129. package/native/mun-runtime/src/validate.rs +677 -0
  130. package/native/mun-runtime/tests/accessibility_semantics.rs +168 -0
  131. package/native/mun-runtime/tests/compiler_contract.rs +110 -0
  132. package/native/mun-runtime/tests/flexible_frames.rs +47 -0
  133. package/native/mun-runtime/tests/host_services.rs +107 -0
  134. package/native/mun-runtime/tests/hot_update.rs +367 -0
  135. package/native/mun-runtime/tests/incremental_runtime.rs +323 -0
  136. package/native/mun-runtime/tests/ir_validation.rs +167 -0
  137. package/native/mun-runtime/tests/keyed_collections.rs +251 -0
  138. package/native/mun-runtime/tests/minimum_window_size.rs +80 -0
  139. package/native/mun-runtime/tests/native_controls_style.rs +491 -0
  140. package/native/mun-runtime/tests/native_demo.rs +285 -0
  141. package/native/mun-runtime/tests/native_layout_style.rs +175 -0
  142. package/native/mun-runtime/tests/native_settings_pane.rs +152 -0
  143. package/native/mun-runtime/tests/priority_proposals.rs +69 -0
  144. package/native/mun-runtime/tests/scroll_view.rs +403 -0
  145. package/native/mun-runtime/tests/text_editing.rs +491 -0
  146. package/native/mun-runtime/tests/text_proposals.rs +42 -0
  147. package/native/mun-runtime/tests/typography.rs +63 -0
  148. package/package.json +213 -3
  149. package/schemas/README.md +19 -0
  150. package/schemas/semantic-ui-ir-v1.schema.json +2061 -0
  151. package/templates/desktop/gitignore +5 -0
  152. package/templates/desktop/package.json +10 -0
  153. package/templates/desktop/src-tauri/Cargo.toml +14 -0
  154. package/templates/desktop/src-tauri/build.rs +1 -0
  155. package/templates/desktop/src-tauri/capabilities/main.json +12 -0
  156. package/templates/desktop/src-tauri/icons/icon.icns +0 -0
  157. package/templates/desktop/src-tauri/icons/icon.ico +0 -0
  158. package/templates/desktop/src-tauri/icons/icon.png +0 -0
  159. package/templates/desktop/src-tauri/src/main.rs +2 -0
  160. package/templates/desktop/src-tauri/tauri.conf.json +42 -0
  161. package/templates/desktop/vite.config.ts +10 -0
  162. package/templates/native/App.mun +15 -0
  163. package/templates/native/gitignore +3 -0
  164. package/templates/native/mun.toml +8 -0
  165. package/templates/project/gitignore +5 -0
  166. package/templates/project/index.html +13 -0
  167. package/templates/project/package.json +24 -0
  168. package/templates/project/src/App.mun +13 -0
  169. package/templates/project/src/index.css +30 -0
  170. package/templates/project/src/main.ts +5 -0
  171. package/templates/project/tsconfig.json +20 -0
  172. package/templates/project/vite.config.ts +6 -0
  173. package/templates/vite/src/App.css +134 -0
  174. package/templates/vite/src/App.tsx +91 -0
  175. package/templates/vite/src/index.css +23 -0
  176. package/templates/vite/vite.config.ts +10 -0
@@ -0,0 +1,306 @@
1
+ import { MunLoweringCache, parseMunStructs, diagnoseMunSource, compileMunUiProgram, nativeLanguageCatalog, munBuiltinSymbols, munOptInFeatures } from '@mun-ui/compiler'
2
+ import { formatSource } from '../../bin/formatter.mjs'
3
+ import { offsetAt, positionAt, rangeAt, scan } from './source.mjs'
4
+
5
+ export const tokenTypes = ['class', 'function', 'parameter', 'property', 'keyword', 'decorator', 'type', 'variable']
6
+ const keywords = new Set(['struct', 'var', 'let', 'some', 'private', 'public', 'init', 'if', 'else', 'switch', 'case', 'default', 'in', 'true', 'false', 'self', 'return'])
7
+ // One registry decides what resolves without an import; completion, hover and
8
+ // highlighting read it so the editor never advertises a name the compiler rejects.
9
+ const builtins = munBuiltinSymbols()
10
+ const types = new Set([...builtins.values()].filter(item => item.kind === 'type').map(item => item.name))
11
+ const catalog = nativeLanguageCatalog()
12
+ // Native catalog entries carry SwiftUI documentation; runtime built-ins fill in the rest.
13
+ const views = new Map([...[...builtins.values()].filter(item => item.kind === 'view').map(item => [item.name, item]), ...catalog.views.map(item => [item.name, item])])
14
+ const builtinDetail = { view: 'built-in View', value: 'built-in value type', function: 'built-in function', type: 'built-in type' }
15
+ const optIn = new Map(munOptInFeatures.flatMap(feature => feature.exports.map(name => [name, feature.module])))
16
+ const modifiers = new Map(catalog.modifiers.map(item => [item.name, item]))
17
+ const values = new Map(catalog.values.map(item => [item.name, item]))
18
+ function canonicalType(type) { return ({ string: 'String', boolean: 'Bool', number: 'Double', array: 'Array', function: '() -> Void', binding: 'Binding' })[type] ?? type ?? 'Value' }
19
+ function signature(name, initializer) {
20
+ return `${name}(${initializer.parameters.map(p => `${p.label ?? '_'} ${p.name ?? 'value'}: ${p.kind === 'viewBuilder' ? '() -> some View' : p.kind === 'action' ? '() -> Void' : p.kind === 'binding' ? 'Binding' : canonicalType(p.type)}${p.required === false ? ' = …' : ''}`).join(', ')})`
21
+ }
22
+ function initials(item) { return item?.initializers ?? [] }
23
+ function tokenAt(snapshot, offset) { return snapshot.tokens.find(token => token.start <= offset && token.end >= offset && /^[A-Za-z_]/u.test(token.text)) }
24
+
25
+ export class LanguageService {
26
+ constructor() {
27
+ this.documents = new Map(); this.parseCount = 0
28
+ // Shared with every diagnostics compile: unchanged View declarations are
29
+ // neither reparsed, revalidated nor relowered when one document changes.
30
+ this.loweringCache = new MunLoweringCache()
31
+ }
32
+ update(uri, source, version = 0) {
33
+ const prior = this.documents.get(uri)
34
+ if (prior?.source === source) return prior
35
+ const { tokens, scopes } = scan(source)
36
+ let structs = []
37
+ try { structs = parseMunStructs(source) } catch { /* Partial syntax still has lexical scopes. */ }
38
+ const snapshot = { uri, source, version, tokens, scopes, structs, declarations: [], diagnostics: undefined }
39
+ const add = (token, kind, extra = {}) => {
40
+ if (token) snapshot.declarations.push({ id: `${uri}#${token.start}`, name: token.text, token, kind, scope: token.scope, ...extra })
41
+ }
42
+ function walk(struct) {
43
+ const name = tokens.find(t => t.text === struct.name && t.start >= struct.range.start && t.end < struct.bodyRange.start)
44
+ add(name, 'view', { struct, range: struct.range })
45
+ for (const field of struct.fields) {
46
+ const token = tokens.find(t => t.start === field.range.start)
47
+ add(token, field.kind === 'state' || field.kind === 'binding' ? field.kind : 'property', { type: field.type, owner: struct.name })
48
+ }
49
+ for (const nested of struct.nested ?? []) walk(nested)
50
+ }
51
+ structs.forEach(walk)
52
+ for (let i = 0; i < tokens.length; i++) {
53
+ const token = tokens[i], previous = tokens[i - 1]
54
+ if ((previous?.text === 'let' || previous?.text === 'var') && !snapshot.declarations.some(d => d.token.start === token.start)) {
55
+ add(token, 'local', { type: tokens[i + 1]?.text === ':' ? tokens[i + 2]?.text : undefined })
56
+ }
57
+ // Closure parameters are declarations owned by the closure block.
58
+ if (token.text === 'in') {
59
+ let j = i - 1
60
+ while (j >= 0 && tokens[j].scope === token.scope && !['{', ';', '}'].includes(tokens[j].text)) j--
61
+ const candidates = tokens.slice(j + 1, i)
62
+ if (candidates.every(t => /^[A-Za-z_][A-Za-z0-9_]*$/u.test(t.text) || [',', '(', ')'].includes(t.text))) {
63
+ for (const parameter of candidates.filter(t => /^[A-Za-z_]/u.test(t.text))) add(parameter, 'parameter')
64
+ }
65
+ }
66
+ // Explicit initializer parameters shadow fields inside that initializer.
67
+ if (token.text === 'init' && tokens[i + 1]?.text === '(') {
68
+ let j = i + 2, depth = 1
69
+ const parameters = []
70
+ while (j < tokens.length && depth) {
71
+ if (tokens[j].text === '(') depth++
72
+ if (tokens[j].text === ')') depth--
73
+ if (depth === 1 && tokens[j + 1]?.text === ':' && /^[A-Za-z_]/u.test(tokens[j].text)) parameters.push({ token: tokens[j], type: tokens[j + 2]?.text })
74
+ j++
75
+ }
76
+ const block = scopes.findIndex(s => s.start === tokens[j]?.start)
77
+ for (const p of parameters) if (block >= 0) add(p.token, 'parameter', { scope: block, type: p.type })
78
+ }
79
+ }
80
+ for (const document of this.documents.values()) document.diagnostics = undefined
81
+ this.documents.set(uri, snapshot); this.parseCount++
82
+ return snapshot
83
+ }
84
+ remove(uri) { this.documents.delete(uri); for (const document of this.documents.values()) document.diagnostics = undefined }
85
+ snapshot(uri) { return this.documents.get(uri) }
86
+ resolve(snapshot, token) {
87
+ if (!token) return undefined
88
+ const declared = snapshot.declarations.find(d => d.token.start === token.start)
89
+ if (declared) return declared
90
+ const index = snapshot.tokens.indexOf(token), previous = snapshot.tokens[index - 1], next = snapshot.tokens[index + 1]
91
+ // A dotted member belongs to the receiver, not any equal local identifier.
92
+ if (previous?.text === '.' && snapshot.tokens[index - 2]?.text !== 'self') return undefined
93
+ // Argument labels resolve to a custom View's property, never to a caller's State.
94
+ if (next?.text === ':') {
95
+ const call = this.callContext(snapshot, token.start)
96
+ const matches = [...this.documents.values()].flatMap(s => s.declarations).filter(d => d.owner === call?.name && d.name === token.text)
97
+ return matches.length === 1 ? matches[0] : undefined
98
+ }
99
+ let scope = token.scope
100
+ while (scope !== null) {
101
+ const matches = snapshot.declarations.filter(d => d.scope === scope && d.name === token.text && (d.kind !== 'local' || d.token.start <= token.start))
102
+ if (matches.length === 1) return matches[0]
103
+ if (matches.length > 1) return undefined
104
+ scope = snapshot.scopes[scope].parent
105
+ }
106
+ const matches = [...this.documents.values()].flatMap(s => s.declarations).filter(d => d.kind === 'view' && d.name === token.text && d.scope === 0)
107
+ return matches.length === 1 ? matches[0] : undefined
108
+ }
109
+ references(uri, position, includeDeclaration = true) {
110
+ const snapshot = this.snapshot(uri)
111
+ if (!snapshot) return []
112
+ const symbol = this.resolve(snapshot, tokenAt(snapshot, offsetAt(snapshot.source, position)))
113
+ if (!symbol) return []
114
+ const result = []
115
+ for (const candidate of this.documents.values()) for (const token of candidate.tokens) {
116
+ if (token.text !== symbol.name || (!includeDeclaration && candidate.uri === uri && token.start === symbol.token.start)) continue
117
+ if (this.resolve(candidate, token)?.id === symbol.id) result.push({ uri: candidate.uri, range: rangeAt(candidate.source, token.start, token.end) })
118
+ }
119
+ return result
120
+ }
121
+ definition(uri, position) {
122
+ const snapshot = this.snapshot(uri)
123
+ const symbol = snapshot && this.resolve(snapshot, tokenAt(snapshot, offsetAt(snapshot.source, position)))
124
+ if (!symbol) return null
125
+ const owner = [...this.documents.values()].find(s => s.declarations.includes(symbol))
126
+ return { uri: owner.uri, range: rangeAt(owner.source, symbol.token.start, symbol.token.end) }
127
+ }
128
+ prepareRename(uri, position) {
129
+ const snapshot = this.snapshot(uri)
130
+ const token = snapshot && tokenAt(snapshot, offsetAt(snapshot.source, position))
131
+ return this.resolve(snapshot, token) ? { range: rangeAt(snapshot.source, token.start, token.end), placeholder: token.text } : null
132
+ }
133
+ rename(uri, position, newName) {
134
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(newName) || keywords.has(newName) || types.has(newName)) throw new Error('Rename requires a non-keyword Mün identifier.')
135
+ const snapshot = this.snapshot(uri)
136
+ const symbol = snapshot && this.resolve(snapshot, tokenAt(snapshot, offsetAt(snapshot.source, position)))
137
+ if (!symbol) throw new Error('No unambiguous source symbol at this position.')
138
+ if ([...this.documents.values()].some(s => s.declarations.some(d => d.name === newName && d.id !== symbol.id && (d.kind === 'view' || s === snapshot)))) throw new Error(`Rename would conflict with ${newName}.`)
139
+ const changes = {}
140
+ for (const location of this.references(uri, position)) (changes[location.uri] ??= []).push({ range: location.range, newText: newName })
141
+ return { changes }
142
+ }
143
+ diagnostics(uri) {
144
+ const snapshot = this.snapshot(uri)
145
+ if (!snapshot) return []
146
+ if (snapshot.diagnostics) return snapshot.diagnostics
147
+ // @main selects the retained native compilation unit. Web modules use the
148
+ // same compiler as Vite and keep their ES module boundary for diagnostics.
149
+ const documents = [snapshot, ...[...this.documents.values()].filter(s => s !== snapshot)]
150
+ const native = documents.some(document => /@main\b/.test(document.source))
151
+ const source = native ? documents.map(document => document.source).join('\n') : snapshot.source
152
+ snapshot.diagnostics = diagnoseMunSource(source, uri, { target: native ? 'native' : 'web', loweringCache: this.loweringCache }).flatMap(d => {
153
+ const start = d.index ?? offsetAt(snapshot.source, { line: (d.line ?? 1) - 1, character: (d.column ?? 1) - 1 })
154
+ if ((d.line ?? 1) > snapshot.source.split('\n').length) return []
155
+ return [{ range: rangeAt(snapshot.source, start, Math.min(snapshot.source.length, start + 1)), severity: d.severity === 'warning' ? 2 : 1, code: d.code, source: 'mun', message: d.message }]
156
+ })
157
+ return snapshot.diagnostics
158
+ }
159
+ codeActions(uri, range, context = {}) {
160
+ if (context.only && !context.only.some(kind => 'quickfix'.startsWith(kind))) return []
161
+ const snapshot = this.snapshot(uri)
162
+ if (!snapshot) return []
163
+ const diagnostics = this.diagnostics(uri)
164
+ const actions = []
165
+ function fields(struct) { return [...struct.fields, ...(struct.nested ?? []).flatMap(fields)] }
166
+ for (const field of snapshot.structs.flatMap(fields)) {
167
+ const replacement = { string: 'String', boolean: 'Bool' }[field.type]
168
+ // `number` is deliberately excluded: choosing Int versus Double requires
169
+ // semantic evidence. Never rewrite matching strings or unrelated names.
170
+ if (!replacement) continue
171
+ const diagnostic = diagnostics.find(d => d.code === 'MUN_NATIVE' && offsetAt(snapshot.source, d.range.start) === field.range.start && d.message.includes(`'${field.type}' is a compatibility-only TypeScript type spelling`))
172
+ if (!diagnostic) continue
173
+ const start = snapshot.tokens.findIndex(t => t.start === field.range.start)
174
+ const colon = snapshot.tokens[start + 1], type = snapshot.tokens[start + 2]
175
+ if (colon?.text !== ':' || type?.text !== field.type) continue
176
+ const editRange = rangeAt(snapshot.source, type.start, type.end)
177
+ if (offsetAt(snapshot.source, range.end) < type.start || offsetAt(snapshot.source, range.start) > type.end) continue
178
+ actions.push({ title: `Use canonical ${replacement}`, kind: 'quickfix', diagnostics: [diagnostic], edit: { changes: { [uri]: [{ range: editRange, newText: replacement }] } } })
179
+ }
180
+ return actions
181
+ }
182
+ customView(name) {
183
+ const matches = [...this.documents.values()].flatMap(s => s.declarations).filter(d => d.kind === 'view' && d.name === name)
184
+ if (matches.length !== 1) return undefined
185
+ const struct = matches[0].struct
186
+ return { name, initializers: struct.initializers.length ? struct.initializers.map(init => ({ signature: `init(${init.parametersSource})`, parameters: this.parameters(init.parametersSource) })) : [{ parameters: struct.fields.filter(f => f.kind !== 'state').map(f => ({ name: f.name, label: f.name, type: f.type, required: f.initializer === undefined, kind: f.kind === 'binding' ? 'binding' : 'value' })) }] }
187
+ }
188
+ parameters(source) {
189
+ return source.split(',').map(item => {
190
+ const match = /^\s*(?:([A-Za-z_]\w*|_)\s+)?([A-Za-z_]\w*)\s*:\s*([^=]+)(?:=(.*))?$/u.exec(item)
191
+ return match ? { name: match[2], label: match[1] === '_' ? undefined : match[1] ?? match[2], type: match[3].trim(), required: match[4] === undefined, kind: 'value' } : null
192
+ }).filter(Boolean)
193
+ }
194
+ callContext(snapshot, offset) {
195
+ const stack = []
196
+ const tokens = snapshot.tokens.filter(t => t.start < offset)
197
+ for (let i = 0; i < tokens.length; i++) {
198
+ const t = tokens[i]
199
+ if (t.text === '(') stack.push({ name: tokens[i - 1]?.text, start: t.end, index: 0, argument: t.end, modifier: tokens[i - 2]?.text === '.' })
200
+ else if (t.text === ')') stack.pop()
201
+ else if (t.text === ',' && stack.length) { stack.at(-1).index++; stack.at(-1).argument = t.end }
202
+ }
203
+ return stack.at(-1)
204
+ }
205
+ callItem(call) { return call && (call.modifier ? modifiers.get(call.name) : views.get(call.name) ?? this.customView(call.name) ?? (values.has(call.name) ? { name: call.name, initializers: values.get(call.name).members.filter(m => m.signature.startsWith('init(')) } : undefined)) }
206
+ completion(uri, position) {
207
+ const snapshot = this.snapshot(uri)
208
+ if (!snapshot) return []
209
+ const offset = offsetAt(snapshot.source, position), prefix = snapshot.source.slice(0, offset)
210
+ const call = this.callContext(snapshot, offset), item = this.callItem(call)
211
+ const fragment = call ? snapshot.source.slice(call.argument, offset).trim() : ''
212
+ const label = /^([A-Za-z_]\w*)\s*:/u.exec(fragment)?.[1]
213
+ const parameters = initials(item).flatMap(i => i.parameters ?? [])
214
+ const expected = label ? parameters.find(p => p.label === label) : parameters[call?.index ?? 0]
215
+ const bindables = snapshot.declarations.filter(d => ['state', 'binding'].includes(d.kind))
216
+ if (/\$[A-Za-z_0-9]*$/u.test(prefix)) return bindables.map(d => ({ label: d.name, kind: 10, detail: `Binding<${canonicalType(d.type)}>` }))
217
+ if (/\.[A-Za-z_0-9]*$/u.test(prefix)) {
218
+ const explicit = /([A-Za-z_]\w*)\.[A-Za-z_0-9]*$/u.exec(prefix)?.[1]
219
+ const semanticType = explicit ?? (label === 'alignment' ? call?.name === 'VStack' ? 'HorizontalAlignment' : call?.name === 'HStack' ? 'VerticalAlignment' : 'Alignment' : label === 'axes' ? 'Axis.Set' : call?.name === 'padding' && !label ? 'Edge.Set' : ['startPoint', 'endPoint', 'anchor'].includes(label) ? 'UnitPoint' : /^max(Width|Height)$/u.test(label ?? '') ? 'CGFloat' : undefined)
220
+ const members = catalog.implicitMembers[semanticType]
221
+ if (members) return members.map(name => ({ label: name, kind: 12, detail: semanticType }))
222
+ const owner = explicit && values.get(explicit)
223
+ let value = owner
224
+ if (!value && call?.name === 'animation') value = values.get('Animation')
225
+ if (!value && call?.name === 'transition') value = values.get('AnyTransition')
226
+ if (!value && ['foregroundStyle', 'fill', 'background'].includes(call?.name)) value = values.get('Color')
227
+ if (value) return [...new Set(value.members.filter(m => !m.signature.startsWith('init(')).map(m => m.signature.split('(')[0]))].map(name => ({ label: name, kind: 12, detail: value.name }))
228
+ // A dot inside unknown argument expressions must not advertise View modifiers.
229
+ if (call) return []
230
+ return catalog.modifiers.map(m => ({ label: m.name, kind: 2, detail: m.initializers.map(i => signature(`.${m.name}`, i)).join(' | ') }))
231
+ }
232
+ if (expected?.kind === 'binding') return bindables.map(d => ({ label: `$${d.name}`, kind: 10, detail: `Binding<${canonicalType(d.type)}>` }))
233
+ const labels = parameters.filter(p => p.label && !p.trailing).map(p => ({ label: `${p.label}:`, kind: 5, detail: canonicalType(p.type), insertText: `${p.label}: ` }))
234
+ if (call && !label) return [...new Map(labels.map(l => [l.label, l])).values()]
235
+ if (expected?.type === 'boolean' || expected?.type === 'Bool') return ['true', 'false'].map(label => ({ label, kind: 12 }))
236
+ const custom = [...this.documents.values()].flatMap(s => s.declarations).filter(d => d.kind === 'view' && d.scope === 0).map(d => this.customView(d.name)).filter(Boolean)
237
+ // Custom Views declared in the workspace shadow built-ins of the same name.
238
+ const entries = new Map([...builtins.values()].filter(b => b.kind !== 'type').map(b => [b.name, b.kind === 'view'
239
+ ? { label: b.name, kind: 7, detail: (views.get(b.name)?.initializers ?? []).map(i => signature(b.name, i)).join(' | ') || builtinDetail.view }
240
+ : { label: b.name, kind: b.kind === 'function' ? 3 : 7, detail: builtinDetail[b.kind] }]))
241
+ for (const v of custom) entries.set(v.name, { label: v.name, kind: 7, detail: v.initializers.map(i => signature(v.name, i)).join(' | ') })
242
+ return [...entries.values()].concat(snapshot.declarations.filter(d => d.kind !== 'view').map(d => ({ label: d.name, kind: 10, detail: canonicalType(d.type) })))
243
+ }
244
+ hover(uri, position) {
245
+ const snapshot = this.snapshot(uri), token = snapshot && tokenAt(snapshot, offsetAt(snapshot.source, position))
246
+ if (!token) return null
247
+ const symbol = this.resolve(snapshot, token)
248
+ const member = snapshot.tokens[snapshot.tokens.indexOf(token) - 1]?.text === '.'
249
+ // A workspace declaration shadows the built-in, so resolve it first.
250
+ const item = (member ? modifiers.get(token.text) : undefined) ?? this.customView(token.text) ?? (member ? undefined : views.get(token.text))
251
+ const builtin = !member && !symbol && !this.customView(token.text) ? builtins.get(token.text) : undefined
252
+ const text = symbol && symbol.kind !== 'view' ? `${symbol.kind === 'state' ? '@State ' : symbol.kind === 'binding' ? '@Binding ' : ''}${symbol.name}: ${canonicalType(symbol.type)}` : item?.initializers?.length ? item.initializers.map(i => signature(token.text, i)).join('\n') : builtin ? `${builtinDetail[builtin.kind]} ${token.text}` : optIn.has(token.text) ? `import { ${token.text} } from "${optIn.get(token.text)}"` : undefined
253
+ if (builtin && text) return { contents: { kind: 'markdown', value: `\`\`\`mun\n${text}\n\`\`\`\n\n${builtin.module ? `Resolved without an import from \`${builtin.module}\`.` : 'Language type.'}${item?.documentation ? `\n\n${item.documentation}` : ''}` }, range: rangeAt(snapshot.source, token.start, token.end) }
254
+ return text ? { contents: { kind: 'markdown', value: `\`\`\`mun\n${text}\n\`\`\`${item?.documentation ? `\n\n${item.documentation}` : ''}` }, range: rangeAt(snapshot.source, token.start, token.end) } : null
255
+ }
256
+ signatureHelp(uri, position) {
257
+ const snapshot = this.snapshot(uri)
258
+ if (!snapshot) return null
259
+ const call = this.callContext(snapshot, offsetAt(snapshot.source, position)), item = this.callItem(call)
260
+ if (!item) return null
261
+ return { signatures: initials(item).map(i => ({ label: signature(item.name, i), parameters: (i.parameters ?? []).map(p => ({ label: p.label ?? p.name ?? 'value' })) })), activeSignature: 0, activeParameter: call.index }
262
+ }
263
+ symbols(uri) {
264
+ const s = this.snapshot(uri)
265
+ return s ? s.declarations.filter(d => d.kind === 'view').map(d => ({ name: d.name, kind: 23, range: rangeAt(s.source, d.range.start, d.range.end), selectionRange: rangeAt(s.source, d.token.start, d.token.end), children: s.declarations.filter(f => f.owner === d.name).map(f => ({ name: f.name, kind: 7, detail: canonicalType(f.type), range: rangeAt(s.source, f.token.start, f.token.end), selectionRange: rangeAt(s.source, f.token.start, f.token.end) })) })) : []
266
+ }
267
+ workspaceSymbols(query) {
268
+ return [...this.documents.values()].flatMap(s => s.declarations.filter(d => d.kind === 'view' && d.name.toLowerCase().includes(query.toLowerCase())).map(d => ({ name: d.name, kind: 23, location: { uri: s.uri, range: rangeAt(s.source, d.token.start, d.token.end) } })))
269
+ }
270
+ semanticTokens(uri) {
271
+ const s = this.snapshot(uri)
272
+ if (!s) return { data: [] }
273
+ const data = []; let line = 0, character = 0
274
+ for (const token of s.tokens) {
275
+ if (!/^[A-Za-z_]/u.test(token.text)) continue
276
+ const symbol = this.resolve(s, token), index = s.tokens.indexOf(token)
277
+ const type = s.tokens[index - 1]?.text === '@' ? 'decorator' : keywords.has(token.text) ? 'keyword' : types.has(token.text) ? 'type' : symbol?.kind === 'view' || views.has(token.text) || builtins.get(token.text)?.kind === 'value' ? 'class' : ['state', 'binding', 'property'].includes(symbol?.kind) ? 'property' : symbol?.kind === 'parameter' ? 'parameter' : symbol?.kind === 'local' ? 'variable' : modifiers.has(token.text) && s.tokens[index - 1]?.text === '.' ? 'function' : undefined
278
+ if (!type) continue
279
+ const p = positionAt(s.source, token.start)
280
+ data.push(p.line - line, p.line === line ? p.character - character : p.character, token.end - token.start, tokenTypes.indexOf(type), 0)
281
+ line = p.line; character = p.character
282
+ }
283
+ return { data }
284
+ }
285
+ formatting(uri) {
286
+ const s = this.snapshot(uri)
287
+ return s ? [{ range: rangeAt(s.source, 0, s.source.length), newText: formatSource(s.source) }] : []
288
+ }
289
+ folding(uri) {
290
+ const s = this.snapshot(uri)
291
+ return s ? s.scopes.slice(1).flatMap(scope => {
292
+ const start = positionAt(s.source, scope.start), end = positionAt(s.source, scope.end)
293
+ return end.line > start.line ? [{ startLine: start.line, endLine: end.line - 1, kind: 'region' }] : []
294
+ }) : []
295
+ }
296
+ selectionRanges(uri, positions) {
297
+ const s = this.snapshot(uri)
298
+ if (!s) return []
299
+ return positions.map(position => {
300
+ const offset = offsetAt(s.source, position), token = tokenAt(s, offset)
301
+ let parent = { range: rangeAt(s.source, 0, s.source.length) }
302
+ for (const scope of s.scopes.filter(sc => sc.parent !== null && sc.start <= offset && sc.end >= offset).sort((a, b) => (b.end - b.start) - (a.end - a.start))) parent = { range: rangeAt(s.source, scope.start, scope.end), parent }
303
+ return token ? { range: rangeAt(s.source, token.start, token.end), parent } : parent
304
+ })
305
+ }
306
+ }
@@ -0,0 +1,58 @@
1
+ // UTF-16 source offsets: JavaScript string indices and LSP character positions
2
+ // share the same unit. Never use Buffer byte offsets for language positions.
3
+ export function positionAt(source, offset) {
4
+ const before = source.slice(0, Math.max(0, Math.min(source.length, offset)))
5
+ return { line: before.split('\n').length - 1, character: before.length - before.lastIndexOf('\n') - 1 }
6
+ }
7
+ export function offsetAt(source, position) {
8
+ const lines = source.split('\n')
9
+ const line = Math.max(0, Math.min(lines.length - 1, position?.line ?? 0))
10
+ return lines.slice(0, line).reduce((sum, text) => sum + text.length + 1, 0) + Math.max(0, Math.min(lines[line].replace(/\r$/u, '').length, position?.character ?? 0))
11
+ }
12
+ export function rangeAt(source, start, end) { return { start: positionAt(source, start), end: positionAt(source, end) } }
13
+
14
+ // Strings/comments are excluded from identifier indexing. Swift interpolation
15
+ // re-enters the code scanner so rename edits expression symbols, not literal text.
16
+ export function scan(source) {
17
+ const tokens = [], scopes = [{ start: 0, end: source.length, parent: null }]
18
+ let scope = 0
19
+ function code(start, stopAtParen = false) {
20
+ let depth = 0
21
+ for (let i = start; i < source.length;) {
22
+ const c = source[i]
23
+ if (stopAtParen && c === ')' && depth === 0) return i + 1
24
+ if (source.startsWith('//', i)) { const end = source.indexOf('\n', i); i = end < 0 ? source.length : end; continue }
25
+ if (source.startsWith('/*', i)) {
26
+ let nesting = 1; i += 2
27
+ while (i < source.length && nesting) { if (source.startsWith('/*', i)) { nesting++; i += 2 } else if (source.startsWith('*/', i)) { nesting--; i += 2 } else i++ }
28
+ continue
29
+ }
30
+ if (c === '"' || c === "'" || c === '`') {
31
+ const quote = c; i++
32
+ while (i < source.length) {
33
+ if (source[i] === quote) { i++; break }
34
+ if (source[i] === '\\') {
35
+ if (quote === '"' && source[i + 1] === '(') i = code(i + 2, true)
36
+ else i += 2
37
+ } else i++
38
+ }
39
+ continue
40
+ }
41
+ if (/[A-Za-z_]/u.test(c)) {
42
+ const start = i++
43
+ while (/[A-Za-z0-9_]/u.test(source[i] ?? '')) i++
44
+ tokens.push({ text: source.slice(start, i), start, end: i, scope })
45
+ continue
46
+ }
47
+ if (c === '{') { const parent = scope; scope = scopes.length; scopes.push({ start: i, end: source.length, parent }) }
48
+ if (c === '}') { scopes[scope].end = i + 1; scope = scopes[scope].parent ?? 0 }
49
+ if (c === '(') depth++
50
+ if (c === ')') depth--
51
+ if (!/\s/u.test(c)) tokens.push({ text: c, start: i, end: i + 1, scope })
52
+ i++
53
+ }
54
+ return source.length
55
+ }
56
+ code(0)
57
+ return { tokens, scopes }
58
+ }
@@ -0,0 +1,40 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { MessageReader, encode } from './protocol.mjs'
3
+ export class LspClient {
4
+ constructor(server, onNotification, onFailure) {
5
+ this.nextId = 0; this.pending = new Map(); this.stopped = false
6
+ this.child = spawn(server.command, server.args, { cwd: server.cwd, env: server.env, stdio: ['pipe', 'pipe', 'pipe'] })
7
+ const fail = error => {
8
+ for (const pending of this.pending.values()) { clearTimeout(pending.timer); pending.reject(error) }
9
+ this.pending.clear()
10
+ if (!this.stopped) onFailure(error)
11
+ }
12
+ const reader = new MessageReader(message => {
13
+ if (message.id !== undefined) {
14
+ const pending = this.pending.get(message.id)
15
+ if (pending) { clearTimeout(pending.timer); this.pending.delete(message.id); message.error ? pending.reject(new Error(message.error.message)) : pending.resolve(message.result) }
16
+ } else onNotification(message.method, message.params)
17
+ }, error => { fail(error); this.child.kill() })
18
+ this.child.stdout.on('data', chunk => reader.feed(chunk))
19
+ this.child.stderr.on('data', chunk => onNotification('mun/log', { message: chunk.toString() }))
20
+ this.child.once('error', fail)
21
+ this.child.once('close', code => fail(new Error(`Mün language server exited (${code}).`)))
22
+ this.child.stdin.on('error', fail)
23
+ }
24
+ send(message) { this.child.stdin.write(encode({ jsonrpc: '2.0', ...message })) }
25
+ notify(method, params) { this.send({ method, params }) }
26
+ request(method, params) {
27
+ const id = ++this.nextId
28
+ return new Promise((resolve, reject) => {
29
+ const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`Mün LSP request timed out: ${method}`)) }, 15000)
30
+ this.pending.set(id, { resolve, reject, timer }); this.send({ id, method, params })
31
+ })
32
+ }
33
+ async dispose() {
34
+ if (this.stopped) return
35
+ this.stopped = true
36
+ try { await this.request('shutdown', null); this.notify('exit') } catch { this.child.kill() }
37
+ const timer = setTimeout(() => this.child.kill('SIGKILL'), 2000)
38
+ this.child.once('close', () => clearTimeout(timer))
39
+ }
40
+ }
@@ -0,0 +1,83 @@
1
+ import { existsSync, readFileSync } from 'node:fs'
2
+ import { connect } from 'node:net'
3
+ import { resolve } from 'node:path'
4
+
5
+ export const DEV_PROTOCOL_VERSION = 2
6
+ const MAX_FRAME_BYTES = 16 * 1024 * 1024
7
+
8
+ export function encodeDevFrame(message) {
9
+ const body = Buffer.from(JSON.stringify(message), 'utf8')
10
+ if (body.length > MAX_FRAME_BYTES) throw new Error(`Mün dev message exceeds ${MAX_FRAME_BYTES} bytes.`)
11
+ const header = Buffer.alloc(4)
12
+ header.writeUInt32BE(body.length)
13
+ return Buffer.concat([header, body])
14
+ }
15
+
16
+ export function createDevFrameDecoder(onMessage) {
17
+ let buffer = Buffer.alloc(0)
18
+ return chunk => {
19
+ buffer = Buffer.concat([buffer, chunk])
20
+ while (buffer.length >= 4) {
21
+ const length = buffer.readUInt32BE(0)
22
+ if (length > MAX_FRAME_BYTES) throw new Error(`Mün dev frame exceeds ${MAX_FRAME_BYTES} bytes.`)
23
+ if (buffer.length < length + 4) return
24
+ const body = buffer.subarray(4, length + 4)
25
+ buffer = buffer.subarray(length + 4)
26
+ onMessage(JSON.parse(body.toString('utf8')))
27
+ }
28
+ }
29
+ }
30
+
31
+ export function readDevSession(projectRoot) {
32
+ const file = resolve(projectRoot, '.mun', 'dev', 'session.json')
33
+ if (!existsSync(file)) throw new Error('No running mun dev session for this project.')
34
+ const session = JSON.parse(readFileSync(file, 'utf8'))
35
+ if (session.protocol !== DEV_PROTOCOL_VERSION) throw new Error(`Mün dev protocol ${session.protocol} does not match extension protocol ${DEV_PROTOCOL_VERSION}.`)
36
+ if (typeof session.endpoint !== 'string' || typeof session.token !== 'string') throw new Error('Invalid Mün dev session metadata.')
37
+ const separator = session.endpoint.lastIndexOf(':')
38
+ const host = session.endpoint.slice(0, separator)
39
+ const port = Number(session.endpoint.slice(separator + 1))
40
+ if (host !== '127.0.0.1' || !Number.isInteger(port) || port <= 0 || port > 65535) throw new Error('Refusing invalid or non-loopback Mün inspector endpoint.')
41
+ return { ...session, file, host, port }
42
+ }
43
+
44
+ export async function inspectDevSession(projectRoot, { includeValues = false, timeoutMs = 2500 } = {}) {
45
+ const session = readDevSession(projectRoot)
46
+ const socket = connect({ host: session.host, port: session.port })
47
+ return await new Promise((resolvePromise, reject) => {
48
+ let settled = false
49
+ const finish = (error, value) => {
50
+ if (settled) return
51
+ settled = true
52
+ clearTimeout(timer)
53
+ socket.destroy()
54
+ if (error) reject(error)
55
+ else resolvePromise(value)
56
+ }
57
+ const timer = setTimeout(() => finish(new Error('Timed out while inspecting the running Mün app.')), timeoutMs)
58
+ const decode = createDevFrameDecoder(message => {
59
+ if (message.type === 'error') finish(new Error(message.message ?? 'Mün inspector rejected the request.'))
60
+ else if (message.type === 'snapshot' && message.snapshot) finish(undefined, message.snapshot)
61
+ else finish(new Error(`Unexpected Mün inspector reply: ${message.type ?? '<missing>'}`))
62
+ })
63
+ socket.once('error', error => finish(new Error(`Could not reach mun dev: ${error.message}`)))
64
+ socket.on('data', chunk => {
65
+ try { decode(chunk) }
66
+ catch (error) { finish(error) }
67
+ })
68
+ socket.once('connect', () => {
69
+ socket.write(encodeDevFrame({ type: 'hello', token: session.token }))
70
+ socket.write(encodeDevFrame({ type: 'inspect', id: 1, includeValues }))
71
+ })
72
+ })
73
+ }
74
+
75
+ export function runtimeTree(snapshot) {
76
+ const byId = new Map((snapshot?.nodes ?? []).map(node => [node.id, node]))
77
+ const roots = (snapshot?.nodes ?? []).filter(node => !node.parent || !byId.has(node.parent))
78
+ return {
79
+ roots,
80
+ byId,
81
+ children(node) { return (node?.children ?? []).map(id => byId.get(id)).filter(Boolean) },
82
+ }
83
+ }
@@ -0,0 +1,46 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { existsSync, readFileSync } from 'node:fs'
3
+ import { dirname, resolve } from 'node:path'
4
+
5
+ export async function discoverMunCommand({ cwd, command, expectedVersion, env = process.env }) {
6
+ let selected
7
+ if (command) selected = { command, args: [] }
8
+ else {
9
+ let directory = resolve(cwd)
10
+ while (true) {
11
+ const root = resolve(directory, 'node_modules/@mun-ui/ui')
12
+ if (existsSync(resolve(root, 'package.json'))) {
13
+ const manifest = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8'))
14
+ if (manifest.version !== expectedVersion) throw new Error(`Workspace Mün ${manifest.version} does not match extension ${expectedVersion}. Install matching versions; refusing a global fallback.`)
15
+ const cli = resolve(root, 'bin/mun.mjs')
16
+ if (!existsSync(cli)) throw new Error(`Workspace Mün CLI is missing: ${cli}`)
17
+ selected = { command: process.execPath, args: [cli], env: { ...env, ELECTRON_RUN_AS_NODE: '1' } }
18
+ break
19
+ }
20
+ const parent = dirname(directory)
21
+ if (parent === directory) break
22
+ directory = parent
23
+ }
24
+ selected ??= { command: 'mun', args: [] }
25
+ }
26
+ const actual = await commandVersion(selected, cwd, env)
27
+ if (actual !== expectedVersion) throw new Error(`Selected Mün ${actual} does not match extension ${expectedVersion}. Install matching versions or set mun.server.command.`)
28
+ return { ...selected, cwd, env: selected.env ?? env }
29
+ }
30
+
31
+ export async function discoverToolchain(options) {
32
+ const selected = await discoverMunCommand(options)
33
+ return { ...selected, args: [...selected.args, 'lsp', '--stdio'] }
34
+ }
35
+
36
+ function commandVersion(selected, cwd, env) {
37
+ return new Promise((resolve, reject) => {
38
+ const child = spawn(selected.command, [...selected.args, '--version'], { cwd, env: selected.env ?? env, stdio: ['ignore', 'pipe', 'pipe'] })
39
+ let output = '', stderr = ''
40
+ const timer = setTimeout(() => { child.kill(); reject(new Error('Mün version check timed out.')) }, 5000)
41
+ child.stdout.on('data', chunk => { output += chunk; if (output.length > 8192) { child.kill(); reject(new Error('Invalid Mün version output.')) } })
42
+ child.stderr.on('data', chunk => { stderr = (stderr + chunk).slice(-8192) })
43
+ child.once('error', error => { clearTimeout(timer); reject(new Error(`Cannot start Mün: ${error.message}. Install @mun-ui/ui or set mun.server.command.`)) })
44
+ child.once('close', code => { clearTimeout(timer); code === 0 ? resolve(output.trim()) : reject(new Error(`Mün version check failed: ${stderr}`)) })
45
+ })
46
+ }
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { cpSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
4
+ import { tmpdir } from 'node:os'
5
+ import { dirname, resolve } from 'node:path'
6
+ import { spawnSync } from 'node:child_process'
7
+ import { fileURLToPath } from 'node:url'
8
+
9
+ const extensionRoot = resolve(dirname(fileURLToPath(import.meta.url)))
10
+ const repositoryRoot = resolve(extensionRoot, '../..')
11
+ const manifest = JSON.parse(readFileSync(resolve(repositoryRoot, 'package.json'), 'utf8'))
12
+ const extensionManifest = JSON.parse(readFileSync(resolve(extensionRoot, 'package.json'), 'utf8'))
13
+ const version = process.env.MUN_EXTENSION_VERSION ?? manifest.version
14
+ const output = resolve(process.argv[2] ?? resolve(repositoryRoot, 'dist', `mun-language-support-${version}.vsix`))
15
+ const stage = mkdtempSync(resolve(tmpdir(), 'mun-vsix-'))
16
+ const extensionStage = resolve(stage, 'extension')
17
+
18
+ try {
19
+ mkdirSync(extensionStage, { recursive: true })
20
+ // Package exactly the extension's declared file surface so adding a runtime
21
+ // helper cannot silently produce a VSIX that passes source tests but fails
22
+ // after installation.
23
+ for (const file of extensionManifest.files) {
24
+ cpSync(resolve(extensionRoot, file), resolve(extensionStage, file), { recursive: true })
25
+ }
26
+ const packagedManifest = { ...extensionManifest, version, private: undefined }
27
+ delete packagedManifest.private
28
+ writeFileSync(resolve(extensionStage, 'package.json'), `${JSON.stringify(packagedManifest, null, 2)}\n`)
29
+ writeFileSync(resolve(stage, '[Content_Types].xml'), `<?xml version="1.0" encoding="utf-8"?>\n<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="json" ContentType="application/json"/><Default Extension="cjs" ContentType="application/javascript"/><Default Extension="xml" ContentType="text/xml"/><Default Extension="tmLanguage" ContentType="application/json"/></Types>\n`)
30
+ writeFileSync(resolve(stage, 'extension.vsixmanifest'), `<?xml version="1.0" encoding="utf-8"?>\n<PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011"><Metadata><Identity Language="en-US" Id="${packagedManifest.name}" Version="${version}" Publisher="${packagedManifest.publisher}"/><DisplayName>${packagedManifest.displayName}</DisplayName><Description xml:space="preserve">${packagedManifest.description}</Description><Tags>mun,lsp,typescript</Tags><Categories>${packagedManifest.categories.join(',')}</Categories></Metadata><Installation><InstallationTarget Id="Microsoft.VisualStudio.Code" Version="^1.85.0"/></Installation><Dependencies/><Assets><Asset Type="Microsoft.VisualStudio.Code.Manifest" Path="extension/package.json"/><Asset Type="Microsoft.VisualStudio.Code.Extension" Path="extension/"/></Assets></PackageManifest>\n`)
31
+ mkdirSync(dirname(output), { recursive: true })
32
+ // Windows ships bsdtar, which writes zip archives; other platforms use zip.
33
+ const zip = process.platform === 'win32'
34
+ ? spawnSync('tar', ['-a', '-c', '--format', 'zip', '-f', output, '.'], { cwd: stage, encoding: 'utf8' })
35
+ : spawnSync('zip', ['-q', '-r', output, '.'], { cwd: stage, encoding: 'utf8' })
36
+ if (zip.error) throw new Error(`Could not create VSIX: ${zip.error.message}`)
37
+ if (zip.status !== 0) throw new Error(`archiver failed with exit code ${zip.status}: ${zip.stderr ?? ''}`)
38
+ console.log(output)
39
+ } finally {
40
+ rmSync(stage, { recursive: true, force: true })
41
+ }
42
+