@nimiplatform/app-tools 0.1.3 → 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 (121) hide show
  1. package/LICENSE +198 -6
  2. package/README.md +83 -27
  3. package/bin/nimi-app.mjs +328 -45
  4. package/lib/app-access-declaration.mjs +49 -0
  5. package/lib/app-doctor-update.mjs +411 -149
  6. package/lib/app-pack.mjs +402 -0
  7. package/lib/app-project-lifecycle.mjs +1141 -0
  8. package/lib/app-scaffold-capabilities.mjs +769 -0
  9. package/lib/app-scaffold-default-source.mjs +21 -0
  10. package/lib/app-scaffold-profiles.mjs +1093 -0
  11. package/lib/app-scaffold.mjs +1266 -813
  12. package/lib/index.mjs +195 -42
  13. package/lib/simulator-conformance-ast.mjs +498 -0
  14. package/lib/simulator-conformance-css.mjs +116 -0
  15. package/lib/simulator-conformance-graph.mjs +757 -0
  16. package/lib/simulator-conformance.d.mts +14 -0
  17. package/lib/simulator-conformance.mjs +203 -0
  18. package/lib/simulator-css-profile.d.mts +27 -0
  19. package/lib/simulator-css-profile.mjs +531 -0
  20. package/lib/simulator-kit-export-resolution.mjs +70 -0
  21. package/lib/simulator-manifest.mjs +334 -0
  22. package/lib/windows-powershell.mjs +7 -0
  23. package/package.json +66 -3
  24. package/scripts/dev-shell.mjs +465 -0
  25. package/scripts/sync-app-source.mjs +300 -0
  26. package/scripts/sync-scaffold-versions.mjs +91 -0
  27. package/templates/app-source/LICENSE +21 -0
  28. package/templates/app-source/src/ai-studio-core/ai-config.ts +100 -0
  29. package/templates/app-source/src/ai-studio-core/ai-studio-core.css +338 -0
  30. package/templates/app-source/src/ai-studio-core/contexts.tsx +61 -0
  31. package/templates/app-source/src/ai-studio-core/history-policy.ts +447 -0
  32. package/templates/app-source/src/ai-studio-core/history.ts +824 -0
  33. package/templates/app-source/src/ai-studio-core/host-context.tsx +79 -0
  34. package/templates/app-source/src/ai-studio-core/index.ts +214 -0
  35. package/templates/app-source/src/ai-studio-core/messages/en.json +310 -0
  36. package/templates/app-source/src/ai-studio-core/messages/index.ts +47 -0
  37. package/templates/app-source/src/ai-studio-core/messages/zh.json +310 -0
  38. package/templates/app-source/src/ai-studio-core/module-registration.ts +109 -0
  39. package/templates/app-source/src/ai-studio-core/non-success-presentation.ts +65 -0
  40. package/templates/app-source/src/ai-studio-core/parameter-fields.tsx +247 -0
  41. package/templates/app-source/src/ai-studio-core/parameters.ts +110 -0
  42. package/templates/app-source/src/ai-studio-core/prompt-drafts.ts +69 -0
  43. package/templates/app-source/src/ai-studio-core/run-target.ts +123 -0
  44. package/templates/app-source/src/ai-studio-core/runtime-dispatcher.ts +35 -0
  45. package/templates/app-source/src/ai-studio-core/runtime-types.ts +86 -0
  46. package/templates/app-source/src/ai-studio-core/runtime.ts +306 -0
  47. package/templates/app-source/src/ai-studio-core/section-ai-testing-admission.ts +38 -0
  48. package/templates/app-source/src/ai-studio-core/section-ai-testing-ai-config.tsx +30 -0
  49. package/templates/app-source/src/ai-studio-core/section-ai-testing-artifact-preview.ts +40 -0
  50. package/templates/app-source/src/ai-studio-core/section-ai-testing-composer.tsx +257 -0
  51. package/templates/app-source/src/ai-studio-core/section-ai-testing-history.tsx +676 -0
  52. package/templates/app-source/src/ai-studio-core/section-ai-testing-input.ts +19 -0
  53. package/templates/app-source/src/ai-studio-core/section-ai-testing-output.tsx +291 -0
  54. package/templates/app-source/src/ai-studio-core/section-ai-testing-result.tsx +413 -0
  55. package/templates/app-source/src/ai-studio-core/section-ai-testing-run.ts +174 -0
  56. package/templates/app-source/src/ai-studio-core/section-ai-testing-studio-result.tsx +449 -0
  57. package/templates/app-source/src/ai-studio-core/section-ai-testing-surface.tsx +45 -0
  58. package/templates/app-source/src/ai-studio-core/section-ai-testing.tsx +494 -0
  59. package/templates/app-source/src/ai-studio-core/studio-directives.ts +33 -0
  60. package/templates/app-source/src/ai-studio-core/workspace.tsx +381 -0
  61. package/templates/app-source/src/product-modules/agent-center/index.tsx +27 -0
  62. package/templates/app-source/src/product-modules/agent-conversation/index.tsx +19 -0
  63. package/templates/app-source/src/product-modules/agent-realtime/index.tsx +29 -0
  64. package/templates/app-source/src/product-modules/kit-recipes/gallery.tsx +142 -0
  65. package/templates/app-source/src/product-modules/kit-recipes/index.tsx +19 -0
  66. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-data-recipes.tsx +336 -0
  67. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-demos.tsx +165 -0
  68. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-recipes.tsx +682 -0
  69. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-surface.tsx +341 -0
  70. package/templates/app-source/src/studio-modules/studio-create/descriptors.ts +26 -0
  71. package/templates/app-source/src/studio-modules/studio-create/index.ts +14 -0
  72. package/templates/app-source/src/studio-modules/studio-create/messages/en.json +67 -0
  73. package/templates/app-source/src/studio-modules/studio-create/messages/index.ts +5 -0
  74. package/templates/app-source/src/studio-modules/studio-create/messages/zh.json +67 -0
  75. package/templates/app-source/src/studio-modules/studio-create/parameter-panel.tsx +153 -0
  76. package/templates/app-source/src/studio-modules/studio-create/parameters.ts +70 -0
  77. package/templates/app-source/src/studio-modules/studio-create/registration.ts +46 -0
  78. package/templates/app-source/src/studio-modules/studio-create/runtime.ts +339 -0
  79. package/templates/app-source/src/studio-modules/studio-media/descriptors.ts +22 -0
  80. package/templates/app-source/src/studio-modules/studio-media/index.ts +12 -0
  81. package/templates/app-source/src/studio-modules/studio-media/messages/en.json +82 -0
  82. package/templates/app-source/src/studio-modules/studio-media/messages/index.ts +5 -0
  83. package/templates/app-source/src/studio-modules/studio-media/messages/zh.json +82 -0
  84. package/templates/app-source/src/studio-modules/studio-media/parameter-panel.tsx +283 -0
  85. package/templates/app-source/src/studio-modules/studio-media/parameters.ts +94 -0
  86. package/templates/app-source/src/studio-modules/studio-media/registration.ts +44 -0
  87. package/templates/app-source/src/studio-modules/studio-media/runtime.ts +113 -0
  88. package/templates/app-source/src/studio-modules/studio-voice/descriptors.ts +28 -0
  89. package/templates/app-source/src/studio-modules/studio-voice/index.ts +16 -0
  90. package/templates/app-source/src/studio-modules/studio-voice/messages/en.json +99 -0
  91. package/templates/app-source/src/studio-modules/studio-voice/messages/index.ts +5 -0
  92. package/templates/app-source/src/studio-modules/studio-voice/messages/zh.json +99 -0
  93. package/templates/app-source/src/studio-modules/studio-voice/parameter-panel.tsx +284 -0
  94. package/templates/app-source/src/studio-modules/studio-voice/parameters.ts +116 -0
  95. package/templates/app-source/src/studio-modules/studio-voice/registration.ts +59 -0
  96. package/templates/app-source/src/studio-modules/studio-voice/runtime.ts +347 -0
  97. package/templates/app-source/src/workbench-core/empty-state.tsx +31 -0
  98. package/templates/app-source/src/workbench-core/index.ts +17 -0
  99. package/templates/app-source/src/workbench-core/runtime-gate.tsx +131 -0
  100. package/templates/app-source/src/workbench-core/workbench-core.css +255 -0
  101. package/templates/app-source/src/workbench-core/workbench-core.tsx +140 -0
  102. package/templates/app-source.manifest.json +333 -0
  103. package/templates/default-starter/AGENTS.md +33 -0
  104. package/templates/default-starter/LICENSE +21 -0
  105. package/templates/default-starter/README.md +41 -0
  106. package/templates/default-starter/SECURITY.md +5 -0
  107. package/templates/default-starter/index.html +12 -0
  108. package/templates/default-starter/scripts/validate.mjs +26 -0
  109. package/templates/default-starter/src/shell/App.tsx +27 -0
  110. package/templates/default-starter/src/shell/auth/app-identity.ts +3 -0
  111. package/templates/default-starter/src/shell/auth/local-app-client.ts +18 -0
  112. package/templates/default-starter/src/shell/auth/runtime-platform.ts +110 -0
  113. package/templates/default-starter/src/shell/authenticated-shell.tsx +20 -0
  114. package/templates/default-starter/src/shell/workbench-target-adapter.ts +40 -0
  115. package/templates/default-starter/src/styles.css +26 -0
  116. package/templates/default-starter/src-tauri/Cargo.toml +17 -0
  117. package/templates/default-starter/src-tauri/build.rs +5 -0
  118. package/templates/default-starter/src-tauri/capabilities/default.json +7 -0
  119. package/templates/default-starter/src-tauri/tauri.conf.json +26 -0
  120. package/templates/default-starter/tsconfig.json +18 -0
  121. package/templates/default-starter.manifest.json +99 -0
