@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,821 @@
1
+ import { STORAGE_HOSTGROUP } from '../workload.js';
2
+ import { ConsoleError, platformSentence, sanitizePublicText } from './errors.js';
3
+ const RESOURCE_NAME = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/;
4
+ const ENV_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
5
+ const HOST_NAME = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$/i;
6
+ const SENSITIVE_KEY = /(TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|PRIVATE|API_KEY|_KEY$)/i;
7
+ 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 PLATFORM_CONTRACTS = new Set([
10
+ 'wasi:http',
11
+ 'wasi:cli',
12
+ 'wasi:config',
13
+ 'wasi:logging',
14
+ 'wasi:random',
15
+ 'wasi:sockets',
16
+ 'wasi:filesystem',
17
+ 'wasi:clocks',
18
+ 'wasi:tls',
19
+ 'wasmcloud:postgres',
20
+ 'wasmcloud:keyvalue',
21
+ 'wasmcloud:messaging',
22
+ 'wasmcloud:blobstore',
23
+ ]);
24
+ const ROUTES_OFF = 'di-framework.dev/routes-off';
25
+ /** The wasi:http host interface that was removed when its last route was turned off. */
26
+ const HTTP_OFF = 'di-framework.dev/http-off';
27
+ const WORKLOAD_INTERFACES = '/spec/template/spec/hostInterfaces';
28
+ const INTERFACE_ARRAY = /^\/spec\/template\/spec\/(hostInterfaces|components\/\d+\/hostInterfaces|service\/hostInterfaces)$/;
29
+ const DEFAULT_HTTP_INTERFACE = {
30
+ namespace: 'wasi',
31
+ package: 'http',
32
+ version: '0.3.0',
33
+ interfaces: ['handler'],
34
+ };
35
+ const NOT_READY = 'This application is not ready yet.';
36
+ export function assertResourceName(name, label) {
37
+ if (!isResourceName(name)) {
38
+ throw new ConsoleError(400, 'INVALID_NAME', `${label} must use lowercase letters, digits, and hyphens.`);
39
+ }
40
+ }
41
+ export function isResourceName(name) {
42
+ return name.length >= 1 && name.length <= 63 && RESOURCE_NAME.test(name);
43
+ }
44
+ /** A tenant credential is one scope. Persistent workloads use the storage host group. */
45
+ export function workloadInTenantScope(document, scope) {
46
+ const namespace = document.metadata?.namespace;
47
+ if (namespace !== undefined && namespace !== scope.namespace)
48
+ return false;
49
+ const hostgroup = document.spec?.template?.spec?.hostSelector?.hostgroup;
50
+ if (scope.hostgroup === undefined || hostgroup === undefined)
51
+ return true;
52
+ const storageHostgroup = scope.storageHostgroup ?? STORAGE_HOSTGROUP;
53
+ return hostgroup === scope.hostgroup || hostgroup === storageHostgroup;
54
+ }
55
+ export function tenantIdentity(hostgroup, target) {
56
+ if (hostgroup?.startsWith('tenant-') && hostgroup.length > 'tenant-'.length) {
57
+ return { tenant: hostgroup.slice('tenant-'.length), hostgroup };
58
+ }
59
+ if (hostgroup !== undefined && hostgroup.length > 0)
60
+ return { tenant: hostgroup, hostgroup };
61
+ return { tenant: target };
62
+ }
63
+ export function summarizeApplications(documents, bindings = [], failures = new Map()) {
64
+ const groups = new Map();
65
+ const labeled = new Map();
66
+ for (const document of documents) {
67
+ if (!isManaged(document))
68
+ continue;
69
+ const label = document.metadata?.labels?.['di-framework.dev/workload'];
70
+ if (typeof label === 'string' && isResourceName(label)) {
71
+ const list = labeled.get(label) ?? [];
72
+ list.push(document);
73
+ labeled.set(label, list);
74
+ continue;
75
+ }
76
+ const name = document.metadata?.name;
77
+ if (name === undefined || !isResourceName(name))
78
+ continue;
79
+ const list = groups.get(name) ?? [];
80
+ list.push(document);
81
+ groups.set(name, list);
82
+ }
83
+ for (const [label, members] of labeled) {
84
+ if (members.length > 1) {
85
+ groups.set(label, members);
86
+ continue;
87
+ }
88
+ const only = members[0];
89
+ const name = only?.metadata?.name;
90
+ if (only !== undefined && name !== undefined && isResourceName(name)) {
91
+ const list = groups.get(name) ?? [];
92
+ list.push(only);
93
+ groups.set(name, list);
94
+ }
95
+ }
96
+ const applications = [];
97
+ for (const [name, members] of groups) {
98
+ members.sort((left, right) => (left.metadata?.name ?? '').localeCompare(right.metadata?.name ?? ''));
99
+ const parts = dedupePartNames(members.flatMap((member) => {
100
+ const failure = currentFailure(member, failures);
101
+ const found = partsFrom(member);
102
+ return failure === undefined ? found : found.map((entry) => ({ ...entry, failure }));
103
+ }));
104
+ const routes = routesFrom(members);
105
+ const environment = environmentFrom(members);
106
+ const secrets = secretsFrom(members).map((secret) => ({ name: secret.name }));
107
+ const memberNames = members
108
+ .map((member) => member.metadata?.name)
109
+ .filter((entry) => typeof entry === 'string');
110
+ const status = applicationStatus(members, failures);
111
+ applications.push({
112
+ name,
113
+ ready: status.ready,
114
+ ...(status.failed ? { failed: true } : {}),
115
+ ...(status.detail ? { detail: status.detail } : {}),
116
+ services: parts.filter((part) => part.kind === 'service').length,
117
+ components: parts.filter((part) => part.kind === 'component').length,
118
+ routeCount: routes.length,
119
+ parts,
120
+ routes,
121
+ environment,
122
+ secrets,
123
+ backingServices: backingBindings(name, memberNames, bindings),
124
+ privateBindings: privateBindings(members),
125
+ });
126
+ }
127
+ return applications.sort((left, right) => left.name.localeCompare(right.name));
128
+ }
129
+ export function toSummary(application) {
130
+ return {
131
+ name: application.name,
132
+ ready: application.ready,
133
+ ...(application.failed ? { failed: true } : {}),
134
+ ...(application.detail ? { detail: application.detail } : {}),
135
+ services: application.services,
136
+ components: application.components,
137
+ routeCount: application.routeCount,
138
+ };
139
+ }
140
+ /**
141
+ * A route's gateway address from the tenant's `di-platform-routes` URL template, e.g.
142
+ * `http://{host}.meshtastic.localhost:28180`. Undefined when the result is not an http(s) URL.
143
+ */
144
+ export function routeUrl(template, host, path) {
145
+ if (!template.includes('{host}'))
146
+ return undefined;
147
+ const base = template.replaceAll('{host}', host);
148
+ try {
149
+ const url = new URL(path === '/' ? base : `${base.replace(/\/$/, '')}${path}`);
150
+ if (url.protocol !== 'http:' && url.protocol !== 'https:')
151
+ return undefined;
152
+ if (url.username !== '' || url.password !== '')
153
+ return undefined;
154
+ return url.href;
155
+ }
156
+ catch {
157
+ return undefined;
158
+ }
159
+ }
160
+ /** Adds gateway links to the enabled routes. */
161
+ export function withRouteUrls(routes, template) {
162
+ if (template === undefined)
163
+ return [...routes];
164
+ return routes.map((route) => {
165
+ const url = route.enabled ? routeUrl(template, route.host, route.path) : undefined;
166
+ return url === undefined ? route : { ...route, url };
167
+ });
168
+ }
169
+ /**
170
+ * wash rejects a wasi:http interface without `host` and keeps serving the old revision, so a route is
171
+ * never turned off by leaving that config empty. Turning off the primary host promotes the next alias.
172
+ * Turning off the last route removes the interface and remembers it in an annotation; turning a route
173
+ * on again restores it.
174
+ */
175
+ export function planRouteUpdate(documents, routeId, enabled) {
176
+ const located = locateRoute(documents, routeId);
177
+ if (located === undefined) {
178
+ throw new ConsoleError(404, 'ROUTE_NOT_FOUND', 'No route with that address.');
179
+ }
180
+ if (located.enabled === enabled)
181
+ return { workload: located.workload, ops: [] };
182
+ const ops = [];
183
+ const annotations = {
184
+ [ROUTES_OFF]: rememberedValue(located.document, located.host, located.path, enabled),
185
+ };
186
+ if (enabled) {
187
+ const restored = located.slot === undefined ? removedInterface(located.document) : undefined;
188
+ if (located.slot !== undefined) {
189
+ ops.push(configOp(located.slot, addRoute(located.slot.config, located.host, located.path)));
190
+ }
191
+ else {
192
+ const array = restored?.array ?? WORKLOAD_INTERFACES;
193
+ const entry = restored?.entry ?? DEFAULT_HTTP_INTERFACE;
194
+ const value = {
195
+ ...entry,
196
+ config: addRoute({ ...(entry.config ?? {}) }, located.host, located.path),
197
+ };
198
+ ops.push(interfaceArray(located.document, array) === undefined
199
+ ? { op: 'add', path: array, value: [value] }
200
+ : { op: 'add', path: `${array}/-`, value });
201
+ annotations[HTTP_OFF] = undefined;
202
+ }
203
+ }
204
+ else {
205
+ const slot = located.slot;
206
+ const next = promoteAlias(stripRoute(slot.config, located.host, located.path));
207
+ if (next.host !== undefined) {
208
+ ops.push(configOp(slot, next));
209
+ }
210
+ else if (hasRouteKeys(next)) {
211
+ throw new ConsoleError(409, 'ROUTE_REQUIRED', 'Turn off the other paths on this host first. wasmCloud needs a host for them.');
212
+ }
213
+ else {
214
+ ops.push({ op: 'remove', path: slot.pointer });
215
+ const entry = { ...slot.entry };
216
+ delete entry.config;
217
+ if (Object.keys(next).length > 0)
218
+ entry.config = next;
219
+ const removed = { array: slot.array, entry };
220
+ annotations[HTTP_OFF] = JSON.stringify(removed);
221
+ }
222
+ }
223
+ ops.push(...annotationOps(located.document, annotations));
224
+ return { workload: located.workload, ops };
225
+ }
226
+ /** Sets a variable on the named part, or where it is already set, or on the first part. */
227
+ export function planEnvironmentSet(documents, key, value, part) {
228
+ assertEnvKey(key);
229
+ if (value.length === 0 || value.length > 4096) {
230
+ throw new ConsoleError(400, 'INVALID_ENVIRONMENT', 'Environment values must be 1 to 4096 characters.');
231
+ }
232
+ if (isSensitiveConfigKey(key) || containsCredential(value)) {
233
+ throw new ConsoleError(400, 'INVALID_ENVIRONMENT', 'Add that credential under Secrets. Environment values cannot contain passwords.');
234
+ }
235
+ const locations = partLocations(documents);
236
+ const target = part !== undefined
237
+ ? requirePart(locations, part)
238
+ : (locations.find((entry) => entry.config[key] !== undefined) ?? locations[0]);
239
+ if (target === undefined) {
240
+ throw new ConsoleError(400, 'NOT_CONFIGURABLE', 'This application has no configurable part.');
241
+ }
242
+ return { workload: target.workload, ops: configValueOps(target, key, value) };
243
+ }
244
+ /** Removes a variable from the named part, or from the first part that sets it. */
245
+ export function planEnvironmentDelete(documents, key, part) {
246
+ assertEnvKey(key);
247
+ const locations = partLocations(documents);
248
+ const existing = part !== undefined
249
+ ? requirePart(locations, part)
250
+ : locations.find((entry) => entry.config[key] !== undefined);
251
+ if (existing === undefined || existing.config[key] === undefined) {
252
+ throw new ConsoleError(404, 'ENV_NOT_FOUND', `No environment variable named ${key}.`);
253
+ }
254
+ return {
255
+ workload: existing.workload,
256
+ ops: [{ op: 'remove', path: `${existing.pointer}/${key}` }],
257
+ };
258
+ }
259
+ export function planSecretReassign(documents, name, value) {
260
+ if (typeof value !== 'string' || value.length === 0 || value.length > 4096) {
261
+ throw new ConsoleError(400, 'INVALID_SECRET', 'Provide a new credential value.');
262
+ }
263
+ const sources = secretsFrom(documents);
264
+ const match = sources.find((secret) => secret.name === name);
265
+ if (match === undefined) {
266
+ throw new ConsoleError(404, 'SECRET_NOT_FOUND', `No credential named ${name}.`);
267
+ }
268
+ if (match.kind === 'secret')
269
+ return { secret: name };
270
+ const located = partLocations(documents).find((entry) => entry.config[name] !== undefined);
271
+ if (located === undefined) {
272
+ throw new ConsoleError(404, 'SECRET_NOT_FOUND', `No credential named ${name}.`);
273
+ }
274
+ return { workload: located.workload, ops: configValueOps(located, name, value) };
275
+ }
276
+ function isManaged(document) {
277
+ return document.metadata?.labels?.['app.kubernetes.io/managed-by'] === 'di-framework';
278
+ }
279
+ function partsFrom(document) {
280
+ const spec = document.spec?.template?.spec;
281
+ const parts = [];
282
+ if (spec?.service !== undefined && typeof spec.service === 'object') {
283
+ parts.push(part(spec.service.name || document.metadata?.name || 'service', 'service'));
284
+ }
285
+ for (const component of spec?.components ?? []) {
286
+ const longLived = component.service !== undefined ||
287
+ (spec?.service === undefined && isLongLivedWorker(component, spec?.hostInterfaces));
288
+ const kind = longLived && !parts.some((entry) => entry.kind === 'service') ? 'service' : 'component';
289
+ parts.push(part(component.name || 'component', kind));
290
+ }
291
+ return parts;
292
+ }
293
+ function part(name, kind) {
294
+ return { name, kind, lifetime: kind === 'service' ? 'long-lived' : 'on-demand' };
295
+ }
296
+ function isLongLivedWorker(component, workloadInterfaces) {
297
+ const http = hasInterface(component, workloadInterfaces, 'wasi', 'http', [
298
+ 'handler',
299
+ 'incoming-handler',
300
+ ]);
301
+ const run = hasInterface(component, workloadInterfaces, 'wasi', 'cli', ['run']);
302
+ const messaging = hasInterface(component, workloadInterfaces, 'wasmcloud', 'messaging', [
303
+ 'handler',
304
+ ]);
305
+ if (run)
306
+ return true;
307
+ if (messaging && !http)
308
+ return true;
309
+ const queue = component.localResources?.environment?.config?.DI_QUEUE_MODE;
310
+ return typeof queue === 'string' && queue.length > 0 && !http;
311
+ }
312
+ function hasInterface(component, workloadInterfaces, namespace, pkg, names) {
313
+ return [...(component.hostInterfaces ?? []), ...(workloadInterfaces ?? [])].some((entry) => entry.namespace === namespace &&
314
+ entry.package === pkg &&
315
+ (entry.interfaces ?? []).some((name) => names.includes(name)));
316
+ }
317
+ function dedupePartNames(parts) {
318
+ const seen = new Map();
319
+ return parts.map((entry) => {
320
+ const count = seen.get(entry.name) ?? 0;
321
+ seen.set(entry.name, count + 1);
322
+ if (count === 0)
323
+ return entry;
324
+ return { ...entry, name: `${entry.name}-${count + 1}` };
325
+ });
326
+ }
327
+ function applicationStatus(members, failures) {
328
+ // A failed start outranks readiness: wash can report a workload Ready that never ran.
329
+ for (const member of members) {
330
+ const failure = currentFailure(member, failures);
331
+ if (failure !== undefined) {
332
+ return { ready: false, failed: true, detail: `${member.metadata?.name} failed: ${failure}` };
333
+ }
334
+ }
335
+ for (const member of members) {
336
+ const status = memberStatus(member);
337
+ if (!status.ready)
338
+ return status;
339
+ }
340
+ return { ready: true };
341
+ }
342
+ function memberStatus(document) {
343
+ const desired = document.spec?.replicas ?? 1;
344
+ const readyCount = document.status?.readyReplicas ?? document.status?.replicas?.ready ?? 0;
345
+ const condition = (document.status?.conditions ?? []).find((entry) => entry.type === 'Ready' || entry.type === 'Available');
346
+ const ready = condition?.status === 'True' || (desired > 0 && readyCount >= desired);
347
+ if (ready)
348
+ return { ready: true };
349
+ return { ready: false, detail: platformSentence(condition?.message) ?? NOT_READY };
350
+ }
351
+ /**
352
+ * The failure message when the newest host failure belongs to the member's current revision. An
353
+ * older revision's failure no longer counts once a new replica set rolls out.
354
+ */
355
+ function currentFailure(member, failures) {
356
+ const name = member.metadata?.name;
357
+ const replicaSet = member.status?.currentReplicaSet?.name;
358
+ if (name === undefined || replicaSet === undefined || replicaSet.length === 0)
359
+ return undefined;
360
+ const failure = failures.get(name);
361
+ if (failure === undefined || !failure.workload.startsWith(`${replicaSet}-`))
362
+ return undefined;
363
+ return sanitizePublicText(failure.message, 200).trim() || 'The host could not start it.';
364
+ }
365
+ function routesFrom(members) {
366
+ const routes = new Map();
367
+ for (const member of members) {
368
+ for (const slot of httpSlots(member)) {
369
+ for (const route of routesInConfig(slot.config)) {
370
+ routes.set(route.id, { ...route, enabled: true });
371
+ }
372
+ }
373
+ for (const route of rememberedRoutes(member)) {
374
+ if (!routes.has(route.id))
375
+ routes.set(route.id, { ...route, enabled: false });
376
+ }
377
+ }
378
+ return [...routes.values()].sort((left, right) => `${left.host}${left.path}`.localeCompare(`${right.host}${right.path}`));
379
+ }
380
+ function locateRoute(documents, routeId) {
381
+ for (const document of documents) {
382
+ const workload = document.metadata?.name;
383
+ if (workload === undefined)
384
+ continue;
385
+ for (const slot of httpSlots(document)) {
386
+ for (const route of routesInConfig(slot.config)) {
387
+ if (route.id !== routeId)
388
+ continue;
389
+ return { ...route, enabled: true, workload, document, slot };
390
+ }
391
+ }
392
+ for (const route of rememberedRoutes(document)) {
393
+ if (route.id !== routeId)
394
+ continue;
395
+ const slot = httpSlots(document)[0];
396
+ return { ...route, enabled: false, workload, document, ...(slot ? { slot } : {}) };
397
+ }
398
+ }
399
+ return undefined;
400
+ }
401
+ function httpSlots(document) {
402
+ const spec = document.spec?.template?.spec;
403
+ const slots = [];
404
+ const visit = (interfaces, array) => {
405
+ interfaces?.forEach((entry, index) => {
406
+ if (entry.namespace !== 'wasi' || entry.package !== 'http')
407
+ return;
408
+ slots.push({
409
+ pointer: `${array}/${index}`,
410
+ array,
411
+ entry,
412
+ hadConfig: entry.config !== undefined,
413
+ config: { ...(entry.config ?? {}) },
414
+ });
415
+ });
416
+ };
417
+ visit(spec?.hostInterfaces, WORKLOAD_INTERFACES);
418
+ spec?.components?.forEach((component, index) => {
419
+ visit(component.hostInterfaces, `/spec/template/spec/components/${index}/hostInterfaces`);
420
+ });
421
+ visit(spec?.service?.hostInterfaces, '/spec/template/spec/service/hostInterfaces');
422
+ return slots;
423
+ }
424
+ function configOp(slot, config) {
425
+ return { op: slot.hadConfig ? 'replace' : 'add', path: `${slot.pointer}/config`, value: config };
426
+ }
427
+ /** wash needs a primary `host`; the first remaining alias takes over when the host is turned off. */
428
+ function promoteAlias(config) {
429
+ if (config.host !== undefined)
430
+ return config;
431
+ const [first, ...rest] = splitComma(config['host-aliases']);
432
+ if (first === undefined)
433
+ return config;
434
+ const next = { ...config, host: first };
435
+ if (rest.length === 0)
436
+ delete next['host-aliases'];
437
+ else
438
+ next['host-aliases'] = rest.join(',');
439
+ return next;
440
+ }
441
+ function hasRouteKeys(config) {
442
+ return config.localRoute !== undefined;
443
+ }
444
+ /** The interface array a pointer names, or undefined when it (or its component) is absent. */
445
+ function interfaceArray(document, array) {
446
+ const spec = document.spec?.template?.spec;
447
+ if (array === WORKLOAD_INTERFACES)
448
+ return spec?.hostInterfaces;
449
+ if (array === '/spec/template/spec/service/hostInterfaces')
450
+ return spec?.service?.hostInterfaces;
451
+ const index = Number(array.split('/')[5]);
452
+ return spec?.components?.[index]?.hostInterfaces;
453
+ }
454
+ function removedInterface(document) {
455
+ const raw = document.metadata?.annotations?.[HTTP_OFF];
456
+ if (typeof raw !== 'string' || raw.length === 0)
457
+ return undefined;
458
+ try {
459
+ const parsed = JSON.parse(raw);
460
+ const { array, entry } = parsed;
461
+ if (typeof array !== 'string' || !INTERFACE_ARRAY.test(array))
462
+ return undefined;
463
+ if (entry === null || typeof entry !== 'object' || Array.isArray(entry))
464
+ return undefined;
465
+ const candidate = entry;
466
+ if (candidate.namespace !== 'wasi' || candidate.package !== 'http')
467
+ return undefined;
468
+ // A component array whose component is gone cannot take the interface back.
469
+ if (array.includes('/components/') && !componentExists(document, array))
470
+ return undefined;
471
+ return { array, entry: candidate };
472
+ }
473
+ catch {
474
+ return undefined;
475
+ }
476
+ }
477
+ function componentExists(document, array) {
478
+ const index = Number(array.split('/')[5]);
479
+ return document.spec?.template?.spec?.components?.[index] !== undefined;
480
+ }
481
+ function routesInConfig(config) {
482
+ const routes = [];
483
+ const seen = new Set();
484
+ const add = (host, path) => {
485
+ if (!isHost(host) || !isPath(path))
486
+ return;
487
+ const id = routeId(host, path);
488
+ if (seen.has(id))
489
+ return;
490
+ seen.add(id);
491
+ routes.push({ id, host, path });
492
+ };
493
+ if (typeof config.host === 'string')
494
+ add(config.host, '/');
495
+ for (const alias of splitComma(config['host-aliases']))
496
+ add(alias, '/');
497
+ for (const entry of splitComma(config.localRoute)) {
498
+ const slash = entry.indexOf('/');
499
+ if (slash === -1)
500
+ add(entry, '/');
501
+ else
502
+ add(entry.slice(0, slash), entry.slice(slash));
503
+ }
504
+ return routes;
505
+ }
506
+ function rememberedRoutes(document) {
507
+ const raw = document.metadata?.annotations?.[ROUTES_OFF];
508
+ if (typeof raw !== 'string' || raw.length === 0)
509
+ return [];
510
+ try {
511
+ const parsed = JSON.parse(raw);
512
+ if (!Array.isArray(parsed))
513
+ return [];
514
+ const routes = [];
515
+ for (const entry of parsed) {
516
+ if (entry === null || typeof entry !== 'object' || Array.isArray(entry))
517
+ continue;
518
+ const host = entry.host;
519
+ const path = entry.path;
520
+ if (typeof host !== 'string' || typeof path !== 'string' || !isHost(host) || !isPath(path))
521
+ continue;
522
+ routes.push({ id: routeId(host, path), host, path });
523
+ }
524
+ return routes;
525
+ }
526
+ catch {
527
+ return [];
528
+ }
529
+ }
530
+ function routeId(host, path) {
531
+ return Buffer.from(`${host}\n${path}`).toString('base64url');
532
+ }
533
+ function addRoute(config, host, path) {
534
+ const next = { ...config };
535
+ if (path === '/') {
536
+ if (next.host === undefined || next.host.length === 0)
537
+ next.host = host;
538
+ else if (next.host !== host)
539
+ next['host-aliases'] = joinComma(splitComma(next['host-aliases']), host);
540
+ return next;
541
+ }
542
+ next.localRoute = joinComma(splitComma(next.localRoute), `${host}${path}`);
543
+ return next;
544
+ }
545
+ function stripRoute(config, host, path) {
546
+ const next = { ...config };
547
+ if (path === '/' && next.host === host)
548
+ delete next.host;
549
+ if (path === '/') {
550
+ const aliases = splitComma(next['host-aliases']).filter((entry) => entry !== host);
551
+ if (aliases.length === 0)
552
+ delete next['host-aliases'];
553
+ else
554
+ next['host-aliases'] = aliases.join(',');
555
+ }
556
+ const token = path === '/' ? host : `${host}${path}`;
557
+ const local = splitComma(next.localRoute).filter((entry) => entry !== token);
558
+ if (local.length === 0)
559
+ delete next.localRoute;
560
+ else
561
+ next.localRoute = local.join(',');
562
+ return next;
563
+ }
564
+ function rememberedValue(document, host, path, enabled) {
565
+ const current = rememberedRoutes(document).map((route) => ({
566
+ host: route.host,
567
+ path: route.path,
568
+ }));
569
+ const next = enabled
570
+ ? current.filter((route) => route.host !== host || route.path !== path)
571
+ : current.some((route) => route.host === host && route.path === path)
572
+ ? current
573
+ : [...current, { host, path }];
574
+ return JSON.stringify(next);
575
+ }
576
+ /** Sets (string) or removes (undefined) annotations. */
577
+ function annotationOps(document, changes) {
578
+ const annotations = document.metadata?.annotations;
579
+ if (annotations === undefined) {
580
+ const value = {};
581
+ for (const [key, entry] of Object.entries(changes))
582
+ if (entry !== undefined)
583
+ value[key] = entry;
584
+ return [{ op: 'add', path: '/metadata/annotations', value }];
585
+ }
586
+ const ops = [];
587
+ for (const [key, value] of Object.entries(changes)) {
588
+ const path = `/metadata/annotations/${key.replaceAll('~', '~0').replaceAll('/', '~1')}`;
589
+ const exists = annotations[key] !== undefined;
590
+ if (value !== undefined)
591
+ ops.push({ op: exists ? 'replace' : 'add', path, value });
592
+ else if (exists)
593
+ ops.push({ op: 'remove', path });
594
+ }
595
+ return ops;
596
+ }
597
+ function environmentFrom(members) {
598
+ const entries = [];
599
+ for (const located of partLocations(members)) {
600
+ for (const [key, value] of Object.entries(located.config)) {
601
+ if (HIDDEN_CONFIG.test(key) || isSensitiveConfigKey(key) || containsCredential(value))
602
+ continue;
603
+ entries.push({ key, value, part: located.name });
604
+ }
605
+ }
606
+ return entries.sort((left, right) => left.key.localeCompare(right.key) || left.part.localeCompare(right.part));
607
+ }
608
+ function secretsFrom(members) {
609
+ const secrets = [];
610
+ const seen = new Set();
611
+ const add = (secret) => {
612
+ if (seen.has(secret.name) ||
613
+ secret.name.endsWith('-control') ||
614
+ secret.name.startsWith('di-binding-'))
615
+ return;
616
+ if (!isResourceName(secret.name) && !ENV_KEY.test(secret.name))
617
+ return;
618
+ seen.add(secret.name);
619
+ secrets.push(secret);
620
+ };
621
+ for (const member of members) {
622
+ const workload = member.metadata?.name;
623
+ if (workload === undefined)
624
+ continue;
625
+ for (const located of configLocations(member)) {
626
+ for (const key of Object.keys(located.config)) {
627
+ const value = located.config[key] ?? '';
628
+ if (HIDDEN_CONFIG.test(key))
629
+ continue;
630
+ if (!isSensitiveConfigKey(key) && !containsCredential(value))
631
+ continue;
632
+ add({ name: key, kind: 'config', workload, pointer: located.pointer });
633
+ }
634
+ for (const ref of located.secretFrom) {
635
+ if (typeof ref.name === 'string')
636
+ add({ name: ref.name, kind: 'secret', workload });
637
+ }
638
+ }
639
+ }
640
+ return secrets.sort((left, right) => left.name.localeCompare(right.name));
641
+ }
642
+ function backingBindings(application, memberNames, bindings) {
643
+ const names = new Set([application, ...memberNames]);
644
+ const views = [];
645
+ for (const binding of bindings) {
646
+ const name = binding.spec?.bindingName;
647
+ const service = binding.spec?.serviceName;
648
+ const workload = binding.spec?.workloadName;
649
+ if (typeof name !== 'string' || typeof service !== 'string' || typeof workload !== 'string')
650
+ continue;
651
+ if (!names.has(workload))
652
+ continue;
653
+ const condition = (binding.status?.conditions ?? []).find((entry) => entry.type === 'Ready');
654
+ const ready = condition?.status === 'True';
655
+ const detail = ready ? undefined : platformSentence(condition?.message);
656
+ views.push({
657
+ name,
658
+ service,
659
+ // The bound service's class comes from the BackingService; see withServiceClasses.
660
+ className: '',
661
+ ready,
662
+ ...(detail ? { detail } : {}),
663
+ });
664
+ }
665
+ return views.sort((left, right) => left.name.localeCompare(right.name));
666
+ }
667
+ /** Names each binding's class from the bound BackingService (service name to class name). */
668
+ export function withServiceClasses(bindings, classes) {
669
+ return bindings.map((binding) => ({ ...binding, className: classes.get(binding.service) ?? '' }));
670
+ }
671
+ function privateBindings(members) {
672
+ const views = new Map();
673
+ for (const member of members) {
674
+ for (const entry of allInterfaces(member)) {
675
+ const namespace = entry.namespace ?? '';
676
+ const pkg = entry.package ?? '';
677
+ const contract = `${namespace}:${pkg}`;
678
+ if (PLATFORM_CONTRACTS.has(contract) || namespace.length === 0 || pkg.length === 0)
679
+ continue;
680
+ const name = entry.name ?? pkg;
681
+ const key = `${name}\n${contract}`;
682
+ views.set(key, { name, contract, bound: (entry.interfaces ?? []).length > 0 });
683
+ }
684
+ }
685
+ return [...views.values()].sort((left, right) => left.name.localeCompare(right.name));
686
+ }
687
+ function allInterfaces(document) {
688
+ const spec = document.spec?.template?.spec;
689
+ return [
690
+ ...(spec?.hostInterfaces ?? []),
691
+ ...(spec?.components ?? []).flatMap((component) => component.hostInterfaces ?? []),
692
+ ...(spec?.service?.hostInterfaces ?? []),
693
+ ];
694
+ }
695
+ function configLocations(document) {
696
+ const workload = document.metadata?.name;
697
+ if (workload === undefined)
698
+ return [];
699
+ const spec = document.spec?.template?.spec;
700
+ const locations = [];
701
+ spec?.components?.forEach((component, index) => {
702
+ locations.push(location(workload, component, `/spec/template/spec/components/${index}`));
703
+ });
704
+ if (spec?.service !== undefined) {
705
+ locations.push(location(workload, spec.service, '/spec/template/spec/service'));
706
+ }
707
+ return locations;
708
+ }
709
+ function location(workload, part, pointer) {
710
+ return {
711
+ workload,
712
+ pointer: `${pointer}/localResources/environment/config`,
713
+ config: { ...(part.localResources?.environment?.config ?? {}) },
714
+ secretFrom: part.localResources?.environment?.secretFrom ?? [],
715
+ part,
716
+ };
717
+ }
718
+ /**
719
+ * Config locations named like the Overview parts: members by name, a member's service before its
720
+ * components, and repeated names numbered the same way.
721
+ */
722
+ function partLocations(documents) {
723
+ const members = [...documents].sort((left, right) => (left.metadata?.name ?? '').localeCompare(right.metadata?.name ?? ''));
724
+ const named = [];
725
+ for (const member of members) {
726
+ const workload = member.metadata?.name;
727
+ const spec = member.spec?.template?.spec;
728
+ if (workload === undefined)
729
+ continue;
730
+ if (spec?.service !== undefined && typeof spec.service === 'object') {
731
+ named.push({
732
+ ...location(workload, spec.service, '/spec/template/spec/service'),
733
+ name: spec.service.name || workload,
734
+ });
735
+ }
736
+ spec?.components?.forEach((component, index) => {
737
+ named.push({
738
+ ...location(workload, component, `/spec/template/spec/components/${index}`),
739
+ name: component.name || 'component',
740
+ });
741
+ });
742
+ }
743
+ const seen = new Map();
744
+ return named.map((entry) => {
745
+ const count = seen.get(entry.name) ?? 0;
746
+ seen.set(entry.name, count + 1);
747
+ return count === 0 ? entry : { ...entry, name: `${entry.name}-${count + 1}` };
748
+ });
749
+ }
750
+ function requirePart(locations, part) {
751
+ const found = locations.find((entry) => entry.name === part);
752
+ if (found === undefined) {
753
+ throw new ConsoleError(404, 'PART_NOT_FOUND', `No part named ${part}.`);
754
+ }
755
+ return found;
756
+ }
757
+ function configValueOps(located, key, value) {
758
+ const resources = located.part.localResources;
759
+ const base = located.pointer.replace(/\/localResources\/environment\/config$/, '');
760
+ if (resources === undefined) {
761
+ return [
762
+ {
763
+ op: 'add',
764
+ path: `${base}/localResources`,
765
+ value: { environment: { config: { [key]: value } } },
766
+ },
767
+ ];
768
+ }
769
+ if (resources.environment === undefined) {
770
+ return [
771
+ {
772
+ op: 'add',
773
+ path: `${base}/localResources/environment`,
774
+ value: { config: { [key]: value } },
775
+ },
776
+ ];
777
+ }
778
+ if (resources.environment.config === undefined) {
779
+ return [
780
+ { op: 'add', path: `${base}/localResources/environment/config`, value: { [key]: value } },
781
+ ];
782
+ }
783
+ return [
784
+ {
785
+ op: resources.environment.config[key] === undefined ? 'add' : 'replace',
786
+ path: `${located.pointer}/${key}`,
787
+ value,
788
+ },
789
+ ];
790
+ }
791
+ function assertEnvKey(key) {
792
+ if (!ENV_KEY.test(key) || key.length > 128) {
793
+ throw new ConsoleError(400, 'INVALID_ENVIRONMENT', 'Environment names use letters, digits, and underscores.');
794
+ }
795
+ if (HIDDEN_CONFIG.test(key)) {
796
+ throw new ConsoleError(400, 'INVALID_ENVIRONMENT', 'That setting is not an environment variable.');
797
+ }
798
+ }
799
+ function isSensitiveConfigKey(key) {
800
+ return SENSITIVE_KEY.test(key);
801
+ }
802
+ function containsCredential(value) {
803
+ return USERINFO.test(value);
804
+ }
805
+ function isHost(value) {
806
+ return value.length > 0 && value.length <= 253 && HOST_NAME.test(value) && !value.includes('*');
807
+ }
808
+ function isPath(value) {
809
+ return value.startsWith('/') && !value.startsWith('//') && !/[\s?#]/.test(value);
810
+ }
811
+ function splitComma(value) {
812
+ if (value === undefined || value.length === 0)
813
+ return [];
814
+ return value
815
+ .split(',')
816
+ .map((entry) => entry.trim())
817
+ .filter((entry) => entry.length > 0);
818
+ }
819
+ function joinComma(values, extra) {
820
+ return [...values.filter((entry) => entry !== extra), extra].join(',');
821
+ }