@di-framework/cli-plugin-platform 6.0.2 → 6.0.5

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 (69) hide show
  1. package/README.md +196 -21
  2. package/dist/args.d.ts +2 -1
  3. package/dist/args.js +9 -5
  4. package/dist/assets/http-adapter.js +63 -0
  5. package/dist/assets/platform/README.md +22 -6
  6. package/dist/assets/sqlite/BUILD-INFO.txt +1 -1
  7. package/dist/assets/wit/deps/wasi-clocks-0.2.12/package.wit +43 -0
  8. package/dist/assets/wit/deps/wasi-filesystem-0.2.12/package.wit +196 -0
  9. package/dist/assets/wit/deps/wasi-io-0.2.12/package.wit +66 -0
  10. package/dist/assets/wit/deps/wasi-logging/package.wit +36 -0
  11. package/dist/build.d.ts +3 -1
  12. package/dist/build.js +4 -2
  13. package/dist/command.js +31 -13
  14. package/dist/console/auth.d.ts +20 -0
  15. package/dist/console/auth.js +82 -0
  16. package/dist/console/catalog.d.ts +196 -0
  17. package/dist/console/catalog.js +821 -0
  18. package/dist/console/cluster.d.ts +30 -0
  19. package/dist/console/cluster.js +299 -0
  20. package/dist/console/errors.d.ts +10 -0
  21. package/dist/console/errors.js +32 -0
  22. package/dist/console/run.d.ts +18 -0
  23. package/dist/console/run.js +102 -0
  24. package/dist/console/server.d.ts +25 -0
  25. package/dist/console/server.js +668 -0
  26. package/dist/console/services.d.ts +47 -0
  27. package/dist/console/services.js +111 -0
  28. package/dist/console-ui/app.css +1 -0
  29. package/dist/console-ui/app.js +260 -0
  30. package/dist/console-ui/di-framework-mark.png +0 -0
  31. package/dist/console-ui/index.html +13 -0
  32. package/dist/deps.d.ts +2 -0
  33. package/dist/deps.js +5 -3
  34. package/dist/dev.js +10 -5
  35. package/dist/egress.d.ts +40 -0
  36. package/dist/egress.js +214 -0
  37. package/dist/host-interface.js +2 -1
  38. package/dist/index.d.ts +1 -0
  39. package/dist/index.js +1 -0
  40. package/dist/manifest.d.ts +7 -0
  41. package/dist/manifest.js +35 -8
  42. package/dist/node-compat/console.d.ts +18 -0
  43. package/dist/node-compat/console.js +42 -0
  44. package/dist/node-compat/env.js +6 -0
  45. package/dist/node-compat/events.d.ts +20 -0
  46. package/dist/node-compat/events.js +55 -0
  47. package/dist/node-compat/fetch-runtime.d.ts +31 -0
  48. package/dist/node-compat/fetch-runtime.js +62 -0
  49. package/dist/node-compat/fs-promises.d.ts +30 -0
  50. package/dist/node-compat/fs-promises.js +3 -0
  51. package/dist/node-compat/fs.d.ts +79 -0
  52. package/dist/node-compat/fs.js +112 -5
  53. package/dist/node-compat/net.d.ts +2 -1
  54. package/dist/node-compat/net.js +3 -1
  55. package/dist/node-compat/storage.d.ts +87 -0
  56. package/dist/node-compat/storage.js +244 -0
  57. package/dist/node-compat/stream.d.ts +24 -0
  58. package/dist/node-compat/stream.js +70 -0
  59. package/dist/platform.js +2 -4
  60. package/dist/project.d.ts +5 -0
  61. package/dist/project.js +4 -0
  62. package/dist/service.d.ts +21 -2
  63. package/dist/service.js +71 -5
  64. package/dist/target.js +6 -1
  65. package/dist/wit.d.ts +8 -0
  66. package/dist/wit.js +28 -0
  67. package/dist/workload.d.ts +45 -0
  68. package/dist/workload.js +98 -26
  69. package/package.json +14 -4
