@bitakit/core 0.1.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 (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +382 -0
  3. package/discovery/entries.mjs +124 -0
  4. package/discovery/generate.mjs +327 -0
  5. package/discovery/host.mjs +12 -0
  6. package/discovery/index.d.ts +41 -0
  7. package/discovery/index.mjs +4 -0
  8. package/discovery/modules.mjs +13 -0
  9. package/discovery/packages.mjs +57 -0
  10. package/discovery/watch.mjs +23 -0
  11. package/dist/actions/action-list.d.ts +69 -0
  12. package/dist/actions/action-list.js +247 -0
  13. package/dist/actions/action.d.ts +96 -0
  14. package/dist/actions/action.js +145 -0
  15. package/dist/actions/base/url-action.d.ts +8 -0
  16. package/dist/actions/base/url-action.js +15 -0
  17. package/dist/actions/core.d.ts +14 -0
  18. package/dist/actions/core.js +8 -0
  19. package/dist/actions/dependencies.d.ts +8 -0
  20. package/dist/actions/dependencies.js +34 -0
  21. package/dist/actions/execution.d.ts +4 -0
  22. package/dist/actions/execution.js +64 -0
  23. package/dist/actions/feedback.d.ts +17 -0
  24. package/dist/actions/feedback.js +21 -0
  25. package/dist/actions/groups.d.ts +13 -0
  26. package/dist/actions/groups.js +21 -0
  27. package/dist/actions/instance-bindings.d.ts +16 -0
  28. package/dist/actions/instance-bindings.js +93 -0
  29. package/dist/actions/interceptors.d.ts +24 -0
  30. package/dist/actions/interceptors.js +42 -0
  31. package/dist/actions/navigation.d.ts +12 -0
  32. package/dist/actions/navigation.js +42 -0
  33. package/dist/actions/reference.d.ts +17 -0
  34. package/dist/actions/reference.js +39 -0
  35. package/dist/actions/state.d.ts +11 -0
  36. package/dist/actions/state.js +8 -0
  37. package/dist/actions/types.d.ts +99 -0
  38. package/dist/actions/types.js +1 -0
  39. package/dist/app/access.d.ts +4 -0
  40. package/dist/app/access.js +85 -0
  41. package/dist/app/action-access.d.ts +4 -0
  42. package/dist/app/action-access.js +20 -0
  43. package/dist/app/service-error.d.ts +8 -0
  44. package/dist/app/service-error.js +19 -0
  45. package/dist/app/types.d.ts +47 -0
  46. package/dist/app/types.js +1 -0
  47. package/dist/config-service.d.ts +49 -0
  48. package/dist/config-service.js +83 -0
  49. package/dist/configuration.d.ts +4 -0
  50. package/dist/configuration.js +42 -0
  51. package/dist/confirmation.d.ts +14 -0
  52. package/dist/confirmation.js +26 -0
  53. package/dist/contracts.d.ts +27 -0
  54. package/dist/contracts.js +3 -0
  55. package/dist/contribution-origin.d.ts +3 -0
  56. package/dist/contribution-origin.js +13 -0
  57. package/dist/contributions/command.d.ts +8 -0
  58. package/dist/contributions/command.js +50 -0
  59. package/dist/contributions/dialog.d.ts +8 -0
  60. package/dist/contributions/dialog.js +18 -0
  61. package/dist/contributions/form.d.ts +10 -0
  62. package/dist/contributions/form.js +67 -0
  63. package/dist/contributions/host.d.ts +40 -0
  64. package/dist/contributions/host.js +1 -0
  65. package/dist/contributions/index.d.ts +26 -0
  66. package/dist/contributions/index.js +18 -0
  67. package/dist/contributions/native.d.ts +11 -0
  68. package/dist/contributions/native.js +87 -0
  69. package/dist/contributions/shared.d.ts +19 -0
  70. package/dist/contributions/shared.js +48 -0
  71. package/dist/contributions/stateful-action.d.ts +29 -0
  72. package/dist/contributions/stateful-action.js +33 -0
  73. package/dist/conventions.d.ts +4 -0
  74. package/dist/conventions.js +38 -0
  75. package/dist/core.d.ts +21 -0
  76. package/dist/core.js +18 -0
  77. package/dist/definitions.d.ts +356 -0
  78. package/dist/definitions.js +60 -0
  79. package/dist/discovered.d.ts +49 -0
  80. package/dist/discovered.js +120 -0
  81. package/dist/interceptors/service-observers.d.ts +3 -0
  82. package/dist/interceptors/service-observers.js +80 -0
  83. package/dist/interceptors/service.d.ts +37 -0
  84. package/dist/interceptors/service.js +7 -0
  85. package/dist/messages.d.ts +9 -0
  86. package/dist/messages.js +21 -0
  87. package/dist/metadata.d.ts +3 -0
  88. package/dist/metadata.js +13 -0
  89. package/dist/pages.d.ts +8 -0
  90. package/dist/pages.js +22 -0
  91. package/dist/presentation.d.ts +4 -0
  92. package/dist/presentation.js +1 -0
  93. package/dist/replacements.d.ts +22 -0
  94. package/dist/replacements.js +54 -0
  95. package/dist/runtime.d.ts +88 -0
  96. package/dist/runtime.js +445 -0
  97. package/dist/scope.d.ts +34 -0
  98. package/dist/scope.js +78 -0
  99. package/dist/service-key.d.ts +13 -0
  100. package/dist/service-key.js +14 -0
  101. package/dist/services.d.ts +6 -0
  102. package/dist/services.js +53 -0
  103. package/dist/translation.d.ts +13 -0
  104. package/dist/translation.js +43 -0
  105. package/dist/validation.d.ts +2 -0
  106. package/dist/validation.js +16 -0
  107. package/docs/file-contributions.md +161 -0
  108. package/package.json +48 -0
@@ -0,0 +1,327 @@
1
+ import { readFile, writeFile, mkdir, realpath } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { files, discoverEntries, contributionKindSpecs } from './entries.mjs';
4
+ import { createJiti } from 'jiti';
5
+ import { installedContributions } from './packages.mjs';
6
+ import { pluginManifests } from './modules.mjs';
7
+ const quote = JSON.stringify;
8
+ async function writeChanged(file, content) {
9
+ if ((await readFile(file, 'utf8').catch(() => null)) !== content) await writeFile(file, content);
10
+ }
11
+ /** Only static imports are generated. Services/actions are never executed by discovery. */
12
+ export async function generateFoundation(root) {
13
+ root = await realpath(root);
14
+ const jiti = createJiti(import.meta.url, {
15
+ moduleCache: false,
16
+ fsCache: false,
17
+ });
18
+ const configFile = path.join(root, 'foundation.config.ts');
19
+ // Missing customization is the default case; errors inside an existing config must propagate.
20
+ const config = await readFile(configFile, 'utf8')
21
+ .then(() => jiti.import(configFile, { default: true }))
22
+ .catch((error) => {
23
+ if (error.code === 'ENOENT' && error.path === configFile) return {};
24
+ throw error;
25
+ });
26
+ const directory = path.resolve(root, config.plugins?.directory ?? './src/plugins');
27
+ const installed = await installedContributions(root, config.packages, jiti);
28
+ const output = path.join(root, '.foundation');
29
+ await mkdir(output, { recursive: true });
30
+ const roots = pluginManifests(directory, await files(directory));
31
+ const imports = [];
32
+ const definitions = [];
33
+ const serviceTypes = [];
34
+ const publicServiceTypes = [];
35
+ const publicServicesByModule = new Map();
36
+ const configTypes = [];
37
+ const allMessages = {};
38
+ const pluginIds = new Set();
39
+ let serial = 0;
40
+ const importFile = (file) => {
41
+ const name = `entry${serial++}`;
42
+ let relative = path
43
+ .relative(output, file)
44
+ .replaceAll(path.sep, '/')
45
+ .replace(/\.tsx?$/, '');
46
+ if (!relative.startsWith('.')) relative = `./${relative}`;
47
+ imports.push(`import ${name} from ${quote(relative)};`);
48
+ return name;
49
+ };
50
+ const conventions = config.conventions !== false;
51
+ // Explicit discovery configuration replaces package defaults by contribution kind.
52
+ const kinds = contributionKindSpecs([
53
+ ...new Map(
54
+ [...contributionKindSpecs(installed.kinds), ...contributionKindSpecs(config.kinds)].map(
55
+ (kind) => [kind.name, kind],
56
+ ),
57
+ ).values(),
58
+ ]);
59
+ const normalizers = new Map();
60
+ const contributionTypes = new Map();
61
+ /** Emits `{ kind: normalize([files], moduleId) }` for kinds with files; normalizers run at import time. */
62
+ const contributions = (entriesByKind, moduleId) => {
63
+ const parts = [];
64
+ kinds.forEach((kind, index) => {
65
+ const entries = entriesByKind[index];
66
+ if (!entries.length) return;
67
+ if (!normalizers.has(kind.name)) {
68
+ const alias = `normalize${index}`;
69
+ imports.push(`import { ${kind.normalize} as ${alias} } from ${quote(kind.from)};`);
70
+ normalizers.set(kind.name, alias);
71
+ }
72
+ const names = fileEntries(entries);
73
+ if (kind.types) {
74
+ if (!contributionTypes.has(kind.name)) {
75
+ imports.push(
76
+ `import type { ${kind.types.entry} as KindEntry${index} } from ${quote(kind.from)};`,
77
+ );
78
+ contributionTypes.set(kind.name, { kind, index, entries: [] });
79
+ }
80
+ contributionTypes
81
+ .get(kind.name)
82
+ .entries.push(
83
+ ...names.map((name) => `KindEntry${index}<typeof ${name}, ${quote(moduleId)}>`),
84
+ );
85
+ }
86
+ parts.push(
87
+ `${quote(kind.name)}: ${normalizers.get(kind.name)}([${names}], ${quote(moduleId)})`,
88
+ );
89
+ });
90
+ return `{ ${parts.join(', ')} }`;
91
+ };
92
+ const actionTypes = [];
93
+ const moduleRoots = new Set(roots.map((file) => path.dirname(file)));
94
+ const appRoot = path.resolve(root, config.directory ?? './src');
95
+ const appManifestFile = path.join(appRoot, 'plugin.config.ts');
96
+ const appManifest = await readFile(appManifestFile, 'utf8')
97
+ .then(() => jiti.import(appManifestFile, { default: true }))
98
+ .catch((error) => {
99
+ if (error.code === 'ENOENT') return {};
100
+ throw error;
101
+ });
102
+ const appId = appManifest.id ?? '@foundation/app';
103
+ if (appId !== '@foundation/app' && !/^[a-z][a-z0-9-]*$/.test(appId))
104
+ throw new Error(`Invalid app module ID: ${appId}`);
105
+ pluginIds.add(appId);
106
+ const enabledModuleIds = new Set([appId]);
107
+ const appFiles = await files(appRoot, moduleRoots);
108
+ const fileEntries = (entries) =>
109
+ entries.map((entry) => {
110
+ const imported = importFile(entry.file);
111
+ const name = `file${serial++}`;
112
+ imports.push(
113
+ `const ${name} = discoveredFile(${imported}, ${quote(entry.path.join('.'))}, ${quote(entry.source)});`,
114
+ );
115
+ return name;
116
+ });
117
+ const emit = (kind, entries, moduleId = '') => {
118
+ const names = fileEntries(entries);
119
+ if (kind === 'actions')
120
+ for (const name of names)
121
+ actionTypes.push(
122
+ `DiscoveredActionEntry<typeof ${name}, ${quote(moduleId)}, ${conventions}>`,
123
+ );
124
+ if (kind === 'services') {
125
+ publicServicesByModule.set(
126
+ moduleId,
127
+ `discoverPublicServices([${names}], ${quote(moduleId)})`,
128
+ );
129
+ for (const name of names) {
130
+ serviceTypes.push(`DiscoveredServiceEntry<typeof ${name}, ${quote(moduleId)}>`);
131
+ publicServiceTypes.push(`DiscoveredPublicServiceEntry<typeof ${name}>`);
132
+ }
133
+ }
134
+ if (kind === 'configs')
135
+ configTypes.push(
136
+ `${quote(moduleId)}: ${names.map((name) => `DiscoveredConfigEntry<typeof ${name}>`).join(' & ') || '{}'};`,
137
+ );
138
+ const fn = {
139
+ actions: 'discoverActions',
140
+ services: 'discoverServices',
141
+ interceptors: 'discoverInterceptors',
142
+ configs: 'discoverConfig',
143
+ }[kind];
144
+ return `${fn}([${names}]${kind === 'actions' ? `, ${quote(moduleId)}, ${conventions}` : kind === 'services' ? `, ${quote(moduleId)}` : ''})`;
145
+ };
146
+ const appEntries = async (kind) => {
147
+ const selected = config[kind];
148
+ if (selected === false) return [];
149
+ if (selected?.directory) {
150
+ const directory = path.resolve(root, selected.directory);
151
+ return discoverEntries(appRoot, await files(directory, moduleRoots), kind, { directory });
152
+ }
153
+ return discoverEntries(appRoot, appFiles, kind);
154
+ };
155
+ const appContributions = contributions(
156
+ await Promise.all(kinds.map((kind) => discoverEntries(appRoot, appFiles, kind))),
157
+ appId,
158
+ );
159
+ const appPages = (await appEntries('pages')).map((entry) => importFile(entry.file));
160
+ const appViews = (await appEntries('views')).map((entry) => importFile(entry.file));
161
+ const appSetupFile = appFiles.find((file) => file === path.join(appRoot, 'setup.ts'));
162
+ const appSetup = appSetupFile ? importFile(appSetupFile) : 'undefined';
163
+ const appActions = emit('actions', await appEntries('actions'), appManifest.id ?? '');
164
+ const appServices = emit('services', await appEntries('services'), appManifest.id ?? '');
165
+ const appPublicServices = publicServicesByModule.get(appManifest.id ?? '');
166
+ const appConfig = emit('configs', await appEntries('configs'), appId);
167
+ let interceptorEntries = await appEntries('interceptors');
168
+ if (config.interceptors?.enabled !== undefined) {
169
+ const enabled = config.interceptors.enabled;
170
+ if (new Set(enabled).size !== enabled.length) throw new Error('Duplicate enabled interceptor.');
171
+ interceptorEntries = enabled.map((id) => {
172
+ const entry = interceptorEntries.find((entry) => entry.path.join('.') === id);
173
+ if (!entry) throw new Error(`Unknown interceptor "${id}".`);
174
+ return entry;
175
+ });
176
+ }
177
+ const interceptors = emit('interceptors', interceptorEntries);
178
+ const providerEntries = await appEntries('providers');
179
+ const enabledProviders = config.providers?.enabled ?? [];
180
+ if (new Set(enabledProviders).size !== enabledProviders.length)
181
+ throw new Error('Duplicate enabled provider.');
182
+ const providers = enabledProviders.map((id) => {
183
+ const entry = providerEntries.find((entry) => entry.path.join('.') === id);
184
+ if (!entry) throw new Error(`Unknown provider "${id}".`);
185
+ return importFile(entry.file);
186
+ });
187
+ for (const manifestFile of roots) {
188
+ const base = path.dirname(manifestFile);
189
+ const overrides = await readFile(manifestFile, 'utf8')
190
+ .then(() => jiti.import(manifestFile, { default: true }))
191
+ .catch((error) => {
192
+ if (error.code === 'ENOENT' && error.path === manifestFile) return {};
193
+ throw error;
194
+ });
195
+ const manifest = { id: path.basename(base), ...overrides };
196
+ if (!/^[a-z][a-z0-9-]*$/.test(manifest.id) || pluginIds.has(manifest.id))
197
+ throw new Error(`Invalid or duplicate plugin ID: ${manifest.id}`);
198
+ pluginIds.add(manifest.id);
199
+ const enabled =
200
+ config.plugins?.overrides?.[manifest.id]?.enabled ?? config.plugins?.autoEnable ?? true;
201
+ const packageInfo = await readFile(path.join(base, 'package.json'), 'utf8')
202
+ .then(JSON.parse)
203
+ .catch((error) => {
204
+ if (error.code === 'ENOENT') return {};
205
+ throw error;
206
+ });
207
+ const metadata = {};
208
+ for (const key of ['name', 'version', 'description', 'author', 'homepage', 'bugs', 'license']) {
209
+ const value = manifest.metadata?.[key] ?? packageInfo[key];
210
+ if (value !== undefined) metadata[key] = value;
211
+ }
212
+
213
+ const resolveEntry = async (name, fallback) => {
214
+ const override = manifest.entries?.[name];
215
+ if (override === false) return [];
216
+ const target = path.resolve(base, override ?? fallback);
217
+ const relative = path.relative(base, target);
218
+ if (relative.startsWith('..') || path.isAbsolute(relative))
219
+ throw new Error(`Entry outside plugin: ${name}`);
220
+ const actual = await realpath(target).catch((error) => {
221
+ if (error.code === 'ENOENT') return null;
222
+ throw error;
223
+ });
224
+ if (!actual) {
225
+ if (override) throw new Error(`Missing explicit entry: ${target}`);
226
+ return [];
227
+ }
228
+ if (actual !== target) throw new Error(`Symlink entry: ${target}`);
229
+ return /\.tsx?$/.test(target) ? [target] : files(target);
230
+ };
231
+ const moduleFiles = await files(
232
+ base,
233
+ new Set([...moduleRoots].filter((item) => item !== base)),
234
+ );
235
+ const entriesFor = async (kind) => {
236
+ const override = manifest.entries?.[kind];
237
+ if (override === false) return [];
238
+ if (override) {
239
+ const paths = await resolveEntry(kind, kind);
240
+ const target = path.resolve(base, override);
241
+ return discoverEntries(
242
+ base,
243
+ paths,
244
+ kind,
245
+ /\.tsx?$/.test(target) ? { explicitFile: target } : { directory: target },
246
+ );
247
+ }
248
+ return discoverEntries(base, moduleFiles, kind);
249
+ };
250
+ const entriesForKind = async (kind) => {
251
+ const override = manifest.entries?.[kind.name];
252
+ if (override === false) return [];
253
+ if (override) {
254
+ const paths = await resolveEntry(kind.name, kind.directory);
255
+ const target = path.resolve(base, override);
256
+ return discoverEntries(
257
+ base,
258
+ paths,
259
+ kind,
260
+ /\.tsx?$/.test(target) ? { explicitFile: target } : { directory: target },
261
+ );
262
+ }
263
+ return discoverEntries(base, moduleFiles, kind);
264
+ };
265
+ const setupFiles = await resolveEntry('setup', 'setup.ts');
266
+ const viewFiles = (await entriesFor('views')).map((entry) => entry.file);
267
+ const pageFiles = (await entriesFor('pages')).map((entry) => entry.file);
268
+ if (!enabled) continue;
269
+ enabledModuleIds.add(manifest.id);
270
+ const actions = emit('actions', await entriesFor('actions'), manifest.id);
271
+ const services = emit('services', await entriesFor('services'), manifest.id);
272
+ const pluginConfig = emit('configs', await entriesFor('configs'), manifest.id);
273
+ const pluginInterceptors = emit('interceptors', await entriesFor('interceptors'));
274
+ const pages = pageFiles.map((file) => importFile(file));
275
+ const views = viewFiles.map((file) => importFile(file));
276
+ const setup = setupFiles[0] ? importFile(setupFiles[0]) : 'undefined';
277
+ const pluginContributions = contributions(
278
+ await Promise.all(kinds.map((kind) => entriesForKind(kind))),
279
+ manifest.id,
280
+ );
281
+ definitions.push(
282
+ `{ id: ${quote(manifest.id)}, publicServices: ${publicServicesByModule.get(manifest.id)}, metadata: ${quote(metadata)}, dependencies: ${quote(manifest.dependencies ?? [])}, actions: ${actions}, services: ${services}, config: ${pluginConfig}, interceptors: ${pluginInterceptors}, views: [${views}], pages: [${pages}], setup: ${setup}, contributions: ${pluginContributions} }`,
283
+ );
284
+ for (const file of await resolveEntry('locales', 'locales')) {
285
+ if (!file.endsWith('.json')) continue;
286
+ const locale = path.basename(file, '.json');
287
+ const messages = JSON.parse(await readFile(file, 'utf8'));
288
+ if (Object.keys(messages).some((key) => key !== manifest.id))
289
+ throw new Error(`Locale keys must use plugin namespace "${manifest.id}".`);
290
+ (allMessages[locale] ??= {})[manifest.id] = messages[manifest.id];
291
+ }
292
+ }
293
+ const header = '// Generated by SaaS Foundation. Do not edit.\n';
294
+ await writeChanged(
295
+ path.join(output, 'plugins.ts'),
296
+ `${header}${[...contributionTypes.values()].map(({ kind, index, entries }) => `type KindMap${index} = ${entries.join(' & ')}; declare module ${quote(kind.from)} { interface ${kind.types.map} extends KindMap${index} {} }`).join('\n')}
297
+ ${imports.join('\n')}\nimport { ${imports.some(entry => entry.includes('= discoveredFile(')) ? 'discoveredFile, ' : ''}discoverActions, discoverServices, discoverPublicServices, discoverInterceptors, discoverConfig, ${actionTypes.length ? 'type DiscoveredActionEntry, ' : ''}${serviceTypes.length ? 'type DiscoveredServiceEntry, ' : ''}${publicServiceTypes.length ? 'type DiscoveredPublicServiceEntry, ' : ''}${configTypes.some(entry => entry.includes('DiscoveredConfigEntry')) ? 'type DiscoveredConfigEntry, ' : ''}type FoundationConfig } from '@bitakit/core';\ntype DiscoveredServices = ${serviceTypes.join(' & ') || '{}'};\ntype DiscoveredPublicServices = ${publicServiceTypes.join(' & ') || '{}'};\ntype DiscoveredActions = ${actionTypes.join(' & ') || '{}'};\ndeclare module '@bitakit/core' { interface PublicServiceMap extends DiscoveredPublicServices {} interface ServiceMap extends DiscoveredServices {} interface ActionMap extends DiscoveredActions {} interface ConfigMap { ${configTypes.join(' \n')} } }\nexport const foundationConfig = { publicServices: ${appPublicServices}, appId: ${quote(appId)}, metadata: ${quote(appManifest.metadata ?? {})}, dependencies: ${quote(appManifest.dependencies ?? [])}, pages: [${appPages}], views: [${appViews}], setup: ${appSetup}, groups: ${quote(config.groups ?? [])}, actionOverrides: ${quote((config.actions && config.actions.overrides) || {})}, config: ${appConfig}, configOverrides: ${quote(Object.fromEntries(Object.entries(config.configOverrides ?? {}).filter(([id]) => !pluginIds.has(id) || enabledModuleIds.has(id))))}, services: ${appServices}, interceptors: ${interceptors}, providers: [${providers}], actions: ${appActions}, contributions: ${appContributions}, plugins: [${definitions.join(',\n')}] } satisfies FoundationConfig;\n`,
298
+ );
299
+ await writeChanged(
300
+ path.join(output, 'messages.json'),
301
+ JSON.stringify(allMessages, null, 2) + '\n',
302
+ );
303
+ const configured = Object.keys(installed.configurations ?? {}).length > 0;
304
+ const pluginFactories = installed.plugins.map((specifier, index) => {
305
+ const configPath = installed.configurations?.[specifier];
306
+ return `packagePlugin${index}(${configPath ? `options.get(${quote(configPath)}, {})` : ''})`;
307
+ });
308
+ await writeChanged(
309
+ path.join(output, 'app.ts'),
310
+ `${header}
311
+ import { foundationConfig } from './plugins';
312
+ ${installed.plugins.map((specifier, index) => `import packagePlugin${index} from ${quote(specifier)};`).join('\n')}
313
+ import { ${configured ? 'ConfigService, type FoundationConfig, ' : ''}type PublicServicesOf } from '@bitakit/core';
314
+ type InstalledPlugins = [${installed.plugins.map((_, index) => `ReturnType<typeof packagePlugin${index}>`).join(', ')}];
315
+ type InstalledPublicServices = PublicServicesOf<InstalledPlugins>;
316
+ declare module '@bitakit/core' { interface PublicServiceMap extends InstalledPublicServices {} }
317
+ /** Factories describe plugins per provider instance; runtime creation and cleanup stay in Core. */
318
+ export function createFoundationConfig() {
319
+ ${configured ? `const { appId = '@foundation/app', config, configOverrides = {} }: FoundationConfig = foundationConfig;
320
+ const options = new ConfigService([{ id: appId, config }], {
321
+ [appId]: configOverrides[appId] ?? {},
322
+ }).plugin(appId);` : ''}
323
+ return { ...foundationConfig, plugins: [...foundationConfig.plugins, ${pluginFactories.join(', ')}] };
324
+ }
325
+ `,
326
+ );
327
+ }
@@ -0,0 +1,12 @@
1
+ import { generateFoundation as generate } from './generate.mjs';
2
+ import { readFile, writeFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+
5
+ /** Connects Core's generated app types to the host compiler without manual imports. */
6
+ export async function generateFoundationHost(root) {
7
+ await generate(root);
8
+ const file = path.join(root, 'foundation-env.d.ts');
9
+ const content =
10
+ '// Generated by SaaS Foundation. Do not edit.\n/// <reference path="./.foundation/app.ts" />\n';
11
+ if ((await readFile(file, 'utf8').catch(() => null)) !== content) await writeFile(file, content);
12
+ }
@@ -0,0 +1,41 @@
1
+ /** An integration-defined contribution kind: folder inside each module root plus its normalizer. */
2
+ export type ContributionKindSpec = {
3
+ /** Kind name used in `contributions`, e.g. "settings.renderers". */
4
+ name: string;
5
+ /** Folder that identifies the kind inside every module root, e.g. "renderers". */
6
+ directory: string;
7
+ /** Module exporting the runtime normalizer; imported by the generated client file. */
8
+ from: string;
9
+ /** Normalizer export: (files, moduleId) => values. It validates and names source files in errors. */
10
+ normalize: string;
11
+ /** Optional package-owned type map populated from discovered files and module IDs. */
12
+ types?: { entry: string; map: string };
13
+ };
14
+ export type DiscoveryConfig = {
15
+ /** Installed opt-in packages are included by default; false disables all, or select by package name. */
16
+ packages?: false | Readonly<Record<string, boolean>>;
17
+ directory?: string;
18
+ /** Contribution kinds provided by optional integrations. Discovery emits imports only. */
19
+ kinds?: readonly ContributionKindSpec[];
20
+ services?: false | { directory?: string };
21
+ configs?: false | { directory?: string };
22
+ configOverrides?: Record<string, Record<string, unknown>>;
23
+ actions?:
24
+ | false
25
+ | { directory?: string; overrides?: Record<string, { enabled?: boolean; visible?: boolean }> };
26
+ providers?: { directory?: string; enabled?: readonly string[] };
27
+ interceptors?: { directory?: string; enabled?: readonly string[] };
28
+ groups?: readonly string[];
29
+ conventions?: boolean;
30
+ plugins?: {
31
+ directory: string;
32
+ autoEnable?: boolean;
33
+ overrides?: Record<string, { enabled: boolean }>;
34
+ };
35
+ };
36
+ export function defineFoundation(config: DiscoveryConfig): DiscoveryConfig;
37
+ export function generateFoundation(root: string): Promise<void>;
38
+ export function watchFoundation(root: string, onError?: (error: unknown) => void): () => void;
39
+
40
+ /** Generates contributions and the host compiler reference without framework imports. */
41
+ export function generateFoundationHost(root: string): Promise<void>;
@@ -0,0 +1,4 @@
1
+ export { generateFoundation } from './generate.mjs';
2
+ export { watchFoundation } from './watch.mjs';
3
+ export const defineFoundation = (config) => config;
4
+ export { generateFoundationHost } from './host.mjs';
@@ -0,0 +1,13 @@
1
+ import path from 'node:path';
2
+
3
+ /** Immediate folders are plugins; explicit nested manifests preserve existing module boundaries. */
4
+ export function pluginManifests(directory, files) {
5
+ const roots = new Set();
6
+ for (const file of files) {
7
+ const segments = path.relative(directory, file).split(path.sep);
8
+ if (segments.some(segment => segment.startsWith('-') || segment.startsWith('.'))) continue;
9
+ if (segments.length > 1) roots.add(path.join(directory, segments[0], 'plugin.config.ts'));
10
+ if (path.basename(file) === 'plugin.config.ts') roots.add(file);
11
+ }
12
+ return [...roots].sort();
13
+ }
@@ -0,0 +1,57 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { createRequire } from 'node:module';
3
+ import path from 'node:path';
4
+
5
+ /** Reads opt-in metadata from direct dependencies. Never imports client plugin code in Node. */
6
+ export async function installedContributions(root, selection, jiti) {
7
+ if (selection === false) return { plugins: [], kinds: [] };
8
+ const manifestFile = path.join(root, 'package.json');
9
+ const manifest = await readFile(manifestFile, 'utf8')
10
+ .then(JSON.parse)
11
+ .catch((error) => {
12
+ if (error.code === 'ENOENT') return {};
13
+ throw error;
14
+ });
15
+ const require = createRequire(manifestFile);
16
+ const plugins = [];
17
+ const kinds = [];
18
+ const configurations = {};
19
+ for (const name of Object.keys({
20
+ ...manifest.dependencies,
21
+ ...manifest.optionalDependencies,
22
+ }).sort()) {
23
+ if (selection?.[name] === false) continue;
24
+ let file;
25
+ try {
26
+ // Opt-in packages expose their manifest as a public subpath.
27
+ file = require.resolve(`${name}/package.json`);
28
+ } catch (error) {
29
+ if (error.code === 'MODULE_NOT_FOUND' || error.code === 'ERR_PACKAGE_PATH_NOT_EXPORTED')
30
+ continue;
31
+ throw error;
32
+ }
33
+ const metadata = JSON.parse(await readFile(file, 'utf8')).foundation;
34
+ if (!metadata) continue;
35
+ const specifier = (entry) => {
36
+ if (
37
+ typeof entry !== 'string' ||
38
+ !/^\.\/[\w./-]+$/.test(entry) ||
39
+ entry.split('/').includes('..')
40
+ )
41
+ throw new Error(`Invalid Foundation export in package "${name}".`);
42
+ return `${name}/${entry.slice(2)}`;
43
+ };
44
+ if (metadata.plugin) {
45
+ const plugin = specifier(metadata.plugin);
46
+ plugins.push(plugin);
47
+ if (metadata.configuration) configurations[plugin] = metadata.configuration;
48
+ }
49
+ if (metadata.discovery) {
50
+ const discover = await jiti.import(require.resolve(specifier(metadata.discovery)), {
51
+ default: true,
52
+ });
53
+ kinds.push(...discover());
54
+ }
55
+ }
56
+ return { plugins, kinds, configurations };
57
+ }
@@ -0,0 +1,23 @@
1
+ import { watch } from 'node:fs';
2
+ import { generateFoundation } from './generate.mjs';
3
+ /** Framework-independent development discovery. The bundler observes generated imports. */
4
+ export function watchFoundation(root, onError = console.error) {
5
+ let timer;
6
+ let stopped = false;
7
+ let chain = Promise.resolve();
8
+ const watcher = watch(root, { recursive: true }, (event, file) => {
9
+ if (!file || /(^|\/)(node_modules|\.next|\.foundation|\.git)(?:\/|$)/.test(file)) return;
10
+ // Directory creation may be the only event before recursive watching attaches.
11
+ if (event !== 'rename' && !/\.(ts|tsx|json)$/.test(file)) return;
12
+ clearTimeout(timer);
13
+ timer = setTimeout(() => {
14
+ chain = chain.then(() => (stopped ? undefined : generateFoundation(root))).catch(onError);
15
+ }, 80);
16
+ });
17
+ watcher.unref();
18
+ return () => {
19
+ stopped = true;
20
+ clearTimeout(timer);
21
+ watcher.close();
22
+ };
23
+ }
@@ -0,0 +1,69 @@
1
+ import { ActionStatus } from './state.js';
2
+ import { type RegistrationOptions } from './groups.js';
3
+ import { Action } from './action.js';
4
+ import type { ActionDefinition, ActionSnapshot, ActionPatch, ActionRegistration, ActionId, ActionInput, ActionResult, ExecutionResult } from './types.js';
5
+ type State = {
6
+ actions: Readonly<Record<string, ActionSnapshot>>;
7
+ };
8
+ /** No global state. This can also be used outside React. */
9
+ export declare function createActionList(initialActions?: readonly (ActionDefinition | Action<any, any>)[], options?: {
10
+ environment?: unknown;
11
+ validate?: (action: ActionSnapshot, actions: State['actions']) => void;
12
+ /** Optional host text projection; source values stay unchanged. */
13
+ project?: (action: ActionSnapshot) => Partial<Pick<ActionSnapshot, 'title' | 'description' | 'tooltip'>>;
14
+ }): {
15
+ get: (id: string) => Readonly<Omit<ActionDefinition, "enabled" | "visible"> & {
16
+ enabled: boolean;
17
+ visible: boolean;
18
+ pending: boolean;
19
+ status: ActionStatus;
20
+ error?: unknown;
21
+ state: unknown;
22
+ }> | undefined;
23
+ resolve: (id: string, input?: unknown) => Readonly<{
24
+ title: string;
25
+ description?: string;
26
+ tooltip?: string;
27
+ id: string;
28
+ groups: readonly import("./groups.js").ActionGroup<any>[] | undefined;
29
+ pending: boolean;
30
+ execute: import("./types.js").ActionHandler<unknown, unknown> | undefined;
31
+ resolve: ((input: unknown) => import("./types.js").ActionPresentation) | undefined;
32
+ enabled: boolean;
33
+ visible: boolean;
34
+ variant?: "default" | "destructive";
35
+ icon?: import("./types.js").ActionIcon;
36
+ href?: string;
37
+ checked?: boolean;
38
+ value?: unknown;
39
+ shortcut?: import("./types.js").ActionShortcut;
40
+ dependsOn?: readonly string[];
41
+ initialState?: object;
42
+ state: unknown;
43
+ internal?: boolean;
44
+ metadata?: unknown;
45
+ order?: number;
46
+ dividerBefore?: boolean;
47
+ status: ActionStatus;
48
+ error?: unknown;
49
+ }> | undefined;
50
+ /** Re-evaluate host presentation after a locale or external context change. */
51
+ refresh: () => void;
52
+ use: (interceptor: import("./interceptors.js").ActionInterceptor) => () => void;
53
+ subscribeExecution: (listener: (event: import("./interceptors.js").ExecutionEvent) => void) => () => void;
54
+ add: <Input, Result>(id: string, action: Action<Input, Result>, placement?: RegistrationOptions) => ActionRegistration;
55
+ register: (definition: ActionDefinition | Action<any, any>, placement?: RegistrationOptions) => ActionRegistration;
56
+ /** Attach an existing action without duplicating it; cleanup owns only this placement. */
57
+ attach(id: string, group: import("./groups.js").ActionGroup): () => void;
58
+ update: (id: string, patch: ActionPatch) => boolean;
59
+ /** Known IDs from ActionMap type their input and result; other IDs stay untyped. */
60
+ execute: <Id extends ActionId>(id: Id, input?: ActionInput<Id>) => Promise<ExecutionResult<ActionResult<Id>>>;
61
+ dispose: () => void;
62
+ mount: (navigate?: (href: string) => void) => () => void;
63
+ /** Read-only subscription surface; mutation stays in the methods above. */
64
+ getState: () => State;
65
+ getInitialState: () => State;
66
+ subscribe: (listener: (state: State, prevState: State) => void) => () => void;
67
+ };
68
+ export type ActionList = ReturnType<typeof createActionList>;
69
+ export {};