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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +112 -24
  2. package/bin/nimi-app.mjs +35 -15
  3. package/lib/app-access-declaration.mjs +3 -0
  4. package/lib/app-dependency-combinations.mjs +70 -24
  5. package/lib/app-doctor-update.mjs +97 -39
  6. package/lib/app-host-support.mjs +6 -0
  7. package/lib/app-identifiers.mjs +27 -0
  8. package/lib/app-info.mjs +292 -1
  9. package/lib/app-lifecycle-guidance.mjs +1 -1
  10. package/lib/app-pack.mjs +65 -39
  11. package/lib/app-project-lifecycle.mjs +149 -244
  12. package/lib/app-scaffold-capabilities.mjs +13 -109
  13. package/lib/app-scaffold-profiles.mjs +81 -115
  14. package/lib/app-scaffold.mjs +74 -166
  15. package/lib/app-toolchain-updates.mjs +45 -0
  16. package/lib/canonical-capability-ids.generated.mjs +2 -0
  17. package/lib/development-environment.d.mts +10 -0
  18. package/lib/development-environment.mjs +39 -0
  19. package/lib/hosted-web-release.mjs +98 -0
  20. package/lib/index.mjs +43 -3
  21. package/lib/mobile-development.mjs +19 -0
  22. package/lib/realm-environments.generated.mjs +5 -0
  23. package/lib/storefront-media.mjs +154 -0
  24. package/lib/web-coordination.mjs +59 -0
  25. package/lib/web-development.d.mts +23 -0
  26. package/lib/web-development.mjs +118 -0
  27. package/lib/web-scaffold.mjs +125 -0
  28. package/package.json +33 -21
  29. package/scripts/dev-shell.mjs +4 -1
  30. package/scripts/sync-scaffold-versions.mjs +0 -2
  31. package/skills/nimi-app-lifecycle/SKILL.md +3 -1
  32. package/skills/nimi-app-lifecycle/references/acceptance.md +6 -2
  33. package/skills/nimi-app-lifecycle/references/adapt.md +5 -3
  34. package/skills/nimi-app-lifecycle/references/audit.md +3 -2
  35. package/skills/nimi-app-lifecycle/references/create.md +6 -2
  36. package/skills/nimi-app-lifecycle/references/release.md +10 -0
  37. package/skills/nimi-app-lifecycle/references/upgrade-platform.md +12 -7
  38. package/templates/app-source/src/ai-studio-core/ai-studio-core.css +87 -52
  39. package/templates/app-source/src/ai-studio-core/history-policy.ts +45 -11
  40. package/templates/app-source/src/ai-studio-core/history.ts +22 -11
  41. package/templates/app-source/src/ai-studio-core/host-context.tsx +9 -4
  42. package/templates/app-source/src/ai-studio-core/index.ts +2 -0
  43. package/templates/app-source/src/ai-studio-core/job-recovery-panel.tsx +15 -5
  44. package/templates/app-source/src/ai-studio-core/job-recovery.ts +2 -2
  45. package/templates/app-source/src/ai-studio-core/messages/en.json +73 -19
  46. package/templates/app-source/src/ai-studio-core/messages/zh.json +73 -19
  47. package/templates/app-source/src/ai-studio-core/module-registration.ts +1 -0
  48. package/templates/app-source/src/ai-studio-core/non-success-presentation.ts +30 -5
  49. package/templates/app-source/src/ai-studio-core/parameter-fields.tsx +12 -6
  50. package/templates/app-source/src/ai-studio-core/parameters.ts +4 -0
  51. package/templates/app-source/src/ai-studio-core/prompt-drafts.ts +42 -0
  52. package/templates/app-source/src/ai-studio-core/runtime-types.ts +9 -2
  53. package/templates/app-source/src/ai-studio-core/runtime.ts +8 -4
  54. package/templates/app-source/src/ai-studio-core/section-ai-testing-composer.tsx +98 -90
  55. package/templates/app-source/src/ai-studio-core/section-ai-testing-exchange-result.tsx +1 -1
  56. package/templates/app-source/src/ai-studio-core/section-ai-testing-history.tsx +205 -48
  57. package/templates/app-source/src/ai-studio-core/section-ai-testing-input.ts +1 -0
  58. package/templates/app-source/src/ai-studio-core/section-ai-testing-output.tsx +36 -14
  59. package/templates/app-source/src/ai-studio-core/section-ai-testing-result.tsx +96 -75
  60. package/templates/app-source/src/ai-studio-core/section-ai-testing-run.ts +59 -16
  61. package/templates/app-source/src/ai-studio-core/section-ai-testing-session-result.tsx +2 -0
  62. package/templates/app-source/src/ai-studio-core/section-ai-testing-studio-result.tsx +12 -21
  63. package/templates/app-source/src/ai-studio-core/section-ai-testing-transcription-result.tsx +2 -2
  64. package/templates/app-source/src/ai-studio-core/section-ai-testing-vision-result.tsx +3 -3
  65. package/templates/app-source/src/ai-studio-core/section-ai-testing.tsx +158 -76
  66. package/templates/app-source/src/ai-studio-core/workspace.tsx +49 -22
  67. package/templates/app-source/src/product-modules/agent-center/index.tsx +2 -3
  68. package/templates/app-source/src/product-modules/agent-conversation/index.tsx +2 -3
  69. package/templates/app-source/src/studio-modules/studio-create/messages/en.json +12 -3
  70. package/templates/app-source/src/studio-modules/studio-create/messages/zh.json +12 -3
  71. package/templates/app-source/src/studio-modules/studio-create/parameter-panel.tsx +11 -2
  72. package/templates/app-source/src/studio-modules/studio-create/parameters.ts +2 -1
  73. package/templates/app-source/src/studio-modules/studio-create/runtime.ts +47 -5
  74. package/templates/app-source/src/studio-modules/studio-media/messages/en.json +59 -8
  75. package/templates/app-source/src/studio-modules/studio-media/messages/zh.json +68 -8
  76. package/templates/app-source/src/studio-modules/studio-media/music-parameters.tsx +2 -1
  77. package/templates/app-source/src/studio-modules/studio-media/parameter-panel.tsx +271 -83
  78. package/templates/app-source/src/studio-modules/studio-media/parameters.ts +120 -2
  79. package/templates/app-source/src/studio-modules/studio-media/registration.ts +1 -0
  80. package/templates/app-source/src/studio-modules/studio-media/runtime.ts +24 -14
  81. package/templates/app-source/src/studio-modules/studio-voice/descriptors.ts +1 -1
  82. package/templates/app-source/src/studio-modules/studio-voice/messages/en.json +3 -2
  83. package/templates/app-source/src/studio-modules/studio-voice/messages/zh.json +3 -2
  84. package/templates/app-source/src/studio-modules/studio-voice/parameter-panel.tsx +46 -23
  85. package/templates/app-source/src/studio-modules/studio-voice/registration.ts +2 -1
  86. package/templates/app-source/src/studio-modules/studio-voice/runtime.ts +2 -2
  87. package/templates/app-source/src/workbench-core/workbench-core.tsx +27 -3
  88. package/templates/default-starter/AGENTS.md +3 -3
  89. package/templates/default-starter/README.md +1 -1
  90. package/templates/default-starter/src/shell/App.tsx +6 -18
  91. package/templates/default-starter/src/shell/auth/local-app-client.ts +6 -15
  92. package/templates/default-starter/src/shell/auth/runtime-platform.ts +7 -107
  93. package/templates/default-starter/src/shell/workbench-target-adapter.ts +9 -126
  94. package/templates/default-starter.manifest.json +0 -16
  95. package/templates/hosted-web-release.yml +98 -0
  96. package/templates/default-starter/src-tauri/Cargo.toml +0 -17
  97. package/templates/default-starter/src-tauri/build.rs +0 -32
  98. package/templates/default-starter/src-tauri/capabilities/default.json +0 -7
  99. package/templates/default-starter/src-tauri/tauri.conf.json +0 -26
