@nimiplatform/app-tools 0.16.0-rc.12 → 0.16.0-rc.14

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.
@@ -1,4 +1,5 @@
1
1
  import { assertDesktopHostSupport } from './app-host-support.mjs';
2
+ import { validateManifestDesktop } from './desktop-window.mjs';
2
3
  import { hostedWebIdentity, isAppId } from './app-identifiers.mjs';
3
4
  import { readWebDevelopment } from './web-development.mjs';
4
5
  import { readAppInfo } from './app-info.mjs';
@@ -53,9 +54,10 @@ const SYNCHRONIZED_NIMI_PACKAGES = new Set([
53
54
  ...KIT_OWNED_NATIVE_CARRIERS,
54
55
  ]);
55
56
  const BUILD_PROFILE_PATH = '.nimi/config/build-profile.yaml';
57
+ const MANAGED_WEB_BUILD_PROFILE_REF = 'managed-web-pnpm-vite';
56
58
  const ELECTRON_BUILD_PROFILE_REF = 'electron-packager-pnpm-vite';
57
59
  const APP_OWNED_ELECTRON_BUILD_PROFILE_REF = 'electron-pnpm';
58
- const SUPPORTED_BUILD_PROFILE_REFS = new Set([ELECTRON_BUILD_PROFILE_REF, APP_OWNED_ELECTRON_BUILD_PROFILE_REF, 'web-pnpm']);
60
+ const SUPPORTED_BUILD_PROFILE_REFS = new Set([MANAGED_WEB_BUILD_PROFILE_REF, ELECTRON_BUILD_PROFILE_REF, APP_OWNED_ELECTRON_BUILD_PROFILE_REF, 'web-pnpm']);
59
61
  const MANAGED_WORKFLOW_PATH = '.github/workflows/nimi-app-release.yml';
60
62
  const HOSTED_WEB_WORKFLOW_PATH = '.github/workflows/nimi-web-release.yml';
