@nimiplatform/app-tools 0.1.2 → 0.2.0

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 (120) hide show
  1. package/LICENSE +198 -6
  2. package/README.md +83 -27
  3. package/bin/nimi-app.mjs +328 -45
  4. package/lib/app-access-declaration.mjs +49 -0
  5. package/lib/app-doctor-update.mjs +411 -149
  6. package/lib/app-pack.mjs +401 -0
  7. package/lib/app-project-lifecycle.mjs +1141 -0
  8. package/lib/app-scaffold-capabilities.mjs +769 -0
  9. package/lib/app-scaffold-default-source.mjs +21 -0
  10. package/lib/app-scaffold-profiles.mjs +1093 -0
  11. package/lib/app-scaffold.mjs +1266 -813
  12. package/lib/index.mjs +194 -42
  13. package/lib/simulator-conformance-ast.mjs +498 -0
  14. package/lib/simulator-conformance-css.mjs +116 -0
  15. package/lib/simulator-conformance-graph.mjs +757 -0
  16. package/lib/simulator-conformance.d.mts +14 -0
  17. package/lib/simulator-conformance.mjs +203 -0
  18. package/lib/simulator-css-profile.d.mts +27 -0
  19. package/lib/simulator-css-profile.mjs +531 -0
  20. package/lib/simulator-kit-export-resolution.mjs +70 -0
  21. package/lib/simulator-manifest.mjs +334 -0
  22. package/package.json +66 -3
  23. package/scripts/dev-shell.mjs +465 -0
  24. package/scripts/sync-app-source.mjs +300 -0
  25. package/scripts/sync-scaffold-versions.mjs +91 -0
  26. package/templates/app-source/LICENSE +21 -0
  27. package/templates/app-source/src/ai-studio-core/ai-config.ts +100 -0
  28. package/templates/app-source/src/ai-studio-core/ai-studio-core.css +338 -0
  29. package/templates/app-source/src/ai-studio-core/contexts.tsx +61 -0
  30. package/templates/app-source/src/ai-studio-core/history-policy.ts +447 -0
  31. package/templates/app-source/src/ai-studio-core/history.ts +824 -0
  32. package/templates/app-source/src/ai-studio-core/host-context.tsx +79 -0
  33. package/templates/app-source/src/ai-studio-core/index.ts +214 -0
  34. package/templates/app-source/src/ai-studio-core/messages/en.json +310 -0
  35. package/templates/app-source/src/ai-studio-core/messages/index.ts +47 -0
  36. package/templates/app-source/src/ai-studio-core/messages/zh.json +310 -0
  37. package/templates/app-source/src/ai-studio-core/module-registration.ts +109 -0
  38. package/templates/app-source/src/ai-studio-core/non-success-presentation.ts +65 -0
  39. package/templates/app-source/src/ai-studio-core/parameter-fields.tsx +247 -0
  40. package/templates/app-source/src/ai-studio-core/parameters.ts +110 -0
  41. package/templates/app-source/src/ai-studio-core/prompt-drafts.ts +69 -0
  42. package/templates/app-source/src/ai-studio-core/run-target.ts +123 -0
  43. package/templates/app-source/src/ai-studio-core/runtime-dispatcher.ts +35 -0
  44. package/templates/app-source/src/ai-studio-core/runtime-types.ts +86 -0
  45. package/templates/app-source/src/ai-studio-core/runtime.ts +306 -0
  46. package/templates/app-source/src/ai-studio-core/section-ai-testing-admission.ts +38 -0
  47. package/templates/app-source/src/ai-studio-core/section-ai-testing-ai-config.tsx +30 -0
  48. package/templates/app-source/src/ai-studio-core/section-ai-testing-artifact-preview.ts +40 -0
  49. package/templates/app-source/src/ai-studio-core/section-ai-testing-composer.tsx +257 -0
  50. package/templates/app-source/src/ai-studio-core/section-ai-testing-history.tsx +676 -0
  51. package/templates/app-source/src/ai-studio-core/section-ai-testing-input.ts +19 -0
  52. package/templates/app-source/src/ai-studio-core/section-ai-testing-output.tsx +291 -0
  53. package/templates/app-source/src/ai-studio-core/section-ai-testing-result.tsx +413 -0
  54. package/templates/app-source/src/ai-studio-core/section-ai-testing-run.ts +174 -0
  55. package/templates/app-source/src/ai-studio-core/section-ai-testing-studio-result.tsx +449 -0
  56. package/templates/app-source/src/ai-studio-core/section-ai-testing-surface.tsx +45 -0
  57. package/templates/app-source/src/ai-studio-core/section-ai-testing.tsx +494 -0
  58. package/templates/app-source/src/ai-studio-core/studio-directives.ts +33 -0
  59. package/templates/app-source/src/ai-studio-core/workspace.tsx +381 -0
  60. package/templates/app-source/src/product-modules/agent-center/index.tsx +27 -0
  61. package/templates/app-source/src/product-modules/agent-conversation/index.tsx +19 -0
  62. package/templates/app-source/src/product-modules/agent-realtime/index.tsx +29 -0
  63. package/templates/app-source/src/product-modules/kit-recipes/gallery.tsx +142 -0
  64. package/templates/app-source/src/product-modules/kit-recipes/index.tsx +19 -0
  65. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-data-recipes.tsx +336 -0
  66. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-demos.tsx +165 -0
  67. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-recipes.tsx +682 -0
  68. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-surface.tsx +341 -0
  69. package/templates/app-source/src/studio-modules/studio-create/descriptors.ts +26 -0
  70. package/templates/app-source/src/studio-modules/studio-create/index.ts +14 -0
  71. package/templates/app-source/src/studio-modules/studio-create/messages/en.json +67 -0
  72. package/templates/app-source/src/studio-modules/studio-create/messages/index.ts +5 -0
  73. package/templates/app-source/src/studio-modules/studio-create/messages/zh.json +67 -0
  74. package/templates/app-source/src/studio-modules/studio-create/parameter-panel.tsx +153 -0
  75. package/templates/app-source/src/studio-modules/studio-create/parameters.ts +70 -0
  76. package/templates/app-source/src/studio-modules/studio-create/registration.ts +46 -0
  77. package/templates/app-source/src/studio-modules/studio-create/runtime.ts +339 -0
  78. package/templates/app-source/src/studio-modules/studio-media/descriptors.ts +22 -0
  79. package/templates/app-source/src/studio-modules/studio-media/index.ts +12 -0
  80. package/templates/app-source/src/studio-modules/studio-media/messages/en.json +82 -0
  81. package/templates/app-source/src/studio-modules/studio-media/messages/index.ts +5 -0
  82. package/templates/app-source/src/studio-modules/studio-media/messages/zh.json +82 -0
  83. package/templates/app-source/src/studio-modules/studio-media/parameter-panel.tsx +283 -0
  84. package/templates/app-source/src/studio-modules/studio-media/parameters.ts +94 -0
  85. package/templates/app-source/src/studio-modules/studio-media/registration.ts +44 -0
  86. package/templates/app-source/src/studio-modules/studio-media/runtime.ts +113 -0
  87. package/templates/app-source/src/studio-modules/studio-voice/descriptors.ts +28 -0
  88. package/templates/app-source/src/studio-modules/studio-voice/index.ts +16 -0
  89. package/templates/app-source/src/studio-modules/studio-voice/messages/en.json +99 -0
  90. package/templates/app-source/src/studio-modules/studio-voice/messages/index.ts +5 -0
  91. package/templates/app-source/src/studio-modules/studio-voice/messages/zh.json +99 -0
  92. package/templates/app-source/src/studio-modules/studio-voice/parameter-panel.tsx +284 -0
  93. package/templates/app-source/src/studio-modules/studio-voice/parameters.ts +116 -0
  94. package/templates/app-source/src/studio-modules/studio-voice/registration.ts +59 -0
  95. package/templates/app-source/src/studio-modules/studio-voice/runtime.ts +347 -0
  96. package/templates/app-source/src/workbench-core/empty-state.tsx +31 -0
  97. package/templates/app-source/src/workbench-core/index.ts +17 -0
  98. package/templates/app-source/src/workbench-core/runtime-gate.tsx +131 -0
  99. package/templates/app-source/src/workbench-core/workbench-core.css +255 -0
  100. package/templates/app-source/src/workbench-core/workbench-core.tsx +140 -0
  101. package/templates/app-source.manifest.json +333 -0
  102. package/templates/default-starter/AGENTS.md +33 -0
  103. package/templates/default-starter/LICENSE +21 -0
  104. package/templates/default-starter/README.md +41 -0
  105. package/templates/default-starter/SECURITY.md +5 -0
  106. package/templates/default-starter/index.html +12 -0
  107. package/templates/default-starter/scripts/validate.mjs +26 -0
  108. package/templates/default-starter/src/shell/App.tsx +27 -0
  109. package/templates/default-starter/src/shell/auth/app-identity.ts +3 -0
  110. package/templates/default-starter/src/shell/auth/local-app-client.ts +18 -0
  111. package/templates/default-starter/src/shell/auth/runtime-platform.ts +110 -0
  112. package/templates/default-starter/src/shell/authenticated-shell.tsx +20 -0
  113. package/templates/default-starter/src/shell/workbench-target-adapter.ts +40 -0
  114. package/templates/default-starter/src/styles.css +26 -0
  115. package/templates/default-starter/src-tauri/Cargo.toml +17 -0
  116. package/templates/default-starter/src-tauri/build.rs +5 -0
  117. package/templates/default-starter/src-tauri/capabilities/default.json +7 -0
  118. package/templates/default-starter/src-tauri/tauri.conf.json +26 -0
  119. package/templates/default-starter/tsconfig.json +18 -0
  120. package/templates/default-starter.manifest.json +99 -0
