@nimiplatform/app-tools 0.16.0-rc.10 → 0.16.0-rc.13

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.
package/lib/app-pack.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { assertDesktopHostSupport } from './app-host-support.mjs';
2
+ import { validateManifestDesktop } from './desktop-window.mjs';
2
3
  import { isAppId } from './app-identifiers.mjs';
3
4
  // @nimi-authority: rule.nimi.platform.app-ecosystem.p-scaf-009b
4
5
  // @nimi-authority: rule.nimi.platform.app-ecosystem.p-napp-014a
@@ -25,7 +26,8 @@ import {
25
26
  } from 'node:fs';
26
27
  import path from 'node:path';
27
28
  import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
28
- import { APP_INFO_DECLARATION_FIELDS, APP_INFO_MAX_BYTES, readAppInfo, validateAppInfo } from './app-info.mjs';
29
+ import { APP_INFO_DECLARATION_FIELDS, APP_INFO_MAX_BYTES, readAppInfo, readAppStorefront, validateAppInfo } from './app-info.mjs';
30
+ import { STOREFRONT_ARCHIVE_MAX_BYTES } from './storefront-media.mjs';
29
31
  import { observeWindowsExecutableFacts } from './windows-powershell.mjs';
30
32
  import { SYMBOLIC_LINK_MODE, validatePayloadLinks } from './payload-links.mjs';
31
33
  import { observeMacOSExecutableFacts } from './macos-native.mjs';
@@ -34,14 +36,103 @@ const PACKAGE_FORMAT = 'nimi.app-package/v2';
34
36
  const TARGET_METADATA_FORMAT = 'nimi.app-target-candidate/v1';
35
37
  const AGGREGATE_FORMAT = 'nimi.app-release-candidate/v1';
36
38
  const BUILD_PROFILE_PATH = '.nimi/config/build-profile.yaml';
39
+ const MANAGED_WEB_BUILD_PROFILE_REF = 'managed-web-pnpm-vite';
40
+ const MANAGED_WEB_EXECUTION_PROFILE_REF = 'nimi-managed-web-v1';
41
+ const MANAGED_WEB_RUNTIME_ENTRY = 'payload/index.html';
42
+ const MANAGED_WEB_MAX_RELEASE_BYTES = 64 * 1024 * 1024;
43
+ const MANAGED_WEB_MAX_RELEASE_ENTRIES = 10_000;
44
+ const MANAGED_WEB_MAX_DIRECTORY_DEPTH = 64;
37
45
  const ELECTRON_BUILD_PROFILE_REF = 'electron-packager-pnpm-vite';
38
46
  const APP_OWNED_ELECTRON_BUILD_PROFILE_REF = 'electron-pnpm';
39
47
  const OUTPUT_DIR = 'dist/nimi-app';
40
- 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;
48
+ 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;
41
49
  const TARGETS = Object.freeze({
42
50
  'windows-x86_64': Object.freeze({ os: 'windows', arch: 'x86_64' }),
43
51
  'macos-aarch64': Object.freeze({ os: 'macos', arch: 'arm64' }),
52
+ 'desktop-universal': Object.freeze({ os: 'any', arch: 'any' }),
44
53
  });
