@di-framework/cli-plugin-platform 6.1.2 → 6.3.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 (60) hide show
  1. package/README.md +154 -12
  2. package/dist/args.d.ts +8 -0
  3. package/dist/args.js +73 -28
  4. package/dist/assets/http-adapter.js +4 -1
  5. package/dist/assets/platform/README.md +68 -19
  6. package/dist/assets/platform/index.ts.tmpl +1 -1
  7. package/dist/assets/platform/tsconfig.json +2 -2
  8. package/dist/assets/sqlite/BUILD-INFO.txt +1 -1
  9. package/dist/build.d.ts +27 -4
  10. package/dist/build.js +159 -18
  11. package/dist/bundle.d.ts +85 -0
  12. package/dist/bundle.js +608 -0
  13. package/dist/command.js +85 -3
  14. package/dist/console/catalog.js +2 -1
  15. package/dist/console/cluster.d.ts +4 -2
  16. package/dist/console/cluster.js +38 -40
  17. package/dist/control/auth.js +14 -2
  18. package/dist/controller/client.d.ts +47 -0
  19. package/dist/controller/client.js +157 -0
  20. package/dist/controller/commands.d.ts +48 -0
  21. package/dist/controller/commands.js +584 -0
  22. package/dist/controller/credentials.d.ts +63 -0
  23. package/dist/controller/credentials.js +156 -0
  24. package/dist/controller/index.d.ts +6 -0
  25. package/dist/controller/index.js +6 -0
  26. package/dist/controller/oidc.d.ts +54 -0
  27. package/dist/controller/oidc.js +121 -0
  28. package/dist/controller/registry.d.ts +15 -0
  29. package/dist/controller/registry.js +47 -0
  30. package/dist/controller/schema.d.ts +157 -0
  31. package/dist/controller/schema.js +1 -0
  32. package/dist/controller/sse.d.ts +12 -0
  33. package/dist/controller/sse.js +61 -0
  34. package/dist/controller/trust.d.ts +14 -0
  35. package/dist/controller/trust.js +39 -0
  36. package/dist/deploy.d.ts +14 -7
  37. package/dist/deploy.js +96 -5
  38. package/dist/deps.d.ts +4 -0
  39. package/dist/destroy.js +26 -2
  40. package/dist/environment-names.d.ts +6 -0
  41. package/dist/environment-names.js +10 -0
  42. package/dist/index.d.ts +5 -3
  43. package/dist/index.js +5 -3
  44. package/dist/manifest.d.ts +45 -1
  45. package/dist/manifest.js +197 -4
  46. package/dist/pglite-encryption.d.ts +79 -0
  47. package/dist/pglite-encryption.js +196 -0
  48. package/dist/pglite.d.ts +61 -4
  49. package/dist/pglite.js +124 -40
  50. package/dist/project.d.ts +7 -0
  51. package/dist/project.js +35 -0
  52. package/dist/publish.d.ts +7 -1
  53. package/dist/publish.js +33 -1
  54. package/dist/service.d.ts +34 -0
  55. package/dist/service.js +156 -145
  56. package/dist/target.d.ts +7 -1
  57. package/dist/target.js +19 -0
  58. package/dist/workload.d.ts +50 -12
  59. package/dist/workload.js +239 -44
  60. package/package.json +1 -1
package/dist/command.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { runWasmcloudBuild } from './build.js';
2
2
  import { runWasmcloudConsole } from './console/run.js';
3
+ import { runWasmcloudLogin, runWasmcloudLogout, runWasmcloudLogs, runWasmcloudSecrets, runWasmcloudVars, runWasmcloudWhoami, } from './controller/index.js';
3
4
  import { runWasmcloudDeploy } from './deploy.js';
4
5
  import { DEFAULT_DEPS } from './deps.js';
5
6
  import { runWasmcloudDestroy } from './destroy.js';
