@nimiplatform/app-tools 0.16.0-rc.12 → 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/README.md CHANGED
@@ -50,6 +50,8 @@ pnpm dev
50
50
 
51
51
  Set `--author` to the person or team responsible for the App and its license.
52
52
 
53
+ Desktop projects default to a static frontend that Home opens in Nimi’s managed carrier on Windows x64 and macOS arm64. Choose `--carrier native` at creation if the App needs its own Electron main process.
54
+
53
55
  ### Feature Profiles
54
56
  - `--features studio-create`: Injects creative text and multimodal generation capabilities along with `runtime.consume` permissions.
55
57
  - `--features studio-media`: Includes music, audio separation, and speech transcription capabilities.
@@ -96,6 +98,16 @@ pnpm dev -- --resume <selector>
96
98
  ## 4. Production Packaging & Distribution
97
99
 
98
100
  ### Building for Targets
101
+
102
+ For the default managed desktop App, build one package for both supported platforms:
103
+
104
+ ```bash
105
+ pnpm exec nimi-app build --target desktop-universal --production
106
+ pnpm exec nimi-app pack --target desktop-universal --production
107
+ ```
108
+
109
+ For an App created with `--carrier native`, build on the matching host:
110
+
99
111
  ```bash
100
112
  # macOS (Apple Silicon)
101
113
  pnpm exec nimi-app build --target macos-aarch64 --production
@@ -162,14 +174,14 @@ Save it as a **secret** (not an Actions variable) and confirm the exact name app
162
174
  Electron packages must keep native add-ons and their companion libraries outside the ASAR archive with their relative directory layout intact. The scaffold configures `asar: { unpack: '**/*.{node,dylib,dll}' }` on macOS and Windows. Apply the equivalent rule to any custom App-owned packager configuration and verify native module loading from the packaged layout—unpacking only `.node` files can leave companion libraries such as Sharp's `libvips` unavailable to the OS dynamic loader.
163
175
 
164
176
  #### Local Pre-Release Check & Tagging
165
- Run the production verification path locally from the App repository:
177
+ Run the production verification path locally from the App repository. For a native App, substitute the matching host target shown above.
166
178
 
167
179
  ```bash
168
180
  pnpm run sync
169
181
  pnpm exec nimi-app check --production
170
182
  pnpm exec nimi-app test