54
+ const WINDOWS_RESERVED_BASES = new Set(['CON', 'PRN', 'AUX', 'NUL', 'CLOCK$', 'CONIN$', 'CONOUT$']);
55
+
56
+ function validWindowsSegment(segment) {
57
+ if (/[<>:"|?*]/u.test(segment) || segment.endsWith('.') || segment.endsWith(' ')) {
58
+ return false;
59
+ }
60
+ const base = segment.split('.', 1)[0].replace(/ +$/u, '').toUpperCase();
61
+ if (WINDOWS_RESERVED_BASES.has(base)) return false;
62
+ if (/^(?:COM|LPT)(?:[1-9]|¹|²|³)$/u.test(base)) return false;
63
+ return true;
64
+ }
65
+
66
+ function unicodeCaseFold(input) {
67
+ let out = '';
68
+ for (const ch of input.normalize('NFC')) {
69
+ const cp = ch.codePointAt(0);
70
+ if (cp === 0x0131) out += '\u0131';
71
+ else if (cp === 0x1e9e) out += 'ss';
72
+ else if (cp >= 0x13f8 && cp <= 0x13fd) out += String.fromCodePoint(cp - 8);
73
+ else if (cp >= 0xab70 && cp <= 0xabbf) out += String.fromCodePoint(cp - 0x97d0);
74
+ else out += ch.toUpperCase().toLowerCase();
75
+ }
76
+ return out;
77
+ }
78
+
79
+ function targetPathCollisionKey(name, targetOS) {
80
+ const normalized = name.normalize('NFC');
81
+ if (targetOS === 'windows' || targetOS === 'any') {
82
+ return unicodeCaseFold(normalized);
83
+ }
84
+ return normalized;
85
+ }
86
+
87
+ function validateCrossPlatformArchiveEntries(entries, targetOS) {
88
+ const roles = new Map();
89
+ let fileCount = 0;
90
+ for (const entry of entries) {
91
+ const name = entry.name;
92
+ const segments = name.split('/');
93
+ if (targetOS === 'any' && segments.length - 1 > MANAGED_WEB_MAX_DIRECTORY_DEPTH) {
94
+ throw new Error(`Managed-web directory depth exceeds ${MANAGED_WEB_MAX_DIRECTORY_DEPTH}: ${name}`);
95
+ }
96
+ for (const segment of segments) {
97
+ for (const ch of segment) {
98
+ const code = ch.codePointAt(0);
99
+ if (code < 0x20 || code === 0x7f) {
100
+ throw new Error(`Archive entry path contains control character: ${name}`);
101
+ }
102
+ }
103
+ if ((targetOS === 'windows' || targetOS === 'any') && !validWindowsSegment(segment)) {
104
+ throw new Error(`Archive entry path uses invalid Windows segment: ${name}`);
105
+ }
106
+ }
107
+ for (let index = 0; index < segments.length; index += 1) {
108
+ const prefix = segments.slice(0, index + 1).join('/');
109
+ const key = targetPathCollisionKey(prefix, targetOS);
110
+ const isFile = index === segments.length - 1;
111
+ const previous = roles.get(key);
112
+ if (previous) {
113
+ if (previous.spelling !== prefix || previous.file || isFile) {
114
+ throw new Error(`Archive entry path collision on ${targetOS}: ${previous.spelling} and ${prefix}`);
115
+ }
116
+ } else {
117
+ roles.set(key, { spelling: prefix, file: isFile });
118
+ }
119
+ }
120
+ fileCount++;
121
+ if (targetOS === 'any' && roles.size - fileCount > MANAGED_WEB_MAX_RELEASE_ENTRIES) {
122
+ throw new Error(`Managed-web package exceeds ${MANAGED_WEB_MAX_RELEASE_ENTRIES} directories`);
123
+ }
124
+ }
125
+ }
126
+
127
+ function pathsOverlapOrEqual(left, right) {
128
+ const a = path.resolve(left);
129
+ const b = path.resolve(right);
130
+ const cmpA = process.platform === 'win32' ? a.toLowerCase() : a;
131
+ const cmpB = process.platform === 'win32' ? b.toLowerCase() : b;
132
+ return cmpA === cmpB
133
+ || cmpA.startsWith(`${cmpB}${path.sep}`)
134
+ || cmpB.startsWith(`${cmpA}${path.sep}`);
135
+ }
45
136
 
46
137
  function compareText(left, right) {
47
138
  return left < right ? -1 : left > right ? 1 : 0;
@@ -274,7 +365,16 @@ export function readNimiAppArchive(bytes) {
274
365
  const commentLength = archive.readUInt16LE(cursor + 32);
275
366
  const localOffset = archive.readUInt32LE(cursor + 42);
276
367
  const unixMode = archive.readUInt32LE(cursor + 38) >>> 16;
277
- const mode = (unixMode & 0o170000) === 0o120000 ? unixMode : unixMode & 0o777;
368
+ const fileType = unixMode & 0o170000;
369
+ const specialBits = unixMode & 0o7000;
370
+ let mode;
371
+ if (unixMode === SYMBOLIC_LINK_MODE) {
372
+ mode = SYMBOLIC_LINK_MODE;
373
+ } else if ((fileType === 0o100000 || fileType === 0) && specialBits === 0) {
374
+ mode = unixMode & 0o777;
375
+ } else {
376
+ throw new Error('Unsupported nimiapp ZIP entry mode');
377
+ }
278
378
  if (method !== 0 || extraLength !== 0 || commentLength !== 0) throw new Error('Unsupported nimiapp ZIP entry encoding');
279
379
  if (mode !== 0o644 && mode !== 0o755 && mode !== SYMBOLIC_LINK_MODE) throw new Error('Unsupported nimiapp ZIP entry mode');
280
380
  const name = zipEntryName(archive.subarray(cursor + 46, cursor + 46 + nameLength).toString('utf8'));
@@ -300,7 +400,7 @@ export function readNimiAppArchive(bytes) {
300
400
  function readNativePackProfile(targetDir) {
301
401
  const profile = readYaml(path.join(targetDir, BUILD_PROFILE_PATH), BUILD_PROFILE_PATH);
302
402
  assertDesktopHostSupport(profile.build_profile_ref);
303
- if (![ELECTRON_BUILD_PROFILE_REF, APP_OWNED_ELECTRON_BUILD_PROFILE_REF].includes(profile.build_profile_ref)) {
403
+ if (![MANAGED_WEB_BUILD_PROFILE_REF, ELECTRON_BUILD_PROFILE_REF, APP_OWNED_ELECTRON_BUILD_PROFILE_REF].includes(profile.build_profile_ref)) {
304
404
  throw new Error(`${BUILD_PROFILE_PATH} build_profile_ref is unsupported: ${String(profile.build_profile_ref)}`);
305
405
  }
306
406
  return profile;
@@ -310,6 +410,13 @@ function readPackInputs(targetDir, targetId) {
310
410
  const buildProfile = readNativePackProfile(targetDir);
311
411
  const target = TARGETS[targetId];
312
412
  if (!target) throw new Error(`Unsupported App package target: ${targetId}`);
413
+ const isManagedWeb = buildProfile.build_profile_ref === MANAGED_WEB_BUILD_PROFILE_REF;
414
+ if (isManagedWeb && targetId !== 'desktop-universal') {
415
+ throw new Error(`managed-web-pnpm-vite only supports target desktop-universal, got: ${targetId}`);
416
+ }
417
+ if (!isManagedWeb && targetId === 'desktop-universal') {
418
+ throw new Error(`Target desktop-universal requires build_profile_ref ${MANAGED_WEB_BUILD_PROFILE_REF}`);
419
+ }
313
420
  const packageJson = readJson(path.join(targetDir, 'package.json'), 'package.json');
314
421
  const licensePath = path.join(targetDir, 'LICENSE');
315
422
  if (!existsSync(licensePath)) throw new Error('App package LICENSE is missing');
@@ -319,7 +426,11 @@ function readPackInputs(targetDir, targetId) {
319
426
  }
320
427
  const manifestPath = path.join(targetDir, 'nimi.app.yaml');
321
428
  const manifest = readYaml(manifestPath, 'nimi.app.yaml');
429
+ const desktop = validateManifestDesktop(manifest.desktop, 'nimi.app.yaml desktop');
322
430
  const appInfo = readAppInfo(targetDir, targetId);
431
+ if (isManagedWeb && appInfo.storage_policy?.kind !== 'nimi-mediated-default') {
432
+ throw new Error('managed-web packages require storage_policy.kind: nimi-mediated-default');
433
+ }
323
434
  const appId = String(manifest.app_id || '');
324
435
  const version = String(packageJson.version || '');
325
436
  if (!isAppId(appId)) throw new Error('nimi.app.yaml app_id must be canonical and dotted');
@@ -330,15 +441,22 @@ function readPackInputs(targetDir, targetId) {
330
441
  if (!configured || typeof configured !== 'object' || Array.isArray(configured)) throw new Error(`Build profile does not declare target: ${targetId}`);
331
442
  if (configured.os !== target.os || configured.arch !== target.arch) throw new Error(`Build profile target identity mismatch: ${targetId}`);
332
443
  const payload = resolveInside(targetDir, configured.payload_path, `targets.${targetId}.payload_path`);
444
+ const outputDir = path.join(targetDir, OUTPUT_DIR);
445
+ if (pathsOverlapOrEqual(payload.resolved, outputDir)) {
446
+ throw new Error(`Pack payload_path (${payload.normalized}) must not overlap ${OUTPUT_DIR}; emit build output to a sibling directory such as dist/renderer`);
447
+ }
333
448
  if (!existsSync(payload.resolved)) throw new Error(`Built target payload is missing: ${payload.normalized}`);
334
449
  const runtimeEntry = canonicalRelative(configured.runtime_entry, `targets.${targetId}.runtime_entry`);
335
450
  if (!runtimeEntry.startsWith('payload/')) throw new Error('runtime_entry must resolve inside the packaged payload');
451
+ if (isManagedWeb && runtimeEntry !== MANAGED_WEB_RUNTIME_ENTRY) {
452
+ throw new Error(`managed-web runtime_entry must be ${MANAGED_WEB_RUNTIME_ENTRY}`);
453
+ }
336
454
  const payloadStat = lstatSync(payload.resolved);
337
455
  const runtimeRelative = runtimeEntry.slice('payload/'.length);
338
456
  const runtimeHostPath = payloadStat.isFile()
339
457
  ? payload.resolved
340
458
  : resolveInside(payload.resolved, runtimeRelative, `targets.${targetId}.runtime_entry`).resolved;
341
- return { target, targetId, targetDir, packageJson, licensePath, manifestPath, appInfo, appId, version, payloadPath: payload.resolved, runtimeEntry, runtimeHostPath };
459
+ return { buildProfile, desktop, target, targetId, targetDir, packageJson, licensePath, manifestPath, appInfo, appId, version, payloadPath: payload.resolved, runtimeEntry, runtimeHostPath };
342
460
  }
343
461
 
344
462
  export function classifyWindowsNativeTrustObservation(observation) {
@@ -382,6 +500,17 @@ function observeProductionWindowsFacts(input, archivedRuntimeEntryBytes) {
382
500
  }
383
501
 
384
502
  function resolveTargetFacts(input, production, archivedRuntimeEntryBytes) {
503
+ if (input.target.os === 'any') {
504
+ return {
505
+ nativeTrust: {
506
+ posture: 'nimi-managed-carrier',
507
+ certificate_subject: null,
508
+ },
509
+ executionProfile: {
510
+ launch_mode: MANAGED_WEB_EXECUTION_PROFILE_REF,
511
+ },
512
+ };
513
+ }
385
514
  if (!production) {
386
515
  return {
387
516
  nativeTrust: { posture: 'development-unsigned' },
@@ -400,6 +529,25 @@ function validateNativeExecutionFacts(nativeTrust, executionProfile, label, os)
400
529
  if (!nativeTrust || typeof nativeTrust !== 'object' || Array.isArray(nativeTrust)) {
401
530
  throw new Error(`${label} native_trust must be an object`);
402
531
  }
532
+ if (os === 'any') {
533
+ if (
534
+ !executionProfile
535
+ || typeof executionProfile !== 'object'
536
+ || Array.isArray(executionProfile)
537
+ || Object.keys(executionProfile).join(',') !== 'launch_mode'
538
+ || executionProfile.launch_mode !== MANAGED_WEB_EXECUTION_PROFILE_REF
539
+ ) {
540
+ throw new Error(`${label} managed-web execution_profile must use ${MANAGED_WEB_EXECUTION_PROFILE_REF}`);
541
+ }
542
+ if (
543
+ Object.keys(nativeTrust).sort().join(',') !== 'certificate_subject,posture'
544
+ || nativeTrust.posture !== 'nimi-managed-carrier'
545
+ || nativeTrust.certificate_subject !== null
546
+ ) {
547
+ throw new Error(`${label} managed-web native_trust posture is inconsistent`);
548
+ }
549
+ return;
550
+ }
403
551
  if (nativeTrust.posture === 'development-unsigned') {
404
552
  if (executionProfile !== null || Object.keys(nativeTrust).length !== 1) {
405
553
  throw new Error(`${label} development native/execution posture is inconsistent`);
@@ -465,10 +613,14 @@ export function packAppTarget(cwd, options = {}) {
465
613
  const targetId = String(options.target || '').trim();
466
614
  if (!targetId) throw new Error('nimi-app pack requires --target');
467
615
  const input = readPackInputs(targetDir, targetId);
616
+ const isManagedWeb = input.target.os === 'any';
468
617
  const payloadEntries = collectPayload(input.payloadPath, input.target.os).map((entry) => {
469
618
  const name = `payload/${entry.relative.replaceAll('\\', '/')}`;
470
619
  if (name === input.runtimeEntry && entry.mode === SYMBOLIC_LINK_MODE) throw new Error('Runtime entry must be a direct regular file');
471
- return { name, bytes: entry.bytes, mode: name === input.runtimeEntry ? 0o755 : entry.mode };
620
+ const mode = isManagedWeb
621
+ ? 0o644
622
+ : name === input.runtimeEntry ? 0o755 : entry.mode;
623
+ return { name, bytes: entry.bytes, mode };
472
624
  });
473
625
  validatePayloadLinks(new Map(payloadEntries.map((entry) => [entry.name, entry])), input.target.os);
474
626
  const runtimeEntry = payloadEntries.find((entry) => entry.name === input.runtimeEntry);
@@ -489,14 +641,28 @@ export function packAppTarget(cwd, options = {}) {
489
641
  if (infoBytes.length > APP_INFO_MAX_BYTES) throw new Error('App info exceeds 1 MiB');
490
642
  // An undeclared safety_profile stays absent from the declaration copy; it is
491
643
  // never serialized as an empty or default declaration.
492
- const declaration = Object.fromEntries(APP_INFO_DECLARATION_FIELDS.filter((key) => input.appInfo[key] !== undefined).map((key) => [key, input.appInfo[key]]));
493
- const archive = writeNimiAppArchive([
644
+ const declaration = {
645
+ ...Object.fromEntries(APP_INFO_DECLARATION_FIELDS.filter((key) => input.appInfo[key] !== undefined).map((key) => [key, input.appInfo[key]])),
646
+ ...(input.desktop !== undefined ? { desktop: input.desktop } : {}),
647
+ };
648
+ const archiveEntries = [
494
649
  { name: 'LICENSE', bytes: readFileSync(input.licensePath), mode: 0o644 },
495
- { name: 'manifest.json', bytes: canonicalJson(packageManifest), mode: 0o644 },
496
- { name: 'nimi.app.yaml', bytes: stringifyYaml(declaration), mode: 0o644 },
650
+ { name: 'manifest.json', bytes: Buffer.from(canonicalJson(packageManifest)), mode: 0o644 },
651
+ { name: 'nimi.app.yaml', bytes: Buffer.from(stringifyYaml(declaration)), mode: 0o644 },
497
652
  { name: 'app-info.json', bytes: infoBytes, mode: 0o644 },
498
653
  ...payloadEntries,
499
- ]);
654
+ ];
655
+ validateCrossPlatformArchiveEntries(archiveEntries, input.target.os);
656
+ if (isManagedWeb) {
657
+ if (archiveEntries.length > MANAGED_WEB_MAX_RELEASE_ENTRIES) {
658
+ throw new Error(`managed-web package exceeds ${MANAGED_WEB_MAX_RELEASE_ENTRIES} entries (${archiveEntries.length})`);
659
+ }
660
+ const totalUncompressedBytes = archiveEntries.reduce((sum, entry) => sum + entry.bytes.length, 0);
661
+ if (totalUncompressedBytes > MANAGED_WEB_MAX_RELEASE_BYTES) {
662
+ throw new Error(`managed-web package exceeds ${MANAGED_WEB_MAX_RELEASE_BYTES} bytes uncompressed (${totalUncompressedBytes})`);
663
+ }
664
+ }
665
+ const archive = writeNimiAppArchive(archiveEntries);
500
666
  const sha256 = hashAppArchive(archive);
501
667
  const outputDir = path.join(targetDir, OUTPUT_DIR);
502
668
  mkdirSync(outputDir, { recursive: true });
@@ -527,7 +693,8 @@ export function packAppTarget(cwd, options = {}) {
527
693
 
528
694
  export function aggregateAppTargetCandidates(cwd, options = {}) {
529
695
  const targetDir = path.resolve(cwd, String(options.dir || '').trim() || '.');
530
- readNativePackProfile(targetDir);
696
+ const buildProfile = readNativePackProfile(targetDir);
697
+ const isManagedWebProfile = buildProfile.build_profile_ref === MANAGED_WEB_BUILD_PROFILE_REF;
531
698
  const outputDir = path.join(targetDir, OUTPUT_DIR);
532
699
  if (!existsSync(outputDir)) throw new Error('No target metadata exists to aggregate');
533
700
  const files = readdirSync(outputDir).filter((name) => name.endsWith('.target.json')).sort();
@@ -536,11 +703,18 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
536
703
  const appId = targets[0].app_id;
537
704
  const version = targets[0].version;
538
705
  const seen = new Set();
706
+ const parsedInfos = [];
539
707
  for (const target of targets) {
540
708
  const metadataLabel = `${target.target_id || 'unknown'} target metadata`;
541
709
  if (target.format !== TARGET_METADATA_FORMAT || target.app_id !== appId || target.version !== version) throw new Error('Target metadata cannot be aggregated across App releases');
542
710
  if (seen.has(target.target_id)) throw new Error(`Duplicate target metadata: ${target.target_id}`);
543
711
  seen.add(target.target_id);
712
+ if (isManagedWebProfile && target.target_id !== 'desktop-universal') {
713
+ throw new Error(`managed-web-pnpm-vite cannot aggregate non-universal target: ${target.target_id}`);
714
+ }
715
+ if (!isManagedWebProfile && target.target_id === 'desktop-universal') {
716
+ throw new Error(`Native build profile cannot aggregate desktop-universal target`);
717
+ }
544
718
  const expectedTarget = TARGETS[target.target_id];
545
719
  if (!expectedTarget || target.os !== expectedTarget.os || target.arch !== expectedTarget.arch) {
546
720
  throw new Error(`Target metadata identity is invalid: ${target.target_id}`);
@@ -552,6 +726,9 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
552
726
  }
553
727
  const runtimeEntry = canonicalRelative(target.runtime_entry, `${metadataLabel}.runtime_entry`);
554
728
  if (!runtimeEntry.startsWith('payload/')) throw new Error(`Target runtime_entry must resolve inside payload: ${runtimeEntry}`);
729
+ if (target.os === 'any' && runtimeEntry !== MANAGED_WEB_RUNTIME_ENTRY) {
730
+ throw new Error(`Target managed-web runtime_entry must be ${MANAGED_WEB_RUNTIME_ENTRY}: ${runtimeEntry}`);
731
+ }
555
732
  validateNativeExecutionFacts(target.native_trust, target.execution_profile, metadataLabel, target.os);
556
733
  const artifactPath = path.join(outputDir, assetName);
557
734
  if (!existsSync(artifactPath)) throw new Error(`Target artifact is missing: ${target.asset_name}`);
@@ -566,7 +743,18 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
566
743
  if (infoBytes.length !== infoAsset.size || createHash('sha256').update(infoBytes).digest('hex') !== infoAsset.sha256 || !entries.get('app-info.json')?.bytes.equals(infoBytes)) throw new Error(`Target App info changed or differs from archive: ${target.target_id}`);
567
744
  const info = validateAppInfo(JSON.parse(infoBytes));
568
745
  if (info.app_id !== appId || info.version !== version || info.target_id !== target.target_id) throw new Error(`Target App info identity differs: ${target.target_id}`);
746
+ if (target.os === 'any' && info.storage_policy?.kind !== 'nimi-mediated-default') {
747
+ throw new Error(`Target managed-web package must use nimi-mediated-default storage: ${target.target_id}`);
748
+ }
749
+ parsedInfos.push({ targetId: target.target_id, info });
569
750
  validatePayloadLinks(entries, target.os);
751
+ validateCrossPlatformArchiveEntries([...entries.entries()].map(([name, entry]) => ({ name, bytes: entry.bytes, mode: entry.mode })), target.os);
752
+ const declarationEntry = entries.get('nimi.app.yaml');
753
+ if (declarationEntry) {
754
+ const declarationYamlText = declarationEntry.bytes.toString('utf8');
755
+ const archivedDeclaration = parseYaml(declarationYamlText);
756
+ validateManifestDesktop(archivedDeclaration?.desktop, `${target.asset_name} nimi.app.yaml desktop`, declarationYamlText);
757
+ }
570
758
  const manifest = readPackageManifestFromArchive(entries, metadataLabel);
571
759
  if (manifest.format !== PACKAGE_FORMAT) throw new Error(`Target archive manifest format is invalid: ${target.asset_name}`);
572
760
  for (const field of ['app_id', 'version', 'target_id', 'os', 'arch', 'runtime_entry', 'native_trust', 'execution_profile']) {
@@ -576,12 +764,69 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
576
764
  }
577
765
  validateNativeExecutionFacts(manifest.native_trust, manifest.execution_profile, `${target.asset_name} archive manifest`, target.os);
578
766
  const runtimeEntryArchive = entries.get(runtimeEntry);
579
- if (!runtimeEntryArchive || runtimeEntryArchive.mode !== 0o755) {
767
+ if (target.os === 'any') {
768
+ if (!runtimeEntryArchive || runtimeEntryArchive.mode !== 0o644) {
769
+ throw new Error(`Target managed-web archive runtime_entry is missing or not 0644: ${runtimeEntry}`);
770
+ }
771
+ if (entries.size > MANAGED_WEB_MAX_RELEASE_ENTRIES) {
772
+ throw new Error(`Target managed-web archive exceeds ${MANAGED_WEB_MAX_RELEASE_ENTRIES} entries: ${target.asset_name}`);
773
+ }
774
+ let totalUncompressedBytes = 0;
775
+ for (const entry of entries.values()) totalUncompressedBytes += entry.bytes.length;
776
+ if (totalUncompressedBytes > MANAGED_WEB_MAX_RELEASE_BYTES) {
777
+ throw new Error(`Target managed-web archive exceeds ${MANAGED_WEB_MAX_RELEASE_BYTES} bytes uncompressed: ${target.asset_name}`);
778
+ }
779
+ } else if (!runtimeEntryArchive || runtimeEntryArchive.mode !== 0o755) {
580
780
  throw new Error(`Target archive runtime_entry is missing or non-executable: ${runtimeEntry}`);
581
781
  }
582
782
  }
583
- const candidate = { format: AGGREGATE_FORMAT, app_id: appId, version, targets: targets.sort((left, right) => compareText(left.target_id, right.target_id)) };
783
+ const firstInfo = parsedInfos[0].info;
784
+ for (const entry of parsedInfos.slice(1)) {
785
+ for (const field of ['display_name', 'summary', 'icon', 'readme_markdown', 'release_notes_markdown', 'safety_profile', 'storefront']) {
786
+ if (!sameCanonicalValue(entry.info[field], firstInfo[field])) {
787
+ throw new Error(`Target App info ${field} differs between ${parsedInfos[0].targetId} and ${entry.targetId}; one release shares one presentation`);
788
+ }
789
+ }
790
+ }
791
+ let storefrontMedia;
792
+ if (firstInfo.storefront?.media !== undefined) {
793
+ const repoManifest = readYaml(path.join(targetDir, 'nimi.app.yaml'), 'nimi.app.yaml');
794
+ const { storefront: repoStorefront, mediaEntries } = readAppStorefront(targetDir, repoManifest);
795
+ if (!sameCanonicalValue(repoStorefront?.media, firstInfo.storefront.media)) {
796
+ throw new Error('Repository storefront media changed after target packing; rebuild targets and aggregate from the same commit');
797
+ }
798
+ const archiveEntries = [...mediaEntries.entries()]
799
+ .sort(([left], [right]) => compareText(left, right))
800
+ .map(([name, bytes]) => ({ name, bytes, mode: 0o644 }));
801
+ const mediaArchive = writeNimiAppArchive(archiveEntries);
802
+ if (mediaArchive.length > STOREFRONT_ARCHIVE_MAX_BYTES) {
803
+ throw new Error(`Storefront media archive exceeds ${STOREFRONT_ARCHIVE_MAX_BYTES} bytes`);
804
+ }
805
+ const mediaAssetName = `${appId}-${version}-storefront-media.zip`;
806
+ const mediaArchivePath = path.join(outputDir, mediaAssetName);
807
+ writeAppArchiveFile(mediaArchivePath, mediaArchive);
808
+ storefrontMedia = {
809
+ asset_name: mediaAssetName,
810
+ size: mediaArchive.length,
811
+ sha256: hashAppArchive(mediaArchive),
812
+ };
813
+ }
814
+ const candidate = {
815
+ format: AGGREGATE_FORMAT,
816
+ app_id: appId,
817
+ version,
818
+ ...(storefrontMedia ? { storefront_media: storefrontMedia } : {}),
819
+ targets: targets.sort((left, right) => compareText(left.target_id, right.target_id)),
820
+ };
584
821
  const candidatePath = path.join(outputDir, `${appId}-${version}.candidate.json`);
585
822
  writeFileSync(candidatePath, canonicalJson(candidate));
586
- return { ok: true, command: 'pack', aggregate: true, dir: targetDir, candidatePath, ...candidate };
823
+ return {
824
+ ok: true,
825
+ command: 'pack',
826
+ aggregate: true,
827
+ dir: targetDir,
828
+ candidatePath,
829
+ ...(storefrontMedia ? { storefrontMediaPath: path.join(outputDir, storefrontMedia.asset_name) } : {}),
830
+ ...candidate,
831
+ };
587
832
  }
@@ -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';",