@@ -0,0 +1,39 @@
1
+ import { REALM_PROFILES } from './realm-environments.generated.mjs';
2
+
3
+ // @nimi-authority: rule.nimi.platform.core-protocol.development-topology
4
+ export function resolveDevelopmentRealm(selection, env = process.env) {
5
+ const name = selection ?? env.NIMI_DEV_REALM ?? 'official';
6
+ if (!Object.hasOwn(REALM_PROFILES, name)) throw new Error('Choose --realm official or --realm local.');
7
+ const profile = { ...REALM_PROFILES[name] };
8
+ if (name === 'local') {
9
+ for (const [field, key] of [['apiOrigin', 'NIMI_DEV_REALM_URL'], ['realtimeOrigin', 'NIMI_DEV_REALTIME_URL'], ['webOrigin', 'NIMI_DEV_WEB_URL']]) {
10
+ if (env[key] !== undefined) profile[field] = exactDevelopmentOrigin(env[key], key);
11
+ }
12
+ if (profile.apiOrigin === REALM_PROFILES.official.apiOrigin) throw new Error('Official Realm requires the official environment.');
13
+ if (env.NIMI_DEV_REALM_ENVIRONMENT_ID !== undefined) profile.environmentId = env.NIMI_DEV_REALM_ENVIRONMENT_ID;
14
+ }
15
+ if (!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(profile.environmentId)) throw new Error('Invalid development Realm environment id.');
16
+ return Object.freeze({ name, ...profile });
17
+ }
18
+
19
+ export function exactDevelopmentOrigin(value, label) {
20
+ const url = new URL(value);
21
+ if (value !== url.origin || url.username || url.password || (url.protocol !== 'https:'
22
+ && !(url.protocol === 'http:' && ['localhost', '127.0.0.1'].includes(url.hostname)))) {
23
+ throw new Error(`${label} requires an exact HTTPS origin (HTTP only for loopback).`);
24
+ }
25
+ return url.origin;
26
+ }
27
+
28
+ export function developmentRealmEnvironment(realm) {
29
+ return {
30
+ NIMI_DEV_REALM: realm.name,
31
+ NIMI_REALM_URL: realm.apiOrigin,
32
+ NIMI_REALTIME_URL: realm.realtimeOrigin,
33
+ NIMI_WEB_URL: realm.webOrigin,
34
+ NIMI_DEV_REALM_URL: realm.apiOrigin,
35
+ NIMI_DEV_REALTIME_URL: realm.realtimeOrigin,
36
+ NIMI_DEV_WEB_URL: realm.webOrigin,
37
+ NIMI_DEV_REALM_ENVIRONMENT_ID: realm.environmentId,
38
+ };
39
+ }
@@ -0,0 +1,98 @@
1
+ import { readdir, readFile, writeFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { writeNimiAppArchive } from './app-pack.mjs';
4
+ import { hostedWebIdentity } from './app-identifiers.mjs';
5
+ import { resolveDevelopmentRealm } from './development-environment.mjs';
6
+
7
+ const versionPattern =
8
+ /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u;
9
+
10
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.hosted-web-publication
11
+ export function hostedWebViteConfig(manifest, env) {
12
+ const identity = hostedWebIdentity(manifest.app_id, manifest.public_slug, env.NIMI_WEB_CLIENT_ID);
13
+ const official = resolveDevelopmentRealm('official');
14
+ const version = env.NIMI_WEB_VERSION ?? manifest.version;
15
+ if (typeof version !== 'string' || version.length > 120 || !versionPattern.test(version))
16
+ throw new Error('Invalid Web release version.');
17
+ const config = {
18
+ appId: identity.appId,
19
+ clientId: identity.clientId,
20
+ realmEnvironmentId: official.environmentId,
21
+ officialWebBaseUrl: official.webOrigin,
22
+ realmBaseUrl: identity.origin,
23
+ redirectUri: identity.redirectUri,
24
+ };
25
+ for (const [key, expected] of Object.entries({
26
+ NIMI_WEB_ORIGIN: identity.origin,
27
+ NIMI_WEB_CLIENT_ID: config.clientId,
28
+ NIMI_WEB_REDIRECT_URI: config.redirectUri,
29
+ NIMI_WEB_REALM_ENVIRONMENT_ID: config.realmEnvironmentId,
30
+ NIMI_WEB_OFFICIAL_WEB_URL: config.officialWebBaseUrl,
31
+ })) {
32
+ if (env[key] !== undefined && env[key] !== expected)
33
+ throw new Error(key + ' conflicts with hosted Web identity.');
34
+ }
35
+ const info = {
36
+ format: 'nimi.web-bundle/v1',
37
+ app_id: identity.appId,
38
+ slug: identity.slug,
39
+ version,
40
+ client_id: config.clientId,
41
+ origin: identity.origin,
42
+ redirect_uri: config.redirectUri,
43
+ official_web_url: config.officialWebBaseUrl,
44
+ realm_environment_id: config.realmEnvironmentId,
45
+ entry: 'index.html',
46
+ app_access: manifest.app_access,
47
+ capability_contract_refs: manifest.capability_contract_refs ?? [],
48
+ };
49
+ return {
50
+ base: '/',
51
+ define: { __NIMI_APP_WEB_CONFIG__: JSON.stringify(config) },
52
+ build: { assetsDir: '_releases/' + version + '/assets' },
53
+ plugins: [
54
+ {
55
+ name: 'nimi-hosted-web-release',
56
+ async writeBundle(options) {
57
+ if (env.NIMI_WEB_ARCHIVE) {
58
+ if (!options.dir) throw new Error('Hosted Web packaging requires one static output directory.');
59
+ await packHostedWeb(options.dir, env.NIMI_WEB_ARCHIVE);
60
+ }
61
+ },
62
+ generateBundle() {
63
+ this.emitFile({
64
+ type: 'asset',
65
+ fileName: 'nimi-web-bundle.json',
66
+ source: JSON.stringify(info, null, 2) + '\n',
67
+ });
68
+ },
69
+ },
70
+ ],
71
+ };
72
+ }
73
+
74
+ export async function packHostedWeb(directory, outputFile) {
75
+ const root = path.resolve(directory);
76
+ if (path.resolve(outputFile).startsWith(root + path.sep))
77
+ throw new Error('Write the archive outside the static directory.');
78
+ const entries = [];
79
+ async function collect(relative) {
80
+ for (const item of await readdir(path.join(root, relative), { withFileTypes: true })) {
81
+ const name = relative ? relative + '/' + item.name : item.name;
82
+ if (/^(?:_headers|_redirects|_routes\.json|_worker\.js|wrangler\.[^/]+|functions)(?:\/|$)/iu.test(name))
83
+ continue;
84
+ if (/^(?:\.git|\.env(?:\..*)?)(?:\/|$)/u.test(name))
85
+ throw new Error('Private working files cannot be hosted: ' + name);
86
+ if (item.isDirectory()) await collect(name);
87
+ else if (item.isFile()) entries.push({ name, bytes: await readFile(path.join(root, name)) });
88
+ else throw new Error('Unsupported file in hosted Web bundle: ' + name);
89
+ }
90
+ }
91
+ await collect('');
92
+ if (
93
+ !entries.some((e) => e.name === 'index.html') ||
94
+ !entries.some((e) => e.name === 'nimi-web-bundle.json')
95
+ )
96
+ throw new Error('Missing hosted Web entry or release manifest.');
97
+ await writeFile(outputFile, writeNimiAppArchive(entries), { flag: 'wx' });
98
+ }
package/lib/index.mjs CHANGED
@@ -19,7 +19,12 @@ import {
19
19
  validateAppInitialization,
20
20
  } from './app-project-lifecycle.mjs';
21
21
  import { aggregateAppTargetCandidates, packAppTarget } from './app-pack.mjs';
22
- export { runDevShell } from '../scripts/dev-shell.mjs';
22
+ import { runDevShell } from '../scripts/dev-shell.mjs';
23
+ export { runDevShell };
24
+ import { parse as parseYaml } from 'yaml';
25
+ import { readWebDevelopment } from './web-development.mjs';
26
+ import { readMobileDevelopment } from './mobile-development.mjs';
27
+ import { resolveDevelopmentRealm, developmentRealmEnvironment } from './development-environment.mjs';
23
28
  export { APP_SCAFFOLD_FEATURE_IDS } from './app-scaffold-capabilities.mjs';
24
29
 
25
30
  const APP_TOOLS_PACKAGE_MANIFEST = JSON.parse(
@@ -106,6 +111,8 @@ function runAppCommand(targetDir, command, options = {}) {
106
111
  shell: true,
107
112
  encoding: 'utf8',
108
113
  stdio: options.capture ? 'pipe' : 'inherit',
114
+ env: options.env ?? process.env,
115
+ windowsHide: true,
109
116
  });
110
117
  return {
111
118
  status: result.status ?? 1,
@@ -125,6 +132,7 @@ export function createApp(cwd, options = {}) {
125
132
  options: {
126
133
  dir: options.dir,
127
134
  profile: options.profile,
135
+ platform: options.platform,
128
136
  appId: options.appId,
129
137
  name: options.name,
130
138
  title: options.title,
@@ -191,8 +199,9 @@ function resolveCreateTopology() {
191
199
 
192
200
  export function initAppScaffold(cwd, options = {}) {
193
201
  if (options.adopt) return adoptAppProject(cwd, options, appScaffoldVersions(), appToolRunners());
194
- validateAppInitialization(path.resolve(cwd, options.dir || '.'), appScaffoldVersions());
195
- return initApp(cwd, options, appScaffoldVersions(), appToolRunners());
202
+ const versions = appScaffoldVersions();
203
+ const workflows = validateAppInitialization(path.resolve(cwd, options.dir || '.'), versions);
204
+ return initApp(cwd, options, versions, appToolRunners(), workflows);
196
205
  }
197
206
 
198
207
  export function syncApp(cwd, options = {}) {
@@ -212,7 +221,38 @@ export function buildApp(cwd, options = {}) {
212
221
  }
213
222
 
214
223
  export function packApp(cwd, options = {}) {
224
+ const manifest = parseYaml(readFileSync(path.join(path.resolve(cwd, options.dir || '.'), 'nimi.app.yaml'), 'utf8'));
225
+ if (manifest.platform === 'web') throw new Error('Web pack is not implemented; use the App-owned website build and deployment process.');
215
226
  return options.aggregate
216
227
  ? aggregateAppTargetCandidates(cwd, options)
217
228
  : packAppTarget(cwd, options);
218
229
  }
230
+
231
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.scaffold-web-carrier
232
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.mobile-development-entry
233
+ export async function runAppDevelopment(cwd, options = {}) {
234
+ const root = path.resolve(cwd, options.dir || '.');
235
+ if (!existsSync(path.join(root, 'nimi.app.yaml'))) throw new Error('nimi.app.yaml is required for App development.');
236
+ const manifest = parseYaml(readFileSync(path.join(root, 'nimi.app.yaml'), 'utf8'));
237
+ const platform = options.platform || manifest.platform || 'desktop';
238
+ if (!['desktop', 'web', 'mobile'].includes(platform)) throw new Error(`Unsupported App development platform: ${platform}`);
239
+ if (platform === 'desktop') return runDevShell(cwd, options);
240
+ if (options.shell || options.cdpPort !== undefined || options.noCdp || options.resume || options.newRegistration || options.listRegistrations) {
241
+ throw new Error('Desktop shell, registration and CDP launch options do not apply to remote Web or Mobile dev.');
242
+ }
243
+ const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8'));
244
+ const selectedRealm = resolveDevelopmentRealm(options.realm || undefined);
245
+ const environment = { ...process.env, ...developmentRealmEnvironment(selectedRealm) };
246
+ if (platform === 'mobile') {
247
+ const mobile = readMobileDevelopment(manifest, pkg);
248
+ process.stdout.write('[nimi-app] Running the App-owned mobile command; native source admission and verified OS callback remain required.\n');
249
+ const result = runAppCommand(root, mobile.command, { env: environment });
250
+ if (result.status !== 0) throw new Error(`Mobile development command exited with ${result.status}: ${result.stderr}`);
251
+ return;
252
+ }
253
+ const web = readWebDevelopment(manifest, { realm: selectedRealm.name, env: environment });
254
+ if (!pkg.scripts?.[web.script] || /\bnimi-app\s+dev\b/u.test(pkg.scripts[web.script])) throw new Error('Web dev requires a real, non-recursive App-owned renderer script.');
255
+ process.stdout.write(`[nimi-app] Web source: ${web.site.origin}; official sign-in and first Home source confirmation are required.\n`);
256
+ const result = runAppCommand(root, web.command, { env: environment });
257
+ if (result.status !== 0) throw new Error(`Web development command exited with ${result.status}: ${result.stderr}`);
258
+ }
@@ -0,0 +1,19 @@
1
+ import { isAppId } from './app-identifiers.mjs';
2
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.mobile-development-entry
3
+ export function readMobileDevelopment(manifest, pkg) {
4
+ const mobile = manifest?.local_development?.mobile;
5
+ if (!mobile || typeof mobile !== 'object' || Array.isArray(mobile)
6
+ || Object.keys(mobile).some(key => key !== 'command')) {
7
+ throw new Error('Declare an App-owned local_development.mobile.command in nimi.app.yaml.');
8
+ }
9
+ if (typeof manifest.app_id !== 'string' || !isAppId(manifest.app_id)) {
10
+ throw new Error('Mobile development requires a canonical App id.');
11
+ }
12
+ const match = typeof mobile.command === 'string' && /^pnpm run ([A-Za-z0-9][A-Za-z0-9:_.-]*)$/u.exec(mobile.command);
13
+ if (!match) throw new Error('Mobile command must name an App-owned pnpm script.');
14
+ const command = pkg?.scripts?.[match[1]];
15
+ if (typeof command !== 'string' || !command.trim() || /\bnimi-app\s+dev\b/u.test(command)) {
16
+ throw new Error('Mobile dev requires a real, non-recursive App-owned native script.');
17
+ }
18
+ return { command: mobile.command, script: match[1] };
19
+ }
@@ -0,0 +1,5 @@
1
+ // Generated by scripts/generate-development-realms.mjs.
2
+ export const REALM_PROFILES = Object.freeze({
3
+ official: Object.freeze({"apiOrigin":"https://realm.nimi.ai","realtimeOrigin":"https://realm.nimi.ai","webOrigin":"https://nimi.ai","environmentId":"production"}),
4
+ local: Object.freeze({"apiOrigin":"http://127.0.0.1:3002","realtimeOrigin":"http://127.0.0.1:3003","webOrigin":"http://localhost:3000","environmentId":"dev"}),
5
+ });
@@ -0,0 +1,154 @@
1
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-napp-042a
2
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-napp-042b
3
+ import { createHash } from 'node:crypto';
4
+ import { createRequire } from 'node:module';
5
+ import { PNG } from 'pngjs';
6
+
7
+ const require = createRequire(import.meta.url);
8
+
9
+ export const STOREFRONT_CATEGORIES = Object.freeze([
10
+ 'companions-worlds',
11
+ 'lifestyle',
12
+ 'writing-notes',
13
+ 'design-diagrams',
14
+ 'audio-music',
15
+ 'video-media',
16
+ 'research-learning',
17
+ 'productivity-automation',
18
+ 'developer-tools',
19
+ ]);
20
+
21
+ export const STOREFRONT_IMAGE_MAX_BYTES = 512 * 1024;
22
+ export const STOREFRONT_ARCHIVE_MAX_BYTES = 8 * 1024 * 1024;
23
+ export const STOREFRONT_COVER_BOUNDS = Object.freeze({ minW: 800, maxW: 2560, minH: 450, maxH: 1600 });
24
+ export const STOREFRONT_GALLERY_BOUNDS = Object.freeze({ minW: 640, maxW: 2560, minH: 360, maxH: 1600 });
25
+
26
+ export const STOREFRONT_LOCALE_PATTERN = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u;
27
+ export const STOREFRONT_GALLERY_ID_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/u;
28
+ export const STOREFRONT_SHA256_PATTERN = /^[0-9a-f]{64}$/u;
29
+
30
+ const PNG_SIGNATURE = Buffer.from('89504e470d0a1a0a', 'hex');
31
+
32
+ export function storefrontMediaExtension(mediaType) {
33
+ if (mediaType === 'image/webp') return 'webp';
34
+ if (mediaType === 'image/png') return 'png';
35
+ throw new Error(`Unsupported storefront image media type: ${mediaType}`);
36
+ }
37
+
38
+ export function inspectStaticStorefrontImage(bytes, bounds, label = 'storefront image') {
39
+ if (!Buffer.isBuffer(bytes) || bytes.length === 0 || bytes.length > STOREFRONT_IMAGE_MAX_BYTES) {
40
+ throw new Error(`${label} must be a nonempty static WebP or PNG of at most ${STOREFRONT_IMAGE_MAX_BYTES} bytes`);
41
+ }
42
+ const sha256 = createHash('sha256').update(bytes).digest('hex');
43
+
44
+ if (bytes.length >= 8 && bytes.subarray(0, 8).equals(PNG_SIGNATURE)) {
45
+ let offset = 8;
46
+ let width = 0;
47
+ let height = 0;
48
+ let ended = false;
49
+ while (offset + 12 <= bytes.length) {
50
+ const length = bytes.readUInt32BE(offset);
51
+ const type = bytes.toString('ascii', offset + 4, offset + 8);
52
+ if (offset + length + 12 > bytes.length) throw new Error(`${label} PNG chunk is truncated`);
53
+ if (type === 'acTL') throw new Error(`${label} animated PNG (APNG) is not allowed`);
54
+ if (offset === 8 && (type !== 'IHDR' || length !== 13)) throw new Error(`${label} PNG header is invalid`);
55
+ if (type === 'IHDR') {
56
+ if (offset !== 8) throw new Error(`${label} PNG has more than one header`);
57
+ width = bytes.readUInt32BE(offset + 8);
58
+ height = bytes.readUInt32BE(offset + 12);
59
+ }
60
+ offset += length + 12;
61
+ if (type === 'IEND') {
62
+ ended = length === 0 && offset === bytes.length;
63
+ break;
64
+ }
65
+ }
66
+ if (!ended) throw new Error(`${label} PNG is truncated or has trailing bytes`);
67
+ assertImageBounds(width, height, bounds, label);
68
+ const decoded = PNG.sync.read(bytes, { checkCRC: true });
69
+ if (decoded.width !== width || decoded.height !== height) throw new Error(`${label} PNG dimensions are inconsistent`);
70
+ return { media_type: 'image/png', width, height, size: bytes.length, sha256 };
71
+ }
72
+
73
+ if (bytes.length >= 16 && bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WEBP') {
74
+ const riffSize = bytes.readUInt32LE(4);
75
+ if (riffSize + 8 !== bytes.length) throw new Error(`${label} WebP RIFF size does not match file length`);
76
+ let offset = 12;
77
+ let width = 0;
78
+ let height = 0;
79
+ let hasBitstream = false;
80
+ while (offset < bytes.length) {
81
+ if (offset + 8 > bytes.length) throw new Error(`${label} WebP chunk header is truncated`);
82
+ const type = bytes.toString('ascii', offset, offset + 4);
83
+ const chunkSize = bytes.readUInt32LE(offset + 4);
84
+ const dataStart = offset + 8;
85
+ const dataEnd = dataStart + chunkSize;
86
+ const paddedEnd = dataEnd + (chunkSize & 1);
87
+ if (paddedEnd > bytes.length) throw new Error(`${label} WebP chunk ${type} is truncated`);
88
+ if (type === 'ANIM' || type === 'ANMF') throw new Error(`${label} animated WebP is not allowed`);
89
+ if (type === 'VP8X') {
90
+ if (offset !== 12 || chunkSize !== 10) throw new Error(`${label} WebP VP8X chunk is invalid`);
91
+ const flags = bytes[dataStart];
92
+ if ((flags & 0x02) !== 0) throw new Error(`${label} animated WebP (VP8X animation flag) is not allowed`);
93
+ width = 1 + (bytes[dataStart + 4] | (bytes[dataStart + 5] << 8) | (bytes[dataStart + 6] << 16));
94
+ height = 1 + (bytes[dataStart + 7] | (bytes[dataStart + 8] << 8) | (bytes[dataStart + 9] << 16));
95
+ } else if (type === 'VP8 ' || type === 'VP8L') {
96
+ const frame = bytes.subarray(dataStart, dataEnd);
97
+ const dimensions = webpFrameDimensions(type, frame, label);
98
+ if (hasBitstream || (width !== 0 && (width !== dimensions.width || height !== dimensions.height))) {
99
+ throw new Error(`${label} WebP dimensions are inconsistent`);
100
+ }
101
+ width = dimensions.width;
102
+ height = dimensions.height;
103
+ hasBitstream = true;
104
+ }
105
+ offset = paddedEnd;
106
+ }
107
+ if (!hasBitstream || width <= 0 || height <= 0) throw new Error(`${label} WebP is missing image bitstream or dimensions`);
108
+ assertImageBounds(width, height, bounds, label);
109
+ const { Transformer } = require('@napi-rs/image');
110
+ try {
111
+ const image = new Transformer(bytes);
112
+ const pixels = image.rawPixelsSync();
113
+ const decoded = image.metadataSync();
114
+ if (decoded.width !== width || decoded.height !== height || !pixels.length) throw new Error('invalid decoded image');
115
+ } catch (cause) {
116
+ throw new Error(`${label} WebP pixels could not be decoded`, { cause });
117
+ }
118
+ return { media_type: 'image/webp', width, height, size: bytes.length, sha256 };
119
+ }
120
+
121
+ throw new Error(`${label} must be a static WebP or PNG image`);
122
+ }
123
+
124
+ function webpFrameDimensions(type, frame, label) {
125
+ if (type === 'VP8L') {
126
+ if (frame.length < 5 || frame[0] !== 0x2f) throw new Error(`${label} WebP VP8L header is invalid`);
127
+ const bits = frame.readUInt32LE(1);
128
+ return { width: (bits & 0x3fff) + 1, height: ((bits >>> 14) & 0x3fff) + 1 };
129
+ }
130
+ if (frame.length < 10 || (frame[0] & 1) !== 0 || frame[3] !== 0x9d || frame[4] !== 1 || frame[5] !== 0x2a) {
131
+ throw new Error(`${label} WebP VP8 keyframe header is invalid`);
132
+ }
133
+ return { width: frame.readUInt16LE(6) & 0x3fff, height: frame.readUInt16LE(8) & 0x3fff };
134
+ }
135
+
136
+ function assertImageBounds(width, height, bounds, label) {
137
+ if (width < bounds.minW || width > bounds.maxW || height < bounds.minH || height > bounds.maxH) {
138
+ throw new Error(`${label} dimensions ${width}x${height} are outside allowed bounds (${bounds.minW}-${bounds.maxW} x ${bounds.minH}-${bounds.maxH})`);
139
+ }
140
+ }
141
+
142
+ export function collectStorefrontImageRefs(media) {
143
+ const refs = [];
144
+ if (!media) return refs;
145
+ if (media.cover) {
146
+ refs.push(media.cover.default);
147
+ for (const ref of Object.values(media.cover.locales || {})) refs.push(ref);
148
+ }
149
+ for (const item of media.gallery || []) {
150
+ refs.push(item.default);
151
+ for (const ref of Object.values(item.locales || {})) refs.push(ref);
152
+ }
153
+ return refs;
154
+ }
@@ -0,0 +1,59 @@
1
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.scaffold-web-carrier
2
+ export function isWebCoordinationPath(method, pathname) {
3
+ if (method === 'GET') {
4
+ return pathname === '/api/runtime-access/context'
5
+ || /^\/api\/runtime-access\/connections\/[A-Za-z0-9_-]+$/u.test(pathname)
6
+ || /^\/api\/auth\/runtime-clients\/[A-Za-z0-9_.-]+$/u.test(pathname);
7
+ }
8
+ return method === 'POST' && (pathname === '/api/runtime-access/token'
9
+ || pathname === '/api/runtime-access/context/end'
10
+ || pathname === '/api/runtime-access/connections');
11
+ }
12
+
13
+ function httpsOrigin(value) {
14
+ try {
15
+ const url = new URL(value);
16
+ return url.protocol === 'https:' && url.origin === value ? url.origin : undefined;
17
+ } catch {
18
+ return undefined;
19
+ }
20
+ }
21
+
22
+ function reject(message, status) {
23
+ return new Response(message, { status, headers: { 'Cache-Control': 'no-store' } });
24
+ }
25
+
26
+ export async function handleNimiWebCoordination({ request, env }) {
27
+ const source = new URL(request.url);
28
+ if (!isWebCoordinationPath(request.method, source.pathname)) return reject('Not found', 404);
29
+
30
+ const site = httpsOrigin(env.NIMI_WEB_ORIGIN);
31
+ const realm = httpsOrigin(env.NIMI_REALM_URL);
32
+ if (!site || !realm || site === realm) return reject('Coordination is not configured', 503);
33
+ const origin = request.headers.get('origin');
34
+ if (source.origin !== site || (origin !== null && origin !== site)) return reject('Origin is not allowed', 403);
35
+
36
+ const headers = new Headers();
37
+ for (const name of ['accept', 'authorization', 'content-type', 'origin']) {
38
+ const value = request.headers.get(name);
39
+ if (value !== null) headers.set(name, value);
40
+ }
41
+ const target = new URL(source.pathname + source.search, realm);
42
+ let upstream;
43
+ try {
44
+ upstream = await fetch(target, { method: request.method, headers, body: request.body, redirect: 'manual' });
45
+ } catch {
46
+ return reject('Realm coordination is unavailable', 502);
47
+ }
48
+ if (upstream.status >= 300 && upstream.status < 400) {
49
+ await upstream.body?.cancel();
50
+ return reject('Unexpected coordination redirect', 502);
51
+ }
52
+
53
+ const responseHeaders = new Headers({ 'Cache-Control': 'no-store' });
54
+ for (const name of ['content-type', 'retry-after']) {
55
+ const value = upstream.headers.get(name);
56
+ if (value !== null) responseHeaders.set(name, value);
57
+ }
58
+ return new Response(upstream.body, { status: upstream.status, headers: responseHeaders });
59
+ }
@@ -0,0 +1,23 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import type { UserConfig } from 'vite';
3
+
4
+ export interface NimiWebClientConfig {
5
+ readonly appId: string;
6
+ readonly clientId: string;
7
+ readonly realmEnvironmentId: string;
8
+ readonly officialWebBaseUrl: string;
9
+ readonly realmBaseUrl: string;
10
+ readonly redirectUri: string;
11
+ }
12
+ export function readWebDevelopment(manifest: unknown, options?: { realm?: 'official' | 'local'; env?: Record<string, string | undefined> }): Readonly<{
13
+ site: URL; realm: URL; official: URL; command: string; script: string;
14
+ config: Readonly<NimiWebClientConfig>;
15
+ }>;
16
+ export function isWebCoordinationPath(method: string, url: string): boolean;
17
+ export function webOriginGuard(site: URL): (request: IncomingMessage, response: ServerResponse, next: () => void) => void;
18
+ export function nimiWebViteConfig(options: {
19
+ root: string;
20
+ env?: Record<string, string | undefined>;
21
+ serve?: boolean;
22
+ release?: boolean;
23
+ }): UserConfig;
@@ -0,0 +1,118 @@
1
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.scaffold-web-carrier
2
+ import { isAppId, isClientId } from './app-identifiers.mjs';
3
+ import { hostedWebViteConfig } from './hosted-web-release.mjs';
4
+ import { readFileSync } from 'node:fs';
5
+ import path from 'node:path';
6
+ import { parse as parseYaml } from 'yaml';
7
+ import { isWebCoordinationPath as isCoordinationPath } from './web-coordination.mjs';
8
+ import { resolveDevelopmentRealm } from './development-environment.mjs';
9
+
10
+ function exactOrigin(value, label, requireHttps = false) {
11
+ let url;
12
+ try { url = new URL(value); } catch { throw new Error(`${label} must be an exact origin.`); }
13
+ if (url.origin !== value || url.username || url.password
14
+ || (url.protocol !== 'https:' && !(url.protocol === 'http:' && !requireHttps && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)))) {
15
+ throw new Error(`${label} requires HTTPS (HTTP is allowed only for loopback coordination).`);
16
+ }
17
+ return url;
18
+ }
19
+
20
+ function readWebSource(appId, web, release = false) {
21
+ const site = exactOrigin(web.origin, 'Web origin', true);
22
+ const official = exactOrigin(web.official_web_url, 'Official Web URL', release);
23
+ if (release && [site, official].some(url => /^(?:localhost|.+\.localhost|127\.\d+\.\d+\.\d+|\[::1\])$/u.test(url.hostname))) {
24
+ throw new Error('Web release requires deployed HTTPS origins.');
25
+ }
26
+ if (site.hostname === official.hostname) throw new Error('Use different hostnames for the App and official sign-in; ports do not isolate cookies.');
27
+ const callback = new URL(web.redirect_uri);
28
+ if (callback.origin !== site.origin || callback.username || callback.password || callback.search || callback.hash || callback.href !== web.redirect_uri) {
29
+ throw new Error('Web callback must be an exact URL on the configured HTTPS App origin.');
30
+ }
31
+ if (!isAppId(appId)) throw new Error('Invalid Web app_id.');
32
+ if (!isClientId(web.client_id)) throw new Error('Invalid Web client_id.');
33
+ if (typeof web.realm_environment_id !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/u.test(web.realm_environment_id)) throw new Error('Invalid Web realm_environment_id.');
34
+ return { site, official, config: Object.freeze({
35
+ appId, clientId: web.client_id, realmEnvironmentId: web.realm_environment_id,
36
+ officialWebBaseUrl: official.origin, realmBaseUrl: site.origin, redirectUri: callback.href,
37
+ }) };
38
+ }
39
+
40
+ export function readWebDevelopment(manifest, options = {}) {
41
+ const declaration = manifest?.local_development?.web;
42
+ if (!declaration || typeof declaration !== 'object' || Array.isArray(declaration)) throw new Error('Declare local_development.web in nimi.app.yaml.');
43
+ const selected = resolveDevelopmentRealm(options.realm, options.env);
44
+ const sourceInput = selected.name === 'official' ? declaration : declaration.local;
45
+ if (!sourceInput || typeof sourceInput !== 'object' || Array.isArray(sourceInput)) throw new Error('Declare local_development.web.local for local Realm development.');
46
+ const web = { realm_url: selected.apiOrigin, official_web_url: selected.webOrigin, realm_environment_id: selected.environmentId, ...sourceInput, command: declaration.command };
47
+ if (!web.origin || !web.redirect_uri || !web.client_id) throw new Error(`Configure the exact registered ${selected.name} Web origin, redirect_uri and client_id in nimi.app.yaml; a scaffold is not source admission.`);
48
+ if (selected.name === 'official' && (web.realm_url !== selected.apiOrigin || web.official_web_url !== selected.webOrigin || web.realm_environment_id !== selected.environmentId)) {
49
+ throw new Error('Official Web development must use official Realm configuration; select --realm local for local inputs.');
50
+ }
51
+ const source = readWebSource(manifest.app_id, web);
52
+ const realm = exactOrigin(web.realm_url, 'Realm URL');
53
+ const match = typeof web.command === 'string' && /^pnpm run ([A-Za-z0-9][A-Za-z0-9:_.-]*)$/u.exec(web.command);
54
+ if (!match) throw new Error('Web command must name an App-owned pnpm script.');
55
+ return Object.freeze({ ...source, realm, command: web.command, script: match[1] });
56
+ }
57
+
58
+ export function isWebCoordinationPath(method, url) {
59
+ return isCoordinationPath(method, url.split('?')[0]);
60
+ }
61
+
62
+ export function webOriginGuard(site) {
63
+ return (request, response, next) => {
64
+ const h1 = request.headers.host;
65
+ const host = request.headers[':authority'] ?? h1;
66
+ if (typeof host !== 'string' || host.toLowerCase() !== site.host
67
+ || (h1 !== undefined && (typeof h1 !== 'string' || h1.toLowerCase() !== site.host))) {
68
+ response.writeHead(421, { 'Content-Type': 'text/plain', 'Cache-Control': 'no-store' });
69
+ response.end('Use the configured App origin.'); return;
70
+ }
71
+ if (request.url?.startsWith('/api/') && !isWebCoordinationPath(request.method, request.url)) {
72
+ response.writeHead(404); response.end(); return;
73
+ }
74
+ next();
75
+ };
76
+ }
77
+
78
+ /** Vite configuration for a declared source. Release hosting owns the same
79
+ * bounded coordination routes independently of the development server. */
80
+ export function nimiWebViteConfig({ root, env = process.env, serve = true, release = false }) {
81
+ const manifest = parseYaml(readFileSync(path.join(root, 'nimi.app.yaml'), 'utf8'));
82
+ if (release) {
83
+ if (serve) throw new Error('Web release configuration requires a build.');
84
+ if (Object.hasOwn(manifest, 'public_slug')) return hostedWebViteConfig(manifest, env);
85
+ const required = key => {
86
+ const value = env[key];
87
+ if (typeof value !== 'string' || !value || value !== value.trim()) throw new Error(`Set ${key} for the Web release.`);
88
+ return value;
89
+ };
90
+ const { config } = readWebSource(manifest.app_id, {
91
+ origin: required('NIMI_WEB_ORIGIN'),
92
+ redirect_uri: required('NIMI_WEB_REDIRECT_URI'),
93
+ client_id: required('NIMI_WEB_CLIENT_ID'),
94
+ realm_environment_id: required('NIMI_WEB_REALM_ENVIRONMENT_ID'),
95
+ official_web_url: required('NIMI_WEB_OFFICIAL_WEB_URL'),
96
+ }, true);
97
+ return { define: { __NIMI_APP_WEB_CONFIG__: JSON.stringify(config) } };
98
+ }
99
+ const { site, realm, config } = readWebDevelopment(manifest, { env });
100
+ const define = { __NIMI_APP_WEB_CONFIG__: JSON.stringify(config) };
101
+ if (!serve) return { define };
102
+ if (!env.NIMI_WEB_TLS_KEY || !env.NIMI_WEB_TLS_CERT) throw new Error('Set NIMI_WEB_TLS_KEY and NIMI_WEB_TLS_CERT to browser-trusted certificate files.');
103
+ return {
104
+ define,
105
+ server: {
106
+ host: env.NIMI_WEB_BIND_HOST || '127.0.0.1', port: Number(site.port || 443), strictPort: true,
107
+ https: { key: readFileSync(path.resolve(root, env.NIMI_WEB_TLS_KEY)), cert: readFileSync(path.resolve(root, env.NIMI_WEB_TLS_CERT)) },
108
+ proxy: { '^/api/(runtime-access/|auth/runtime-clients/)': {
109
+ target: realm.origin, changeOrigin: true,
110
+ configure(proxy) {
111
+ proxy.on('proxyReq', request => request.removeHeader('cookie'));
112
+ proxy.on('proxyRes', response => { delete response.headers['set-cookie']; });
113
+ },
114
+ } },
115
+ },
116
+ plugins: [{ name: 'nimi-web-origin', enforce: 'pre', configureServer(server) { server.middlewares.use(webOriginGuard(site)); } }],
117
+ };
118
+ }