@@ -0,0 +1,30 @@
1
+ import type { WasmcloudDeps } from '../deps.js';
2
+ import type { ClusterConnection } from '../target.js';
3
+ import type { BindingDocument, HostFailure, JsonPatchOp, WorkloadDocument } from './catalog.js';
4
+ export type SignalView = {
5
+ success: number;
6
+ error: number;
7
+ compute?: number[];
8
+ };
9
+ export type BindInput = {
10
+ workload: string;
11
+ binding: string;
12
+ service: string;
13
+ capability: string;
14
+ };
15
+ export type ConsoleCluster = {
16
+ listWorkloads(connection: ClusterConnection): Promise<WorkloadDocument[]>;
17
+ listBindings(connection: ClusterConnection): Promise<BindingDocument[]>;
18
+ patchWorkload(connection: ClusterConnection, name: string, ops: readonly JsonPatchOp[]): Promise<void>;
19
+ reassignSecret(connection: ClusterConnection, name: string, value: string): Promise<void>;
20
+ canWrite(connection: ClusterConnection): Promise<boolean>;
21
+ readLogs(connection: ClusterConnection, application: string): Promise<string[] | undefined>;
22
+ readSignals(connection: ClusterConnection, application: string): Promise<SignalView | undefined>;
23
+ /** `data.urlTemplate` of the tenant's `di-platform-routes` ConfigMap, if the platform has one. */
24
+ readRouteTemplate(connection: ClusterConnection): Promise<string | undefined>;
25
+ /** Host failures by WorkloadDeployment name, from every logs projection in the namespace. */
26
+ readFailures(connection: ClusterConnection): Promise<Map<string, HostFailure>>;
27
+ bindService(connection: ClusterConnection, input: BindInput): Promise<void>;
28
+ unbindService(connection: ClusterConnection, workload: string, binding: string): Promise<void>;
29
+ };
30
+ export declare function createKubectlConsoleCluster(deps: WasmcloudDeps, log?: (line: string) => void): ConsoleCluster;
@@ -0,0 +1,299 @@
1
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { EGRESS_BINDING_NAME, egressResourceName } from '../egress.js';
5
+ import { captureKubectl } from '../kubernetes.js';
6
+ import { associationName } from '../managed-bindings.js';
7
+ import { MANAGED_BY_LABEL, WORKLOAD_DEPLOYMENT_RESOURCE } from '../workload.js';
8
+ import { ConsoleError, sanitizePublicText } from './errors.js';
9
+ const BINDING_RESOURCE = 'servicebindings.platform.di-framework.dev';
10
+ /** Published by the platform controller in each tenant namespace (contract C-ROUTES). */
11
+ const ROUTES_CONFIG_MAP = 'di-platform-routes';
12
+ export function createKubectlConsoleCluster(deps, log = () => undefined) {
13
+ const label = `app.kubernetes.io/managed-by=${MANAGED_BY_LABEL}`;
14
+ return {
15
+ async listWorkloads(connection) {
16
+ const body = await kubectlJson(deps, connection, ['get', WORKLOAD_DEPLOYMENT_RESOURCE, '-l', label, '-o', 'json'], log);
17
+ return items(body);
18
+ },
19
+ async listBindings(connection) {
20
+ const result = await captureKubectl(deps, connection, ['get', BINDING_RESOURCE, '-o', 'json'], deps.cwd());
21
+ if (result.exitCode !== 0 && /forbidden|not found|resource type/i.test(result.stderr)) {
22
+ log(sanitizePublicText(result.stderr));
23
+ return [];
24
+ }
25
+ if (result.exitCode !== 0) {
26
+ log(sanitizePublicText(result.stderr || result.stdout || 'request failed'));
27
+ throw new ConsoleError(502, 'REQUEST_FAILED', 'Backing services could not be read.');
28
+ }
29
+ try {
30
+ return items(JSON.parse(result.stdout));
31
+ }
32
+ catch (error) {
33
+ if (error instanceof ConsoleError)
34
+ throw error;
35
+ log('The backing service list could not be read.');
36
+ throw new ConsoleError(502, 'REQUEST_FAILED', 'Backing services could not be read.');
37
+ }
38
+ },
39
+ async patchWorkload(connection, name, ops) {
40
+ await kubectlOk(deps, connection, ['patch', WORKLOAD_DEPLOYMENT_RESOURCE, name, '--type=json', `-p=${JSON.stringify(ops)}`], log, 'The application could not be updated.');
41
+ },
42
+ async reassignSecret(connection, name, value) {
43
+ const directory = mkdtempSync(join(tmpdir(), 'di-console-secret-'));
44
+ try {
45
+ const path = join(directory, 'patch.json');
46
+ writeFileSync(path, JSON.stringify({ stringData: { credential: value } }), { mode: 0o600 });
47
+ const result = await captureKubectl(deps, connection, ['patch', 'secret', name, '--type=merge', `--patch-file=${path}`], deps.cwd());
48
+ if (result.exitCode !== 0 && /not ?found/i.test(result.stderr)) {
49
+ log(sanitizePublicText(result.stderr));
50
+ throw new ConsoleError(404, 'SECRET_NOT_FOUND', `No credential named ${name}.`);
51
+ }
52
+ if (result.exitCode !== 0) {
53
+ log(sanitizePublicText(result.stderr || result.stdout || 'request failed'));
54
+ throw new ConsoleError(502, 'REQUEST_FAILED', 'The credential could not be reassigned.');
55
+ }
56
+ }
57
+ finally {
58
+ rmSync(directory, { recursive: true, force: true });
59
+ }
60
+ },
61
+ async canWrite(connection) {
62
+ const result = await captureKubectl(deps, connection, ['auth', 'can-i', 'update', WORKLOAD_DEPLOYMENT_RESOURCE], deps.cwd());
63
+ if (result.exitCode !== 0) {
64
+ log(sanitizePublicText(result.stderr || result.stdout || 'request failed'));
65
+ return false;
66
+ }
67
+ return result.stdout.trim() === 'yes';
68
+ },
69
+ async readLogs(connection, application) {
70
+ return readProjection(deps, connection, application, 'logs', log, (data) => {
71
+ const raw = data.lines ?? data.log;
72
+ if (typeof raw !== 'string')
73
+ return undefined;
74
+ const lines = raw
75
+ .split('\n')
76
+ .slice(0, 200)
77
+ .map((line) => sanitizePublicText(line, 500));
78
+ return lines;
79
+ });
80
+ },
81
+ async readSignals(connection, application) {
82
+ return readProjection(deps, connection, application, 'signals', log, (data) => {
83
+ const success = whole(data.success);
84
+ const error = whole(data.error);
85
+ if (success === undefined || error === undefined)
86
+ return undefined;
87
+ const compute = series(data.compute);
88
+ return { success, error, ...(compute ? { compute } : {}) };
89
+ });
90
+ },
91
+ async readRouteTemplate(connection) {
92
+ const result = await captureKubectl(deps, connection, ['get', 'configmap', ROUTES_CONFIG_MAP, '-o', 'json'], deps.cwd());
93
+ if (result.exitCode !== 0) {
94
+ // No ConfigMap means no gateway is known; the console then shows hosts as text.
95
+ if (/not ?found|forbidden/i.test(result.stderr))
96
+ return undefined;
97
+ log(sanitizePublicText(result.stderr || result.stdout || 'request failed'));
98
+ return undefined;
99
+ }
100
+ try {
101
+ const template = JSON.parse(result.stdout)
102
+ ?.data?.urlTemplate;
103
+ return typeof template === 'string' && template.length > 0 ? template : undefined;
104
+ }
105
+ catch {
106
+ log('The route address template could not be read.');
107
+ return undefined;
108
+ }
109
+ },
110
+ async readFailures(connection) {
111
+ const result = await captureKubectl(deps, connection, ['get', 'configmap', '-l', 'di-framework.dev/projection=logs', '-o', 'json'], deps.cwd());
112
+ const failures = new Map();
113
+ if (result.exitCode !== 0) {
114
+ log(sanitizePublicText(result.stderr || result.stdout || 'request failed'));
115
+ if (/forbidden|not found/i.test(result.stderr))
116
+ return failures;
117
+ throw new ConsoleError(502, 'REQUEST_FAILED', 'The application could not be read.');
118
+ }
119
+ let list;
120
+ try {
121
+ list = items(JSON.parse(result.stdout));
122
+ }
123
+ catch {
124
+ log('The logs projections could not be read.');
125
+ throw new ConsoleError(502, 'REQUEST_FAILED', 'The application could not be read.');
126
+ }
127
+ for (const entry of list) {
128
+ const raw = entry?.data?.failures;
129
+ for (const [name, failure] of parseFailures(raw)) {
130
+ const current = failures.get(name);
131
+ if (current === undefined || failure.time > current.time)
132
+ failures.set(name, failure);
133
+ }
134
+ }
135
+ return failures;
136
+ },
137
+ async bindService(connection, input) {
138
+ const directory = mkdtempSync(join(tmpdir(), 'di-console-binding-'));
139
+ try {
140
+ const path = join(directory, 'binding.json');
141
+ writeFileSync(path, JSON.stringify({
142
+ apiVersion: 'platform.di-framework.dev/v1alpha1',
143
+ kind: 'ServiceBinding',
144
+ metadata: {
145
+ name: associationName(input.workload, input.binding),
146
+ labels: {
147
+ 'app.kubernetes.io/managed-by': MANAGED_BY_LABEL,
148
+ 'di-framework.dev/binding-workload': input.workload,
149
+ },
150
+ },
151
+ spec: {
152
+ serviceName: input.service,
153
+ bindingName: input.binding,
154
+ capability: input.capability,
155
+ workloadName: input.workload,
156
+ },
157
+ }), { mode: 0o600 });
158
+ await kubectlOk(deps, connection, ['apply', '-f', path], log, 'The backing service could not be bound.');
159
+ }
160
+ finally {
161
+ rmSync(directory, { recursive: true, force: true });
162
+ }
163
+ },
164
+ async unbindService(connection, workload, binding) {
165
+ let result = await captureKubectl(deps, connection, ['delete', BINDING_RESOURCE, associationName(workload, binding)], deps.cwd());
166
+ // Deploy names the egress binding after the WorkloadDeployment.
167
+ if (result.exitCode !== 0 &&
168
+ binding === EGRESS_BINDING_NAME &&
169
+ /not ?found/i.test(result.stderr))
170
+ result = await captureKubectl(deps, connection, ['delete', BINDING_RESOURCE, egressResourceName(workload)], deps.cwd());
171
+ if (result.exitCode !== 0 && /not ?found/i.test(result.stderr)) {
172
+ log(sanitizePublicText(result.stderr));
173
+ throw new ConsoleError(404, 'BINDING_NOT_FOUND', 'That backing service is not bound to this application.');
174
+ }
175
+ if (result.exitCode !== 0) {
176
+ log(sanitizePublicText(result.stderr || result.stdout || 'request failed'));
177
+ throw new ConsoleError(502, 'REQUEST_FAILED', 'The backing service could not be unbound.');
178
+ }
179
+ },
180
+ };
181
+ }
182
+ async function readProjection(deps, connection, application, projection, log, parse) {
183
+ const result = await captureKubectl(deps, connection, [
184
+ 'get',
185
+ 'configmap',
186
+ '-l',
187
+ `di-framework.dev/projection=${projection},di-framework.dev/application=${application}`,
188
+ '-o',
189
+ 'json',
190
+ ], deps.cwd());
191
+ if (result.exitCode !== 0) {
192
+ log(sanitizePublicText(result.stderr || result.stdout || 'request failed'));
193
+ if (/forbidden|not found/i.test(result.stderr))
194
+ return undefined;
195
+ throw new ConsoleError(502, 'REQUEST_FAILED', 'The application could not be read.');
196
+ }
197
+ let body;
198
+ try {
199
+ body = JSON.parse(result.stdout);
200
+ }
201
+ catch {
202
+ log('The application projection could not be read.');
203
+ throw new ConsoleError(502, 'REQUEST_FAILED', 'The application could not be read.');
204
+ }
205
+ const list = items(body);
206
+ const first = list[0];
207
+ if (first === undefined || first === null || typeof first !== 'object')
208
+ return undefined;
209
+ const data = first.data;
210
+ if (data === null || typeof data !== 'object' || Array.isArray(data))
211
+ return undefined;
212
+ const strings = {};
213
+ for (const [key, value] of Object.entries(data)) {
214
+ if (typeof value === 'string')
215
+ strings[key] = value;
216
+ }
217
+ return parse(strings);
218
+ }
219
+ async function kubectlJson(deps, connection, args, log) {
220
+ const result = await captureKubectl(deps, connection, args, deps.cwd());
221
+ if (result.exitCode !== 0) {
222
+ log(sanitizePublicText(result.stderr || result.stdout || 'request failed'));
223
+ throw new ConsoleError(502, 'REQUEST_FAILED', 'The application could not be read.');
224
+ }
225
+ try {
226
+ return JSON.parse(result.stdout);
227
+ }
228
+ catch {
229
+ log('The application list could not be read.');
230
+ throw new ConsoleError(502, 'REQUEST_FAILED', 'The application could not be read.');
231
+ }
232
+ }
233
+ async function kubectlOk(deps, connection, args, log, message) {
234
+ const result = await captureKubectl(deps, connection, args, deps.cwd());
235
+ if (result.exitCode !== 0) {
236
+ log(sanitizePublicText(result.stderr || result.stdout || 'request failed'));
237
+ if (/forbidden/i.test(result.stderr)) {
238
+ throw new ConsoleError(403, 'WRITES_FORBIDDEN', 'This credential cannot change the application.');
239
+ }
240
+ throw new ConsoleError(502, 'REQUEST_FAILED', message);
241
+ }
242
+ }
243
+ function items(body) {
244
+ if (body === null || typeof body !== 'object' || !('items' in body)) {
245
+ throw new ConsoleError(502, 'REQUEST_FAILED', 'The application could not be read.');
246
+ }
247
+ const list = body.items;
248
+ if (!Array.isArray(list)) {
249
+ throw new ConsoleError(502, 'REQUEST_FAILED', 'The application could not be read.');
250
+ }
251
+ return list;
252
+ }
253
+ /** `data.failures` entries; malformed JSON or entries are ignored. */
254
+ function parseFailures(raw) {
255
+ if (typeof raw !== 'string')
256
+ return [];
257
+ let parsed;
258
+ try {
259
+ parsed = JSON.parse(raw);
260
+ }
261
+ catch {
262
+ return [];
263
+ }
264
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
265
+ return [];
266
+ const entries = [];
267
+ for (const [name, value] of Object.entries(parsed)) {
268
+ const failure = value;
269
+ if (typeof failure?.workload === 'string' &&
270
+ typeof failure.time === 'string' &&
271
+ (failure.level === 'WARN' || failure.level === 'ERROR') &&
272
+ typeof failure.message === 'string') {
273
+ entries.push([
274
+ name,
275
+ {
276
+ workload: failure.workload,
277
+ time: failure.time,
278
+ level: failure.level,
279
+ message: failure.message,
280
+ },
281
+ ]);
282
+ }
283
+ }
284
+ return entries;
285
+ }
286
+ function whole(value) {
287
+ if (value === undefined || !/^\d+$/.test(value))
288
+ return undefined;
289
+ const parsed = Number(value);
290
+ return Number.isSafeInteger(parsed) ? parsed : undefined;
291
+ }
292
+ function series(value) {
293
+ if (value === undefined || value.length === 0)
294
+ return undefined;
295
+ const numbers = value.split(',').map((entry) => Number(entry.trim()));
296
+ if (numbers.length === 0 || numbers.some((entry) => !Number.isFinite(entry)))
297
+ return undefined;
298
+ return numbers;
299
+ }
@@ -0,0 +1,10 @@
1
+ /** Operator-facing console failure. Messages are safe to return to the browser. */
2
+ export declare class ConsoleError extends Error {
3
+ readonly status: number;
4
+ readonly code: string;
5
+ constructor(status: number, code: string, message: string);
6
+ }
7
+ /** Remove credential-shaped substrings before text is shown or logged. */
8
+ export declare function sanitizePublicText(value: string, max?: number): string;
9
+ /** A status sentence the tenant can read. Infrastructure wording is dropped. */
10
+ export declare function platformSentence(value: string | undefined, max?: number): string | undefined;
@@ -0,0 +1,32 @@
1
+ /** Operator-facing console failure. Messages are safe to return to the browser. */
2
+ export class ConsoleError extends Error {
3
+ status;
4
+ code;
5
+ constructor(status, code, message) {
6
+ super(message);
7
+ this.name = 'ConsoleError';
8
+ this.status = status;
9
+ this.code = code;
10
+ }
11
+ }
12
+ const BEARER = /Bearer\s+[A-Za-z0-9._~+/-]+=*/gi;
13
+ const ASSIGNED_SECRET = /\b(token|password|secret|kubeconfig|authorization)\b\s*[:=]\s*\S+/gi;
14
+ const LONG_TOKEN = /[A-Za-z0-9+/_=-]{40,}/g;
15
+ const INFRASTRUCTURE = /\b(pods?|namespaces?|cronjobs?|replicasets?|deployments?|replicas?|hostselectors?|hostgroups?|hostpath|nodes?|containers?|kubernetes|apiversions?|configmaps?|serviceaccounts?|secrets?|events?|kind|kubeconfigs?)\b|di-runtime|di-tenant|cluster\.local/i;
16
+ /** Remove credential-shaped substrings before text is shown or logged. */
17
+ export function sanitizePublicText(value, max = 400) {
18
+ const text = value
19
+ .replace(BEARER, '[redacted]')
20
+ .replace(ASSIGNED_SECRET, '[redacted]')
21
+ .replace(LONG_TOKEN, '[redacted]');
22
+ return text.length > max ? `${text.slice(0, max)}…` : text;
23
+ }
24
+ /** A status sentence the tenant can read. Infrastructure wording is dropped. */
25
+ export function platformSentence(value, max = 200) {
26
+ if (value === undefined || value.length === 0)
27
+ return undefined;
28
+ const text = sanitizePublicText(value, max).trim();
29
+ if (text.length === 0 || text === '[redacted]' || INFRASTRUCTURE.test(text))
30
+ return undefined;
31
+ return text;
32
+ }
@@ -0,0 +1,18 @@
1
+ import { type CliIo, type CliStream, type CommandResult } from '@di-framework/cli-extension';
2
+ import { type WasmcloudDeps } from '../deps.js';
3
+ import { type DeployManifest, type ExternalTarget } from '../manifest.js';
4
+ export type ConsoleOptions = {
5
+ host: string;
6
+ port: number;
7
+ target?: string;
8
+ };
9
+ export declare function parseConsoleArgs(args: readonly string[]): ConsoleOptions;
10
+ /** The console uses one tenant kubeconfig, namespace, and host group. */
11
+ export declare function selectConsoleTenant(manifest: DeployManifest, requested: string | undefined): ExternalTarget;
12
+ export declare function consoleAssetsDirectory(): string;
13
+ /**
14
+ * The host CLI buffers `io.stdout` until a command returns, and the console runs until it is
15
+ * stopped. The address goes to `live` (the process stdout) so it is readable while the console runs,
16
+ * including when stdout is a file.
17
+ */
18
+ export declare function runWasmcloudConsole(args: readonly string[], io: CliIo, deps?: WasmcloudDeps, live?: CliStream): Promise<CommandResult>;
@@ -0,0 +1,102 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { CommandFailure, } from '@di-framework/cli-extension';
5
+ import { DEFAULT_DEPS } from '../deps.js';
6
+ import { loadDeployManifest } from '../manifest.js';
7
+ import { invalidUsage, readOptionValue } from '../support.js';
8
+ import { resolveConnection, resolveTarget } from '../target.js';
9
+ import { tenantIdentity } from './catalog.js';
10
+ import { startConsoleServer } from './server.js';
11
+ const LOOPBACK = new Set(['127.0.0.1', '::1', 'localhost']);
12
+ export function parseConsoleArgs(args) {
13
+ let host;
14
+ let port;
15
+ let target;
16
+ for (let position = 0; position < args.length; position++) {
17
+ const token = args[position] ?? '';
18
+ switch (token) {
19
+ case '--host':
20
+ if (host !== undefined)
21
+ invalidUsage(`Option may be provided only once: ${token}`, token);
22
+ host = readOptionValue(args, ++position, token);
23
+ break;
24
+ case '--port':
25
+ if (port !== undefined)
26
+ invalidUsage(`Option may be provided only once: ${token}`, token);
27
+ port = readOptionValue(args, ++position, token);
28
+ break;
29
+ case '--target':
30
+ if (target !== undefined)
31
+ invalidUsage(`Option may be provided only once: ${token}`, token);
32
+ target = readOptionValue(args, ++position, token);
33
+ break;
34
+ default:
35
+ invalidUsage(`Unknown option or argument: ${token}`, token, {
36
+ command: 'platform console',
37
+ });
38
+ }
39
+ }
40
+ const resolvedHost = host ?? '127.0.0.1';
41
+ if (!LOOPBACK.has(resolvedHost)) {
42
+ invalidUsage('The console binds to loopback only.', '--host', { command: 'platform console' });
43
+ }
44
+ // Port 0 lets the operating system pick a free port; the listening line reports it.
45
+ const resolvedPort = port === undefined ? 0 : Number(port);
46
+ if (!Number.isInteger(resolvedPort) || resolvedPort < 0 || resolvedPort > 65535) {
47
+ invalidUsage('Console port must be an integer from 0 through 65535.', '--port', {
48
+ command: 'platform console',
49
+ });
50
+ }
51
+ return { host: resolvedHost, port: resolvedPort, ...(target !== undefined ? { target } : {}) };
52
+ }
53
+ /** The console uses one tenant kubeconfig, namespace, and host group. */
54
+ export function selectConsoleTenant(manifest, requested) {
55
+ const target = resolveTarget(manifest, requested);
56
+ if (target.kind !== 'external' || target.hostgroup === undefined) {
57
+ throw new CommandFailure('WASMCLOUD_CONSOLE_TENANT_REQUIRED', `Target "${target.name}" is not a tenant credential. Start the console with a target that sets tenant = "<name>" (or namespace and hostgroup) and the tenant user's kubeconfig.`, 2, { target: target.name });
58
+ }
59
+ return target;
60
+ }
61
+ export function consoleAssetsDirectory() {
62
+ const compiled = fileURLToPath(new URL('../console-ui', import.meta.url));
63
+ if (existsSync(join(compiled, 'index.html')))
64
+ return compiled;
65
+ return fileURLToPath(new URL('../../dist/console-ui', import.meta.url));
66
+ }
67
+ /**
68
+ * The host CLI buffers `io.stdout` until a command returns, and the console runs until it is
69
+ * stopped. The address goes to `live` (the process stdout) so it is readable while the console runs,
70
+ * including when stdout is a file.
71
+ */
72
+ export async function runWasmcloudConsole(args, io, deps = DEFAULT_DEPS, live = process.stdout) {
73
+ const options = parseConsoleArgs(args);
74
+ const assetsDirectory = consoleAssetsDirectory();
75
+ if (!existsSync(join(assetsDirectory, 'index.html'))) {
76
+ throw new CommandFailure('WASMCLOUD_CONSOLE_ASSETS_MISSING', `Console assets are missing at ${assetsDirectory}. Rebuild @di-framework/cli-plugin-platform.`, 3, { directory: assetsDirectory });
77
+ }
78
+ const manifest = loadDeployManifest(deps.cwd(), deps.env);
79
+ const tenant = selectConsoleTenant(manifest, options.target);
80
+ const connection = await resolveConnection(tenant, manifest.workspaceRoot, manifest.path, deps);
81
+ const identity = tenantIdentity(connection.hostgroup, tenant.name);
82
+ const server = await startConsoleServer({
83
+ host: options.host,
84
+ port: options.port,
85
+ target: tenant.name,
86
+ deps,
87
+ assetsDirectory,
88
+ io,
89
+ });
90
+ const scope = identity.hostgroup === undefined
91
+ ? identity.tenant
92
+ : `${identity.tenant} on host group ${identity.hostgroup}`;
93
+ live.write(`Console listening on ${server.url}\nScoped to tenant ${scope}.\nThe tenant credential stays in this process.\n`);
94
+ await new Promise((resolve) => {
95
+ const stop = () => {
96
+ void server.close().finally(resolve);
97
+ };
98
+ process.once('SIGINT', stop);
99
+ process.once('SIGTERM', stop);
100
+ });
101
+ return { text: `Console stopped (${server.url}).` };
102
+ }
@@ -0,0 +1,25 @@
1
+ import { type CliIo } from '@di-framework/cli-extension';
2
+ import type { WasmcloudDeps } from '../deps.js';
3
+ import { type WorkloadDocument } from './catalog.js';
4
+ import { type ConsoleCluster } from './cluster.js';
5
+ import { type ConsoleServices } from './services.js';
6
+ export type ConsoleServer = {
7
+ port: number;
8
+ url: string;
9
+ close: () => Promise<void>;
10
+ };
11
+ export type ConsoleServerOptions = {
12
+ host: string;
13
+ port: number;
14
+ /** Deployment target whose kubeconfig is the tenant credential. */
15
+ target: string;
16
+ deps: WasmcloudDeps;
17
+ assetsDirectory: string;
18
+ io?: CliIo;
19
+ cluster?: ConsoleCluster;
20
+ services?: ConsoleServices;
21
+ now?: () => number;
22
+ };
23
+ export declare function startConsoleServer(options: ConsoleServerOptions): Promise<ConsoleServer>;
24
+ /** Egress is granted to one WorkloadDeployment, so only a single-part application can bind it here. */
25
+ export declare function egressWorkload(members: readonly WorkloadDocument[]): string;