@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,58 @@
1
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs'
2
+ import { resolve } from 'node:path'
3
+
4
+ function decodeKey(source) {
5
+ const value = source.trim()
6
+ if (!value) return undefined
7
+ if (value.startsWith('"')) {
8
+ try { return JSON.parse(value) } catch { return undefined }
9
+ }
10
+ if (value.startsWith("'") && value.endsWith("'")) return value.slice(1, -1).replaceAll("''", "'")
11
+ return value
12
+ }
13
+
14
+ function overrideKey(line) {
15
+ const match = /^ {2}((?:"(?:\\.|[^"\\])*")|(?:'(?:''|[^'])*')|(?:[^:#][^:]*?)):\s*/u.exec(line)
16
+ return match ? decodeKey(match[1]) : undefined
17
+ }
18
+
19
+ function renderedEntries(overrides) {
20
+ return Object.entries(overrides)
21
+ .sort(([left], [right]) => left.localeCompare(right))
22
+ .map(([name, specifier]) => ` ${JSON.stringify(name)}: ${JSON.stringify(specifier)}`)
23
+ }
24
+
25
+ /**
26
+ * Merge package overrides into pnpm 11+'s canonical settings file without
27
+ * destroying unrelated workspace settings or user-defined overrides.
28
+ */
29
+ export function updatePnpmWorkspaceOverrides(projectRoot, overrides) {
30
+ const path = resolve(projectRoot, 'pnpm-workspace.yaml')
31
+ const source = existsSync(path) ? readFileSync(path, 'utf8').replaceAll('\r\n', '\n') : ''
32
+ const lines = source ? source.split('\n') : []
33
+ if (lines.at(-1) === '') lines.pop()
34
+
35
+ const start = lines.findIndex(line => /^overrides:\s*(?:#.*)?$/u.test(line))
36
+ const entries = renderedEntries(overrides)
37
+
38
+ if (start < 0) {
39
+ if (lines.length > 0 && lines.at(-1)?.trim() !== '') lines.push('')
40
+ lines.push('overrides:', ...entries)
41
+ } else {
42
+ let end = start + 1
43
+ while (end < lines.length) {
44
+ const line = lines[end]
45
+ if (/^\S/u.test(line) && line.trim() !== '' && !line.startsWith('#')) break
46
+ end += 1
47
+ }
48
+ const names = new Set(Object.keys(overrides))
49
+ const preserved = lines.slice(start + 1, end).filter(line => {
50
+ const key = overrideKey(line)
51
+ return !key || !names.has(key)
52
+ })
53
+ lines.splice(start + 1, end - start - 1, ...preserved, ...entries)
54
+ }
55
+
56
+ writeFileSync(path, `${lines.join('\n').replace(/\n{3,}/gu, '\n\n')}\n`)
57
+ return path
58
+ }
@@ -0,0 +1,104 @@
1
+ function same(a, b) {
2
+ return Object.is(a, b)
3
+ }
4
+
5
+ function diffValue(before, after, path, operations) {
6
+ if (same(before, after)) return
7
+
8
+ const beforeObject = before !== null && typeof before === 'object'
9
+ const afterObject = after !== null && typeof after === 'object'
10
+ if (!beforeObject || !afterObject || Array.isArray(before) !== Array.isArray(after)) {
11
+ operations.push({ op: 'set', path, value: after })
12
+ return
13
+ }
14
+
15
+ if (Array.isArray(before)) {
16
+ if (before.length !== after.length) {
17
+ operations.push({ op: 'set', path, value: after })
18
+ return
19
+ }
20
+ for (let index = 0; index < before.length; index++) diffValue(before[index], after[index], [...path, index], operations)
21
+ return
22
+ }
23
+
24
+ const beforeKeys = Object.keys(before)
25
+ const afterKeys = Object.keys(after)
26
+ const afterSet = new Set(afterKeys)
27
+ for (const key of beforeKeys) if (!afterSet.has(key)) operations.push({ op: 'remove', path: [...path, key] })
28
+ for (const key of afterKeys) {
29
+ if (!Object.hasOwn(before, key)) operations.push({ op: 'set', path: [...path, key], value: after[key] })
30
+ else diffValue(before[key], after[key], [...path, key], operations)
31
+ }
32
+ }
33
+
34
+ export function diffProgram(before, after) {
35
+ const operations = []
36
+ diffValue(before, after, [], operations)
37
+ return operations
38
+ }
39
+
40
+ function parentAt(root, path) {
41
+ let current = root
42
+ for (const part of path) {
43
+ if (typeof part === 'number') {
44
+ if (!Array.isArray(current) || part < 0 || part >= current.length) throw new Error(`Patch array index out of range: ${part}`)
45
+ current = current[part]
46
+ } else {
47
+ if (current === null || typeof current !== 'object' || Array.isArray(current) || !Object.hasOwn(current, part)) throw new Error(`Patch object path is missing: ${part}`)
48
+ current = current[part]
49
+ }
50
+ }
51
+ return current
52
+ }
53
+
54
+ /** Test/tooling mirror of the native dev host patch semantics. */
55
+ export function applyProgramPatch(program, operations) {
56
+ let result = structuredClone(program)
57
+ for (const operation of operations) {
58
+ const path = operation.path
59
+ if (!Array.isArray(path)) throw new Error('Patch path must be an array')
60
+ if (path.length === 0) {
61
+ if (operation.op !== 'set') throw new Error('Cannot remove the program root')
62
+ result = structuredClone(operation.value)
63
+ continue
64
+ }
65
+ const key = path.at(-1)
66
+ const parent = parentAt(result, path.slice(0, -1))
67
+ if (operation.op === 'set') {
68
+ if (typeof key === 'number') {
69
+ if (!Array.isArray(parent) || key < 0 || key >= parent.length) throw new Error(`Patch array index out of range: ${key}`)
70
+ parent[key] = structuredClone(operation.value)
71
+ } else {
72
+ if (parent === null || typeof parent !== 'object' || Array.isArray(parent)) throw new Error('Patch object parent is invalid')
73
+ parent[key] = structuredClone(operation.value)
74
+ }
75
+ } else if (operation.op === 'remove') {
76
+ if (typeof key === 'number') throw new Error('Array element removal is not emitted; arrays are replaced atomically')
77
+ if (parent === null || typeof parent !== 'object' || Array.isArray(parent) || !Object.hasOwn(parent, key)) throw new Error(`Patch remove path is missing: ${key}`)
78
+ delete parent[key]
79
+ } else {
80
+ throw new Error(`Unsupported patch operation: ${operation.op}`)
81
+ }
82
+ }
83
+ return result
84
+ }
85
+
86
+ /**
87
+ * Choose the smaller dev update representation. Revisions are monotonic per
88
+ * native process; the host rejects stale/out-of-order messages.
89
+ */
90
+ export function createProgramUpdate(before, after, { baseRevision, revision, preserve, patchRatio = 0.9 }) {
91
+ if (!Number.isSafeInteger(baseRevision) || baseRevision < 0 || !Number.isSafeInteger(revision) || revision !== baseRevision + 1) {
92
+ throw new Error('Dev revisions must advance exactly by one')
93
+ }
94
+ const operations = diffProgram(before, after)
95
+ const common = { baseRevision, revision, preserve }
96
+ const patchPayload = { ...common, operations }
97
+ const fullPayload = { ...common, program: after }
98
+ const patchBytes = Buffer.byteLength(JSON.stringify({ type: 'patch', ...patchPayload }), 'utf8')
99
+ const fullBytes = Buffer.byteLength(JSON.stringify({ type: 'update', ...fullPayload }), 'utf8')
100
+ if (operations.length > 0 && patchBytes < fullBytes * patchRatio) {
101
+ return { type: 'patch', payload: patchPayload, bytes: patchBytes, fullBytes, operationCount: operations.length }
102
+ }
103
+ return { type: 'update', payload: fullPayload, bytes: fullBytes, fullBytes, operationCount: operations.length }
104
+ }
@@ -0,0 +1,322 @@
1
+ import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from 'node:fs'
2
+ import { dirname, relative, resolve, sep } from 'node:path'
3
+ import { MunLoweringCache, compileMunDevProgram, compileMunDevProgramFromStructs, compileMunUiProgram, munStructParseStats, parseMunStructs, shiftMunStruct } from '@mun-ui/compiler'
4
+
5
+ const fields = new Set(['manifest_version', 'name', 'entry', 'identifier', 'version', 'minimum_mun_version', 'platforms', 'resources', 'fonts', 'icon', 'window_title'])
6
+ const platforms = { darwin: 'macos', win32: 'windows', linux: 'linux' }
7
+
8
+ // Version 1 deliberately uses a strict, flat TOML subset: quoted strings,
9
+ // integer manifest_version and single-line string arrays. Reject unknown input.
10
+ export function parseManifest(source, path = 'mun.toml') {
11
+ const manifest = {}
12
+ for (const [index, raw] of source.split(/\r?\n/u).entries()) {
13
+ const line = raw.trim()
14
+ if (!line || line.startsWith('#')) continue
15
+ const match = /^([a-z_]+)\s*=\s*(.*)$/u.exec(line)
16
+ if (!match || !fields.has(match[1])) throw new Error(`${path}:${index + 1}: Unsupported manifest field or malformed TOML.`)
17
+ const [, key, value] = match
18
+ if (Object.hasOwn(manifest, key)) throw new Error(`${path}:${index + 1}: Duplicate ${key} definition.`)
19
+ try { manifest[key] = JSON.parse(value) } catch { throw new Error(`${path}:${index + 1}: Expected a quoted string, integer, or string array.`) }
20
+ }
21
+ if (manifest.manifest_version !== 1) throw new Error(`${path}: Unsupported manifest version ${manifest.manifest_version}; expected 1.`)
22
+ for (const key of ['name', 'entry', 'identifier', 'version']) {
23
+ if (typeof manifest[key] !== 'string' || !manifest[key].trim()) throw new Error(`${path}: ${key} must be a nonempty string.`)
24
+ }
25
+ for (const key of ['minimum_mun_version', 'icon', 'window_title']) {
26
+ if (manifest[key] !== undefined && typeof manifest[key] !== 'string') throw new Error(`${path}: ${key} must be a string.`)
27
+ }
28
+ for (const key of ['platforms', 'resources', 'fonts']) {
29
+ if (manifest[key] !== undefined && (!Array.isArray(manifest[key]) || manifest[key].some(value => typeof value !== 'string'))) throw new Error(`${path}: ${key} must be a string array.`)
30
+ }
31
+ if (manifest.platforms?.some(value => !Object.values(platforms).includes(value))) throw new Error(`${path}: Unsupported platform configuration; use macos, windows, linux.`)
32
+ if (!/^[A-Za-z0-9][A-Za-z0-9.-]+$/u.test(manifest.identifier)) throw new Error(`${path}: Invalid application identifier.`)
33
+ if (!/^\d+\.\d+\.\d+$/u.test(manifest.version)) throw new Error(`${path}: version must be major.minor.patch.`)
34
+ if (manifest.minimum_mun_version !== undefined && !/^\d+\.\d+\.\d+$/u.test(manifest.minimum_mun_version)) throw new Error(`${path}: minimum_mun_version must be major.minor.patch.`)
35
+ return manifest
36
+ }
37
+
38
+ export function projectPath(root, path) {
39
+ const resolved = resolve(root, path)
40
+ const local = relative(root, resolved)
41
+ if (!local || local === '..' || local.startsWith(`..${sep}`) || resolve(path) === path) throw new Error(`Project path must be relative and inside the project: ${path}`)
42
+ if (existsSync(resolved)) {
43
+ const actual = relative(realpathSync(root), realpathSync(resolved))
44
+ if (actual === '..' || actual.startsWith(`..${sep}`)) throw new Error(`Project path escapes through a symlink: ${path}`)
45
+ }
46
+ return resolved
47
+ }
48
+
49
+ export function discoverProject(start = process.cwd()) {
50
+ let root = resolve(start)
51
+ while (!existsSync(resolve(root, 'mun.toml'))) {
52
+ const parent = dirname(root)
53
+ if (parent === root) throw new Error(`No Mün project found from ${start}. Run mun new <name> or mun init to create mun.toml.`)
54
+ root = parent
55
+ }
56
+ const path = resolve(root, 'mun.toml')
57
+ const manifest = parseManifest(readFileSync(path, 'utf8'), path)
58
+ const entry = projectPath(root, manifest.entry)
59
+ if (!entry.endsWith('.mun') || !existsSync(entry) || !statSync(entry).isFile()) throw new Error(`${path}: Missing canonical entry source: ${manifest.entry}`)
60
+ return { root, manifest, entry }
61
+ }
62
+
63
+ export function sourceFiles(project) {
64
+ const files = []
65
+ function walk(directory) {
66
+ for (const item of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
67
+ if (item.name.startsWith('.') || ['node_modules', 'Assets', 'build', 'dist'].includes(item.name) || item.isSymbolicLink()) continue
68
+ const path = resolve(directory, item.name)
69
+ if (item.isDirectory()) walk(path)
70
+ else if (item.isFile() && item.name.endsWith('.mun')) files.push(path)
71
+ }
72
+ }
73
+ walk(project.root)
74
+ if (!files.includes(project.entry)) files.push(project.entry)
75
+ return files.sort()
76
+ }
77
+
78
+ export function validateAssets(project) {
79
+ for (const path of [...(project.manifest.resources ?? []), ...(project.manifest.fonts ?? []), ...(project.manifest.icon ? [project.manifest.icon] : [])]) {
80
+ const full = projectPath(project.root, path)
81
+ const local = relative(project.root, full)
82
+ if (local === '.mun' || local.startsWith(`.mun${sep}`)) throw new Error('Build output cannot be bundled as a project resource.')
83
+ if (!existsSync(full)) throw new Error(`Missing project resource: ${path}`)
84
+ // Reject nested symlinks rather than copying arbitrary machine files.
85
+ function validate(file) {
86
+ if (statSync(file).isDirectory()) for (const item of readdirSync(file, { withFileTypes: true })) {
87
+ if (item.isSymbolicLink()) throw new Error(`Resource symlinks are unsupported: ${file}/${item.name}`)
88
+ validate(resolve(file, item.name))
89
+ }
90
+ }
91
+ validate(full)
92
+ }
93
+ }
94
+
95
+ export function compileProject(project) {
96
+ return compileSources(project, sourceFiles(project).map(path => ({ path, source: readFileSync(path, 'utf8') }))).program
97
+ }
98
+
99
+ /** Qualified View name -> declaration source for a file's struct forest. */
100
+ function declarationSources(declarations, prefix = '', result = new Map()) {
101
+ for (const declaration of declarations) {
102
+ const name = prefix ? `${prefix}.${declaration.name}` : declaration.name
103
+ result.set(name, declaration.source)
104
+ declarationSources(declaration.nested ?? [], name, result)
105
+ }
106
+ return result
107
+ }
108
+
109
+ /** Declarations added, removed or edited between two struct forests of one file. */
110
+ function changedDeclarations(before, after) {
111
+ const previous = declarationSources(before)
112
+ const next = declarationSources(after)
113
+ const changed = []
114
+ for (const [name, source] of next) if (previous.get(name) !== source) changed.push(name)
115
+ for (const name of previous.keys()) if (!next.has(name)) changed.push(name)
116
+ return changed
117
+ }
118
+
119
+ function sourceError(path, source, error) {
120
+ const offset = Math.max(0, Math.min(source.length, typeof error.offset === 'number' ? error.offset : 0))
121
+ const before = source.slice(0, offset)
122
+ return new Error(`${path}:${before.split('\n').length}:${before.length - before.lastIndexOf('\n')}: ${error.message}`)
123
+ }
124
+
125
+ /** Offsets at which each line of `source` starts; built once per file version. */
126
+ const lineIndexes = new Map()
127
+ function lineStarts(source) {
128
+ let starts = lineIndexes.get(source)
129
+ if (starts) return starts
130
+ starts = [0]
131
+ for (let index = source.indexOf('\n'); index !== -1; index = source.indexOf('\n', index + 1)) starts.push(index + 1)
132
+ if (lineIndexes.size > 256) lineIndexes.clear()
133
+ lineIndexes.set(source, starts)
134
+ return starts
135
+ }
136
+
137
+ function sourcePoint(source, offset) {
138
+ const bounded = Math.max(0, Math.min(source.length, offset))
139
+ const starts = lineStarts(source)
140
+ let low = 0, high = starts.length - 1
141
+ while (low < high) {
142
+ const middle = (low + high + 1) >> 1
143
+ if (starts[middle] <= bounded) low = middle
144
+ else high = middle - 1
145
+ }
146
+ return { line: low + 1, column: bounded - starts[low] + 1 }
147
+ }
148
+
149
+ function mapDevMetadata(project, sources, metadata) {
150
+ const ranges = []
151
+ let base = 0
152
+ for (const item of sources) {
153
+ ranges.push({ ...item, base, end: base + item.source.length, file: relative(project.root, item.path).split(sep).join('/') })
154
+ base += item.source.length + 1
155
+ }
156
+ const locate = offset => {
157
+ let low = 0, high = ranges.length - 1
158
+ while (low < high) {
159
+ const middle = (low + high) >> 1
160
+ if (offset <= ranges[middle].end) high = middle
161
+ else low = middle + 1
162
+ }
163
+ const owner = ranges[low]
164
+ if (!owner) return undefined
165
+ const local = Math.max(0, Math.min(owner.source.length, offset - owner.base))
166
+ return { owner, local, ...sourcePoint(owner.source, local) }
167
+ }
168
+ return {
169
+ ...metadata,
170
+ nodes: (metadata.nodes ?? []).map(span => {
171
+ const start = locate(span.start)
172
+ const end = locate(span.end)
173
+ if (!start) return span
174
+ const sameFileEnd = end?.owner.path === start.owner.path ? end : start
175
+ return {
176
+ ...span,
177
+ file: start.owner.file,
178
+ line: start.line,
179
+ column: start.column,
180
+ endLine: sameFileEnd.line,
181
+ endColumn: sameFileEnd.column,
182
+ }
183
+ }),
184
+ }
185
+ }
186
+
187
+ function compileSources(project, sources, development = false, preparedStructs, loweringCache) {
188
+ const timings = {}
189
+ const started = performance.now()
190
+ sources = [...sources].sort((a, b) => a.path === project.entry ? -1 : b.path === project.entry ? 1 : a.path.localeCompare(b.path))
191
+ const combined = sources.map(item => item.source).join('\n')
192
+ try {
193
+ if (!development) return { program: compileMunUiProgram(combined, project.entry), timings }
194
+ const result = preparedStructs
195
+ ? compileMunDevProgramFromStructs(combined, preparedStructs, project.entry, { loweringCache })
196
+ : compileMunDevProgram(combined, project.entry, { loweringCache })
197
+ timings.lower = performance.now() - started
198
+ return { ...result, metadata: mapDevMetadata(project, sources, result.metadata), timings }
199
+ } catch (error) {
200
+ let offset = typeof error.offset === 'number' ? error.offset : 0
201
+ let owner = sources[0]
202
+ for (const item of sources) {
203
+ owner = item
204
+ if (offset <= item.source.length) break
205
+ offset -= item.source.length + 1
206
+ }
207
+ const before = owner.source.slice(0, offset)
208
+ throw new Error(`${owner.path}:${before.split('\n').length}:${before.length - before.lastIndexOf('\n')}: ${error.message}`)
209
+ }
210
+ }
211
+
212
+ /**
213
+ * Development project compiler with per-file snapshots. Unchanged files (same
214
+ * mtime and size) are not re-read; an edit that leaves every source byte-equal
215
+ * (editors often save twice) reuses the previous compilation outright.
216
+ *
217
+ * Changed files are reparsed per file. Lowering reuses every custom View
218
+ * instance whose declaration, transitive View dependencies and call-site
219
+ * inputs are unchanged (`MunLoweringCache`); stats report what was actually
220
+ * relowered versus reused, and which Views the previous dependency graph
221
+ * marks as affected by the changed declarations.
222
+ */
223
+ export function createProjectCompiler(project, { fs = { readFileSync, statSync }, incremental = true } = {}) {
224
+ const snapshots = new Map()
225
+ const loweringCache = incremental ? new MunLoweringCache() : undefined
226
+ let last
227
+ return {
228
+ compile() {
229
+ const started = performance.now()
230
+ const paths = sourceFiles(project)
231
+ let filesRead = 0
232
+ let filesReparsed = 0
233
+ let declarationsReparsed = 0
234
+ const changedFiles = []
235
+ const changed = []
236
+ for (const path of [...snapshots.keys()]) {
237
+ if (paths.includes(path)) continue
238
+ changed.push(...declarationSources(snapshots.get(path).structs).keys())
239
+ snapshots.delete(path); changedFiles.push(path)
240
+ }
241
+ for (const path of paths) {
242
+ const { mtimeMs, size } = fs.statSync(path)
243
+ const previous = snapshots.get(path)
244
+ if (previous && previous.mtimeMs === mtimeMs && previous.size === size) continue
245
+ const source = fs.readFileSync(path, 'utf8'); filesRead++
246
+ let structs = previous?.structs ?? []
247
+ if (previous?.source !== source) {
248
+ changedFiles.push(path)
249
+ const before = munStructParseStats().parsed
250
+ try { structs = parseMunStructs(source) }
251
+ catch (error) { throw sourceError(path, source, error) }
252
+ filesReparsed++
253
+ // Declarations whose text is unchanged are reused, not reparsed.
254
+ declarationsReparsed += munStructParseStats().parsed - before
255
+ changed.push(...changedDeclarations(previous?.structs ?? [], structs))
256
+ }
257
+ snapshots.set(path, { mtimeMs, size, source, structs })
258
+ }
259
+ const read = performance.now() - started
260
+ if (last && changedFiles.length === 0) {
261
+ return {
262
+ ...last,
263
+ timings: { read },
264
+ stats: {
265
+ ...last.stats,
266
+ filesRead,
267
+ filesReparsed: 0,
268
+ declarationsReparsed: 0,
269
+ declarationsRechecked: 0,
270
+ viewDeclarationsRelowered: 0,
271
+ changedFiles,
272
+ reused: true,
273
+ },
274
+ }
275
+ }
276
+ last = undefined // a failed compile must never fall back to an older result
277
+ const sources = paths
278
+ .map(path => ({ path, source: snapshots.get(path).source }))
279
+ .sort((a, b) => a.path === project.entry ? -1 : b.path === project.entry ? 1 : a.path.localeCompare(b.path))
280
+ const preparedStructs = []
281
+ let offset = 0
282
+ for (const item of sources) {
283
+ for (const declaration of snapshots.get(item.path).structs) preparedStructs.push(shiftMunStruct(declaration, offset))
284
+ offset += item.source.length + 1
285
+ }
286
+ // Affected Views per the dependency graph of the last successful compile.
287
+ const affectedViews = loweringCache ? [...loweringCache.affectedBy(changed)].sort() : undefined
288
+ const result = compileSources(project, sources, true, preparedStructs, loweringCache)
289
+ const lowering = result.stats?.lowering
290
+ last = {
291
+ ...result,
292
+ timings: { read, ...result.timings },
293
+ stats: {
294
+ filesRead,
295
+ filesReparsed,
296
+ declarationsReparsed,
297
+ declarationsRechecked: result.stats?.declarationsChecked ?? 0,
298
+ viewDeclarationsRelowered: lowering ? lowering.declarationsLowered.length : result.stats?.viewDeclarationsLowered ?? 0,
299
+ ...(lowering ? {
300
+ viewInstancesLowered: lowering.instancesLowered,
301
+ viewInstancesReused: lowering.instancesReused,
302
+ relowered: lowering.declarationsLowered,
303
+ changedDeclarations: [...new Set(changed)].sort(),
304
+ affectedViews,
305
+ } : {}),
306
+ changedFiles,
307
+ reused: false,
308
+ },
309
+ }
310
+ return last
311
+ },
312
+ /** Forget the last successful result (e.g. after the manifest changed). */
313
+ invalidate() { last = undefined; snapshots.clear(); loweringCache?.clear() },
314
+ /** View -> custom Views it uses, from the last successful compile. */
315
+ dependencyGraph() { return loweringCache?.dependencyGraph() ?? new Map() },
316
+ }
317
+ }
318
+
319
+ export function requirePlatform(project) {
320
+ const platform = platforms[process.platform]
321
+ if (!platform || (project.manifest.platforms && !project.manifest.platforms.includes(platform))) throw new Error(`Unsupported platform configuration for ${process.platform}.`)
322
+ }