61
63
  function hostedWorkflowSource() {
@@ -73,10 +75,11 @@ function planHostedWorkflow(targetDir) {
73
75
  }
74
76
  const APP_IDENTITY_PATH = '.nimi/config/app-identity.yaml';
75
77
  const SUBMISSION_PATH = '.nimi/admission/submission.yaml';
76
- 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;
78
+ const SEMVER_PATTERN = /^(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)(?:-(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u;
77
79
  const CURRENT_APP_TARGETS = Object.freeze({
78
80
  'windows-x86_64': Object.freeze({ os: 'windows', arch: 'x86_64' }),
79
81
  'macos-aarch64': Object.freeze({ os: 'macos', arch: 'arm64' }),
82
+ 'desktop-universal': Object.freeze({ os: 'any', arch: 'any' }),
80
83
  });
81
84
 
82
85
  function resolveTargetDir(cwd, options = {}) {
@@ -169,7 +172,8 @@ function readSubmittedManifest(targetDir, sources) {
169
172
  throw new Error(`nimi.app.yaml ${error instanceof Error ? error.message : String(error)}`, { cause: error });
170
173
  }
171
174
  }
172
- return Object.freeze({ appId, displayName, profile, platform, version, publicSlug: hosted?.slug, rendererOrigin: parsedOrigin.origin, capabilityContractRefs: document.capability_contract_refs, requiredStandardizedFeatureRefs: document.required_standardized_feature_refs, storagePolicy: document.storage_policy, safetyProfile });
175
+ const desktop = validateManifestDesktop(document.desktop, 'nimi.app.yaml desktop', source);
176
+ return Object.freeze({ appId, displayName, profile, platform, version, publicSlug: hosted?.slug, rendererOrigin: parsedOrigin.origin, capabilityContractRefs: document.capability_contract_refs, requiredStandardizedFeatureRefs: document.required_standardized_feature_refs, storagePolicy: document.storage_policy, safetyProfile, desktop });
173
177
  }
174
178
 
175
179
  function assertNoRetiredScaffoldState(targetDir) {
@@ -352,6 +356,13 @@ function normalizePackageManifest(packageJson, descriptor, versions, buildProfil
352
356
  normalized.scripts.dev = 'nimi-app dev --platform web';
353
357
  normalized.scripts.sync ||= 'nimi-app sync';
354
358
  if (normalized.scripts.pack === 'nimi-app pack') delete normalized.scripts.pack;
359
+ } else if (buildProfileRef === MANAGED_WEB_BUILD_PROFILE_REF) {
360
+ normalized.scripts.dev = 'nimi-app dev --shell electron';
361
+ normalized.scripts['dev:shell'] = 'nimi-app dev';
362
+ normalized.scripts['dev:renderer'] = `vite --host 127.0.0.1 --port ${new URL(descriptor.rendererOrigin).port} --strictPort`;
363
+ normalized.scripts.sync ||= 'nimi-app sync';
364
+ normalized.scripts.pack = 'nimi-app pack';
365
+ delete normalized.scripts.publish;
355
366
  } else {
356
367
  if (typeof normalized.scripts['build:electron'] !== 'string' || !normalized.scripts['build:electron'].trim()) {
357
368
  throw new Error('package.json build:electron must build the Desktop-supervised Electron host');
@@ -961,14 +972,27 @@ function readBuildProfile(targetDir, sources) {
961
972
  if (Object.keys(targets).length === 0) {
962
973
  throw new Error(`${BUILD_PROFILE_PATH} must declare at least one target`);
963
974
  }
975
+ if (buildProfileRef === MANAGED_WEB_BUILD_PROFILE_REF) {
976
+ const keys = Object.keys(targets);
977
+ if (keys.length !== 1 || keys[0] !== 'desktop-universal') {
978
+ throw new Error(`${BUILD_PROFILE_PATH} managed-web-pnpm-vite must declare only the desktop-universal target`);
979
+ }
980
+ }
964
981
  for (const [targetId, target] of Object.entries(targets)) {
965
- const expected = buildProfileRef === 'web-pnpm' ? (targetId === 'web' ? {} : null) : CURRENT_APP_TARGETS[targetId];
982
+ const expected = buildProfileRef === 'web-pnpm'
983
+ ? (targetId === 'web' ? {} : null)
984
+ : buildProfileRef === MANAGED_WEB_BUILD_PROFILE_REF
985
+ ? (targetId === 'desktop-universal' ? CURRENT_APP_TARGETS['desktop-universal'] : null)
986
+ : (targetId === 'desktop-universal' ? null : CURRENT_APP_TARGETS[targetId]);
966
987
  if (!expected || !target || typeof target !== 'object' || Array.isArray(target)) {
967
988
  throw new Error(`${BUILD_PROFILE_PATH} declares unsupported target: ${targetId}`);
968
989
  }
969
990
  if (buildProfileRef !== 'web-pnpm' && (target.os !== expected.os || target.arch !== expected.arch)) {
970
991
  throw new Error(`${BUILD_PROFILE_PATH} target identity mismatch: ${targetId}`);
971
992
  }
993
+ if (buildProfileRef === MANAGED_WEB_BUILD_PROFILE_REF && target.runtime_entry !== 'payload/index.html') {
994
+ throw new Error(`${BUILD_PROFILE_PATH} desktop-universal runtime_entry must be payload/index.html`);
995
+ }
972
996
  }
973
997
  return {
974
998
  buildProfileRef,
@@ -985,7 +1009,13 @@ function currentTargetId() {
985
1009
  }
986
1010
 
987
1011
  function selectBuildOwner(profile, requestedTarget) {
988
- const target = String(requestedTarget || '').trim() || (profile.buildProfileRef === 'web-pnpm' ? 'web' : currentTargetId());
1012
+ const target = String(requestedTarget || '').trim() || (
1013
+ profile.buildProfileRef === 'web-pnpm'
1014
+ ? 'web'
1015
+ : profile.buildProfileRef === MANAGED_WEB_BUILD_PROFILE_REF
1016
+ ? 'desktop-universal'
1017
+ : currentTargetId()
1018
+ );
989
1019
  const targetProfile = profile.targets[target];
990
1020
  if (Object.keys(profile.targets).length > 0 && (!targetProfile || typeof targetProfile !== 'object' || Array.isArray(targetProfile))) {
991
1021
  throw new Error(`Unsupported App build target: ${target}`);
@@ -1046,6 +1076,9 @@ function assertProjectLifecycleCurrent(targetDir, versions, options = {}) {
1046
1076
  const descriptor = readSubmittedManifest(targetDir, sources);
1047
1077
  const buildProfile = readBuildProfile(targetDir, sources);
1048
1078
  if ((descriptor.platform === 'web') !== (buildProfile.buildProfileRef === 'web-pnpm')) throw new Error('Manifest platform and build owner disagree.');
1079
+ if (buildProfile.buildProfileRef === MANAGED_WEB_BUILD_PROFILE_REF && descriptor.storagePolicy?.kind !== 'nimi-mediated-default') {
1080
+ throw new Error('managed-web Apps must declare storage_policy.kind: nimi-mediated-default (use --carrier native for app-owned-os-storage).');
1081
+ }
1049
1082
  const files = readProjectLifecycleFiles(targetDir, sources);
1050
1083
  const combination = selectDependencyCombination(files.packageJson, versions, options.managed === true);
1051
1084
  assertPackageManifestCurrent(files.packageJson, versions, combination, descriptor.platform);
@@ -1071,6 +1104,9 @@ function buildExistingSubmittedAppSyncPlan(targetDir, versions, sources, managed
1071
1104
  const descriptor = readSubmittedManifest(targetDir, sources);
1072
1105
  const buildProfile = readBuildProfile(targetDir, sources);
1073
1106
  if ((descriptor.platform === 'web') !== (buildProfile.buildProfileRef === 'web-pnpm')) throw new Error('Manifest platform and build owner disagree.');
1107
+ if (buildProfile.buildProfileRef === MANAGED_WEB_BUILD_PROFILE_REF && descriptor.storagePolicy?.kind !== 'nimi-mediated-default') {
1108
+ throw new Error('managed-web Apps must declare storage_policy.kind: nimi-mediated-default (use --carrier native for app-owned-os-storage).');
1109
+ }
1074
1110
  const files = readProjectLifecycleFiles(targetDir, sources);
1075
1111
  const version = files.packageJson.version;
1076
1112
  if (typeof version !== 'string' || !SEMVER_PATTERN.test(version)) {
@@ -13,6 +13,7 @@ function frozenModule(definition) {
13
13
  return Object.freeze({
14
14
  ...definition,
15
15
  carriers: Object.freeze([...(definition.carriers || ['desktop'])]),
16
+ desktopCarriers: Object.freeze([...(definition.desktopCarriers || ['managed-web', 'native'])]),
16
17
  requires: Object.freeze([...(definition.requires || [])]),
17
18
  sourceMappings: Object.freeze([...(definition.sourceMappings || [])]),
18
19
  appAccessItems: Object.freeze([...(definition.appAccessItems || [])]),
@@ -177,6 +178,7 @@ export const APP_SCAFFOLD_MODULE_REGISTRY = Object.freeze({
177
178
  }),
178
179
  'agent-conversation': frozenModule({
179
180
  id: 'agent-conversation',
181
+ desktopCarriers: ['managed-web', 'native'],
180
182
  kind: 'feature',
181
183
  lifecycle: 'admitted',
182
184
  order: 60,
@@ -201,6 +203,7 @@ export const APP_SCAFFOLD_MODULE_REGISTRY = Object.freeze({
201
203
  }),
202
204
  'agent-realtime': frozenModule({
203
205
  id: 'agent-realtime',
206
+ desktopCarriers: ['native'],
204
207
  kind: 'feature',
205
208
  lifecycle: 'admitted',
206
209
  order: 70,
@@ -679,3 +682,28 @@ export function resolveWebAppScaffoldFeatures(selection, resolver = resolveAppSc
679
682
  for (const module of resolution.modules) if (!module.carriers.includes('web')) throw new Error(`Feature ${module.id} has no admitted Web carrier.`);
680
683
  return resolution;
681
684
  }
685
+
686
+ export const APP_SCAFFOLD_MANAGED_WEB_FEATURE_IDS = Object.freeze(
687
+ registryEntries(APP_SCAFFOLD_MODULE_REGISTRY)
688
+ .filter(([, entry]) => entry.kind === 'feature' && entry.lifecycle === 'admitted' && entry.desktopCarriers.includes('managed-web'))
689
+ .map(([id]) => id),
690
+ );
691
+
692
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-scaf-019c
693
+ export function resolveDesktopAppScaffoldFeatures(selection, carrier = 'managed-web', resolver = resolveAppScaffoldFeatures) {
694
+ if (carrier !== 'managed-web' && carrier !== 'native') {
695
+ throw new Error(`Unsupported desktop App carrier: ${String(carrier)}`);
696
+ }
697
+ if (carrier === 'native') {
698
+ return resolver(selection);
699
+ }
700
+ const isAll = selection === 'all' || (Array.isArray(selection) && selection.length === 1 && selection[0] === 'all');
701
+ const selected = isAll ? [...APP_SCAFFOLD_MANAGED_WEB_FEATURE_IDS] : selection;
702
+ const resolution = resolver(selected);
703
+ for (const module of resolution.modules) {
704
+ if (!module.desktopCarriers.includes('managed-web')) {
705
+ throw new Error(`Feature ${module.id} requires the native desktop carrier (OS microphone or custom host mechanics); rerun with --carrier native.`);
706
+ }
707
+ }
708
+ return resolution;
709
+ }
@@ -44,6 +44,31 @@ export function resolveWindowsResourceVersion(appVersion) {
44
44
 
45
45
  export function buildDefaultStarterFiles(identity) {
46
46
  if (identity.platform === 'web') return [...buildWebStarterFiles(identity, { productArea: renderDefaultProductArea(identity), navigation: renderDefaultAppNavigation() }), ...buildGeneratedModuleCompositionFiles(identity)];
47
+ if (identity.carrier === 'managed-web') {
48
+ return [
49
+ {
50
+ path: 'src/main.tsx',
51
+ content: renderDefaultMain(identity),
52
+ mutationClass: 'scaffold-managed glue',
53
+ },
54
+ {
55
+ path: 'src/shell/routes/product-area.tsx',
56
+ content: renderDefaultProductArea(identity),
57
+ mutationClass: 'app-owned product code',
58
+ },
59
+ {
60
+ path: 'src/shell/routes/app-navigation.tsx',
61
+ content: renderDefaultAppNavigation(),
62
+ mutationClass: 'app-owned product code',
63
+ },
64
+ ...buildGeneratedModuleCompositionFiles(identity),
65
+ {
66
+ path: 'vite.config.ts',
67
+ content: MANAGED_WEB_VITE_CONFIG,
68
+ mutationClass: 'scaffold-managed glue',
69
+ },
70
+ ];
71
+ }
47
72
  return [
48
73
  {
49
74
  path: 'src/main.tsx',
@@ -125,6 +150,31 @@ const DEFAULT_VITE_CONFIG = [
125
150
  '',
126
151
  ].join('\n');
127
152
 
153
+ const MANAGED_WEB_VITE_CONFIG = [
154
+ "import { defineConfig } from 'vite';",
155
+ "import react from '@vitejs/plugin-react';",
156
+ "import tailwindcss from '@tailwindcss/vite';",
157
+ '',
158
+ 'export default defineConfig({',
159
+ " base: './',",
160
+ " cacheDir: '.vite',",
161
+ " optimizeDeps: { entries: ['index.html'] },",
162
+ ' // The bootstrap creates the root once; only components participate in Fast Refresh.',
163
+ " plugins: [react({ exclude: [/\\/node_modules\\//, /\\/src\\/main\\.tsx$/] }), tailwindcss()],",
164
+ ' build: {',
165
+ " outDir: 'dist/renderer',",
166
+ ' emptyOutDir: true,',
167
+ ' },',
168
+ ' server: {',
169
+ " watch: { ignored: ['**/.nimi/local/**', '**/dist/**', '**/dist-web/**', '**/dist-mobile/**', '**/android/**/build/**', '**/android/app/src/main/assets/public/**'] },",
170
+ ' },',
171
+ ' resolve: {',
172
+ " dedupe: ['react', 'react-dom', 'react/jsx-runtime', 'react/jsx-dev-runtime'],",
173
+ ' },',
174
+ '});',
175
+ '',
176
+ ].join('\n');
177
+
128
178
  const DEFAULT_ELECTRON_PRELOAD = [
129
179
  "import { contextBridge, ipcRenderer } from 'electron';",
130
180
  "import { installNimiElectronRuntimeBridge } from '@nimiplatform/kit/shell/electron/preload-cjs';",
@@ -142,7 +192,7 @@ const DEFAULT_ELECTRON_PRELOAD_BUNDLER = [
142
192
  "const appRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');",
143
193
  'prepareElectronIcons(appRoot);',
144
194
  '',
145
- 'await build({',
195
+ 'const result = await build({',
146
196
  " entryPoints: [path.join(appRoot, 'src-electron/preload.cts')],",
147
197
  " outfile: path.join(appRoot, 'dist-electron/preload.cjs'),",
148
198
  ' bundle: true,',
@@ -150,8 +200,16 @@ const DEFAULT_ELECTRON_PRELOAD_BUNDLER = [
150
200
  " target: 'node22',",
151
201
  " format: 'cjs',",
152
202
  " external: ['electron'],",
203
+ ' metafile: true,',
153
204
  " logLevel: 'silent',",
154
205
  '});',
206
+ "for (const output of Object.values(result.metafile?.outputs || {})) {",
207
+ ' for (const imp of output.imports || []) {',
208
+ " if (imp.external && imp.path.startsWith('@nimiplatform/')) {",
209
+ ' throw new Error(`Electron preload bundle must not retain external Nimi import: ${imp.path}`);',
210
+ ' }',
211
+ ' }',
212
+ '}',
155
213
  '',
156
214
  ].join('\n');
157
215
 
@@ -168,19 +226,17 @@ const DEFAULT_ELECTRON_PRODUCTION_CLEANER = [
168
226
  function renderDefaultElectronProductionPackager(identity) {
169
227
  return [
170
228
  "import { spawn } from 'node:child_process';",
171
- "import { copyFile, cp, mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';",
229
+ "import { copyFile, cp, mkdir, mkdtemp, open, readdir, readFile, realpath, rm, writeFile } from 'node:fs/promises';",
172
230
  "import { createRequire } from 'node:module';",
173
231
  "import path from 'node:path';",
174
232
  "import { fileURLToPath } from 'node:url';",
175
233
  "import { packager } from '@electron/packager';",
176
234
  "import { prepareElectronIcons } from './app-icons.mjs';",
177
235
  "import { build } from 'esbuild';",
178
- "import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';",
179
236
  '',
180
237
  `const APP_EXECUTABLE_NAME = ${JSON.stringify(identity.cargoPackageName)};`,
181
238
  `const APP_PRODUCT_NAME = ${JSON.stringify(identity.appTitle)};`,
182
239
  resolveWindowsResourceVersion.toString(),
183
- rebaseLocalPackagePaths.toString(),
184
240
  "const MACOS_BUILD = process.platform === 'darwin' && process.arch === 'arm64';",
185
241
  "const NATIVE_PLATFORM = MACOS_BUILD ? 'darwin' : 'win32';",
186
242
  "const NATIVE_ARCH = MACOS_BUILD ? 'arm64' : 'x64';",
@@ -224,54 +280,66 @@ function renderDefaultElectronProductionPackager(identity) {
224
280
  '',
225
281
  'try {',
226
282
  ' const icons = prepareElectronIcons(appRoot, { required: true });',
283
+ " const mainBundlePath = path.join(appRoot, 'dist-electron/main.js');",
227
284
  ' await build({',
228
285
  " entryPoints: [path.join(appRoot, 'src-electron/main.ts')],",
229
- " outfile: path.join(appRoot, 'dist-electron/main.js'),",
286
+ ' outfile: mainBundlePath,',
230
287
  ' bundle: true,',
231
288
  " platform: 'node',",
232
289
  " target: 'node22',",
233
290
  " format: 'esm',",
234
- " packages: 'external',",
235
- " external: ['electron'],",
291
+ " external: ['electron', 'original-fs', 'sharp', '@nimiplatform/kit-protected-local-win32-x64', '@nimiplatform/kit-protected-local-darwin-arm64'],",
292
+ ' banner: {',
293
+ ' js: "import { createRequire as __nimiCreateRequire } from \'node:module\'; const require = __nimiCreateRequire(import.meta.url);",',
294
+ ' },',
236
295
  " define: { __NIMI_ELECTRON_PRODUCTION__: 'true' },",
237
296
  " logLevel: 'silent',",
238
297
  ' });',
298
+ ' await verifyNodeSyntax(mainBundlePath);',
239
299
  '',
240
300
  " await realpath(path.join(appRoot, 'dist', 'index.html'));",
241
301
  " await realpath(path.join(appRoot, 'dist-electron', 'preload.cjs'));",
302
+ ' const preloadCheck = await build({',
303
+ " entryPoints: [path.join(appRoot, 'src-electron/preload.cts')],",
304
+ " outfile: path.join(stagingRoot, 'preload-check.cjs'),",
305
+ ' bundle: true,',
306
+ " platform: 'node',",
307
+ " target: 'node22',",
308
+ " format: 'cjs',",
309
+ " external: ['electron'],",
310
+ ' metafile: true,',
311
+ ' write: false,',
312
+ " logLevel: 'silent',",
313
+ ' });',
314
+ ' for (const output of Object.values(preloadCheck.metafile?.outputs || {})) {',
315
+ ' for (const imp of output.imports || []) {',
316
+ " if (imp.external && imp.path.startsWith('@nimiplatform/')) {",
317
+ ' throw new Error(`Electron preload bundle must not retain external Nimi import: ${imp.path}`);',
318
+ ' }',
319
+ ' }',
320
+ ' }',
242
321
  '',
243
322
  ' await mkdir(path.join(productionSourceRoot, \'dist-electron\'), { recursive: true });',
244
- " await copyFile(path.join(appRoot, 'package.json'), path.join(productionSourceRoot, 'package.json'));",
245
- " const dependencyLock = parseYaml(await readFile(path.join(appRoot, 'pnpm-lock.yaml'), 'utf8'));",
246
- " await writeFile(path.join(productionSourceRoot, 'pnpm-lock.yaml'), stringifyYaml(rebaseLocalPackagePaths(dependencyLock, appRoot, productionSourceRoot)));",
247
- ' try {',
248
- " const workspace = parseYaml(await readFile(path.join(appRoot, 'pnpm-workspace.yaml'), 'utf8'));",
249
- " await writeFile(path.join(productionSourceRoot, 'pnpm-workspace.yaml'), stringifyYaml({ ...rebaseLocalPackagePaths(workspace, appRoot, productionSourceRoot), packages: ['.'] }));",
250
- " } catch (cause) {",
251
- " if (cause.code !== 'ENOENT') throw cause;",
252
- ' // Staging sits inside the project: keep pnpm from adopting an enclosing workspace.',
253
- " await writeFile(path.join(productionSourceRoot, 'pnpm-workspace.yaml'), stringifyYaml({ packages: ['.'] }));",
254
- ' }',
323
+ ' const productionManifest = {',
324
+ ' name: appPackage.name,',
325
+ ' version: APP_VERSION,',
326
+ " type: 'module',",
327
+ " main: 'dist-electron/main.js',",
328
+ ' ...(appPackage.license ? { license: appPackage.license } : {}),',
329
+ ' ...(appPackage.author ? { author: appPackage.author } : {}),',
330
+ ' };',
331
+ " await writeFile(path.join(productionSourceRoot, 'package.json'), `${JSON.stringify(productionManifest, null, 2)}\\n`);",
255
332
  " await cp(path.join(appRoot, 'dist'), path.join(productionSourceRoot, 'dist'), { recursive: true, force: false });",
256
- " await copyFile(path.join(appRoot, 'dist-electron', 'main.js'), path.join(productionSourceRoot, 'dist-electron', 'main.js'));",
333
+ " await copyFile(mainBundlePath, path.join(productionSourceRoot, 'dist-electron', 'main.js'));",
257
334
  " await copyFile(path.join(appRoot, 'dist-electron', 'preload.cjs'), path.join(productionSourceRoot, 'dist-electron', 'preload.cjs'));",
258
335
  " await copyFile(icons.png, path.join(productionSourceRoot, 'dist-electron', 'app-icon.png'));",
259
336
  " await copyFile(icons.macPng, path.join(productionSourceRoot, 'dist-electron', 'app-icon-macos.png'));",
260
337
  " await copyFile(icons.ico, path.join(productionSourceRoot, 'dist-electron', 'app-icon.ico'));",
261
- ' await installProductionDependencies(productionSourceRoot);',
262
- '',
263
- " const productionManifestPath = path.join(productionSourceRoot, 'package.json');",
264
- " const productionManifest = JSON.parse(await readFile(productionManifestPath, 'utf8'));",
265
- ' delete productionManifest.devDependencies;',
266
- " await writeFile(productionManifestPath, `${JSON.stringify(productionManifest, null, 2)}\\n`);",
267
- " await rm(path.join(productionSourceRoot, 'pnpm-lock.yaml'));",
268
- " await rm(path.join(productionSourceRoot, 'pnpm-workspace.yaml'), { force: true });",
269
338
  '',
270
339
  " const installedNativePackage = path.join(productionSourceRoot, 'node_modules', ...NATIVE_BINDING_PACKAGE.split('/'));",
271
340
  ' const nativeDestination = MACOS_BUILD',
272
341
  " ? path.join(stagingRoot, 'nimi-native', 'protected-local')",
273
342
  ' : installedNativePackage;',
274
- ' await rm(installedNativePackage, { recursive: true, force: true });',
275
343
  ' await mkdir(path.dirname(nativeDestination), { recursive: true });',
276
344
  ' await cp(nativePackageRoot, nativeDestination, { recursive: true, dereference: true, force: false });',
277
345
  ' await mkdir(packagerTempRoot, { recursive: true });',
@@ -329,6 +397,10 @@ function renderDefaultElectronProductionPackager(identity) {
329
397
  ' await realpath(MACOS_BUILD',
330
398
  " ? path.join(expectedPackageRoot, `${APP_EXECUTABLE_NAME}.app`, 'Contents', 'MacOS', APP_EXECUTABLE_NAME)",
331
399
  ' : path.join(expectedPackageRoot, `${APP_EXECUTABLE_NAME}.exe`));',
400
+ ' const resourcesRoot = MACOS_BUILD',
401
+ " ? path.join(expectedPackageRoot, `${APP_EXECUTABLE_NAME}.app`, 'Contents', 'Resources')",
402
+ " : path.join(expectedPackageRoot, 'resources');",
403
+ ' await assertCleanAppBundle(resourcesRoot);',
332
404
  ' packageCompleted = true;',
333
405
  ' process.stdout.write(`[nimi-app] Electron production package: ${expectedPackageRoot}\\n`);',
334
406
  '} finally {',
@@ -337,27 +409,82 @@ function renderDefaultElectronProductionPackager(identity) {
337
409
  ' await Promise.all(cleanupTasks);',
338
410
  '}',
339
411
  '',
340
- 'async function installProductionDependencies(projectRoot) {',
341
- " const command = 'pnpm install --prod --frozen-lockfile --ignore-scripts --node-linker=hoisted';",
342
- " const commandShell = MACOS_BUILD ? 'pnpm' : process.env.ComSpec || 'cmd.exe';",
343
- " const commandArguments = MACOS_BUILD ? ['install', '--prod', '--frozen-lockfile', '--ignore-scripts', '--node-linker=hoisted'] : ['/d', '/s', '/c', command];",
412
+ 'async function verifyNodeSyntax(scriptPath) {',
344
413
  ' await new Promise((resolve, reject) => {',
345
- ' const child = spawn(commandShell, commandArguments, {',
346
- ' cwd: projectRoot,',
347
- " stdio: 'inherit',",
348
- ' windowsHide: true,',
349
- ' });',
414
+ " const child = spawn(process.execPath, ['--check', scriptPath], { stdio: 'inherit', windowsHide: true });",
350
415
  " child.once('error', reject);",
351
416
  " child.once('exit', (code, signal) => {",
352
- ' if (code === 0) {',
353
- ' resolve();',
354
- ' return;',
355
- ' }',
356
- " reject(new Error(`pnpm production dependency staging failed (${signal || `exit ${String(code)}`}).`));",
417
+ ' if (code === 0) { resolve(); return; }',
418
+ ' reject(new Error(`Node syntax check failed for ${scriptPath} (${signal || `exit ${String(code)}`}).`));',
357
419
  ' });',
358
420
  ' });',
359
421
  '}',
360
422
  '',
423
+ 'async function listAsarPaths(asarPath) {',
424
+ " const handle = await open(asarPath, 'r');",
425
+ ' try {',
426
+ ' const headerPrefix = Buffer.alloc(16);',
427
+ ' const prefixRead = await handle.read(headerPrefix, 0, 16, 0);',
428
+ " if (prefixRead.bytesRead !== 16) throw new Error('Invalid app.asar header.');",
429
+ ' const jsonLength = headerPrefix.readUInt32LE(12);',
430
+ " if (jsonLength === 0 || jsonLength > 64 * 1024 * 1024) throw new Error('Invalid app.asar header length.');",
431
+ ' const jsonBuffer = Buffer.alloc(jsonLength);',
432
+ ' const jsonRead = await handle.read(jsonBuffer, 0, jsonLength, 16);',
433
+ " if (jsonRead.bytesRead !== jsonLength) throw new Error('Truncated app.asar header.');",
434
+ " const root = JSON.parse(jsonBuffer.toString('utf8'));",
435
+ ' const entries = [];',
436
+ ' const walk = (node, prefix) => {',
437
+ ' for (const [name, child] of Object.entries(node?.files || {})) {',
438
+ ' const next = prefix ? `${prefix}/${name}` : name;',
439
+ " if (child && typeof child === 'object' && child.files) walk(child, next);",
440
+ ' else entries.push(next);',
441
+ ' }',
442
+ ' };',
443
+ " walk(root, '');",
444
+ ' return entries;',
445
+ ' } finally {',
446
+ ' await handle.close();',
447
+ ' }',
448
+ '}',
449
+ '',
450
+ "async function listTreePaths(rootDir, prefix = '') {",
451
+ ' let items;',
452
+ ' try {',
453
+ ' items = await readdir(rootDir, { withFileTypes: true });',
454
+ ' } catch (error) {',
455
+ " if (error?.code === 'ENOENT') return [];",
456
+ ' throw error;',
457
+ ' }',
458
+ ' const paths = [];',
459
+ ' for (const item of items) {',
460
+ ' const rel = prefix ? `${prefix}/${item.name}` : item.name;',
461
+ ' if (item.isDirectory()) paths.push(...(await listTreePaths(path.join(rootDir, item.name), rel)));',
462
+ ' else paths.push(rel);',
463
+ ' }',
464
+ ' return paths;',
465
+ '}',
466
+ '',
467
+ 'async function assertCleanAppBundle(resourcesRoot) {',
468
+ " const asarPaths = await listAsarPaths(path.join(resourcesRoot, 'app.asar'));",
469
+ " const unpackedPaths = await listTreePaths(path.join(resourcesRoot, 'app.asar.unpacked'));",
470
+ ' const allPaths = [...asarPaths, ...unpackedPaths];',
471
+ ' const forbiddenPatterns = [',
472
+ ' /(?:^|\\/)@electron-internal(?:\\/|$)/,',
473
+ ' /(?:^|\\/)node_modules\\/typescript(?:\\/|$)/,',
474
+ ' /(?:^|\\/)@img\\/sharp-/,',
475
+ ' ...(MACOS_BUILD',
476
+ ' ? [/\\.dll$/i, /(?:^|\\/)kit-protected-local-win32-x64(?:\\/|$)/, /win32-x64.*\\.node$/i, /linux-.*\\.node$/i]',
477
+ ' : [/\\.dylib$/i, /(?:^|\\/)kit-protected-local-darwin-arm64(?:\\/|$)/, /darwin-arm64.*\\.node$/i, /linux-.*\\.node$/i]),',
478
+ ' ];',
479
+ ' for (const entryPath of allPaths) {',
480
+ ' for (const pattern of forbiddenPatterns) {',
481
+ ' if (pattern.test(entryPath)) {',
482
+ ' throw new Error(`Unexpected contaminated payload entry in Electron bundle: ${entryPath}`);',
483
+ ' }',
484
+ ' }',
485
+ ' }',
486
+ '}',
487
+ '',
361
488
  'async function findPackageRoot(entry, expectedName) {',
362
489
  ' let current = path.dirname(await realpath(entry));',
363
490
  ' for (;;) {',