@@ -14,7 +15,14 @@ export function createWasmcloudCommand(deps = DEFAULT_DEPS) {
14
15
  children: {
15
16
  build: {
16
17
  description: 'Bundle the app entry and componentize it for WASI HTTP',
17
- usage: 'di-framework platform build',
18
+ usage: 'di-framework platform build [--bundle <out.json>] [--env <prod|staging>] [--target <name>] [--registry <registry>] [--tag <tag>] [name]',
19
+ options: [
20
+ '--bundle <out.json> Build, push, and write a controller-compatible DeployBundle JSON file',
21
+ '--env <prod|staging> Target deployment environment for --bundle (default: prod)',
22
+ '--target <name> Deployment target from di-framework.deploy.toml (default: default-target)',
23
+ '--registry <registry> OCI registry override when building a DeployBundle',
24
+ '--tag <tag> OCI image tag override when building a DeployBundle',
25
+ ],
18
26
  run: ({ args, io }) => runWasmcloudBuild(args, io, deps),
19
27
  },
20
28
  dev: {
@@ -28,22 +36,96 @@ export function createWasmcloudCommand(deps = DEFAULT_DEPS) {
28
36
  },
29
37
  deploy: {
30
38
  description: 'Build, publish, and apply a wasmCloud WorkloadDeployment for a project in di-framework.deploy.toml',
31
- usage: 'di-framework platform deploy [name] [--target <name>] [--yes]',
39
+ usage: 'di-framework platform deploy [name] [--target <name>] [--env <prod|staging>] [--preview] [--yes]',
32
40
  options: [
33
41
  '--target <name> Deployment target from di-framework.deploy.toml (default: default-target)',
42
+ '--env <prod|staging> Deployment environment for account/controller targets (default: prod)',
43
+ '--preview Preview deployment plan on account/controller targets without applying',
34
44
  '--yes Accepted for compatibility; application deploy does not prompt',
35
45
  ],
36
46
  run: ({ args, io }) => runWasmcloudDeploy(args, io, deps),
37
47
  },
38
48
  destroy: {
39
49
  description: 'Remove the generated WorkloadDeployment and Service for a project; does not destroy the platform',
40
- usage: 'di-framework platform destroy [name] [--target <name>] [--yes]',
50
+ usage: 'di-framework platform destroy [name] [--target <name>] [--env <prod|staging>] [--yes]',
41
51
  options: [
42
52
  '--target <name> Deployment target from di-framework.deploy.toml (default: default-target)',
53
+ '--env <prod|staging> Deployment environment for account/controller targets (default: prod)',
43
54
  '--yes Accepted for compatibility; application destroy does not prompt',
44
55
  ],
45
56
  run: ({ args, io }) => runWasmcloudDestroy(args, io, deps),
46
57
  },
58
+ login: {
59
+ description: 'Log in to a tenant controller over /v1 (OIDC browser PKCE or API key)',
60
+ usage: 'di-framework platform login [--target <name>] [--controller <url>] [--account <tenant>] [--api-key <key>] [--ca-file <pem> | --no-ca] [--no-browser]',
61
+ options: [
62
+ '--target <name> Account or controller target from di-framework.deploy.toml',
63
+ '--controller <url> Explicit tenant controller URL',
64
+ '--account <tenant> Tenant account name',
65
+ '--api-key <key> Authenticate with a tenant API key instead of OIDC browser login',
66
+ '--ca-file <pem> Trust a PEM certificate authority for the controller',
67
+ '--no-ca Drop any previously stored certificate authority for the controller',
68
+ '--no-browser Print the OIDC login URL without opening a browser',
69
+ ],
70
+ run: ({ args, io }) => runWasmcloudLogin(args, io, deps),
71
+ },
72
+ logout: {
73
+ description: 'Revoke and remove a stored tenant controller credential',
74
+ usage: 'di-framework platform logout [--target <name>] [--account <tenant>]',
75
+ options: [
76
+ '--target <name> Account or controller target from di-framework.deploy.toml',
77
+ '--account <tenant> Tenant account name',
78
+ ],
79
+ run: ({ args, io }) => runWasmcloudLogout(args, io, deps),
80
+ },
81
+ whoami: {
82
+ description: 'Show the authenticated user and role for a tenant controller credential',
83
+ usage: 'di-framework platform whoami [--target <name>] [--account <tenant>]',
84
+ options: [
85
+ '--target <name> Account or controller target from di-framework.deploy.toml',
86
+ '--account <tenant> Tenant account name',
87
+ ],
88
+ run: ({ args, io }) => runWasmcloudWhoami(args, io, deps),
89
+ },
90
+ logs: {
91
+ description: 'Read or follow service logs from the tenant controller over /v1',
92
+ usage: 'di-framework platform logs [service] [--service <name>] [--target <name>] [--account <tenant>] [--env <prod|staging>] [--deployment <id>] [--follow] [--since <dur>] [--tail <n>]',
93
+ options: [
94
+ '--service <name> Service name (defaults to the current project service)',
95
+ '--target <name> Account or controller target from di-framework.deploy.toml',
96
+ '--account <tenant> Tenant account name',
97
+ '--env <prod|staging> Deployment environment (default: prod)',
98
+ '--deployment <id> Filter logs to one deployment ID',
99
+ '--follow Follow log stream until disconnected',
100
+ '--since <dur> Show logs since duration or timestamp',
101
+ '--tail <n> Number of recent log lines to return',
102
+ ],
103
+ run: ({ args, io }) => runWasmcloudLogs(args, io, deps),
104
+ },
105
+ secrets: {
106
+ description: 'Manage environment secrets via the tenant controller /v1 API',
107
+ usage: 'di-framework platform secrets <list|set|update|unset> [name] [--target <name>] [--account <tenant>] [--env <prod|staging>] [--from-file <path|->] [--value <val>]',
108
+ options: [
109
+ '--target <name> Account or controller target from di-framework.deploy.toml',
110
+ '--account <tenant> Tenant account name',
111
+ '--env <prod|staging> Deployment environment (default: prod)',
112
+ '--from-file <path|-> Read secret value from file or stdin (-)',
113
+ '--value <val> Provide secret value directly',
114
+ ],
115
+ run: ({ args, io }) => runWasmcloudSecrets(args, io, deps),
116
+ },
117
+ vars: {
118
+ description: 'Manage environment variables via the tenant controller /v1 API',
119
+ usage: 'di-framework platform vars <list|set|update|unset> [name] [--target <name>] [--account <tenant>] [--env <prod|staging>] [--from-file <path|->] [--value <val>]',
120
+ options: [
121
+ '--target <name> Account or controller target from di-framework.deploy.toml',
122
+ '--account <tenant> Tenant account name',
123
+ '--env <prod|staging> Deployment environment (default: prod)',
124
+ '--from-file <path|-> Read variable value from file or stdin (-)',
125
+ '--value <val> Provide variable value directly',
126
+ ],
127
+ run: ({ args, io }) => runWasmcloudVars(args, io, deps),
128
+ },
47
129
  cluster: {
48
130
  description: 'Initialize, provision, or tear down a managed wasmCloud platform target',
49
131
  children: {
@@ -1,3 +1,4 @@
1
+ import { RENDERED_ENVIRONMENT_KEYS } from '../environment-names.js';
1
2
  import { STORAGE_HOSTGROUP } from '../workload.js';
2
3
  import { ConsoleError, platformSentence, sanitizePublicText } from './errors.js';
3
4
  const RESOURCE_NAME = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/;
@@ -5,7 +6,7 @@ const ENV_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
5
6
  const HOST_NAME = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$/i;
6
7
  const SENSITIVE_KEY = /(TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|PRIVATE|API_KEY|_KEY$)/i;
7
8
  const USERINFO = /:\/\/[^/\s:]+:[^/\s@]+@/;
8
- const HIDDEN_CONFIG = /^(DI_CONTROL_|DI_QUEUE_|DI_CRON_|DI_SQLITE_|DI_STORAGE_)|^(ACTOR_STORAGE_DIR|QUEUE_DB_PATH|MIGRATION_DB_PATH)$/;
9
+ const HIDDEN_CONFIG = new RegExp(`^(DI_CONTROL_|DI_QUEUE_|DI_CRON_|DI_SQLITE_|DI_STORAGE_)|^(${RENDERED_ENVIRONMENT_KEYS.join('|')})$`);
9
10
  const PLATFORM_CONTRACTS = new Set([
10
11
  'wasi:http',
11
12
  'wasi:cli',
@@ -15,14 +15,15 @@ export type BindInput = {
15
15
  service: string;
16
16
  capability: string;
17
17
  };
18
+ export type ProjectionEnvironment = 'prod' | 'staging';
18
19
  export type ConsoleCluster = {
19
20
  listWorkloads(connection: ClusterConnection): Promise<WorkloadDocument[]>;
20
21
  listBindings(connection: ClusterConnection): Promise<BindingDocument[]>;
21
22
  patchWorkload(connection: ClusterConnection, name: string, ops: readonly JsonPatchOp[]): Promise<void>;
22
23
  reassignSecret(connection: ClusterConnection, name: string, value: string): Promise<void>;
23
24
  canWrite(connection: ClusterConnection): Promise<boolean>;
24
- readLogs(connection: ClusterConnection, application: string): Promise<string[] | undefined>;
25
- readSignals(connection: ClusterConnection, application: string): Promise<SignalView | undefined>;
25
+ readLogs(connection: ClusterConnection, application: string, env?: ProjectionEnvironment): Promise<string[] | undefined>;
26
+ readSignals(connection: ClusterConnection, application: string, env?: ProjectionEnvironment): Promise<SignalView | undefined>;
26
27
  /** `data.urlTemplate` of the tenant's `di-platform-routes` ConfigMap, if the platform has one. */
27
28
  readRouteTemplate(connection: ClusterConnection): Promise<string | undefined>;
28
29
  /** Host failures by WorkloadDeployment name, from every logs projection in the namespace. */
@@ -30,4 +31,5 @@ export type ConsoleCluster = {
30
31
  bindService(connection: ClusterConnection, input: BindInput): Promise<void>;
31
32
  unbindService(connection: ClusterConnection, workload: string, binding: string): Promise<void>;
32
33
  };
34
+ export declare function projectionSelector(projection: 'logs' | 'signals', application: string, env?: ProjectionEnvironment): string;
33
35
  export declare function createKubectlConsoleCluster(deps: WasmcloudDeps, log?: (line: string) => void): ConsoleCluster;
@@ -24,6 +24,10 @@ export function isPlatformManagedSecretName(name) {
24
24
  }
25
25
  // Denial messages of the platform's Secret admission policies; see `../secret-admission`.
26
26
  export { MANAGED_SECRET_DENIALS, SECRET_UPDATE_KEYS_MESSAGE } from '../secret-admission.js';
27
+ export function projectionSelector(projection, application, env) {
28
+ const envSelector = env === undefined ? '!platform.di-framework.dev/env' : `platform.di-framework.dev/env=${env}`;
29
+ return `di-framework.dev/projection=${projection},di-framework.dev/application=${application},${envSelector}`;
30
+ }
27
31
  export function createKubectlConsoleCluster(deps, log = () => undefined) {
28
32
  const label = `app.kubernetes.io/managed-by=${MANAGED_BY_LABEL}`;
29
33
  return {
@@ -68,43 +72,23 @@ export function createKubectlConsoleCluster(deps, log = () => undefined) {
68
72
  const directory = mkdtempSync(join(tmpdir(), 'di-console-secret-'));
69
73
  try {
70
74
  const path = join(directory, 'secret.json');
75
+ const encoded = Buffer.from(value, 'utf8').toString('base64');
71
76
  const document = {
72
77
  apiVersion: 'v1',
73
78
  kind: 'Secret',
74
79
  metadata: { name, namespace: connection.namespace },
75
80
  type: 'Opaque',
76
- data: { credential: Buffer.from(value, 'utf8').toString('base64') },
81
+ data: { credential: encoded },
77
82
  };
78
83
  writeFileSync(path, JSON.stringify(document), { mode: 0o600 });
79
84
  const uri = `/api/v1/namespaces/${encodeURIComponent(connection.namespace)}/secrets/${encodeURIComponent(name)}`;
80
85
  const result = await captureKubectl(deps, connection, ['replace', '--raw', uri, '-f', path], deps.cwd());
81
- const reason = result.exitCode === 0 ? undefined : kubectlStatusReason(result.stderr);
82
- if (reason === 'NotFound') {
83
- log(sanitizePublicText(result.stderr));
84
- throw new ConsoleError(404, 'SECRET_NOT_FOUND', `No credential named ${name}.`);
85
- }
86
- if (result.exitCode !== 0 && result.stderr.includes(SECRET_UPDATE_KEYS_MESSAGE)) {
87
- log(sanitizePublicText(result.stderr));
88
- throw new ConsoleError(409, 'SECRET_NOT_SINGLE_KEY', `${name} holds values other than a single credential, so it cannot be reassigned here.`);
89
- }
90
- if (result.exitCode !== 0 &&
91
- MANAGED_SECRET_DENIALS.some((message) => result.stderr.includes(message))) {
92
- log(sanitizePublicText(result.stderr));
93
- throw new ConsoleError(403, 'SECRET_MANAGED', `${name} is managed by the platform and cannot be reassigned.`);
94
- }
95
- // A Secret's type is immutable, so a non-Opaque Secret cannot take the Opaque document.
96
- if (reason === 'Invalid' &&
97
- /\btype: Invalid value:.*field is immutable/.test(result.stderr)) {
98
- log(sanitizePublicText(result.stderr));
99
- throw new ConsoleError(409, 'SECRET_TYPE_MISMATCH', `${name} is not a plain (Opaque) Secret and its type cannot change, so it cannot be reassigned here.`);
100
- }
101
- if (reason === 'Forbidden') {
102
- log(sanitizePublicText(result.stderr));
103
- throw new ConsoleError(403, 'WRITES_FORBIDDEN', 'This credential cannot change the application.');
104
- }
105
86
  if (result.exitCode !== 0) {
106
- log(sanitizePublicText(result.stderr || result.stdout || 'request failed'));
107
- throw new ConsoleError(502, 'REQUEST_FAILED', 'The credential could not be reassigned.');
87
+ const scrub = (text) => [value, encoded]
88
+ .filter((secret) => secret.length > 0)
89
+ .sort((a, b) => b.length - a.length)
90
+ .reduce((current, secret) => current.split(secret).join('[redacted]'), text);
91
+ classifySecretError(name, result.stderr, (raw = result.stderr) => log(sanitizePublicText(scrub(raw || result.stdout || 'request failed'))));
108
92
  }
109
93
  }
110
94
  finally {
@@ -119,7 +103,7 @@ export function createKubectlConsoleCluster(deps, log = () => undefined) {
119
103
  }
120
104
  return result.stdout.trim() === 'yes';
121
105
  },
122
- async readLogs(connection, application) {
106
+ async readLogs(connection, application, env) {
123
107
  return readProjection(deps, connection, application, 'logs', log, (data) => {
124
108
  const raw = data.lines ?? data.log;
125
109
  if (typeof raw !== 'string')
@@ -129,9 +113,9 @@ export function createKubectlConsoleCluster(deps, log = () => undefined) {
129
113
  .slice(0, 200)
130
114
  .map((line) => sanitizePublicText(line, 500));
131
115
  return lines;
132
- });
116
+ }, env);
133
117
  },
134
- async readSignals(connection, application) {
118
+ async readSignals(connection, application, env) {
135
119
  return readProjection(deps, connection, application, 'signals', log, (data) => {
136
120
  const success = whole(data.success);
137
121
  const error = whole(data.error);
@@ -139,7 +123,7 @@ export function createKubectlConsoleCluster(deps, log = () => undefined) {
139
123
  return undefined;
140
124
  const compute = series(data.compute);
141
125
  return { success, error, ...(compute ? { compute } : {}) };
142
- });
126
+ }, env);
143
127
  },
144
128
  async readRouteTemplate(connection) {
145
129
  const result = await captureKubectl(deps, connection, ['get', 'configmap', ROUTES_CONFIG_MAP, '-o', 'json'], deps.cwd());
@@ -232,15 +216,29 @@ export function createKubectlConsoleCluster(deps, log = () => undefined) {
232
216
  },
233
217
  };
234
218
  }
235
- async function readProjection(deps, connection, application, projection, log, parse) {
236
- const result = await captureKubectl(deps, connection, [
237
- 'get',
238
- 'configmap',
239
- '-l',
240
- `di-framework.dev/projection=${projection},di-framework.dev/application=${application}`,
241
- '-o',
242
- 'json',
243
- ], deps.cwd());
219
+ function classifySecretError(name, stderr, logFailure) {
220
+ const reason = kubectlStatusReason(stderr);
221
+ logFailure();
222
+ if (reason === 'NotFound') {
223
+ throw new ConsoleError(404, 'SECRET_NOT_FOUND', `No credential named ${name}.`);
224
+ }
225
+ if (stderr.includes(SECRET_UPDATE_KEYS_MESSAGE)) {
226
+ throw new ConsoleError(409, 'SECRET_NOT_SINGLE_KEY', `${name} holds values other than a single credential, so it cannot be reassigned here.`);
227
+ }
228
+ if (MANAGED_SECRET_DENIALS.some((message) => stderr.includes(message))) {
229
+ throw new ConsoleError(403, 'SECRET_MANAGED', `${name} is managed by the platform and cannot be reassigned.`);
230
+ }
231
+ // A Secret's type is immutable, so a non-Opaque Secret cannot take the Opaque document.
232
+ if (reason === 'Invalid' && /\btype: Invalid value:.*field is immutable/.test(stderr)) {
233
+ throw new ConsoleError(409, 'SECRET_TYPE_MISMATCH', `${name} is not a plain (Opaque) Secret and its type cannot change, so it cannot be reassigned here.`);
234
+ }
235
+ if (reason === 'Forbidden') {
236
+ throw new ConsoleError(403, 'WRITES_FORBIDDEN', 'This credential cannot change the application.');
237
+ }
238
+ throw new ConsoleError(502, 'REQUEST_FAILED', 'The credential could not be reassigned.');
239
+ }
240
+ async function readProjection(deps, connection, application, projection, log, parse, env) {
241
+ const result = await captureKubectl(deps, connection, ['get', 'configmap', '-l', projectionSelector(projection, application, env), '-o', 'json'], deps.cwd());
244
242
  if (result.exitCode !== 0) {
245
243
  log(sanitizePublicText(result.stderr || result.stdout || 'request failed'));
246
244
  if (/forbidden|not found/i.test(result.stderr))
@@ -1,5 +1,5 @@
1
1
  /** Cluster-private control-plane authentication for cron/queue/actor admin APIs. */
2
- /** Unconfigured local/dev only. Never includes `admin`. */
2
+ /** Unconfigured local/dev only (never a deployed workload). Never includes `admin`. */
3
3
  const ANONYMOUS_IDENTITY = { id: 'anonymous', token: '', roles: ['invoke'] };
4
4
  function isIdentityEntry(entry) {
5
5
  if (entry === null || typeof entry !== 'object')
@@ -46,7 +46,19 @@ function parseIdentities() {
46
46
  return { identities: singleTokenIdentities(), configured: true };
47
47
  }
48
48
  const identities = singleTokenIdentities();
49
- return { identities, configured: identities.length > 0 };
49
+ return { identities, configured: identities.length > 0 || isDeployed() };
50
+ }
51
+ /**
52
+ * A deployed workload: deploy renders the control host settings, and the control Secret supplies
53
+ * `DI_CONTROL_IDENTITY`. Such a workload without a usable token fails closed instead of falling
54
+ * back to anonymous invoke, so a control Secret that lost `DI_CONTROL_TOKEN` (for example one
55
+ * rewritten by app tooling) cannot open cron, queue and actor endpoints.
56
+ */
57
+ function isDeployed() {
58
+ return (process.env.DI_CONTROL_REJECT_FORWARDED === '1' ||
59
+ (process.env.DI_CONTROL_HTTP_HOST ?? '').trim() !== '' ||
60
+ process.env.DI_CONTROL_IDENTITY !== undefined ||
61
+ process.env.DI_CONTROL_TOKEN !== undefined);
50
62
  }
51
63
  function hasRequiredRole(identity, requiredRoles) {
52
64
  return !requiredRoles.some((role) => !identity.roles.includes(role) && !identity.roles.includes('admin'));
@@ -0,0 +1,47 @@
1
+ import type { AuthInfo, ConfigList, CreateServiceRequest, DeployBundle, Deployment, DeploymentList, DeploymentStats, DeploymentsQuery, DeployPlan, Env, LogEvent, LogsQuery, Principal, Problem, ProxyRequest, ProxySession, RegistryInfo, RollbackRequest, SecretList, Service, VarUnset } from './schema.js';
2
+ export type { AuthInfo, ConfigList, ControllerPath, CreateServiceRequest, DeployBundle, Deployment, DeploymentList, DeploymentStats, DeploymentsQuery, DeployPlan, Env, LogEvent, LogsQuery, Principal, Problem, ProxyRequest, ProxySession, RegistryInfo, RollbackRequest, SecretList, Service, VarUnset, } from './schema.js';
3
+ export { events, type SseEvent } from './sse.js';
4
+ /** A non-2xx answer from the controller, carrying its problem details when it sent any. */
5
+ export declare class ControllerError extends Error {
6
+ readonly status: number;
7
+ readonly problem: Partial<Problem>;
8
+ constructor(status: number, problem: Partial<Problem>);
9
+ }
10
+ export interface ClientOptions {
11
+ /** The controller's base URL, without a trailing slash. */
12
+ baseUrl: string;
13
+ /** Identity-server access token or tenant API key; absent only for `authInfo`. */
14
+ token?: string;
15
+ fetch?: typeof fetch;
16
+ }
17
+ export declare function createClient(options: ClientOptions): {
18
+ authInfo: () => Promise<AuthInfo>;
19
+ whoami: () => Promise<Principal>;
20
+ logout: () => Promise<void>;
21
+ previewDeploy: (bundle: DeployBundle) => Promise<DeployPlan>;
22
+ deploy: (bundle: DeployBundle) => Promise<Deployment>;
23
+ /** The tenant's OCI registry and how to log in to it; the credential is the caller's own. */
24
+ registry: () => Promise<RegistryInfo>;
25
+ createService: (request: CreateServiceRequest) => Promise<Service>;
26
+ proxy: (service: string, request: ProxyRequest) => Promise<ProxySession>;
27
+ /** Yields one LogEvent per `log` event until the server sends `end` or the stream closes. */
28
+ logs(service: string, query: LogsQuery): AsyncGenerator<LogEvent>;
29
+ deployments: (query: DeploymentsQuery) => Promise<DeploymentList>;
30
+ deploymentStats: (env: Env) => Promise<DeploymentStats>;
31
+ rollback: (request: RollbackRequest) => Promise<Deployment>;
32
+ removeDeployment: (env: Env, service: string) => Promise<void>;
33
+ deleteService: (env: Env, service: string) => Promise<void>;
34
+ secrets: (env: Env) => Promise<SecretList>;
35
+ setSecret: (env: Env, name: string, value: string) => Promise<void>;
36
+ updateSecret: (env: Env, name: string, value: string) => Promise<void>;
37
+ unsetSecret: (env: Env, name: string) => Promise<void>;
38
+ vars: (env: Env) => Promise<ConfigList>;
39
+ setVar: (env: Env, name: string, value: string) => Promise<void>;
40
+ updateVar: (env: Env, name: string, value: string) => Promise<void>;
41
+ /**
42
+ * Removes the var; `warnings` names deployed workloads that injected it (platform#100). A
43
+ * controller from before #100 answers 204 with no body, read as no warnings.
44
+ */
45
+ unsetVar(env: Env, name: string): Promise<VarUnset>;
46
+ };
47
+ export type TenantClient = ReturnType<typeof createClient>;
@@ -0,0 +1,157 @@
1
+ import { events } from './sse.js';
2
+ export { events } from './sse.js';
3
+ /**
4
+ * Every path the client calls, checked against `ControllerPath` at compile time: an
5
+ * operation that leaves the contract stops the client from building.
6
+ */
7
+ const PATHS = {
8
+ authInfo: '/v1/auth/info',
9
+ whoami: '/v1/auth/whoami',
10
+ logout: '/v1/auth/logout',
11
+ previewDeploy: '/v1/deploy/preview',
12
+ deploy: '/v1/deploy',
13
+ registry: '/v1/deploy/registry',
14
+ createService: '/v1/services',
15
+ deleteService: '/v1/services/{service}',
16
+ logs: '/v1/services/{service}/logs',
17
+ proxy: '/v1/services/{service}/proxy',
18
+ deployments: '/v1/deployments',
19
+ deploymentStats: '/v1/deployments/stats',
20
+ removeDeployment: '/v1/deployments/{service}',
21
+ rollback: '/v1/deployments/rollback',
22
+ secrets: '/v1/secrets',
23
+ secret: '/v1/secrets/{name}',
24
+ vars: '/v1/vars',
25
+ var: '/v1/vars/{name}',
26
+ };
27
+ /** A non-2xx answer from the controller, carrying its problem details when it sent any. */
28
+ export class ControllerError extends Error {
29
+ status;
30
+ problem;
31
+ constructor(status, problem) {
32
+ super(problem.detail ?? problem.title ?? `controller answered ${status}`);
33
+ this.status = status;
34
+ this.problem = problem;
35
+ this.name = 'ControllerError';
36
+ }
37
+ }
38
+ export function createClient(options) {
39
+ const base = options.baseUrl.replace(/\/$/, '');
40
+ const doFetch = options.fetch ?? fetch;
41
+ const url = (call) => {
42
+ const path = call.path.replace(/\{(\w+)\}/g, (_, key) => encodeURIComponent(call.params?.[key] ?? ''));
43
+ const search = new URLSearchParams();
44
+ for (const [key, value] of Object.entries(call.query ?? {})) {
45
+ if (value !== undefined)
46
+ search.set(key, String(value));
47
+ }
48
+ const qs = search.toString();
49
+ const querySuffix = qs ? `?${qs}` : '';
50
+ return `${base}${path}${querySuffix}`;
51
+ };
52
+ const send = async (call) => {
53
+ const headers = new Headers({ accept: call.accept ?? 'application/json' });
54
+ if (options.token)
55
+ headers.set('authorization', `Bearer ${options.token}`);
56
+ if (call.body !== undefined)
57
+ headers.set('content-type', 'application/json');
58
+ const response = await doFetch(url(call), {
59
+ method: call.method,
60
+ headers,
61
+ body: call.body === undefined ? undefined : JSON.stringify(call.body),
62
+ });
63
+ if (response.ok)
64
+ return response;
65
+ let problem = {};
66
+ try {
67
+ problem = (await response.json());
68
+ }
69
+ catch {
70
+ // Not a problem document; the status alone carries the error.
71
+ }
72
+ throw new ControllerError(response.status, problem);
73
+ };
74
+ const json = async (call) => (await send(call)).json();
75
+ const empty = async (call) => {
76
+ await send(call);
77
+ };
78
+ return {
79
+ authInfo: () => json({ method: 'GET', path: PATHS.authInfo }),
80
+ whoami: () => json({ method: 'GET', path: PATHS.whoami }),
81
+ logout: () => empty({ method: 'POST', path: PATHS.logout }),
82
+ previewDeploy: (bundle) => json({ method: 'POST', path: PATHS.previewDeploy, body: bundle }),
83
+ deploy: (bundle) => json({ method: 'POST', path: PATHS.deploy, body: bundle }),
84
+ /** The tenant's OCI registry and how to log in to it; the credential is the caller's own. */
85
+ registry: () => json({ method: 'GET', path: PATHS.registry }),
86
+ createService: (request) => json({ method: 'POST', path: PATHS.createService, body: request }),
87
+ proxy: (service, request) => json({ method: 'POST', path: PATHS.proxy, params: { service }, body: request }),
88
+ /** Yields one LogEvent per `log` event until the server sends `end` or the stream closes. */
89
+ async *logs(service, query) {
90
+ const response = await send({
91
+ method: 'GET',
92
+ path: PATHS.logs,
93
+ params: { service },
94
+ query,
95
+ accept: 'text/event-stream',
96
+ });
97
+ if (!response.body)
98
+ return;
99
+ for await (const event of events(response.body)) {
100
+ if (event.event === 'end')
101
+ return;
102
+ if (event.event === undefined || event.event === 'log') {
103
+ yield JSON.parse(event.data);
104
+ }
105
+ }
106
+ },
107
+ deployments: (query) => json({ method: 'GET', path: PATHS.deployments, query: { ...query } }),
108
+ deploymentStats: (env) => json({ method: 'GET', path: PATHS.deploymentStats, query: { env } }),
109
+ rollback: (request) => json({ method: 'POST', path: PATHS.rollback, body: request }),
110
+ removeDeployment: (env, service) => empty({
111
+ method: 'DELETE',
112
+ path: PATHS.removeDeployment,
113
+ params: { service },
114
+ query: { env },
115
+ }),
116
+ deleteService: (env, service) => empty({ method: 'DELETE', path: PATHS.deleteService, params: { service }, query: { env } }),
117
+ secrets: (env) => json({ method: 'GET', path: PATHS.secrets, query: { env } }),
118
+ setSecret: (env, name, value) => empty({
119
+ method: 'PUT',
120
+ path: PATHS.secret,
121
+ params: { name },
122
+ query: { env },
123
+ body: { value },
124
+ }),
125
+ updateSecret: (env, name, value) => empty({
126
+ method: 'PATCH',
127
+ path: PATHS.secret,
128
+ params: { name },
129
+ query: { env },
130
+ body: { value },
131
+ }),
132
+ unsetSecret: (env, name) => empty({ method: 'DELETE', path: PATHS.secret, params: { name }, query: { env } }),
133
+ vars: (env) => json({ method: 'GET', path: PATHS.vars, query: { env } }),
134
+ setVar: (env, name, value) => empty({ method: 'PUT', path: PATHS.var, params: { name }, query: { env }, body: { value } }),
135
+ updateVar: (env, name, value) => empty({
136
+ method: 'PATCH',
137
+ path: PATHS.var,
138
+ params: { name },
139
+ query: { env },
140
+ body: { value },
141
+ }),
142
+ /**
143
+ * Removes the var; `warnings` names deployed workloads that injected it (platform#100). A
144
+ * controller from before #100 answers 204 with no body, read as no warnings.
145
+ */
146
+ async unsetVar(env, name) {
147
+ const response = await send({
148
+ method: 'DELETE',
149
+ path: PATHS.var,
150
+ params: { name },
151
+ query: { env },
152
+ });
153
+ const text = await response.text();
154
+ return text.trim() ? JSON.parse(text) : { warnings: [] };
155
+ },
156
+ };
157
+ }
@@ -0,0 +1,48 @@
1
+ import { type CliIo, type CommandResult } from '@di-framework/cli-extension';
2
+ import { type WasmcloudDeps } from '../deps.js';
3
+ import { type DeployEnvironment } from '../manifest.js';
4
+ export declare function tlsTrustCode(error: unknown): string | undefined;
5
+ export declare function wrapControllerError(error: unknown): never;
6
+ export type LoginOptions = {
7
+ target?: string;
8
+ controller?: string;
9
+ account?: string;
10
+ apiKey?: string;
11
+ caFile?: string;
12
+ noCa: boolean;
13
+ noBrowser: boolean;
14
+ };
15
+ export declare function parseLoginArgs(args: readonly string[]): LoginOptions;
16
+ export declare function runWasmcloudLogin(args: readonly string[], io: CliIo, deps?: WasmcloudDeps): Promise<CommandResult>;
17
+ export type AccountCommandOptions = {
18
+ target?: string;
19
+ account?: string;
20
+ };
21
+ export declare function parseAccountCommandArgs(args: readonly string[], command: string): AccountCommandOptions;
22
+ export declare function runWasmcloudLogout(args: readonly string[], io: CliIo, deps?: WasmcloudDeps): Promise<CommandResult>;
23
+ export declare function runWasmcloudWhoami(args: readonly string[], _io: CliIo, deps?: WasmcloudDeps): Promise<CommandResult>;
24
+ export type LogsCommandOptions = {
25
+ service?: string;
26
+ target?: string;
27
+ account?: string;
28
+ env?: DeployEnvironment;
29
+ deployment?: string;
30
+ follow: boolean;
31
+ since?: string;
32
+ tail?: number;
33
+ };
34
+ export declare function parseLogsArgs(args: readonly string[]): LogsCommandOptions;
35
+ export declare function runWasmcloudLogs(args: readonly string[], io: CliIo, deps?: WasmcloudDeps): Promise<CommandResult>;
36
+ export type ConfigAction = 'list' | 'set' | 'update' | 'unset';
37
+ export type ConfigCommandOptions = {
38
+ action: ConfigAction;
39
+ name?: string;
40
+ target?: string;
41
+ account?: string;
42
+ env?: DeployEnvironment;
43
+ fromFile?: string;
44
+ value?: string;
45
+ };
46
+ export declare function parseConfigArgs(args: readonly string[], command: string): ConfigCommandOptions;
47
+ export declare function runWasmcloudSecrets(args: readonly string[], io: CliIo, deps?: WasmcloudDeps): Promise<CommandResult>;
48
+ export declare function runWasmcloudVars(args: readonly string[], io: CliIo, deps?: WasmcloudDeps): Promise<CommandResult>;