@@ -0,0 +1,1141 @@
1
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-scaf-018c
2
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-napp-009b
3
+
4
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
5
+ import path from 'node:path';
6
+ import { parse as parseYaml, parseDocument as parseYamlDocument, stringify as stringifyYaml } from 'yaml';
7
+
8
+ import { assertManifestAppAccessDeclaration } from './app-access-declaration.mjs';
9
+ import { syncManagedApp, validateAppProject } from './app-doctor-update.mjs';
10
+ import {
11
+ SCAFFOLD_INTENT_PATH,
12
+ SCAFFOLD_LOCK_PATH,
13
+ SUPPORTED_APP_SCAFFOLD_PROFILES,
14
+ managedAppReleaseWorkflowSource,
15
+ renderAppBuildProfile,
16
+ renderAppIdentityInput,
17
+ renderAppSubmissionInput,
18
+ } from './app-scaffold.mjs';
19
+ import { validateAppScaffoldNpmRegistryVersion } from './app-scaffold-capabilities.mjs';
20
+
21
+ const LEGACY_SCAFFOLD_LOCK_PATH = '.nimi/scaffold.lock.json';
22
+ const NPM_DEPENDENCY_SECTIONS = Object.freeze([
23
+ 'dependencies',
24
+ 'devDependencies',
25
+ 'optionalDependencies',
26
+ 'peerDependencies',
27
+ ]);
28
+ const KIT_OWNED_NATIVE_CARRIERS = Object.freeze([
29
+ '@nimiplatform/kit-protected-local-darwin-arm64',
30
+ '@nimiplatform/kit-protected-local-win32-x64',
31
+ ]);
32
+ const SYNCHRONIZED_NIMI_PACKAGES = new Set([
33
+ '@nimiplatform/sdk',
34
+ '@nimiplatform/kit',
35
+ '@nimiplatform/app-tools',
36
+ '@nimiplatform/nimi-coding',
37
+ ...KIT_OWNED_NATIVE_CARRIERS,
38
+ ]);
39
+ const BUILD_PROFILE_PATH = '.nimi/config/build-profile.yaml';
40
+ const MANAGED_WORKFLOW_PATH = '.github/workflows/nimi-app-release.yml';
41
+ const APP_IDENTITY_PATH = '.nimi/config/app-identity.yaml';
42
+ const SUBMISSION_PATH = '.nimi/admission/submission.yaml';
43
+ const SEMVER_PATTERN = /^(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)(?:-[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?(?:\+[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?$/u;
44
+ const CURRENT_APP_TARGETS = Object.freeze({
45
+ 'windows-x86_64': Object.freeze({ os: 'windows', arch: 'x86_64' }),
46
+ });
47
+
48
+ function resolveTargetDir(cwd, options = {}) {
49
+ return path.resolve(cwd, String(options.dir || '').trim() || '.');
50
+ }
51
+
52
+ function readJsonFile(filePath, label) {
53
+ try {
54
+ return JSON.parse(readFileSync(filePath, 'utf8'));
55
+ } catch (error) {
56
+ const message = error instanceof Error ? error.message : String(error);
57
+ throw new Error(`Invalid ${label}: ${filePath}: ${message}`);
58
+ }
59
+ }
60
+
61
+ function readSubmittedManifest(targetDir) {
62
+ const manifestPath = path.join(targetDir, 'nimi.app.yaml');
63
+ if (!existsSync(manifestPath)) {
64
+ throw new Error('Existing submitted app requires nimi.app.yaml');
65
+ }
66
+ const source = readFileSync(manifestPath, 'utf8');
67
+ assertManifestAppAccessDeclaration(source, manifestPath);
68
+ let document;
69
+ try {
70
+ document = parseYaml(source);
71
+ } catch (error) {
72
+ throw new Error(`Submitted manifest YAML cannot be parsed: ${error instanceof Error ? error.message : String(error)}`);
73
+ }
74
+ const appId = typeof document?.app_id === 'string' ? document.app_id.trim() : '';
75
+ const displayName = typeof document?.display_name === 'string' ? document.display_name : '';
76
+ const profile = typeof document?.profile === 'string' ? document.profile.trim() : '';
77
+ if (
78
+ !appId
79
+ || appId !== document?.app_id
80
+ || !displayName.trim()
81
+ || displayName !== displayName.trim()
82
+ || !/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/u.test(appId)
83
+ || !SUPPORTED_APP_SCAFFOLD_PROFILES.includes(profile)
84
+ ) {
85
+ throw new Error('Existing submitted app requires canonical app_id and supported profile');
86
+ }
87
+ if (document?.manifest_role !== 'submitted-input') {
88
+ throw new Error('Submitted manifest marker missing');
89
+ }
90
+ const rendererOrigin = document?.local_development?.electron?.renderer_origin;
91
+ let parsedOrigin;
92
+ try {
93
+ parsedOrigin = new URL(rendererOrigin);
94
+ } catch {
95
+ throw new Error('nimi.app.yaml local_development.electron.renderer_origin must be a canonical loopback origin');
96
+ }
97
+ if (
98
+ typeof rendererOrigin !== 'string'
99
+ || rendererOrigin.trim() !== rendererOrigin
100
+ || parsedOrigin.protocol !== 'http:'
101
+ || parsedOrigin.hostname !== '127.0.0.1'
102
+ || !parsedOrigin.port
103
+ || parsedOrigin.username
104
+ || parsedOrigin.password
105
+ || parsedOrigin.pathname !== '/'
106
+ || parsedOrigin.search
107
+ || parsedOrigin.hash
108
+ || rendererOrigin !== parsedOrigin.origin
109
+ ) {
110
+ throw new Error('nimi.app.yaml local_development.electron.renderer_origin must be a canonical 127.0.0.1 origin');
111
+ }
112
+ const version = typeof document?.version === 'string' ? document.version : '';
113
+ if (!SEMVER_PATTERN.test(version) || version !== document.version) {
114
+ throw new Error('Existing submitted app version must be an exact semantic version');
115
+ }
116
+ return Object.freeze({ appId, displayName, profile, version, rendererOrigin: parsedOrigin.origin });
117
+ }
118
+
119
+ function assertNoRetiredScaffoldState(targetDir) {
120
+ if (existsSync(path.join(targetDir, LEGACY_SCAFFOLD_LOCK_PATH))) {
121
+ throw new Error(`Unsupported legacy scaffold lock: ${LEGACY_SCAFFOLD_LOCK_PATH}`);
122
+ }
123
+ if (
124
+ existsSync(path.join(targetDir, SCAFFOLD_INTENT_PATH))
125
+ && !existsSync(path.join(targetDir, SCAFFOLD_LOCK_PATH))
126
+ ) {
127
+ throw new Error(`Missing initialized scaffold lock: ${SCAFFOLD_LOCK_PATH}`);
128
+ }
129
+ }
130
+
131
+ function expectedNimiDependencies(versions) {
132
+ return Object.freeze([
133
+ Object.freeze({ name: '@nimiplatform/sdk', section: 'dependencies', version: versions.sdkVersion }),
134
+ Object.freeze({ name: '@nimiplatform/kit', section: 'dependencies', version: versions.kitVersion }),
135
+ Object.freeze({ name: '@nimiplatform/app-tools', section: 'devDependencies', version: versions.appToolsVersion }),
136
+ Object.freeze({ name: '@nimiplatform/nimi-coding', section: 'devDependencies', version: versions.nimicodingVersion }),
137
+ ]);
138
+ }
139
+
140
+ function dependencySection(packageJson, sectionName) {
141
+ const section = packageJson[sectionName];
142
+ if (section === undefined) return null;
143
+ if (!section || typeof section !== 'object' || Array.isArray(section)) {
144
+ throw new Error(`package.json ${sectionName} must be an object`);
145
+ }
146
+ return section;
147
+ }
148
+
149
+ function isLocalDependencySpec(value) {
150
+ const normalized = typeof value === 'string' ? value.trim() : '';
151
+ return /^(?:file|link|patch|path|portal|workspace):/iu.test(normalized)
152
+ || /^(?:\.{1,2}[\\/]|~[\\/]|[A-Za-z]:[\\/]|\\\\)/u.test(normalized)
153
+ || /\.(?:tar\.gz|tgz)(?:[?#].*)?$/iu.test(normalized);
154
+ }
155
+
156
+ function synchronizedNimiPackageName(key) {
157
+ const normalized = String(key || '').replace(/^\/+/, '');
158
+ for (const packageName of SYNCHRONIZED_NIMI_PACKAGES) {
159
+ if (normalized === packageName || normalized.startsWith(`${packageName}@`)) return packageName;
160
+ }
161
+ return '';
162
+ }
163
+
164
+ function installRequiredError(detail) {
165
+ return new Error(`${detail}. Run pnpm install, then rerun nimi-app sync and nimi-app check.`);
166
+ }
167
+
168
+ function assertPublicNimiDependencySpecs(packageJson) {
169
+ for (const sectionName of NPM_DEPENDENCY_SECTIONS) {
170
+ const section = dependencySection(packageJson, sectionName);
171
+ if (!section) continue;
172
+ for (const [name, version] of Object.entries(section)) {
173
+ if (!name.startsWith('@nimiplatform/')) continue;
174
+ if (isLocalDependencySpec(version)) {
175
+ throw new Error(`Nimi dependency must use a public registry version: ${sectionName}.${name}`);
176
+ }
177
+ try {
178
+ validateAppScaffoldNpmRegistryVersion(version, `package.json ${sectionName}.${name}`);
179
+ } catch {
180
+ throw new Error(`Nimi dependency must use a public registry version: ${sectionName}.${name}`);
181
+ }
182
+ }
183
+ }
184
+ }
185
+
186
+ function assertPackageManifestCurrent(packageJson, versions) {
187
+ if (packageJson.private !== true || Object.hasOwn(packageJson, 'publishConfig')) {
188
+ throw new Error('Nimi App package.json must be private and must not declare npm publishConfig');
189
+ }
190
+ if (packageJson.packageManager !== versions.packageManager) {
191
+ throw new Error(`package.json packageManager must be ${versions.packageManager}`);
192
+ }
193
+ assertPublicNimiDependencySpecs(packageJson);
194
+ for (const expected of expectedNimiDependencies(versions)) {
195
+ const section = dependencySection(packageJson, expected.section);
196
+ if (section?.[expected.name] !== expected.version) {
197
+ throw new Error(`package.json ${expected.section}.${expected.name} must be ${expected.version}`);
198
+ }
199
+ for (const otherSectionName of NPM_DEPENDENCY_SECTIONS) {
200
+ if (otherSectionName === expected.section) continue;
201
+ const otherSection = dependencySection(packageJson, otherSectionName);
202
+ if (Object.hasOwn(otherSection || {}, expected.name)) {
203
+ throw new Error(`package.json ${expected.name} must appear only in ${expected.section}`);
204
+ }
205
+ }
206
+ }
207
+ for (const carrier of KIT_OWNED_NATIVE_CARRIERS) {
208
+ for (const sectionName of NPM_DEPENDENCY_SECTIONS) {
209
+ if (Object.hasOwn(dependencySection(packageJson, sectionName) || {}, carrier)) {
210
+ throw new Error(`Direct native carrier dependency is Kit-owned and must be removed: ${sectionName}.${carrier}`);
211
+ }
212
+ }
213
+ }
214
+ const scripts = dependencySection({ scripts: packageJson.scripts }, 'scripts') || {};
215
+ for (const [name, command] of Object.entries(scripts)) {
216
+ if (typeof command !== 'string') throw new Error(`package.json scripts.${name} must be a string`);
217
+ if (/\bnimi-app\s+(?:doctor|update)\b/u.test(command) || /\bpnpm\s+run\s+(?:doctor|update)\b/u.test(command)) {
218
+ throw new Error(`package.json scripts.${name} retains a retired nimi-app command`);
219
+ }
220
+ if (
221
+ /^(?:preinstall|install|postinstall|prepare|prepublishOnly)$/u.test(name)
222
+ && (/\bnimi-app\s+(?:init|sync)\b/u.test(command) || /\bnimicoding\s+sync\s+--apply\b/u.test(command))
223
+ ) {
224
+ throw new Error(`package.json scripts.${name} must not mutate managed App state during dependency installation`);
225
+ }
226
+ }
227
+ if (scripts.pack !== 'nimi-app pack') {
228
+ throw new Error('package.json scripts.pack must use the canonical nimi-app pack owner');
229
+ }
230
+ if (scripts.publish !== undefined) {
231
+ throw new Error('package.json scripts.publish is unavailable until publisher GitHub and registry orchestration is implemented');
232
+ }
233
+ }
234
+
235
+ function normalizePackageManifest(packageJson, descriptor, versions) {
236
+ if (!packageJson || typeof packageJson !== 'object' || Array.isArray(packageJson)) {
237
+ throw new Error('package.json must contain an object');
238
+ }
239
+ const normalized = JSON.parse(JSON.stringify(packageJson));
240
+ normalized.private = true;
241
+ delete normalized.publishConfig;
242
+ for (const sectionName of NPM_DEPENDENCY_SECTIONS) dependencySection(normalized, sectionName);
243
+ for (const expected of expectedNimiDependencies(versions)) {
244
+ for (const sectionName of NPM_DEPENDENCY_SECTIONS) {
245
+ const section = dependencySection(normalized, sectionName);
246
+ if (section) delete section[expected.name];
247
+ }
248
+ normalized[expected.section] ||= {};
249
+ normalized[expected.section][expected.name] = expected.version;
250
+ }
251
+ for (const carrier of KIT_OWNED_NATIVE_CARRIERS) {
252
+ for (const sectionName of NPM_DEPENDENCY_SECTIONS) {
253
+ const section = dependencySection(normalized, sectionName);
254
+ if (section) delete section[carrier];
255
+ }
256
+ }
257
+ normalized.packageManager = versions.packageManager;
258
+ normalized.scripts ||= {};
259
+ if (!normalized.scripts || typeof normalized.scripts !== 'object' || Array.isArray(normalized.scripts)) {
260
+ throw new Error('package.json scripts must be an object');
261
+ }
262
+ if (typeof normalized.scripts['build:electron'] !== 'string' || !normalized.scripts['build:electron'].trim()) {
263
+ throw new Error('package.json build:electron must build the Desktop-supervised Electron host');
264
+ }
265
+ normalized.scripts.dev = 'nimi-app dev --shell electron';
266
+ normalized.scripts['dev:shell'] = 'nimi-app dev';
267
+ normalized.scripts['dev:electron'] = 'nimi-app dev --shell electron';
268
+ normalized.scripts['dev:renderer'] = `vite --host 127.0.0.1 --port ${new URL(descriptor.rendererOrigin).port} --strictPort`;
269
+ normalized.scripts.sync ||= 'nimi-app sync';
270
+ normalized.scripts.pack = 'nimi-app pack';
271
+ delete normalized.scripts.publish;
272
+ for (const name of ['doctor', 'update']) {
273
+ if (/^nimi-app\s+(?:doctor|update)$/u.test(String(normalized.scripts[name] || '').trim())) {
274
+ delete normalized.scripts[name];
275
+ }
276
+ }
277
+ for (const [name, command] of Object.entries(normalized.scripts)) {
278
+ if (typeof command !== 'string') continue;
279
+ normalized.scripts[name] = command
280
+ .replace(/\bpnpm\s+run\s+doctor\s*&&\s*/gu, '')
281
+ .replace(/\bnimi-app\s+doctor\s*&&\s*/gu, '');
282
+ }
283
+ assertPackageManifestCurrent(normalized, versions);
284
+ return `${JSON.stringify(normalized, null, 2)}\n`;
285
+ }
286
+
287
+ function parseYamlFile(source, filePath) {
288
+ try {
289
+ return parseYaml(source);
290
+ } catch (error) {
291
+ throw new Error(`Invalid ${path.basename(filePath)}: ${error instanceof Error ? error.message : String(error)}`);
292
+ }
293
+ }
294
+
295
+ function requireObject(value, label) {
296
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${label} must contain an object`);
297
+ return value;
298
+ }
299
+
300
+ function assertExactKeys(value, label, required, optional = []) {
301
+ const object = requireObject(value, label);
302
+ const allowed = new Set([...required, ...optional]);
303
+ for (const key of Object.keys(object)) {
304
+ if (!allowed.has(key)) throw new Error(`${label} contains unsupported field: ${key}`);
305
+ }
306
+ for (const key of required) {
307
+ if (!Object.hasOwn(object, key)) throw new Error(`${label} is missing required field: ${key}`);
308
+ }
309
+ return object;
310
+ }
311
+
312
+ function canonicalInputText(value, label) {
313
+ if (typeof value !== 'string' || !value || value !== value.trim() || /[\0\r\n]/u.test(value)) {
314
+ throw new Error(`${label} must be a non-empty canonical string`);
315
+ }
316
+ return value;
317
+ }
318
+
319
+ function canonicalInputList(value, label, allowEmpty = true) {
320
+ if (!Array.isArray(value) || (!allowEmpty && value.length === 0)) throw new Error(`${label} must be ${allowEmpty ? 'an array' : 'a non-empty array'}`);
321
+ const entries = value.map((item, index) => canonicalInputText(item, `${label}[${index}]`));
322
+ if (new Set(entries).size !== entries.length) throw new Error(`${label} must not contain duplicates`);
323
+ return entries;
324
+ }
325
+
326
+ function normalizeSupportInput(value, label) {
327
+ const support = assertExactKeys(value, label, [
328
+ 'diagnostics_bundle_fields',
329
+ 'redaction_rules',
330
+ 'user_visible_issue_categories',
331
+ 'escalation_path',
332
+ 'kill_switch_visibility',
333
+ 'recovery_instructions',
334
+ ]);
335
+ if (support.kill_switch_visibility !== 'visible') throw new Error(`${label}.kill_switch_visibility must be visible`);
336
+ return {
337
+ diagnostics_bundle_fields: canonicalInputList(support.diagnostics_bundle_fields, `${label}.diagnostics_bundle_fields`, false),
338
+ redaction_rules: canonicalInputList(support.redaction_rules, `${label}.redaction_rules`, false),
339
+ user_visible_issue_categories: canonicalInputList(support.user_visible_issue_categories, `${label}.user_visible_issue_categories`, false),
340
+ escalation_path: canonicalInputText(support.escalation_path, `${label}.escalation_path`),
341
+ kill_switch_visibility: 'visible',
342
+ recovery_instructions: canonicalInputText(support.recovery_instructions, `${label}.recovery_instructions`),
343
+ };
344
+ }
345
+
346
+ function normalizeStorageInput(value, label) {
347
+ const storage = requireObject(value, label);
348
+ if (storage.kind === 'nimi-mediated-default') {
349
+ assertExactKeys(storage, label, ['kind']);
350
+ return { kind: 'nimi-mediated-default' };
351
+ }
352
+ if (storage.kind !== 'app-owned-os-storage') throw new Error(`${label}.kind is unsupported`);
353
+ assertExactKeys(storage, label, ['kind', 'os_storage_disclosure']);
354
+ if (!Array.isArray(storage.os_storage_disclosure) || storage.os_storage_disclosure.length === 0) {
355
+ throw new Error(`${label}.os_storage_disclosure must be a non-empty array`);
356
+ }
357
+ return {
358
+ kind: storage.kind,
359
+ os_storage_disclosure: storage.os_storage_disclosure.map((entry, index) => {
360
+ const item = assertExactKeys(entry, `${label}.os_storage_disclosure[${index}]`, ['path_pattern', 'purpose', 'expected_size_band']);
361
+ return {
362
+ path_pattern: canonicalInputText(item.path_pattern, `${label}.os_storage_disclosure[${index}].path_pattern`),
363
+ purpose: canonicalInputText(item.purpose, `${label}.os_storage_disclosure[${index}].purpose`),
364
+ expected_size_band: canonicalInputText(item.expected_size_band, `${label}.os_storage_disclosure[${index}].expected_size_band`),
365
+ };
366
+ }),
367
+ };
368
+ }
369
+
370
+ function normalizePnpmWorkspace(targetDir) {
371
+ const workspacePath = path.join(targetDir, 'pnpm-workspace.yaml');
372
+ if (!existsSync(workspacePath)) return null;
373
+ const source = readFileSync(workspacePath, 'utf8');
374
+ const document = parseYamlDocument(source);
375
+ if (document.errors.length > 0) {
376
+ throw new Error(`Invalid pnpm-workspace.yaml: ${document.errors[0].message}`);
377
+ }
378
+ const workspace = document.toJS();
379
+ const overrides = workspace?.overrides;
380
+ if (overrides !== undefined && (!overrides || typeof overrides !== 'object' || Array.isArray(overrides))) {
381
+ throw new Error('pnpm-workspace.yaml overrides must be an object');
382
+ }
383
+ let removed = false;
384
+ for (const key of Object.keys(overrides || {})) {
385
+ if (synchronizedNimiPackageName(key)) {
386
+ document.deleteIn(['overrides', key]);
387
+ removed = true;
388
+ }
389
+ }
390
+ const remainingOverrides = document.toJS()?.overrides;
391
+ if (remainingOverrides && Object.keys(remainingOverrides).length === 0) document.deleteIn(['overrides']);
392
+ return {
393
+ path: workspacePath,
394
+ previous: source,
395
+ content: removed ? String(document) : source,
396
+ };
397
+ }
398
+
399
+ function assertPnpmWorkspaceCurrent(targetDir) {
400
+ const workspacePath = path.join(targetDir, 'pnpm-workspace.yaml');
401
+ if (!existsSync(workspacePath)) return;
402
+ const source = readFileSync(workspacePath, 'utf8');
403
+ const workspace = parseYamlFile(source, workspacePath);
404
+ const overrides = workspace?.overrides;
405
+ if (overrides !== undefined && (!overrides || typeof overrides !== 'object' || Array.isArray(overrides))) {
406
+ throw new Error('pnpm-workspace.yaml overrides must be an object');
407
+ }
408
+ for (const key of Object.keys(overrides || {})) {
409
+ if (synchronizedNimiPackageName(key)) {
410
+ throw installRequiredError(`pnpm-workspace.yaml retains a Nimi dependency override: ${key}`);
411
+ }
412
+ }
413
+ }
414
+
415
+ function findLocalNimiResolution(value, currentPackage = '', pathParts = []) {
416
+ if (Array.isArray(value)) {
417
+ for (let index = 0; index < value.length; index += 1) {
418
+ const finding = findLocalNimiResolution(value[index], currentPackage, [...pathParts, String(index)]);
419
+ if (finding) return finding;
420
+ }
421
+ return null;
422
+ }
423
+ if (!value || typeof value !== 'object') return null;
424
+ for (const [key, child] of Object.entries(value)) {
425
+ const packageName = synchronizedNimiPackageName(key) || currentPackage;
426
+ const normalizedKey = String(key).replace(/^\/+/, '');
427
+ if (
428
+ packageName
429
+ && normalizedKey.startsWith(`${packageName}@`)
430
+ && isLocalDependencySpec(normalizedKey.slice(packageName.length + 1))
431
+ ) {
432
+ return [...pathParts, key].join('.');
433
+ }
434
+ if (packageName && typeof child === 'string' && isLocalDependencySpec(child)) {
435
+ return [...pathParts, key].join('.');
436
+ }
437
+ const finding = findLocalNimiResolution(child, packageName, [...pathParts, key]);
438
+ if (finding) return finding;
439
+ }
440
+ return null;
441
+ }
442
+
443
+ function assertPnpmLockCurrent(targetDir, packageJson) {
444
+ const lockPath = path.join(targetDir, 'pnpm-lock.yaml');
445
+ if (!existsSync(lockPath)) {
446
+ throw installRequiredError('pnpm-lock.yaml is missing');
447
+ }
448
+ const lock = parseYamlFile(readFileSync(lockPath, 'utf8'), lockPath);
449
+ const finding = findLocalNimiResolution(lock);
450
+ if (finding) {
451
+ throw installRequiredError(`pnpm-lock.yaml retains a local Nimi resolution at ${finding}`);
452
+ }
453
+ const importer = lock?.importers?.['.'];
454
+ if (!importer || typeof importer !== 'object' || Array.isArray(importer)) {
455
+ throw installRequiredError('pnpm-lock.yaml root importer is missing');
456
+ }
457
+ for (const sectionName of NPM_DEPENDENCY_SECTIONS) {
458
+ const packageSection = dependencySection(packageJson, sectionName) || {};
459
+ const lockSection = importer[sectionName] || {};
460
+ for (const [name, specifier] of Object.entries(packageSection)) {
461
+ if (!name.startsWith('@nimiplatform/')) continue;
462
+ if (lockSection?.[name]?.specifier !== specifier) {
463
+ throw installRequiredError(`pnpm-lock.yaml ${sectionName}.${name} specifier does not match package.json`);
464
+ }
465
+ }
466
+ for (const name of Object.keys(lockSection || {})) {
467
+ if (name.startsWith('@nimiplatform/') && !Object.hasOwn(packageSection, name)) {
468
+ throw installRequiredError(`pnpm-lock.yaml retains stale Nimi dependency: ${sectionName}.${name}`);
469
+ }
470
+ }
471
+ }
472
+ }
473
+
474
+ function assertCargoLockCurrent(targetDir, version) {
475
+ const cargoLockError = (detail) => new Error(`${detail}. Run cargo update -p nimi-shell-tauri --precise ${version}, then rerun nimi-app check.`);
476
+ const lockPath = path.join(targetDir, 'src-tauri', 'Cargo.lock');
477
+ if (!existsSync(lockPath)) {
478
+ throw cargoLockError('src-tauri/Cargo.lock is missing');
479
+ }
480
+ const blocks = readFileSync(lockPath, 'utf8').split(/\r?\n\[\[package\]\]\r?\n/u);
481
+ const block = blocks.find((entry) => /^name\s*=\s*"nimi-shell-tauri"\s*$/mu.test(entry));
482
+ if (!block) throw cargoLockError('src-tauri/Cargo.lock is missing nimi-shell-tauri');
483
+ const lockedVersion = block.match(/^version\s*=\s*"([^"]+)"\s*$/mu)?.[1];
484
+ const source = block.match(/^source\s*=\s*"([^"]+)"\s*$/mu)?.[1];
485
+ const checksum = block.match(/^checksum\s*=\s*"([a-f0-9]{64})"\s*$/mu)?.[1];
486
+ if (lockedVersion !== version || !source?.startsWith('registry+') || !checksum) {
487
+ throw cargoLockError(`src-tauri/Cargo.lock nimi-shell-tauri must resolve registry version ${version} with checksum`);
488
+ }
489
+ }
490
+
491
+ function cargoDependencyLocations(source) {
492
+ const lines = source.split(/\r?\n/u);
493
+ let section = '';
494
+ const entries = [];
495
+ let dependenciesHeader = -1;
496
+ for (let index = 0; index < lines.length; index += 1) {
497
+ const header = lines[index].match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/u);
498
+ if (header) {
499
+ section = header[1];
500
+ if (section === 'dependencies') dependenciesHeader = index;
501
+ continue;
502
+ }
503
+ if (/^\s*nimi-shell-tauri\s*=/u.test(lines[index])) {
504
+ entries.push({ index, section, line: lines[index].trim() });
505
+ }
506
+ }
507
+ return { lines, entries, dependenciesHeader };
508
+ }
509
+
510
+ function normalizeCargoManifest(source, version) {
511
+ const newline = source.includes('\r\n') ? '\r\n' : '\n';
512
+ const hadFinalNewline = source.endsWith('\n');
513
+ const { lines, entries, dependenciesHeader } = cargoDependencyLocations(source);
514
+ if (entries.length > 1 || entries.some((entry) => entry.section !== 'dependencies')) {
515
+ throw new Error('src-tauri/Cargo.toml must declare nimi-shell-tauri exactly once under [dependencies]');
516
+ }
517
+ const canonicalLine = `nimi-shell-tauri = "${version}"`;
518
+ if (entries.length === 1) {
519
+ lines[entries[0].index] = canonicalLine;
520
+ } else if (dependenciesHeader >= 0) {
521
+ let insertion = lines.length;
522
+ for (let index = dependenciesHeader + 1; index < lines.length; index += 1) {
523
+ if (/^\s*\[[^\]]+\]/u.test(lines[index])) {
524
+ insertion = index;
525
+ break;
526
+ }
527
+ }
528
+ if (insertion === lines.length && lines.at(-1) === '') insertion -= 1;
529
+ lines.splice(insertion, 0, canonicalLine);
530
+ } else {
531
+ if (lines.at(-1) === '') lines.pop();
532
+ if (lines.length > 0 && lines.at(-1) !== '') lines.push('');
533
+ lines.push('[dependencies]', canonicalLine);
534
+ }
535
+ const rendered = lines.join(newline);
536
+ return hadFinalNewline && !rendered.endsWith(newline) ? `${rendered}${newline}` : rendered;
537
+ }
538
+
539
+ function assertCargoManifestCurrent(source, version) {
540
+ const { entries } = cargoDependencyLocations(source);
541
+ const expected = `nimi-shell-tauri = "${version}"`;
542
+ if (entries.length !== 1 || entries[0].section !== 'dependencies' || entries[0].line !== expected) {
543
+ throw new Error(`src-tauri/Cargo.toml nimi-shell-tauri must use exact public version ${version}`);
544
+ }
545
+ }
546
+
547
+ function normalizeTauriConfig(config, appId) {
548
+ if (!config || typeof config !== 'object' || Array.isArray(config)) {
549
+ throw new Error('src-tauri/tauri.conf.json must contain an object');
550
+ }
551
+ const normalized = JSON.parse(JSON.stringify(config));
552
+ normalized.identifier = `ai.nimi.apps.${appId}`;
553
+ return `${JSON.stringify(normalized, null, 2)}\n`;
554
+ }
555
+
556
+ function assertTauriConfigCurrent(config, appId) {
557
+ const expected = `ai.nimi.apps.${appId}`;
558
+ if (config?.identifier !== expected) {
559
+ throw new Error(`src-tauri/tauri.conf.json identifier must be ${expected}`);
560
+ }
561
+ }
562
+
563
+ function normalizeStandaloneSourceFiles(targetDir) {
564
+ const planned = [];
565
+ for (const name of ['vite.config.ts', 'vite.config.js', 'vite.config.mjs']) {
566
+ const filePath = path.join(targetDir, name);
567
+ if (!existsSync(filePath)) continue;
568
+ const previous = readFileSync(filePath, 'utf8');
569
+ let content = previous
570
+ .replace(/^const nimiRepoRoot\s*=.*\r?\n/gmu, '')
571
+ .replace(/^const nimiSdkSourceRoot\s*=.*\r?\n/gmu, '')
572
+ .replace(/^const nimiKitSourceRoot\s*=.*\r?\n/gmu, '')
573
+ .replace(/^\s*\|\|\s*normalizedId\.includes\(['"]\/nimi-realm\/nimi\/(?:sdks\/typescript|kit)\/['"]\)\r?\n/gmu, '')
574
+ .replace(/^\s*\{\s*find:\s*\/\^@nimiplatform\\\/(?:sdk|kit).*replacement:\s*path\.resolve\(nimi(?:Sdk|Kit)SourceRoot.*\r?\n/gmu, '')
575
+ .replace(/\n\s*server:\s*\{\s*\n\s*fs:\s*\{\s*\n\s*allow:\s*\[\s*\n\s*appRoot,\s*\n\s*nimiRepoRoot,\s*\n\s*\],\s*\n\s*\},\s*\n\s*\},?/mu, '\n');
576
+ if (!content.includes('appRoot')) content = content.replace(/^const appRoot\s*=.*\r?\n/gmu, '');
577
+ planned.push({ path: filePath, content, previous });
578
+ }
579
+ const stylesPath = path.join(targetDir, 'src', 'styles.css');
580
+ if (existsSync(stylesPath)) {
581
+ const previous = readFileSync(stylesPath, 'utf8');
582
+ const content = previous.replace(
583
+ /^@source\s+["'][^"']*\/nimi\/kit\/\*\*\/\*\.\{ts,tsx\}["'];?\r?$/gmu,
584
+ '@source "../node_modules/@nimiplatform/kit/**/*.{js,mjs,ts,tsx}";',
585
+ );
586
+ planned.push({ path: stylesPath, content, previous });
587
+ }
588
+ return planned;
589
+ }
590
+
591
+ function assertNoStandaloneParentSources(targetDir) {
592
+ for (const relativePath of ['vite.config.ts', 'vite.config.js', 'vite.config.mjs', 'src/styles.css']) {
593
+ const filePath = path.join(targetDir, ...relativePath.split('/'));
594
+ if (!existsSync(filePath)) continue;
595
+ const source = readFileSync(filePath, 'utf8');
596
+ if (
597
+ /nimiRepoRoot|nimiSdkSourceRoot|nimiKitSourceRoot|\/nimi-realm\/nimi\/(?:sdks|kit)\//u.test(source)
598
+ || /find:\s*\/\^@nimiplatform\\\/(?:sdk|kit)(?:\\\/|\$)/u.test(source)
599
+ || /server\s*:\s*\{[\s\S]*?fs\s*:\s*\{[\s\S]*?allow\s*:/u.test(source)
600
+ || /@source\s+["'][^"']*\/nimi\/kit\//u.test(source)
601
+ || /(?:\.\.[\\/])+(?:nimi[\\/])?(?:sdks|kit)(?:[\\/]|['"])/u.test(source)
602
+ ) {
603
+ throw new Error(`Standalone App retains a parent Nimi source path: ${relativePath}`);
604
+ }
605
+ }
606
+ }
607
+
608
+ function readProjectLifecycleFiles(targetDir) {
609
+ const packagePath = path.join(targetDir, 'package.json');
610
+ const cargoPath = path.join(targetDir, 'src-tauri', 'Cargo.toml');
611
+ const tauriPath = path.join(targetDir, 'src-tauri', 'tauri.conf.json');
612
+ for (const requiredPath of [packagePath, cargoPath, tauriPath]) {
613
+ if (!existsSync(requiredPath)) throw new Error(`Required App lifecycle file is missing: ${path.relative(targetDir, requiredPath)}`);
614
+ }
615
+ return {
616
+ packagePath,
617
+ packageSource: readFileSync(packagePath, 'utf8'),
618
+ packageJson: readJsonFile(packagePath, 'package.json'),
619
+ cargoPath,
620
+ cargoSource: readFileSync(cargoPath, 'utf8'),
621
+ tauriPath,
622
+ tauriSource: readFileSync(tauriPath, 'utf8'),
623
+ tauriConfig: readJsonFile(tauriPath, 'src-tauri/tauri.conf.json'),
624
+ };
625
+ }
626
+
627
+ function readCargoPackageVersion(source) {
628
+ let inPackage = false;
629
+ for (const line of source.split(/\r?\n/u)) {
630
+ const header = line.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/u);
631
+ if (header) {
632
+ inPackage = header[1] === 'package';
633
+ continue;
634
+ }
635
+ if (!inPackage) continue;
636
+ const match = line.match(/^\s*version\s*=\s*"([^"]+)"\s*(?:#.*)?$/u);
637
+ if (match) return match[1];
638
+ }
639
+ throw new Error('src-tauri/Cargo.toml [package] version is missing');
640
+ }
641
+
642
+ function readCargoPackageName(source) {
643
+ let inPackage = false;
644
+ for (const line of source.split(/\r?\n/u)) {
645
+ const header = line.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/u);
646
+ if (header) {
647
+ inPackage = header[1] === 'package';
648
+ continue;
649
+ }
650
+ if (!inPackage) continue;
651
+ const match = line.match(/^\s*name\s*=\s*"([^"]+)"\s*(?:#.*)?$/u);
652
+ if (match) return match[1];
653
+ }
654
+ throw new Error('src-tauri/Cargo.toml [package] name is missing');
655
+ }
656
+
657
+ function assertVersionLockstep(files, descriptor) {
658
+ const version = files.packageJson.version;
659
+ if (typeof version !== 'string' || !SEMVER_PATTERN.test(version)) {
660
+ throw new Error('package.json version must be an exact semantic version');
661
+ }
662
+ const observed = [
663
+ ['nimi.app.yaml', descriptor.version],
664
+ ['src-tauri/Cargo.toml', readCargoPackageVersion(files.cargoSource)],
665
+ ['src-tauri/tauri.conf.json', files.tauriConfig.version],
666
+ ];
667
+ for (const [name, candidate] of observed) {
668
+ if (candidate !== null && candidate !== undefined && candidate !== version) {
669
+ throw new Error(`${name} version must match package.json version ${version}`);
670
+ }
671
+ }
672
+ return version;
673
+ }
674
+
675
+ function assertCanonicalAuthoringInputs(targetDir, descriptor, files, version) {
676
+ const identityPath = path.join(targetDir, APP_IDENTITY_PATH);
677
+ const submissionPath = path.join(targetDir, SUBMISSION_PATH);
678
+ if (!existsSync(identityPath)) throw new Error(`Required App lifecycle file is missing: ${APP_IDENTITY_PATH}`);
679
+ if (!existsSync(submissionPath)) throw new Error(`Required App lifecycle file is missing: ${SUBMISSION_PATH}`);
680
+ const identity = assertExactKeys(parseYamlFile(readFileSync(identityPath, 'utf8'), identityPath), APP_IDENTITY_PATH, [
681
+ 'app_id', 'display_name', 'version', 'npm_package_name', 'cargo_package_name', 'tauri_identifier', 'package_author', 'identity_role',
682
+ ]);
683
+ const packageAuthor = files.packageJson.author === undefined ? null : files.packageJson.author;
684
+ if (packageAuthor !== null) canonicalInputText(packageAuthor, 'package.json author');
685
+ const expectedIdentity = {
686
+ app_id: descriptor.appId,
687
+ display_name: descriptor.displayName,
688
+ version,
689
+ npm_package_name: canonicalInputText(files.packageJson.name, 'package.json name'),
690
+ cargo_package_name: readCargoPackageName(files.cargoSource),
691
+ tauri_identifier: files.tauriConfig.identifier,
692
+ package_author: packageAuthor,
693
+ identity_role: 'scaffold-generated-authoring-input',
694
+ };
695
+ for (const [key, expected] of Object.entries(expectedIdentity)) {
696
+ if (identity[key] !== expected) throw new Error(`${APP_IDENTITY_PATH} ${key} must match its canonical owner`);
697
+ }
698
+
699
+ const submission = assertExactKeys(parseYamlFile(readFileSync(submissionPath, 'utf8'), submissionPath), SUBMISSION_PATH, [
700
+ 'app_id',
701
+ 'display_name',
702
+ 'version',
703
+ 'profile',
704
+ 'npm_package_name',
705
+ 'cargo_package_name',
706
+ 'tauri_identifier',
707
+ 'package_author',
708
+ 'submission_role',
709
+ 'capability_contract_refs',
710
+ 'required_standardized_feature_refs',
711
+ 'storage_policy',
712
+ 'support_manifest',
713
+ 'review_inputs',
714
+ 'admission_truth',
715
+ ], ['ai_profile_recommendation_ref']);
716
+ const expectedSubmissionIdentity = {
717
+ app_id: descriptor.appId,
718
+ display_name: descriptor.displayName,
719
+ version,
720
+ profile: descriptor.profile,
721
+ npm_package_name: expectedIdentity.npm_package_name,
722
+ cargo_package_name: expectedIdentity.cargo_package_name,
723
+ tauri_identifier: expectedIdentity.tauri_identifier,
724
+ package_author: packageAuthor,
725
+ submission_role: 'developer-submitted-input',
726
+ admission_truth: 'platform-owned-after-review',
727
+ };
728
+ for (const [key, expected] of Object.entries(expectedSubmissionIdentity)) {
729
+ if (submission[key] !== expected) throw new Error(`${SUBMISSION_PATH} ${key} must match its canonical owner`);
730
+ }
731
+ canonicalInputList(submission.capability_contract_refs, `${SUBMISSION_PATH} capability_contract_refs`);
732
+ canonicalInputList(submission.required_standardized_feature_refs, `${SUBMISSION_PATH} required_standardized_feature_refs`);
733
+ if (submission.ai_profile_recommendation_ref !== undefined) {
734
+ canonicalInputText(submission.ai_profile_recommendation_ref, `${SUBMISSION_PATH} ai_profile_recommendation_ref`);
735
+ }
736
+ normalizeStorageInput(submission.storage_policy, `${SUBMISSION_PATH} storage_policy`);
737
+ normalizeSupportInput(submission.support_manifest, `${SUBMISSION_PATH} support_manifest`);
738
+ const reviewInputs = assertExactKeys(submission.review_inputs, `${SUBMISSION_PATH} review_inputs`, ['manifest', 'build_profile', 'scaffold_boundary']);
739
+ const expectedReviewInputs = {
740
+ manifest: 'nimi.app.yaml',
741
+ build_profile: BUILD_PROFILE_PATH,
742
+ scaffold_boundary: '.nimi/contracts/scaffold-boundary.yaml',
743
+ };
744
+ for (const [key, expected] of Object.entries(expectedReviewInputs)) {
745
+ if (reviewInputs[key] !== expected) throw new Error(`${SUBMISSION_PATH} review_inputs.${key} must be ${expected}`);
746
+ }
747
+ return { identity, submission };
748
+ }
749
+
750
+ function assertManagedWorkflowCurrent(targetDir) {
751
+ const workflowPath = path.join(targetDir, MANAGED_WORKFLOW_PATH);
752
+ if (!existsSync(workflowPath)) throw new Error(`Required App lifecycle file is missing: ${MANAGED_WORKFLOW_PATH}`);
753
+ if (readFileSync(workflowPath, 'utf8') !== managedAppReleaseWorkflowSource()) {
754
+ throw new Error(`${MANAGED_WORKFLOW_PATH} must match the app-tools managed workflow`);
755
+ }
756
+ const workflowDir = path.dirname(workflowPath);
757
+ for (const name of readdirSync(workflowDir).sort()) {
758
+ const candidatePath = path.join(workflowDir, name);
759
+ if (candidatePath === workflowPath || !/\.ya?ml$/iu.test(name)) continue;
760
+ const source = readFileSync(candidatePath, 'utf8');
761
+ if (
762
+ /\bgh\s+release\s+(?:create|upload|edit|delete)\b/iu.test(source)
763
+ || /(?:softprops\/action-gh-release|ncipollo\/release-action|actions\/create-release)/iu.test(source)
764
+ || /candidate-uploads|\/api\/platform\/apps\/candidates/iu.test(source)
765
+ ) {
766
+ throw new Error(`Parallel App production workflow is forbidden: .github/workflows/${name}`);
767
+ }
768
+ }
769
+ if (existsSync(path.join(targetDir, 'scripts', 'pack.mjs'))) {
770
+ throw new Error('App-local scripts/pack.mjs is forbidden; use nimi-app pack');
771
+ }
772
+ }
773
+
774
+ function canonicalOwnerCommand(value, field) {
775
+ if (typeof value !== 'string' || !value.trim() || value !== value.trim() || /[\r\n\0]/u.test(value)) {
776
+ throw new Error(`${field} must be a non-empty single-line command`);
777
+ }
778
+ if (/\bnimi-app\s+(?:test|build)\b/u.test(value)) {
779
+ throw new Error(`${field} must not recursively invoke nimi-app test or build`);
780
+ }
781
+ return value;
782
+ }
783
+
784
+ function canonicalProjectPath(value, field) {
785
+ if (typeof value !== 'string' || !value || value !== value.trim() || value.includes('\\')) {
786
+ throw new Error(`${field} must be a canonical relative path`);
787
+ }
788
+ const parts = value.split('/');
789
+ if (value.startsWith('/') || parts.some((part) => !part || part === '.' || part === '..')) {
790
+ throw new Error(`${field} must be a canonical relative path`);
791
+ }
792
+ return value;
793
+ }
794
+
795
+ function readBuildProfile(targetDir) {
796
+ const filePath = path.join(targetDir, BUILD_PROFILE_PATH);
797
+ if (!existsSync(filePath)) throw new Error(`Required App lifecycle file is missing: ${BUILD_PROFILE_PATH}`);
798
+ const profile = parseYamlFile(readFileSync(filePath, 'utf8'), filePath);
799
+ if (!profile || typeof profile !== 'object' || Array.isArray(profile)) {
800
+ throw new Error(`${BUILD_PROFILE_PATH} must contain an object`);
801
+ }
802
+ if (profile.profile_role !== 'developer-workflow-input') {
803
+ throw new Error(`${BUILD_PROFILE_PATH} profile_role must be developer-workflow-input`);
804
+ }
805
+ const targets = profile.targets === undefined ? {} : profile.targets;
806
+ if (!targets || typeof targets !== 'object' || Array.isArray(targets)) {
807
+ throw new Error(`${BUILD_PROFILE_PATH} targets must be an object`);
808
+ }
809
+ if (Object.keys(targets).length === 0) {
810
+ throw new Error(`${BUILD_PROFILE_PATH} must declare at least one target`);
811
+ }
812
+ for (const [targetId, target] of Object.entries(targets)) {
813
+ const expected = CURRENT_APP_TARGETS[targetId];
814
+ if (!expected || !target || typeof target !== 'object' || Array.isArray(target)) {
815
+ throw new Error(`${BUILD_PROFILE_PATH} declares unsupported target: ${targetId}`);
816
+ }
817
+ if (target.os !== expected.os || target.arch !== expected.arch) {
818
+ throw new Error(`${BUILD_PROFILE_PATH} target identity mismatch: ${targetId}`);
819
+ }
820
+ }
821
+ return {
822
+ testCommand: canonicalOwnerCommand(profile.test_command, `${BUILD_PROFILE_PATH} test_command`),
823
+ buildCommand: canonicalOwnerCommand(profile.build_command, `${BUILD_PROFILE_PATH} build_command`),
824
+ targets,
825
+ };
826
+ }
827
+
828
+ function currentTargetId() {
829
+ if (process.platform === 'win32' && process.arch === 'x64') return 'windows-x86_64';
830
+ if (process.platform === 'darwin' && process.arch === 'arm64') return 'macos-aarch64';
831
+ throw new Error(`Unsupported App build host: ${process.platform}-${process.arch}`);
832
+ }
833
+
834
+ function selectBuildOwner(profile, requestedTarget) {
835
+ const target = String(requestedTarget || '').trim() || currentTargetId();
836
+ const targetProfile = profile.targets[target];
837
+ if (Object.keys(profile.targets).length > 0 && (!targetProfile || typeof targetProfile !== 'object' || Array.isArray(targetProfile))) {
838
+ throw new Error(`Unsupported App build target: ${target}`);
839
+ }
840
+ const command = targetProfile?.build_command === undefined
841
+ ? profile.buildCommand
842
+ : canonicalOwnerCommand(targetProfile.build_command, `${BUILD_PROFILE_PATH} targets.${target}.build_command`);
843
+ const payloadPath = canonicalProjectPath(targetProfile?.payload_path, `${BUILD_PROFILE_PATH} targets.${target}.payload_path`);
844
+ const runtimeEntry = canonicalProjectPath(targetProfile?.runtime_entry, `${BUILD_PROFILE_PATH} targets.${target}.runtime_entry`);
845
+ if (!runtimeEntry.startsWith('payload/')) {
846
+ throw new Error(`${BUILD_PROFILE_PATH} targets.${target}.runtime_entry must resolve inside the packaged payload`);
847
+ }
848
+ return { target, command, payloadPath, runtimeEntry };
849
+ }
850
+
851
+ function resolveProductionSignTarget(targetDir, selected) {
852
+ const projectRoot = path.resolve(targetDir);
853
+ const payloadPath = path.resolve(projectRoot, ...selected.payloadPath.split('/'));
854
+ const projectPrefix = `${projectRoot}${path.sep}`;
855
+ if (!payloadPath.startsWith(projectPrefix) || !existsSync(payloadPath)) {
856
+ throw new Error(`Production payload is missing or noncanonical: ${selected.payloadPath}`);
857
+ }
858
+ const payloadStat = lstatSync(payloadPath);
859
+ let signTarget = payloadPath;
860
+ if (payloadStat.isDirectory()) {
861
+ const runtimeRelative = selected.runtimeEntry.slice('payload/'.length);
862
+ signTarget = path.resolve(payloadPath, ...runtimeRelative.split('/'));
863
+ } else if (!payloadStat.isFile() || payloadStat.isSymbolicLink()) {
864
+ throw new Error(`Production payload is not a direct file or directory: ${selected.payloadPath}`);
865
+ }
866
+ const payloadPrefix = `${payloadPath}${path.sep}`;
867
+ if (
868
+ !existsSync(signTarget)
869
+ || (!payloadStat.isFile() && !signTarget.startsWith(payloadPrefix))
870
+ ) {
871
+ throw new Error(`Production Runtime entry is missing or noncanonical: ${selected.runtimeEntry}`);
872
+ }
873
+ const signTargetStat = lstatSync(signTarget);
874
+ if (!signTargetStat.isFile() || signTargetStat.isSymbolicLink()) {
875
+ throw new Error(`Production Runtime entry must be a direct regular file: ${selected.runtimeEntry}`);
876
+ }
877
+ return path.relative(projectRoot, signTarget).split(path.sep).join('/');
878
+ }
879
+
880
+ function runOwnerCommand(targetDir, kind, command, options, runners) {
881
+ if (typeof runners?.runAppCommand !== 'function') throw new Error('Missing App command runner');
882
+ const result = runners.runAppCommand(targetDir, command, { capture: options.json === true });
883
+ if (!result || result.status !== 0) {
884
+ const detail = [result?.stdout, result?.stderr].filter(Boolean).join('\n').trim();
885
+ throw new Error(`${kind} command failed${detail ? `: ${detail}` : ''}`);
886
+ }
887
+ return result;
888
+ }
889
+
890
+ function assertProjectLifecycleCurrent(targetDir, versions, options = {}) {
891
+ const descriptor = readSubmittedManifest(targetDir);
892
+ const files = readProjectLifecycleFiles(targetDir);
893
+ assertPackageManifestCurrent(files.packageJson, versions);
894
+ const version = assertVersionLockstep(files, descriptor);
895
+ assertCargoManifestCurrent(files.cargoSource, versions.nimiShellTauriVersion);
896
+ assertTauriConfigCurrent(files.tauriConfig, descriptor.appId);
897
+ assertNoStandaloneParentSources(targetDir);
898
+ const authoring = assertCanonicalAuthoringInputs(targetDir, descriptor, files, version);
899
+ if (existsSync(path.join(targetDir, SCAFFOLD_LOCK_PATH))) {
900
+ const lock = readJsonFile(path.join(targetDir, SCAFFOLD_LOCK_PATH), 'scaffold lock');
901
+ for (const [field, expected] of [
902
+ ['capability_contract_refs', lock.capabilityContractRefs],
903
+ ['required_standardized_feature_refs', lock.requiredStandardizedFeatureRefs],
904
+ ]) {
905
+ if (JSON.stringify(authoring.submission[field]) !== JSON.stringify(expected || [])) {
906
+ throw new Error(`${SUBMISSION_PATH} ${field} must match the selected scaffold feature closure`);
907
+ }
908
+ }
909
+ }
910
+ const buildProfile = readBuildProfile(targetDir);
911
+ assertManagedWorkflowCurrent(targetDir);
912
+ assertPnpmWorkspaceCurrent(targetDir);
913
+ if (options.requireInstalledLock === true) {
914
+ assertPnpmLockCurrent(targetDir, files.packageJson);
915
+ assertCargoLockCurrent(targetDir, versions.nimiShellTauriVersion);
916
+ }
917
+ return { descriptor, files, version, buildProfile, authoring };
918
+ }
919
+
920
+ function buildExistingSubmittedAppSyncPlan(targetDir, versions) {
921
+ const descriptor = readSubmittedManifest(targetDir);
922
+ const files = readProjectLifecycleFiles(targetDir);
923
+ const version = files.packageJson.version;
924
+ if (typeof version !== 'string' || !SEMVER_PATTERN.test(version)) {
925
+ throw new Error('package.json version must be an exact semantic version before sync');
926
+ }
927
+ const identity = {
928
+ appId: descriptor.appId,
929
+ appTitle: descriptor.displayName,
930
+ version,
931
+ profile: descriptor.profile,
932
+ packageName: files.packageJson.name,
933
+ cargoPackageName: readCargoPackageName(files.cargoSource),
934
+ tauriIdentifier: `ai.nimi.apps.${descriptor.appId}`,
935
+ author: typeof files.packageJson.author === 'string' ? files.packageJson.author : '',
936
+ };
937
+ const planned = [
938
+ { path: files.packagePath, content: normalizePackageManifest(files.packageJson, descriptor, versions), previous: files.packageSource },
939
+ { path: files.cargoPath, content: normalizeCargoManifest(files.cargoSource, versions.nimiShellTauriVersion), previous: files.cargoSource },
940
+ { path: files.tauriPath, content: normalizeTauriConfig(files.tauriConfig, descriptor.appId), previous: files.tauriSource },
941
+ ];
942
+ planned.push(...normalizeStandaloneSourceFiles(targetDir));
943
+ const identityPath = path.join(targetDir, APP_IDENTITY_PATH);
944
+ planned.push({
945
+ path: identityPath,
946
+ content: renderAppIdentityInput(identity),
947
+ previous: existsSync(identityPath) ? readFileSync(identityPath, 'utf8') : '',
948
+ });
949
+ const submissionPath = path.join(targetDir, SUBMISSION_PATH);
950
+ const currentSubmissionSource = existsSync(submissionPath) ? readFileSync(submissionPath, 'utf8') : '';
951
+ const currentSubmission = currentSubmissionSource ? parseYamlFile(currentSubmissionSource, submissionPath) : null;
952
+ let supportManifest;
953
+ if (currentSubmission) {
954
+ assertExactKeys(currentSubmission, SUBMISSION_PATH, [
955
+ 'app_id',
956
+ 'display_name',
957
+ 'version',
958
+ 'profile',
959
+ 'npm_package_name',
960
+ 'cargo_package_name',
961
+ 'tauri_identifier',
962
+ 'package_author',
963
+ 'submission_role',
964
+ 'capability_contract_refs',
965
+ 'required_standardized_feature_refs',
966
+ 'storage_policy',
967
+ 'support_manifest',
968
+ 'review_inputs',
969
+ 'admission_truth',
970
+ ], ['ai_profile_recommendation_ref']);
971
+ canonicalInputList(currentSubmission.capability_contract_refs, `${SUBMISSION_PATH} capability_contract_refs`);
972
+ canonicalInputList(currentSubmission.required_standardized_feature_refs, `${SUBMISSION_PATH} required_standardized_feature_refs`);
973
+ normalizeStorageInput(currentSubmission.storage_policy, `${SUBMISSION_PATH} storage_policy`);
974
+ supportManifest = normalizeSupportInput(currentSubmission.support_manifest, `${SUBMISSION_PATH} support_manifest`);
975
+ }
976
+ const submissionContent = renderAppSubmissionInput(identity, {
977
+ capabilityContractRefs: currentSubmission?.capability_contract_refs || [],
978
+ requiredStandardizedFeatureRefs: currentSubmission?.required_standardized_feature_refs || [],
979
+ aiProfileRecommendationRef: currentSubmission?.ai_profile_recommendation_ref,
980
+ storagePolicy: currentSubmission?.storage_policy || { kind: 'nimi-mediated-default' },
981
+ supportManifest,
982
+ });
983
+ planned.push({ path: submissionPath, content: submissionContent, previous: currentSubmissionSource });
984
+ const buildProfilePath = path.join(targetDir, BUILD_PROFILE_PATH);
985
+ const currentBuildProfile = existsSync(buildProfilePath) ? readFileSync(buildProfilePath, 'utf8') : '';
986
+ const buildProfile = currentBuildProfile
987
+ ? parseYamlFile(currentBuildProfile, buildProfilePath)
988
+ : {};
989
+ const scripts = files.packageJson.scripts || {};
990
+ const testCommand = buildProfile.test_command
991
+ || (typeof scripts['test:app'] === 'string' ? 'pnpm run test:app' : null)
992
+ || (typeof scripts.test === 'string' && !/\bnimi-app\s+test\b/u.test(scripts.test) ? 'pnpm run test' : null);
993
+ const buildCommand = buildProfile.build_command
994
+ || (typeof scripts['build:shell'] === 'string' ? 'pnpm run build:shell' : null)
995
+ || (typeof scripts.build === 'string' && !/\bnimi-app\s+build\b/u.test(scripts.build) ? 'pnpm run build' : null);
996
+ if (!testCommand || !buildCommand) {
997
+ throw new Error('Existing submitted App requires declared test and build owner commands');
998
+ }
999
+ const normalizedBuildProfile = currentBuildProfile
1000
+ ? stringifyYaml({
1001
+ ...buildProfile,
1002
+ test_command: testCommand,
1003
+ build_command: buildCommand,
1004
+ profile_role: 'developer-workflow-input',
1005
+ }, { lineWidth: 0 })
1006
+ : renderAppBuildProfile({ testCommand, buildCommand });
1007
+ planned.push({
1008
+ path: buildProfilePath,
1009
+ content: normalizedBuildProfile,
1010
+ previous: currentBuildProfile,
1011
+ });
1012
+ const workflowPath = path.join(targetDir, MANAGED_WORKFLOW_PATH);
1013
+ planned.push({
1014
+ path: workflowPath,
1015
+ content: managedAppReleaseWorkflowSource(),
1016
+ previous: existsSync(workflowPath) ? readFileSync(workflowPath, 'utf8') : '',
1017
+ });
1018
+ const workspace = normalizePnpmWorkspace(targetDir);
1019
+ if (workspace) planned.push(workspace);
1020
+ return { descriptor, planned };
1021
+ }
1022
+
1023
+ function runNimicodingSync(targetDir, mode, runners) {
1024
+ if (!runners?.runNimicodingSync) throw new Error('Missing nimicoding sync runner');
1025
+ const result = runners.runNimicodingSync(targetDir, mode);
1026
+ if (result && result.ok === false) {
1027
+ throw new Error(`nimicoding package-owned projection ${mode} failed`);
1028
+ }
1029
+ return result;
1030
+ }
1031
+
1032
+ function emitResult(payload, options, message) {
1033
+ if (options.json) process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
1034
+ else process.stdout.write(`[nimi-app] ${message}\n`);
1035
+ return payload;
1036
+ }
1037
+
1038
+ function applySyncPlan(targetDir, plan) {
1039
+ const synchronizedFiles = [];
1040
+ for (const file of plan.planned) {
1041
+ if (file.content === file.previous) continue;
1042
+ mkdirSync(path.dirname(file.path), { recursive: true });
1043
+ writeFileSync(file.path, file.content);
1044
+ synchronizedFiles.push(path.relative(targetDir, file.path).split(path.sep).join('/'));
1045
+ }
1046
+ return synchronizedFiles;
1047
+ }
1048
+
1049
+ export function syncAppProject(cwd, options = {}, versions, runners = {}) {
1050
+ const targetDir = resolveTargetDir(cwd, options);
1051
+ assertNoRetiredScaffoldState(targetDir);
1052
+ const managed = existsSync(path.join(targetDir, SCAFFOLD_LOCK_PATH));
1053
+ if (managed) {
1054
+ const refreshed = syncManagedApp(cwd, { dir: targetDir, silent: true }, versions, runners);
1055
+ const plan = buildExistingSubmittedAppSyncPlan(targetDir, versions);
1056
+ const synchronizedFiles = applySyncPlan(targetDir, plan);
1057
+ validateAppProject(cwd, { dir: targetDir, silent: true }, versions, runners);
1058
+ assertProjectLifecycleCurrent(targetDir, versions);
1059
+ return emitResult({
1060
+ ...refreshed,
1061
+ managed: true,
1062
+ synchronizedFiles,
1063
+ nextSteps: ['pnpm install', `cargo update -p nimi-shell-tauri --precise ${versions.nimiShellTauriVersion}`, 'nimi-app sync', 'nimi-app check'],
1064
+ }, options, `sync completed for ${targetDir}`);
1065
+ }
1066
+ const plan = managed ? null : buildExistingSubmittedAppSyncPlan(targetDir, versions);
1067
+ const nimicoding = runNimicodingSync(targetDir, 'apply', runners);
1068
+ const synchronizedFiles = applySyncPlan(targetDir, plan);
1069
+ validateAppProject(cwd, { dir: targetDir, silent: true }, versions, runners);
1070
+ assertProjectLifecycleCurrent(targetDir, versions);
1071
+ return emitResult({
1072
+ ok: true,
1073
+ command: 'sync',
1074
+ dir: targetDir,
1075
+ managed,
1076
+ appId: plan?.descriptor.appId || readSubmittedManifest(targetDir).appId,
1077
+ synchronizedFiles,
1078
+ nimicodingSync: nimicoding?.summary || null,
1079
+ nextSteps: ['pnpm install', `cargo update -p nimi-shell-tauri --precise ${versions.nimiShellTauriVersion}`, 'nimi-app sync', 'nimi-app check'],
1080
+ }, options, `sync completed for ${targetDir}`);
1081
+ }
1082
+
1083
+ export function checkAppProject(cwd, options = {}, versions, runners = {}) {
1084
+ const targetDir = resolveTargetDir(cwd, options);
1085
+ if (options.conformance) {
1086
+ return validateAppProject(cwd, { dir: targetDir, conformance: options.conformance, json: options.json }, versions, runners);
1087
+ }
1088
+ assertNoRetiredScaffoldState(targetDir);
1089
+ const managed = existsSync(path.join(targetDir, SCAFFOLD_LOCK_PATH));
1090
+ const validation = validateAppProject(cwd, { dir: targetDir, silent: true }, versions, runners);
1091
+ let nimicoding = null;
1092
+ if (!managed) nimicoding = runNimicodingSync(targetDir, 'check', runners);
1093
+ const { descriptor, buildProfile } = assertProjectLifecycleCurrent(targetDir, versions, { requireInstalledLock: true });
1094
+ return emitResult({
1095
+ ok: true,
1096
+ command: 'check',
1097
+ dir: targetDir,
1098
+ production: options.production === true,
1099
+ managed,
1100
+ appId: descriptor.appId,
1101
+ profile: descriptor.profile,
1102
+ targets: Object.keys(buildProfile.targets).sort(),
1103
+ checkedManagedFiles: validation.checkedManagedFiles,
1104
+ checkedExistingFiles: validation.checkedExistingFiles,
1105
+ nimicodingSync: nimicoding?.summary || null,
1106
+ }, options, `check passed for ${targetDir}`);
1107
+ }
1108
+
1109
+ export function testAppProject(cwd, options = {}, runners = {}) {
1110
+ const targetDir = resolveTargetDir(cwd, options);
1111
+ const profile = readBuildProfile(targetDir);
1112
+ const result = runOwnerCommand(targetDir, 'test', profile.testCommand, options, runners);
1113
+ return emitResult({
1114
+ ok: true,
1115
+ command: 'test',
1116
+ dir: targetDir,
1117
+ ownerCommand: profile.testCommand,
1118
+ ...(options.json ? { stdout: result.stdout || '', stderr: result.stderr || '' } : {}),
1119
+ }, options, `test passed for ${targetDir}`);
1120
+ }
1121
+
1122
+ export function buildAppProject(cwd, options = {}, runners = {}) {
1123
+ const targetDir = resolveTargetDir(cwd, options);
1124
+ const profile = readBuildProfile(targetDir);
1125
+ const selected = selectBuildOwner(profile, options.target);
1126
+ const result = runOwnerCommand(targetDir, 'build', selected.command, options, runners);
1127
+ if (options.production === true) {
1128
+ if (selected.target !== 'windows-x86_64' || typeof runners?.signWindowsTarget !== 'function') {
1129
+ throw new Error(`Production signing is unavailable for target: ${selected.target}`);
1130
+ }
1131
+ runners.signWindowsTarget(targetDir, resolveProductionSignTarget(targetDir, selected));
1132
+ }
1133
+ return emitResult({
1134
+ ok: true,
1135
+ command: 'build',
1136
+ dir: targetDir,
1137
+ target: selected.target,
1138
+ ownerCommand: selected.command,
1139
+ ...(options.json ? { stdout: result.stdout || '', stderr: result.stderr || '' } : {}),
1140
+ }, options, `build completed for ${selected.target}`);
1141
+ }