171
- pnpm exec nimi-app build --target windows-x86_64 --production
172
- pnpm exec nimi-app pack --target windows-x86_64 --production
183
+ pnpm exec nimi-app build --target desktop-universal --production
184
+ pnpm exec nimi-app pack --target desktop-universal --production
173
185
  ```
174
186
 
175
187
  Ensure `package.json` and `nimi.app.yaml` declare the exact same version, commit all release changes, and land that exact commit on the repository's canonical default branch. Then create and push an annotated tag matching that version (`0.1.0` shown as an example):
package/bin/nimi-app.mjs CHANGED
@@ -14,14 +14,14 @@ import {
14
14
  syncApp,
15
15
  testApp,
16
16
  } from '../lib/index.mjs';
17
- import { APP_SCAFFOLD_MODULE_REGISTRY } from '../lib/app-scaffold-capabilities.mjs';
17
+ import { APP_SCAFFOLD_MANAGED_WEB_FEATURE_IDS, APP_SCAFFOLD_MODULE_REGISTRY } from '../lib/app-scaffold-capabilities.mjs';
18
18
  import { LIFECYCLE_SKILL_PATH } from '../lib/app-lifecycle-guidance.mjs';
19
19
  import { createInterface } from 'node:readline/promises';
20
20
 
21
21
  function parseArgs(argv) {
22
22
  const [command = '', ...rest] = argv;
23
23
  const values = {
24
- dir: '', profile: '', platform: '', appId: '', version: '', title: '', packageName: '', author: '',
24
+ dir: '', profile: '', platform: '', carrier: '', appId: '', version: '', title: '', packageName: '', author: '',
25
25
  features: undefined, shell: '', cdpPort: undefined, noCdp: false, listRegistrations: false, resume: '', newRegistration: false, target: '', aggregate: false, production: false, json: false,
26
26
  adopt: false, dryRun: false, input: '', realm: '',
27
27
  };
@@ -90,6 +90,10 @@ function parseArgs(argv) {
90
90
  index = readValue(index, '--platform', 'platform');
91
91
  continue;
92
92
  }
93
+ if (rest[index] === '--carrier') {
94
+ index = readValue(index, '--carrier', 'carrier');
95
+ continue;
96
+ }
93
97
  if (rest[index] === '--features') {
94
98
  index = readValue(index, '--features', 'features');
95
99
  continue;
@@ -157,7 +161,7 @@ function parseArgs(argv) {
157
161
 
158
162
  function assertCommandOptions(command, providedOptions) {
159
163
  const allowed = {
160
- create: new Set(['dir', 'profile', 'platform', 'appId', 'version', 'title', 'packageName', 'author', 'features', 'json']),
164
+ create: new Set(['dir', 'profile', 'platform', 'carrier', 'appId', 'version', 'title', 'packageName', 'author', 'features', 'json']),
161
165
  init: new Set(['dir', 'json', 'adopt', 'input', 'dryRun']),
162
166
  sync: new Set(['dir', 'json', 'dryRun']),
163
167
  check: new Set(['dir', 'json', 'production']),
@@ -188,7 +192,7 @@ function printUsage() {
188
192
  'Nimi App developer tools',
189
193
  '',
190
194
  'Usage:',
191
- ' nimi-app create [--dir path] [--profile standalone] [--platform desktop|web] [--features admitted-ids|all] [--app-id dotted.id] [--version semver] [--title title] [--package-name name] [--author person-or-team] [--json]',
195
+ ' nimi-app create [--dir path] [--profile standalone] [--platform desktop|web] [--carrier managed-web|native] [--features admitted-ids|all] [--app-id dotted.id] [--version semver] [--title title] [--package-name name] [--author person-or-team] [--json]',
192
196
  ' nimi-app init [--adopt [--input json-path]] [--dry-run] [--dir path] [--json]',
193
197
  ' nimi-app sync [--dry-run] [--dir path] [--json]',
194
198
  ' nimi-app check [--dir path] [--production] [--json]',
@@ -207,6 +211,7 @@ function printUsage() {
207
211
  '',
208
212
  'Current module registry:',
209
213
  ` Admitted features: ${featureList(admitted)}`,
214
+ ` Managed desktop features (--carrier managed-web, default): ${APP_SCAFFOLD_MANAGED_WEB_FEATURE_IDS.join(', ') || '(none)'}`,
210
215
  ` Web features: ${featureList(admitted.filter(entry => entry.carriers.includes('web')))}`,
211
216
  ` Candidate features (not public-selectable): ${featureList(candidates)}`,
212
217
  ` Internal modules (dependency-only): ${internalList}`,
@@ -324,6 +329,7 @@ try {
324
329
  dir,
325
330
  profile,
326
331
  platform,
332
+ carrier,
327
333
  appId,
328
334
  version,
329
335
  title,
@@ -366,6 +372,7 @@ try {
366
372
  dir,
367
373
  profile,
368
374
  platform,
375
+ carrier,
369
376
  appId,
370
377
  version,
371
378
  title,
@@ -1,4 +1,5 @@
1
1
  import { isAppId } from './app-identifiers.mjs';
2
+ import { validateManifestDesktop } from './desktop-window.mjs';
2
3
  import { readWebDevelopment } from './web-development.mjs';
3
4
  import { readMobileDevelopment } from './mobile-development.mjs';
4
5
  import { APP_AUTHOR_DECLARATION_FIELDS, hashScaffoldManagedContent } from './app-scaffold.mjs';
@@ -186,6 +187,7 @@ function expectedSnapshotFromLock(lock, versions, intent, targetDir, options = {
186
187
  }
187
188
  for (const [intentField, lockField, label] of [
188
189
  ['profile', 'profile', 'profile'],
190
+ ['carrier', 'carrier', 'carrier'],
189
191
  ['appId', 'appId', 'App ID'],
190
192
  ['appTitle', 'appTitle', 'display name'],
191
193
  ['packageName', 'packageName', 'package name'],
@@ -479,12 +481,20 @@ function assertRequiredSupportFiles(targetDir, snapshot) {
479
481
  }
480
482
  }
481
483
 
482
- function usesAppOwnedRenderer(targetDir, plannedSources) {
484
+ function readBuildProfileRef(targetDir, plannedSources) {
483
485
  const relativePath = '.nimi/config/build-profile.yaml';
484
486
  const filePath = path.join(targetDir, relativePath);
485
487
  const source = plannedSources?.get(relativePath)
486
488
  ?? (existsSync(filePath) ? readFileSync(filePath, 'utf8') : undefined);
487
- return source !== undefined && parseYaml(source)?.build_profile_ref === 'electron-pnpm';
489
+ return source !== undefined ? parseYaml(source)?.build_profile_ref : undefined;
490
+ }
491
+
492
+ function usesAppOwnedRenderer(targetDir, plannedSources) {
493
+ return readBuildProfileRef(targetDir, plannedSources) === 'electron-pnpm';
494
+ }
495
+
496
+ function usesManagedWebCarrier(targetDir, plannedSources) {
497
+ return readBuildProfileRef(targetDir, plannedSources) === 'managed-web-pnpm-vite';
488
498
  }
489
499
 
490
500
  function assertProjectConfiguration(targetDir, parsedManifest = null, managed = true) {
@@ -499,6 +509,7 @@ function assertProjectConfiguration(targetDir, parsedManifest = null, managed =
499
509
  throw new Error(`Submitted manifest YAML cannot be parsed: ${error instanceof Error ? error.message : String(error)}`);
500
510
  }
501
511
  }
512
+ validateManifestDesktop(document?.desktop, 'nimi.app.yaml desktop', manifest);
502
513
  readAppIntroduction(targetDir, document);
503
514
  readAppStorefront(targetDir, document);
504
515
  assertCarrierDevelopmentInputs(targetDir, document, readJsonFile(path.join(targetDir, 'package.json')), managed);
@@ -551,7 +562,7 @@ function assertDeclaredHostSourceDirectory(targetDir, document) {
551
562
  }
552
563
  }
553
564
 
554
- function assertOfficialDevelopmentEntrypoints(targetDir, rendererOrigin, packageJson = readJsonFile(path.join(targetDir, 'package.json'), 'package.json'), managed = true) {
565
+ function assertOfficialDevelopmentEntrypoints(targetDir, rendererOrigin, packageJson = readJsonFile(path.join(targetDir, 'package.json'), 'package.json'), managed = true, managedWeb = false) {
555
566
  const scripts = packageJson?.scripts;
556
567
  if (!scripts || typeof scripts !== 'object' || Array.isArray(scripts)) {
557
568
  throw new Error('package.json scripts are required');
@@ -573,11 +584,11 @@ function assertOfficialDevelopmentEntrypoints(targetDir, rendererOrigin, package
573
584
  || /\b(?:nimi-app\s+dev|(?:pnpm|npm)\s+(?:run\s+)?(?:dev|dev:renderer))(?=\s|$)/u.test(rendererCommand)) {
574
585
  throw new Error('package.json dev:renderer must be a non-recursive App-owned renderer command for the declared loopback origin');
575
586
  }
576
- if (
587
+ if (!managedWeb && (
577
588
  typeof scripts['build:electron'] !== 'string'
578
589
  || scripts['build:electron'].trim() !== scripts['build:electron']
579
590
  || scripts['build:electron'].length === 0
580
- ) {
591
+ )) {
581
592
  throw new Error('package.json build:electron must build the Desktop-supervised Electron host');
582
593
  }
583
594
  for (const [name, value] of Object.entries(scripts)) {
@@ -615,14 +626,16 @@ function assertCarrierDevelopmentInputs(targetDir, manifest, packageJson, manage
615
626
  }
616
627
  if (manifest.platform !== 'web') {
617
628
  if (manifest.platform !== undefined && manifest.platform !== 'desktop') throw new Error('Unsupported App platform.');
629
+ const managedWeb = usesManagedWebCarrier(targetDir, plannedSources);
618
630
  const rendererOrigin = assertElectronLocalDevelopmentManifest(manifest);
619
631
  assertDeclaredHostSourceDirectory(targetDir, manifest);
620
- assertOfficialDevelopmentEntrypoints(targetDir, rendererOrigin, packageJson, managed || !usesAppOwnedRenderer(targetDir, plannedSources));
632
+ assertOfficialDevelopmentEntrypoints(targetDir, rendererOrigin, packageJson, managed || !usesAppOwnedRenderer(targetDir, plannedSources), managedWeb);
621
633
  }
622
634
  }
623
635
 
624
636
  export function validateAppProjectInputs(targetDir, manifest, packageJson, managed = false, plannedSources) {
625
637
  assertManifestAppAccessDeclaration(stringifyYaml(manifest), 'nimi.app.yaml');
638
+ validateManifestDesktop(manifest?.desktop, 'nimi.app.yaml desktop');
626
639
  readAppIntroduction(targetDir, manifest);
627
640
  readAppStorefront(targetDir, manifest);
628
641
  assertCarrierDevelopmentInputs(targetDir, manifest, packageJson, managed, plannedSources);
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
@@ -35,14 +36,103 @@ const PACKAGE_FORMAT = 'nimi.app-package/v2';
35
36
  const TARGET_METADATA_FORMAT = 'nimi.app-target-candidate/v1';
36
37
  const AGGREGATE_FORMAT = 'nimi.app-release-candidate/v1';
37
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;
38
45
  const ELECTRON_BUILD_PROFILE_REF = 'electron-packager-pnpm-vite';
39
46
  const APP_OWNED_ELECTRON_BUILD_PROFILE_REF = 'electron-pnpm';
40
47
  const OUTPUT_DIR = 'dist/nimi-app';
41
- 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;
42
49
  const TARGETS = Object.freeze({
43
50
  'windows-x86_64': Object.freeze({ os: 'windows', arch: 'x86_64' }),
44
51
  'macos-aarch64': Object.freeze({ os: 'macos', arch: 'arm64' }),
52
+ 'desktop-universal': Object.freeze({ os: 'any', arch: 'any' }),
45
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
+ }
46
136
 
47
137
  function compareText(left, right) {
48
138
  return left < right ? -1 : left > right ? 1 : 0;
@@ -275,7 +365,16 @@ export function readNimiAppArchive(bytes) {
275
365
  const commentLength = archive.readUInt16LE(cursor + 32);
276
366
  const localOffset = archive.readUInt32LE(cursor + 42);
277
367
  const unixMode = archive.readUInt32LE(cursor + 38) >>> 16;
278
- 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
+ }
279
378
  if (method !== 0 || extraLength !== 0 || commentLength !== 0) throw new Error('Unsupported nimiapp ZIP entry encoding');
280
379
  if (mode !== 0o644 && mode !== 0o755 && mode !== SYMBOLIC_LINK_MODE) throw new Error('Unsupported nimiapp ZIP entry mode');
281
380
  const name = zipEntryName(archive.subarray(cursor + 46, cursor + 46 + nameLength).toString('utf8'));
@@ -301,7 +400,7 @@ export function readNimiAppArchive(bytes) {
301
400
  function readNativePackProfile(targetDir) {
302
401
  const profile = readYaml(path.join(targetDir, BUILD_PROFILE_PATH), BUILD_PROFILE_PATH);
303
402
  assertDesktopHostSupport(profile.build_profile_ref);
304
- 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)) {
305
404
  throw new Error(`${BUILD_PROFILE_PATH} build_profile_ref is unsupported: ${String(profile.build_profile_ref)}`);
306
405
  }
307
406
  return profile;
@@ -311,6 +410,13 @@ function readPackInputs(targetDir, targetId) {
311
410
  const buildProfile = readNativePackProfile(targetDir);
312
411
  const target = TARGETS[targetId];
313
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
+ }
314
420
  const packageJson = readJson(path.join(targetDir, 'package.json'), 'package.json');
315
421
  const licensePath = path.join(targetDir, 'LICENSE');
316
422
  if (!existsSync(licensePath)) throw new Error('App package LICENSE is missing');
@@ -320,7 +426,11 @@ function readPackInputs(targetDir, targetId) {
320
426
  }
321
427
  const manifestPath = path.join(targetDir, 'nimi.app.yaml');
322
428
  const manifest = readYaml(manifestPath, 'nimi.app.yaml');
429
+ const desktop = validateManifestDesktop(manifest.desktop, 'nimi.app.yaml desktop');
323
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
+ }
324
434
  const appId = String(manifest.app_id || '');
325
435
  const version = String(packageJson.version || '');
326
436
  if (!isAppId(appId)) throw new Error('nimi.app.yaml app_id must be canonical and dotted');
@@ -331,15 +441,22 @@ function readPackInputs(targetDir, targetId) {
331
441
  if (!configured || typeof configured !== 'object' || Array.isArray(configured)) throw new Error(`Build profile does not declare target: ${targetId}`);
332
442
  if (configured.os !== target.os || configured.arch !== target.arch) throw new Error(`Build profile target identity mismatch: ${targetId}`);
333
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
+ }
334
448
  if (!existsSync(payload.resolved)) throw new Error(`Built target payload is missing: ${payload.normalized}`);
335
449
  const runtimeEntry = canonicalRelative(configured.runtime_entry, `targets.${targetId}.runtime_entry`);
336
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
+ }
337
454
  const payloadStat = lstatSync(payload.resolved);
338
455
  const runtimeRelative = runtimeEntry.slice('payload/'.length);
339
456
  const runtimeHostPath = payloadStat.isFile()
340
457
  ? payload.resolved
341
458
  : resolveInside(payload.resolved, runtimeRelative, `targets.${targetId}.runtime_entry`).resolved;
342
- 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 };
343
460
  }
344
461
 
345
462
  export function classifyWindowsNativeTrustObservation(observation) {
@@ -383,6 +500,17 @@ function observeProductionWindowsFacts(input, archivedRuntimeEntryBytes) {
383
500
  }
384
501
 
385
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
+ }
386
514
  if (!production) {
387
515
  return {
388
516
  nativeTrust: { posture: 'development-unsigned' },
@@ -401,6 +529,25 @@ function validateNativeExecutionFacts(nativeTrust, executionProfile, label, os)
401
529
  if (!nativeTrust || typeof nativeTrust !== 'object' || Array.isArray(nativeTrust)) {
402
530
  throw new Error(`${label} native_trust must be an object`);
403
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
+ }
404
551
  if (nativeTrust.posture === 'development-unsigned') {
405
552
  if (executionProfile !== null || Object.keys(nativeTrust).length !== 1) {
406
553
  throw new Error(`${label} development native/execution posture is inconsistent`);
@@ -466,10 +613,14 @@ export function packAppTarget(cwd, options = {}) {
466
613
  const targetId = String(options.target || '').trim();
467
614
  if (!targetId) throw new Error('nimi-app pack requires --target');
468
615
  const input = readPackInputs(targetDir, targetId);
616
+ const isManagedWeb = input.target.os === 'any';
469
617
  const payloadEntries = collectPayload(input.payloadPath, input.target.os).map((entry) => {
470
618
  const name = `payload/${entry.relative.replaceAll('\\', '/')}`;
471
619
  if (name === input.runtimeEntry && entry.mode === SYMBOLIC_LINK_MODE) throw new Error('Runtime entry must be a direct regular file');
472
- 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 };
473
624
  });
474
625
  validatePayloadLinks(new Map(payloadEntries.map((entry) => [entry.name, entry])), input.target.os);
475
626
  const runtimeEntry = payloadEntries.find((entry) => entry.name === input.runtimeEntry);
@@ -490,14 +641,28 @@ export function packAppTarget(cwd, options = {}) {
490
641
  if (infoBytes.length > APP_INFO_MAX_BYTES) throw new Error('App info exceeds 1 MiB');
491
642
  // An undeclared safety_profile stays absent from the declaration copy; it is
492
643
  // never serialized as an empty or default declaration.
493
- const declaration = Object.fromEntries(APP_INFO_DECLARATION_FIELDS.filter((key) => input.appInfo[key] !== undefined).map((key) => [key, input.appInfo[key]]));
494
- 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 = [
495
649
  { name: 'LICENSE', bytes: readFileSync(input.licensePath), mode: 0o644 },
496
- { name: 'manifest.json', bytes: canonicalJson(packageManifest), mode: 0o644 },
497
- { 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 },
498
652
  { name: 'app-info.json', bytes: infoBytes, mode: 0o644 },
499
653
  ...payloadEntries,
500
- ]);
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);
501
666
  const sha256 = hashAppArchive(archive);
502
667
  const outputDir = path.join(targetDir, OUTPUT_DIR);
503
668
  mkdirSync(outputDir, { recursive: true });
@@ -528,7 +693,8 @@ export function packAppTarget(cwd, options = {}) {
528
693
 
529
694
  export function aggregateAppTargetCandidates(cwd, options = {}) {
530
695
  const targetDir = path.resolve(cwd, String(options.dir || '').trim() || '.');
531
- readNativePackProfile(targetDir);
696
+ const buildProfile = readNativePackProfile(targetDir);
697
+ const isManagedWebProfile = buildProfile.build_profile_ref === MANAGED_WEB_BUILD_PROFILE_REF;
532
698
  const outputDir = path.join(targetDir, OUTPUT_DIR);
533
699
  if (!existsSync(outputDir)) throw new Error('No target metadata exists to aggregate');
534
700
  const files = readdirSync(outputDir).filter((name) => name.endsWith('.target.json')).sort();
@@ -543,6 +709,12 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
543
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');
544
710
  if (seen.has(target.target_id)) throw new Error(`Duplicate target metadata: ${target.target_id}`);
545
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
+ }
546
718
  const expectedTarget = TARGETS[target.target_id];
547
719
  if (!expectedTarget || target.os !== expectedTarget.os || target.arch !== expectedTarget.arch) {
548
720
  throw new Error(`Target metadata identity is invalid: ${target.target_id}`);
@@ -554,6 +726,9 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
554
726
  }
555
727
  const runtimeEntry = canonicalRelative(target.runtime_entry, `${metadataLabel}.runtime_entry`);
556
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
+ }
557
732
  validateNativeExecutionFacts(target.native_trust, target.execution_profile, metadataLabel, target.os);
558
733
  const artifactPath = path.join(outputDir, assetName);
559
734
  if (!existsSync(artifactPath)) throw new Error(`Target artifact is missing: ${target.asset_name}`);
@@ -568,8 +743,18 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
568
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}`);
569
744
  const info = validateAppInfo(JSON.parse(infoBytes));
570
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
+ }
571
749
  parsedInfos.push({ targetId: target.target_id, info });
572
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
+ }
573
758
  const manifest = readPackageManifestFromArchive(entries, metadataLabel);
574
759
  if (manifest.format !== PACKAGE_FORMAT) throw new Error(`Target archive manifest format is invalid: ${target.asset_name}`);
575
760
  for (const field of ['app_id', 'version', 'target_id', 'os', 'arch', 'runtime_entry', 'native_trust', 'execution_profile']) {
@@ -579,7 +764,19 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
579
764
  }
580
765
  validateNativeExecutionFacts(manifest.native_trust, manifest.execution_profile, `${target.asset_name} archive manifest`, target.os);
581
766
  const runtimeEntryArchive = entries.get(runtimeEntry);
582
- 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) {
583
780
  throw new Error(`Target archive runtime_entry is missing or non-executable: ${runtimeEntry}`);
584
781
  }
585
782
  }