@@ -0,0 +1,531 @@
1
+ import { createRequire } from 'node:module';
2
+ import { existsSync, readFileSync, realpathSync, readdirSync, statSync } from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ import postcss from 'postcss';
6
+ import selectorParser from 'postcss-selector-parser';
7
+ import ts from 'typescript';
8
+
9
+ import { SimulatorConformanceError } from './simulator-manifest.mjs';
10
+
11
+ export const SIMULATOR_CSS_PROFILE_PROTOCOL = 'nimi.simulator.css-profile/v1';
12
+ export const SIMULATOR_CSS_PROFILE_REVISION = 'tailwind-v4-canonical-closure-1';
13
+ export const SIMULATOR_CSS_COMPILER_VERSION = '4.3.3';
14
+ export const SIMULATOR_KIT_FOUNDATION_CSS_EXPORTS = Object.freeze([
15
+ '@nimiplatform/kit/ui/styles.css',
16
+ '@nimiplatform/kit/ui/themes/light.css',
17
+ '@nimiplatform/kit/ui/themes/dark.css',
18
+ '@nimiplatform/kit/ui/themes/nimi-accent.css',
19
+ '@nimiplatform/kit/ui/themes/nimi-density-compact.css',
20
+ '@nimiplatform/kit/auth/styles.css',
21
+ ]);
22
+
23
+ const SCANNER_EXTENSIONS = new Set(['.cjs', '.cts', '.js', '.jsx', '.mjs', '.mts', '.ts', '.tsx']);
24
+ const KIT_SCANNER_EXTENSIONS = new Set(['.cjs', '.js', '.mjs']);
25
+ const DYNAMIC_UTILITY_PREFIX = /(?:^|\s)(?:-?(?:m|p)[trblxy]?|w|h|min-w|max-w|min-h|max-h|bg|text|border|rounded|grid|flex|gap|space-[xy]|inset|top|right|bottom|left|z|opacity|shadow|ring|translate-[xy]|scale|rotate|duration|delay|ease|animate|backdrop-[a-z-]+|overflow|object|items|justify|content|place-[a-z-]+|col|row|font|leading|tracking)-$/u;
26
+
27
+ function fail(code, message, fieldPath = '') {
28
+ throw new SimulatorConformanceError(code, message, fieldPath);
29
+ }
30
+
31
+ function relativePath(rootDir, absolutePath) {
32
+ return path.relative(rootDir, absolutePath).split(path.sep).join('/');
33
+ }
34
+
35
+ function reachableFiles(graph, entry) {
36
+ const queue = [entry];
37
+ const seen = new Set();
38
+ while (queue.length > 0) {
39
+ const current = queue.shift();
40
+ if (seen.has(current)) continue;
41
+ seen.add(current);
42
+ queue.push(...(graph.nodes.get(current)?.imports || []));
43
+ }
44
+ return [...seen];
45
+ }
46
+
47
+ function assertNoDynamicUtilityInterpolation(source, sourcePath) {
48
+ const visit = (node) => {
49
+ if (ts.isTemplateExpression(node)) {
50
+ let preceding = node.head.text;
51
+ for (const span of node.templateSpans) {
52
+ if (DYNAMIC_UTILITY_PREFIX.test(preceding)) {
53
+ fail(
54
+ 'SIM_CSS_DYNAMIC_UTILITY',
55
+ 'Tailwind utility names must be complete literal tokens; dynamic interpolation is forbidden',
56
+ sourcePath,
57
+ );
58
+ }
59
+ preceding = span.literal.text;
60
+ }
61
+ }
62
+ ts.forEachChild(node, visit);
63
+ };
64
+ visit(source);
65
+ }
66
+
67
+ function inputInventory(rootDir, graph, files) {
68
+ return files
69
+ .filter((filePath) => SCANNER_EXTENSIONS.has(path.extname(filePath)))
70
+ .map((filePath) => {
71
+ const node = graph.nodes.get(filePath);
72
+ const relative = relativePath(rootDir, filePath);
73
+ if (!node || node.type !== 'module') fail('SIM_CSS_SCANNER_GRAPH', 'scanner input is absent from the canonical module graph', relative);
74
+ assertNoDynamicUtilityInterpolation(node.source, relative);
75
+ return { path: relative };
76
+ })
77
+ .sort((left, right) => left.path.localeCompare(right.path));
78
+ }
79
+
80
+ export function buildSimulatorCssProfile(input) {
81
+ const compositionInputs = inputInventory(
82
+ input.rootDir,
83
+ input.graph,
84
+ reachableFiles(input.graph, input.factoryPath),
85
+ );
86
+ if (compositionInputs.length === 0) {
87
+ fail('SIM_CSS_SCANNER_EMPTY', 'canonical factory closure has no scanner inputs', input.factoryEntry);
88
+ }
89
+ const scanner = {
90
+ inputs: compositionInputs,
91
+ };
92
+ const foundation = {
93
+ theme_layer: 'simulator.foundation.preflight',
94
+ kit_layer: 'simulator.foundation.kit',
95
+ utility_emission: 'shared-once',
96
+ };
97
+ const utility = {
98
+ owner: input.moduleId,
99
+ layer: `simulator.module.${input.moduleId}`,
100
+ root_class: input.rootClass,
101
+ source: 'canonical-composition-closure',
102
+ };
103
+ const profile = {
104
+ protocol: SIMULATOR_CSS_PROFILE_PROTOCOL,
105
+ revision: SIMULATOR_CSS_PROFILE_REVISION,
106
+ compiler: {
107
+ package: 'tailwindcss',
108
+ version: SIMULATOR_CSS_COMPILER_VERSION,
109
+ },
110
+ scanner,
111
+ foundation,
112
+ utility,
113
+ style: {
114
+ entry: input.styleEntry,
115
+ inputs: input.styleInputs,
116
+ root_class: input.rootClass,
117
+ global_prefix: input.globalPrefix,
118
+ },
119
+ };
120
+ return Object.freeze({
121
+ entry: input.styleEntry,
122
+ inputs: input.styleInputs,
123
+ rootClass: input.rootClass,
124
+ globalPrefix: input.globalPrefix,
125
+ profile: Object.freeze(profile),
126
+ });
127
+ }
128
+
129
+ function walkFiles(rootDir, extensions) {
130
+ const files = [];
131
+ const visit = (directory) => {
132
+ for (const entry of readdirSync(directory, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name))) {
133
+ const absolute = path.join(directory, entry.name);
134
+ if (entry.isDirectory()) visit(absolute);
135
+ else if (entry.isFile() && extensions.has(path.extname(entry.name))) files.push(absolute);
136
+ else if (!entry.isFile()) fail('SIM_CSS_FOUNDATION_FILE_KIND', 'Kit foundation contains an unsupported filesystem entry', absolute);
137
+ }
138
+ };
139
+ visit(rootDir);
140
+ return files;
141
+ }
142
+
143
+ function packageRootFromEntry(entryPath, packageName) {
144
+ let directory = path.dirname(realpathSync(entryPath));
145
+ while (directory !== path.dirname(directory)) {
146
+ const packagePath = path.join(directory, 'package.json');
147
+ if (existsSync(packagePath)) {
148
+ const packageJson = JSON.parse(readFileSync(packagePath, 'utf8'));
149
+ if (packageJson.name === packageName) return directory;
150
+ }
151
+ directory = path.dirname(directory);
152
+ }
153
+ fail('SIM_CSS_PACKAGE_ROOT', `cannot locate installed package root for ${JSON.stringify(packageName)}`);
154
+ }
155
+
156
+ function resolveInstalledPackage(require, packageName) {
157
+ let packageRoot;
158
+ try {
159
+ packageRoot = path.dirname(realpathSync(require.resolve(`${packageName}/package.json`)));
160
+ } catch {
161
+ try {
162
+ packageRoot = packageRootFromEntry(require.resolve(packageName), packageName);
163
+ } catch {
164
+ const candidate = (require.resolve.paths(packageName) || [])
165
+ .map((modulesRoot) => path.join(modulesRoot, ...packageName.split('/')))
166
+ .find((root) => existsSync(path.join(root, 'package.json')));
167
+ if (!candidate) fail('SIM_CSS_PACKAGE_ROOT', `cannot resolve installed package ${JSON.stringify(packageName)}`);
168
+ packageRoot = realpathSync(candidate);
169
+ }
170
+ }
171
+ const packagePath = path.join(packageRoot, 'package.json');
172
+ const bytes = readFileSync(packagePath);
173
+ const packageJson = JSON.parse(bytes.toString('utf8'));
174
+ return {
175
+ packageRoot,
176
+ packageJson,
177
+ };
178
+ }
179
+
180
+ function cssExportTargets(packageRoot, packageJson) {
181
+ const targets = [];
182
+ for (const [specifier, value] of Object.entries(packageJson.exports || {})) {
183
+ if (typeof value !== 'string' || !value.endsWith('.css')) continue;
184
+ const absolute = realpathSync(path.resolve(packageRoot, value));
185
+ const relative = relativePath(packageRoot, absolute);
186
+ if (relative.startsWith('../')) fail('SIM_CSS_KIT_EXPORT_ESCAPE', 'Kit CSS export escapes its package root', specifier);
187
+ const closure = kitCssClosure(packageRoot, absolute, specifier);
188
+ targets.push({
189
+ specifier,
190
+ target: relative,
191
+ closure,
192
+ });
193
+ }
194
+ return targets.sort((left, right) => left.specifier.localeCompare(right.specifier));
195
+ }
196
+
197
+ function cssImportSpecifier(params) {
198
+ return params.trim().match(/^(?:url\(\s*)?['"]([^'"]+)['"]\s*\)?/u)?.[1] || '';
199
+ }
200
+
201
+ function kitCssImportSpecifier(params, fieldPath) {
202
+ const trimmed = params.trim();
203
+ const match = trimmed.match(/^(['"])([^'"]+)\1$/u)
204
+ ?? trimmed.match(/^url\(\s*(['"])([^'"]+)\1\s*\)$/u);
205
+ if (!match) {
206
+ fail('SIM_CSS_KIT_IMPORT', 'Kit CSS imports must be exact static quoted paths without conditions or modifiers', fieldPath);
207
+ }
208
+ const specifier = match[2];
209
+ if (
210
+ !specifier.startsWith('./')
211
+ && !specifier.startsWith('../')
212
+ ) {
213
+ fail('SIM_CSS_KIT_IMPORT', 'Kit CSS imports must be relative package-local paths', fieldPath);
214
+ }
215
+ if (specifier.includes('?') || specifier.includes('#') || path.extname(specifier) !== '.css') {
216
+ fail('SIM_CSS_KIT_IMPORT', 'Kit CSS imports must resolve directly to a CSS file', fieldPath);
217
+ }
218
+ return specifier;
219
+ }
220
+
221
+ function kitCssClosure(packageRoot, entryPath, exportSpecifier) {
222
+ const absoluteRoot = realpathSync(packageRoot);
223
+ const queue = [realpathSync(entryPath)];
224
+ const seen = new Set();
225
+ const rows = [];
226
+ while (queue.length > 0) {
227
+ const current = queue.shift();
228
+ if (seen.has(current)) continue;
229
+ seen.add(current);
230
+ const relative = relativePath(absoluteRoot, current);
231
+ if (relative.startsWith('../') || path.isAbsolute(relative)) {
232
+ fail('SIM_CSS_KIT_EXPORT_ESCAPE', 'Kit CSS closure escapes its package root', exportSpecifier);
233
+ }
234
+ const code = readFileSync(current, 'utf8');
235
+ rows.push({ path: relative });
236
+ const css = postcss.parse(code, { from: current });
237
+ css.walkAtRules('import', (rule) => {
238
+ const imported = kitCssImportSpecifier(rule.params, `${exportSpecifier}:${relative}`);
239
+ let target;
240
+ try {
241
+ target = realpathSync(path.resolve(path.dirname(current), imported));
242
+ } catch {
243
+ fail('SIM_CSS_KIT_IMPORT_MISSING', 'Kit CSS import target does not exist', `${exportSpecifier}:${relative}`);
244
+ }
245
+ const targetRelative = relativePath(absoluteRoot, target);
246
+ if (targetRelative.startsWith('../') || path.isAbsolute(targetRelative)) {
247
+ fail('SIM_CSS_KIT_EXPORT_ESCAPE', 'Kit CSS import escapes its package root', `${exportSpecifier}:${relative}`);
248
+ }
249
+ queue.push(target);
250
+ });
251
+ }
252
+ return rows.sort((left, right) => left.path.localeCompare(right.path));
253
+ }
254
+
255
+ function resolveKitCssExports(kitRoot) {
256
+ const absoluteRoot = realpathSync(kitRoot);
257
+ const packageJson = JSON.parse(readFileSync(path.join(absoluteRoot, 'package.json'), 'utf8'));
258
+ return Object.freeze(cssExportTargets(absoluteRoot, packageJson));
259
+ }
260
+
261
+ export function assertSimulatorFoundationEntry(code, filePath) {
262
+ const css = postcss.parse(code, { from: filePath });
263
+ const imports = [];
264
+ css.walkAtRules('import', (rule) => {
265
+ if (rule.parent !== css) {
266
+ fail('SIM_CSS_FOUNDATION_IMPORTS', 'foundation imports must be top-level', filePath);
267
+ }
268
+ imports.push({ specifier: cssImportSpecifier(rule.params), params: rule.params.trim() });
269
+ });
270
+ const expectedSpecifiers = [...SIMULATOR_KIT_FOUNDATION_CSS_EXPORTS, 'tailwindcss'];
271
+ const actualSpecifiers = imports.map((entry) => entry.specifier);
272
+ if (JSON.stringify(actualSpecifiers) !== JSON.stringify(expectedSpecifiers)) {
273
+ fail('SIM_CSS_FOUNDATION_IMPORTS', 'foundation entry must contain only the exact protocol-owned CSS import sequence', filePath);
274
+ }
275
+ for (const [index, specifier] of SIMULATOR_KIT_FOUNDATION_CSS_EXPORTS.entries()) {
276
+ if (![JSON.stringify(specifier), `'${specifier}'`].includes(imports[index].params)) {
277
+ fail('SIM_CSS_FOUNDATION_IMPORTS', 'Kit foundation imports cannot carry conditions or layer modifiers', filePath);
278
+ }
279
+ }
280
+ const tailwindImport = imports.at(-1);
281
+ if (!tailwindImport
282
+ || !["'tailwindcss' source(none)", '"tailwindcss" source(none)'].includes(tailwindImport.params)) {
283
+ fail('SIM_CSS_FOUNDATION_TAILWIND', 'foundation entry must import tailwindcss source(none) exactly once', filePath);
284
+ }
285
+ }
286
+
287
+ function resolveSimulatorCssCompiler(compilerRoot) {
288
+ const require = createRequire(path.join(path.resolve(compilerRoot), 'package.json'));
289
+ const tailwind = resolveInstalledPackage(require, 'tailwindcss');
290
+ const packageRoot = tailwind.packageRoot;
291
+ const packageJson = tailwind.packageJson;
292
+ const themePath = path.join(packageRoot, 'theme.css');
293
+ const themeBytes = readFileSync(themePath);
294
+ if (packageJson.version !== SIMULATOR_CSS_COMPILER_VERSION) {
295
+ fail('SIM_CSS_COMPILER_VERSION', `CSS profile requires tailwindcss@${SIMULATOR_CSS_COMPILER_VERSION}`);
296
+ }
297
+ return Object.freeze({
298
+ themeReference: themeBytes.toString('utf8').replace('@theme default {', '@theme reference {'),
299
+ });
300
+ }
301
+
302
+ function findKitFoundationScannerInputs(kitRoot) {
303
+ const absoluteRoot = realpathSync(kitRoot);
304
+ const distRoot = path.join(absoluteRoot, 'dist');
305
+ if (!existsSync(distRoot) || !statSync(distRoot).isDirectory()) {
306
+ fail('SIM_CSS_KIT_DIST', 'Kit dist is required before CSS profile construction');
307
+ }
308
+ const inputs = walkFiles(distRoot, KIT_SCANNER_EXTENSIONS)
309
+ .map((filePath) => ({ path: relativePath(absoluteRoot, filePath) }));
310
+ return Object.freeze({
311
+ inputs,
312
+ });
313
+ }
314
+
315
+ function sourceDirective(fromFile, targetFile) {
316
+ let relative = path.relative(path.dirname(fromFile), targetFile).split(path.sep).join('/');
317
+ if (!relative.startsWith('.')) relative = `./${relative}`;
318
+ return `@source ${JSON.stringify(relative)};`;
319
+ }
320
+
321
+ function stripQuery(id) {
322
+ return id.split('?', 1)[0];
323
+ }
324
+
325
+ function cssAssetSource(asset) {
326
+ if (typeof asset.source === 'string') return asset.source;
327
+ return Buffer.from(asset.source).toString('utf8');
328
+ }
329
+
330
+ function moduleSelectorRows(root, style) {
331
+ const rootClass = style.rootClass;
332
+ const globalPrefix = style.globalPrefix;
333
+ const rootScope = `(.${rootClass})`;
334
+ const rows = [];
335
+ root.walkRules((rule) => {
336
+ const atRules = [];
337
+ let parent = rule.parent;
338
+ let insideRootScope = false;
339
+ let insideKeyframes = false;
340
+ while (parent) {
341
+ if (parent.type === 'atrule') {
342
+ const name = parent.name.toLowerCase();
343
+ if (/keyframes$/u.test(name)) insideKeyframes = true;
344
+ if (name === 'scope' && parent.params.trim() === rootScope) insideRootScope = true;
345
+ atRules.push(`@${name}${parent.params.trim() ? ` ${parent.params.trim()}` : ''}`);
346
+ }
347
+ parent = parent.parent;
348
+ }
349
+ if (insideKeyframes) return;
350
+ const context = atRules.reverse();
351
+ selectorParser((selectors) => {
352
+ selectors.each((selector) => {
353
+ const classes = [];
354
+ selector.walkClasses((classNode) => classes.push(classNode.value));
355
+ const moduleOwned = insideRootScope
356
+ || classes.includes(rootClass)
357
+ || classes.some((className) => className.startsWith(globalPrefix));
358
+ if (moduleOwned) rows.push({ context, selector: selector.toString() });
359
+ });
360
+ }).processSync(rule.selector);
361
+ });
362
+ const unique = new Map(rows.map((row) => [JSON.stringify(row), row]));
363
+ return [...unique.values()].sort((left, right) => JSON.stringify(left).localeCompare(JSON.stringify(right)));
364
+ }
365
+
366
+ function postprocessSimulatorCssBundle(bundle, profileEntries) {
367
+ const cssAssets = [];
368
+ for (const output of Object.values(bundle)) {
369
+ if (output.type !== 'asset' || !output.fileName.endsWith('.css')) continue;
370
+ cssAssets.push({ output, root: postcss.parse(cssAssetSource(output), { from: output.fileName }) });
371
+ }
372
+ const assigned = new Map();
373
+ for (const { style } of profileEntries) {
374
+ const layer = style.profile.utility.layer;
375
+ const matches = cssAssets.filter(({ root }) => {
376
+ let found = false;
377
+ root.walkAtRules('layer', (rule) => {
378
+ if (rule.params.trim() === layer) found = true;
379
+ });
380
+ return found;
381
+ });
382
+ if (matches.length !== 1) {
383
+ fail('SIM_CSS_MODULE_ASSET', `CSS profile ${JSON.stringify(layer)} must resolve to exactly one lazy asset`);
384
+ }
385
+ assigned.set(style.profile.utility.owner, matches[0]);
386
+ }
387
+ const moduleAssets = new Set(assigned.values());
388
+ if (moduleAssets.size !== assigned.size) {
389
+ fail('SIM_CSS_MODULE_ASSET_SHARED', 'each App CSS profile must resolve to its own lazy asset');
390
+ }
391
+ const foundationProperties = new Set();
392
+ for (const asset of cssAssets) {
393
+ if (moduleAssets.has(asset)) continue;
394
+ asset.root.walkAtRules('property', (rule) => {
395
+ const name = rule.params.trim();
396
+ if (name.startsWith('--tw-')) foundationProperties.add(name);
397
+ });
398
+ }
399
+ for (const { style } of profileEntries) {
400
+ const moduleId = style.profile.utility.owner;
401
+ const asset = assigned.get(moduleId);
402
+ const properties = new Set();
403
+ asset.root.walkAtRules('property', (rule) => {
404
+ const name = rule.params.trim();
405
+ if (name.startsWith('--tw-')) properties.add(name);
406
+ });
407
+ const missing = [...properties].filter((name) => !foundationProperties.has(name)).sort();
408
+ if (missing.length > 0) {
409
+ fail(
410
+ 'SIM_CSS_FOUNDATION_PROPERTY_MISSING',
411
+ `module ${JSON.stringify(moduleId)} requires Tailwind properties absent from the shared foundation: ${missing.join(', ')}`,
412
+ );
413
+ }
414
+ asset.root.walkAtRules('layer', (rule) => {
415
+ if (rule.params.trim() === 'properties') rule.remove();
416
+ });
417
+ asset.root.walkAtRules('property', (rule) => {
418
+ if (rule.params.trim().startsWith('--tw-')) rule.remove();
419
+ });
420
+ const layer = style.profile.utility.layer;
421
+ const rootScope = `(.${style.rootClass})`;
422
+ asset.root.walkAtRules('layer', (layerRule) => {
423
+ if (layerRule.params.trim() !== layer) return;
424
+ layerRule.walkRules((rule) => {
425
+ let parent = rule.parent;
426
+ let scoped = false;
427
+ while (parent && parent !== layerRule) {
428
+ if (parent.type === 'atrule' && parent.name === 'scope' && parent.params.trim() === rootScope) scoped = true;
429
+ parent = parent.parent;
430
+ }
431
+ if (!scoped) fail('SIM_CSS_UTILITY_SCOPE', `generated utility selector ${JSON.stringify(rule.selector)} is outside ${rootScope}`);
432
+ });
433
+ });
434
+ const output = asset.root.toString();
435
+ asset.output.source = output;
436
+ const selectorsOutsideCanonicalAsset = cssAssets
437
+ .filter((candidate) => candidate !== asset)
438
+ .flatMap((candidate) => moduleSelectorRows(candidate.root, style));
439
+ if (selectorsOutsideCanonicalAsset.length > 0) {
440
+ fail(
441
+ 'SIM_CSS_MODULE_SELECTOR_SPLIT',
442
+ `module ${JSON.stringify(moduleId)} selectors escaped the canonical CSS asset`,
443
+ );
444
+ }
445
+ }
446
+ }
447
+
448
+ export function createSimulatorCssProfileVitePlugin(options) {
449
+ const compiler = resolveSimulatorCssCompiler(options.compilerRoot);
450
+ const kitRoot = realpathSync(path.join(options.compilerRoot, 'node_modules', '@nimiplatform', 'kit'));
451
+ const foundation = findKitFoundationScannerInputs(kitRoot);
452
+ const foundationEntry = realpathSync(options.foundationEntry);
453
+ const kitCssRoot = path.join(kitRoot, 'dist');
454
+ const kitCssInputs = new Map();
455
+ for (const exported of resolveKitCssExports(kitRoot)) {
456
+ for (const input of exported.closure) {
457
+ const absolute = realpathSync(path.join(kitRoot, ...input.path.split('/')));
458
+ kitCssInputs.set(absolute, input);
459
+ }
460
+ }
461
+ const profiles = new Map();
462
+ for (const entry of options.apps) {
463
+ const rootDir = realpathSync(entry.rootDir);
464
+ const style = entry.style;
465
+ const stylePath = realpathSync(path.join(rootDir, ...style.entry.split('/')));
466
+ profiles.set(stylePath, { rootDir, style });
467
+ for (const input of style.inputs) {
468
+ const absolute = realpathSync(path.join(rootDir, ...input.path.split('/')));
469
+ if (absolute !== rootDir && !absolute.startsWith(`${rootDir}${path.sep}`)) {
470
+ fail('SIM_CSS_APP_INPUT_ESCAPE', 'App CSS input escapes its source root', input.path);
471
+ }
472
+ }
473
+ }
474
+ const profileEntries = [...profiles.values()].map(({ style }) => ({ style }));
475
+ return {
476
+ name: 'nimi-simulator-css-profile',
477
+ enforce: 'pre',
478
+ transform(code, id) {
479
+ const filePath = stripQuery(id);
480
+ let real;
481
+ try {
482
+ real = realpathSync(filePath);
483
+ } catch {
484
+ return null;
485
+ }
486
+ if (real.startsWith(`${kitCssRoot}${path.sep}`) && real.endsWith('.css')) {
487
+ const input = kitCssInputs.get(real);
488
+ if (!input) {
489
+ fail('SIM_CSS_KIT_INPUT_UNQUALIFIED', 'build reached Kit CSS outside the canonical export closure', relativePath(kitRoot, real));
490
+ }
491
+ const css = postcss.parse(code, { from: real });
492
+ css.walkAtRules('source', (rule) => rule.remove());
493
+ return { code: css.toString(), map: null };
494
+ }
495
+ if (real === foundationEntry) {
496
+ assertSimulatorFoundationEntry(code, real);
497
+ const directives = foundation.inputs.map((input) => sourceDirective(
498
+ real,
499
+ path.join(kitRoot, ...input.path.split('/')),
500
+ ));
501
+ return {
502
+ code: `${code}\n/* ${SIMULATOR_CSS_PROFILE_PROTOCOL} Kit foundation */\n${directives.join('\n')}\n`,
503
+ map: null,
504
+ };
505
+ }
506
+ const profile = profiles.get(real);
507
+ if (!profile) return null;
508
+ const { style, rootDir } = profile;
509
+ const directives = style.profile.scanner.inputs.map((input) => sourceDirective(
510
+ real,
511
+ path.join(rootDir, ...input.path.split('/')),
512
+ ));
513
+ const layer = style.profile.utility.layer;
514
+ const rootClass = style.rootClass;
515
+ const generated = [
516
+ `/* ${SIMULATOR_CSS_PROFILE_PROTOCOL} */`,
517
+ compiler.themeReference,
518
+ ...directives,
519
+ `@layer ${layer} {`,
520
+ ` @scope (.${rootClass}) {`,
521
+ ' @tailwind utilities source(none);',
522
+ ' }',
523
+ '}',
524
+ ].join('\n');
525
+ return { code: `${code}\n${generated}\n`, map: null };
526
+ },
527
+ generateBundle(_outputOptions, bundle) {
528
+ postprocessSimulatorCssBundle(bundle, profileEntries);
529
+ },
530
+ };
531
+ }
@@ -0,0 +1,70 @@
1
+ import { readFileSync, realpathSync, statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { SimulatorConformanceError } from './simulator-manifest.mjs';
5
+
6
+ export const SIMULATOR_CANONICAL_KIT_EXPORT_REQUIREMENTS = Object.freeze([
7
+ Object.freeze({
8
+ subpath: './features/agent-center',
9
+ exports: Object.freeze(['createAppAgentCenterSession', 'AppAgentCenterEntry']),
10
+ }),
11
+ Object.freeze({
12
+ subpath: './features/chat',
13
+ exports: Object.freeze(['AppConversationEntry', 'createBrowserAppConversationHostPort']),
14
+ }),
15
+ Object.freeze({
16
+ subpath: './features/agent-realtime',
17
+ exports: Object.freeze(['AgentRealtimeEntry', 'createBrowserAgentRealtimeHostMediaPort']),
18
+ }),
19
+ ]);
20
+
21
+ function fail(code, message, fieldPath = '') {
22
+ throw new SimulatorConformanceError(code, message, fieldPath);
23
+ }
24
+
25
+ function exactPackageTarget(packageRoot, value, fieldPath) {
26
+ if (typeof value !== 'string' || !value.startsWith('./') || value.includes('..') || value.includes('\\')) {
27
+ fail('SIM_KIT_EXPORT_TARGET_INVALID', 'Kit package export target is invalid', fieldPath);
28
+ }
29
+ const root = realpathSync(packageRoot);
30
+ const absolute = path.resolve(root, value);
31
+ if (!absolute.startsWith(`${root}${path.sep}`)) {
32
+ fail('SIM_KIT_EXPORT_TARGET_ESCAPE', 'Kit package export target escapes its package root', fieldPath);
33
+ }
34
+ try {
35
+ if (!statSync(absolute).isFile()) fail('SIM_KIT_EXPORT_TARGET_MISSING', 'Kit package export target is not a file', fieldPath);
36
+ } catch {
37
+ fail('SIM_KIT_EXPORT_TARGET_MISSING', 'Kit package export target is missing', fieldPath);
38
+ }
39
+ return realpathSync(absolute);
40
+ }
41
+
42
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-scaf-019c
43
+ export async function validateSimulatorCanonicalKitExports(input) {
44
+ const packageRoot = realpathSync(String(input?.kitPackageRoot || ''));
45
+ const requirements = input?.requirements ?? SIMULATOR_CANONICAL_KIT_EXPORT_REQUIREMENTS;
46
+ if (!Array.isArray(requirements) || requirements.length === 0) {
47
+ fail('SIM_KIT_EXPORT_REQUIREMENTS_INVALID', 'Canonical Kit export requirements are missing');
48
+ }
49
+ const packageJson = JSON.parse(readFileSync(path.join(packageRoot, 'package.json'), 'utf8'));
50
+ const resolved = [];
51
+ for (const requirement of requirements) {
52
+ const subpath = String(requirement?.subpath || '');
53
+ const names = requirement?.exports;
54
+ if (!subpath.startsWith('./') || !Array.isArray(names) || names.length === 0
55
+ || names.some((name) => typeof name !== 'string' || !name || name !== name.trim())) {
56
+ fail('SIM_KIT_EXPORT_REQUIREMENTS_INVALID', 'Canonical Kit export requirement is invalid', subpath);
57
+ }
58
+ const row = packageJson.exports?.[subpath];
59
+ const importTarget = typeof row === 'string' ? row : row?.import ?? row?.default;
60
+ const target = exactPackageTarget(packageRoot, importTarget, subpath);
61
+ const module = await import(`${pathToFileURL(target).href}?simulator-conformance=${encodeURIComponent(subpath)}`);
62
+ for (const name of names) {
63
+ if (!Object.hasOwn(module, name) || typeof module[name] === 'undefined') {
64
+ fail('SIM_KIT_EXPORT_MISSING', `Kit ${subpath} does not export ${name}`, `${subpath}.${name}`);
65
+ }
66
+ }
67
+ resolved.push(Object.freeze({ subpath, exports: Object.freeze([...names]), target }));
68
+ }
69
+ return Object.freeze(resolved);
70
+ }