@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/pglite.js CHANGED
@@ -28,18 +28,51 @@ export const EXCLUSIVE_INSTANCE_KEY = 'di-framework.dev/exclusive-instance';
28
28
  export const DEFAULT_PGLITE_STORAGE_MOUNT = '/data';
29
29
  /** File name of the provider inside a cache entry. */
30
30
  export const PGLITE_WASM_FILE = 'di-framework-pglite.wasm';
31
+ /**
32
+ * Encrypting `wasi:filesystem` layer for the provider (`pglite.encryption`), published by
33
+ * di-framework/platform. The build composes it into the provider with an explicit `wac compose`
34
+ * document (`.di-framework/pglite-encryption.wac`, see `encryptProvider`) before the provider is
35
+ * plugged into the guest, so only the engine sees the encrypted view.
36
+ */
37
+ export const PGLITE_ENCFS_REPOSITORY = 'ghcr.io/di-framework/pglite-encfs';
38
+ /** Absolute (or cwd-relative) path of a local encryption layer build; wins over the config. */
39
+ export const PGLITE_ENCFS_WASM_ENV = 'DI_FRAMEWORK_PGLITE_ENCFS_WASM';
40
+ /** File name of the encryption layer inside a cache entry. */
41
+ export const PGLITE_ENCFS_WASM_FILE = 'di-framework-pglite-encfs.wasm';
42
+ /** The provider with the encryption layer plugged in, as the build plugs it into the guest. */
43
+ export const PGLITE_ENCRYPTED_WASM_FILE = 'di-framework-pglite.encrypted.wasm';
44
+ /**
45
+ * The guest environment variable the encryption layer reads its master key from. It must come
46
+ * from the control Secret, so the project declares it in `controlSecretKeys`.
47
+ */
48
+ export const PGLITE_KEY_ENV = 'DI_PGLITE_KEY';
31
49
  const WASM_LAYER_MEDIA_TYPE = 'application/wasm';
32
50
  const SHA256_DIGEST = /^sha256:[0-9a-f]{64}$/;
33
51
  const DIGEST_REFERENCE = /^([a-z0-9]+(?:[.:-][a-z0-9]+)*(?:\/[a-z0-9]+(?:[._-][a-z0-9]+)*)+)@(.+)$/;
34
- const CONFIG_KEYS = ['image', 'wasm', 'storageMount', 'dataDir'];
52
+ const CONFIG_KEYS = ['image', 'wasm', 'storageMount', 'dataDir', 'encryption'];
53
+ const ENCRYPTION_KEYS = ['image', 'wasm'];
54
+ export const PGLITE_PROVIDER = {
55
+ label: 'PGlite provider',
56
+ field: 'pglite',
57
+ repository: PGLITE_REPOSITORY,
58
+ localEnv: PGLITE_WASM_ENV,
59
+ file: PGLITE_WASM_FILE,
60
+ };
61
+ export const PGLITE_ENCFS = {
62
+ label: 'PGlite encryption layer',
63
+ field: 'pglite.encryption',
64
+ repository: PGLITE_ENCFS_REPOSITORY,
65
+ localEnv: PGLITE_ENCFS_WASM_ENV,
66
+ file: PGLITE_ENCFS_WASM_FILE,
67
+ };
35
68
  function configInvalid(message, configPath) {
36
69
  throw new CommandFailure('WASMCLOUD_CONFIG_INVALID', message, 2, { configPath });
37
70
  }
38
- export function parseDigestReference(reference) {
71
+ export function parseDigestReference(reference, repository = PGLITE_REPOSITORY) {
39
72
  const match = DIGEST_REFERENCE.exec(reference);
40
73
  const digest = match?.[2] ?? '';
41
74
  if (match === null || !SHA256_DIGEST.test(digest)) {
42
- throw new Error(`"${reference}" is not pinned by digest. Use ${PGLITE_REPOSITORY}@sha256:<64 hex>; tags such as :${DI_PGLITE_VERSION} move`);
75
+ throw new Error(`"${reference}" is not pinned by digest. Use ${repository}@sha256:<64 hex>; tags such as :${DI_PGLITE_VERSION} move`);
43
76
  }
44
77
  return { repository: match[1], digest };
45
78
  }
@@ -50,21 +83,37 @@ function absoluteGuestPath(value, label, configPath) {
50
83
  return normalized.length > 1 && normalized.endsWith('/') ? normalized.slice(0, -1) : normalized;
51
84
  }
52
85
  /** `image` must be a digest pin and `wasm` a path; at least one of them is required. */
53
- function validateProviderSource(entry, configPath) {
86
+ function validateProviderSource(entry, configPath, component = PGLITE_PROVIDER) {
87
+ const field = component.field;
54
88
  if (entry.image !== undefined) {
55
89
  if (typeof entry.image !== 'string')
56
- configInvalid('pglite.image must be a string', configPath);
90
+ configInvalid(`${field}.image must be a string`, configPath);
57
91
  try {
58
- parseDigestReference(entry.image);
92
+ parseDigestReference(entry.image, component.repository);
59
93
  }
60
94
  catch (error) {
61
- configInvalid(`pglite.image: ${error.message}`, configPath);
95
+ configInvalid(`${field}.image: ${error.message}`, configPath);
62
96
  }
63
97
  }
64
98
  if (entry.wasm !== undefined && (typeof entry.wasm !== 'string' || entry.wasm.trim() === ''))
65
- configInvalid('pglite.wasm must be a non-empty path', configPath);
99
+ configInvalid(`${field}.wasm must be a non-empty path`, configPath);
66
100
  if (entry.image === undefined && entry.wasm === undefined)
67
- configInvalid(`pglite needs "image" (${PGLITE_REPOSITORY}@sha256:<digest>) or a local "wasm" path`, configPath);
101
+ configInvalid(`${field} needs "image" (${component.repository}@sha256:<digest>) or a local "wasm" path`, configPath);
102
+ }
103
+ function parseEncryption(value, configPath, resolveFile) {
104
+ if (value === undefined)
105
+ return undefined;
106
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
107
+ configInvalid('pglite.encryption must be an object', configPath);
108
+ const entry = value;
109
+ const unknown = Object.keys(entry).filter((key) => !ENCRYPTION_KEYS.includes(key));
110
+ if (unknown.length > 0)
111
+ configInvalid(`pglite.encryption has unsupported fields: ${unknown.join(', ')}. Use ${ENCRYPTION_KEYS.join(', ')}`, configPath);
112
+ validateProviderSource(entry, configPath, PGLITE_ENCFS);
113
+ return {
114
+ ...(entry.image === undefined ? {} : { image: entry.image }),
115
+ ...(entry.wasm === undefined ? {} : { wasm: resolveFile(entry.wasm) }),
116
+ };
68
117
  }
69
118
  /** True when `path` is `directory` or below it (both normalized guest paths). */
70
119
  export function isWithin(path, directory) {
@@ -89,11 +138,21 @@ export function parsePgliteConfig(value, configPath, resolveFile) {
89
138
  : absoluteGuestPath(entry.dataDir, 'dataDir', configPath);
90
139
  if (!isWithin(dataDir, storageMount))
91
140
  configInvalid(`pglite.dataDir ${dataDir} must be inside storageMount ${storageMount}; only that directory is persistent`, configPath);
141
+ const encryption = parseEncryption(entry.encryption, configPath, resolveFile);
142
+ if (encryption?.image !== undefined) {
143
+ const layer = parseDigestReference(encryption.image, PGLITE_ENCFS_REPOSITORY);
144
+ const provider = entry.image === undefined ? undefined : parseDigestReference(entry.image);
145
+ if (layer.repository === PGLITE_REPOSITORY || layer.repository === provider?.repository)
146
+ configInvalid(`pglite.encryption.image must pin the encryption layer (${PGLITE_ENCFS_REPOSITORY}), not the provider repository ${layer.repository}`, configPath);
147
+ if (layer.digest === provider?.digest)
148
+ configInvalid('pglite.encryption.image pins the same digest as pglite.image', configPath);
149
+ }
92
150
  return {
93
151
  ...(entry.image === undefined ? {} : { image: entry.image }),
94
152
  ...(entry.wasm === undefined ? {} : { wasm: resolveFile(entry.wasm) }),
95
153
  storageMount,
96
154
  dataDir,
155
+ ...(encryption === undefined ? {} : { encryption }),
97
156
  };
98
157
  }
99
158
  export function cacheRoot(env) {
@@ -154,9 +213,9 @@ export function verifyLayer(bytes, image, layerDigest) {
154
213
  throw failure('WASMCLOUD_PGLITE_MANIFEST_INVALID', `Provider layer of ${image} is not a WebAssembly binary`, { image });
155
214
  }
156
215
  /** The verified provider bytes of a cache entry, or undefined when it is absent or stale. */
157
- function readVerifiedEntry(directory, image) {
216
+ function readVerifiedEntry(directory, image, file) {
158
217
  const manifestPath = join(directory, 'manifest.json');
159
- const wasmPath = join(directory, PGLITE_WASM_FILE);
218
+ const wasmPath = join(directory, file);
160
219
  if (!existsSync(manifestPath) || !existsSync(wasmPath))
161
220
  return undefined;
162
221
  try {
@@ -184,27 +243,27 @@ function sweepStaleStaging(root, now) {
184
243
  }
185
244
  }
186
245
  }
187
- async function oras(deps, args, image, cwd) {
246
+ async function oras(deps, args, image, cwd, component) {
188
247
  const result = await deps.runCaptured('oras', args, { cwd });
189
248
  if (result.exitCode === 0)
190
249
  return;
191
250
  const reason = (result.stderr || result.stdout).trim();
192
251
  const detail = reason ? `: ${reason}` : '';
193
252
  throw failure('WASMCLOUD_PGLITE_PULL_FAILED', `oras ${args.slice(0, 2).join(' ')} failed for ${image}${detail}. ` +
194
- `If the package is private, run \`oras login ghcr.io\`; offline, set ${PGLITE_WASM_ENV} or pglite.wasm`, { image, exitCode: String(result.exitCode) });
253
+ `If the package is private, run \`oras login ghcr.io\`; offline, set ${component.localEnv} or ${component.field}.wasm`, { image, exitCode: String(result.exitCode) });
195
254
  }
196
255
  /**
197
256
  * Stores a verified staging directory as the cache entry. A concurrent build may have
198
257
  * stored the same digest first; its entry is used when it verifies.
199
258
  */
200
- function storeEntry(staging, entry, image, bytes) {
259
+ function storeEntry(staging, entry, image, bytes, file) {
201
260
  mkdirSync(join(entry, '..'), { recursive: true });
202
261
  try {
203
262
  renameSync(staging, entry);
204
263
  return bytes;
205
264
  }
206
265
  catch (error) {
207
- const winner = readVerifiedEntry(entry, image);
266
+ const winner = readVerifiedEntry(entry, image, file);
208
267
  if (winner !== undefined)
209
268
  return winner;
210
269
  throw failure('WASMCLOUD_PGLITE_CACHE_CONFLICT', `Could not store ${image} in the cache at ${entry} (${error.code ?? 'unknown error'}), ` +
@@ -216,10 +275,10 @@ function storeEntry(staging, entry, image, bytes) {
216
275
  * digest, into the cache. A cached entry is re-verified on every use; a corrupt one is
217
276
  * pulled again. Returns the verified bytes, so later readers never see a swapped file.
218
277
  */
219
- export async function pullPgliteComponent(image, io, deps, cwd) {
220
- const { repository, digest } = parseDigestReference(image);
278
+ export async function pullPgliteComponent(image, io, deps, cwd, component = PGLITE_PROVIDER) {
279
+ const { repository, digest } = parseDigestReference(image, component.repository);
221
280
  const entry = cacheEntry(deps.env, digest);
222
- const cached = readVerifiedEntry(entry, image);
281
+ const cached = readVerifiedEntry(entry, image, component.file);
223
282
  if (cached !== undefined) {
224
283
  io.stdout.write(`Using cached ${image}\n`);
225
284
  return { bytes: cached, source: 'cache', image };
@@ -229,7 +288,7 @@ export async function pullPgliteComponent(image, io, deps, cwd) {
229
288
  rmSync(entry, { recursive: true, force: true });
230
289
  }
231
290
  if (deps.capture('oras', ['version']) === undefined)
232
- throw failure('WASMCLOUD_ORAS_REQUIRED', `oras is required to pull ${image}; install it from https://oras.land or set ${PGLITE_WASM_ENV} to a local provider build`, { image, tool: 'oras' });
291
+ throw failure('WASMCLOUD_ORAS_REQUIRED', `oras is required to pull ${image}; install it from https://oras.land or set ${component.localEnv} to a local build`, { image, tool: 'oras' });
233
292
  const root = cacheRoot(deps.env);
234
293
  mkdirSync(root, { recursive: true });
235
294
  sweepStaleStaging(root, Date.now());
@@ -237,13 +296,17 @@ export async function pullPgliteComponent(image, io, deps, cwd) {
237
296
  try {
238
297
  io.stdout.write(`Pulling ${image}...\n`);
239
298
  const manifestPath = join(staging, 'manifest.json');
240
- await oras(deps, ['manifest', 'fetch', '--output', manifestPath, image], image, cwd);
299
+ await oras(deps, ['manifest', 'fetch', '--output', manifestPath, image], image, cwd, component);
241
300
  const layerDigest = verifyManifest(readFileSync(manifestPath), image);
242
- const stagedWasm = join(staging, PGLITE_WASM_FILE);
243
- await oras(deps, ['blob', 'fetch', '--output', stagedWasm, `${repository}@${layerDigest}`], image, cwd);
301
+ const stagedWasm = join(staging, component.file);
302
+ await oras(deps, ['blob', 'fetch', '--output', stagedWasm, `${repository}@${layerDigest}`], image, cwd, component);
244
303
  const bytes = readFileSync(stagedWasm);
245
304
  verifyLayer(bytes, image, layerDigest);
246
- return { bytes: storeEntry(staging, entry, image, bytes), source: 'registry', image };
305
+ return {
306
+ bytes: storeEntry(staging, entry, image, bytes, component.file),
307
+ source: 'registry',
308
+ image,
309
+ };
247
310
  }
248
311
  finally {
249
312
  rmSync(staging, { recursive: true, force: true });
@@ -251,28 +314,34 @@ export async function pullPgliteComponent(image, io, deps, cwd) {
251
314
  }
252
315
  /** Set to `1` to let `deploy` or a CI build use a local, unverified provider. */
253
316
  export const ALLOW_LOCAL_PGLITE_ENV = 'DI_FRAMEWORK_ALLOW_LOCAL_PGLITE';
254
- function readLocalProvider(local, origin, config, io, deps, options) {
317
+ function isCiEnv(value) {
318
+ return Boolean(value && value !== '0' && value.toLowerCase() !== 'false');
319
+ }
320
+ function readLocalProvider(local, origin, config, io, deps, options, component = PGLITE_PROVIDER) {
255
321
  if (!existsSync(local))
256
- throw failure('WASMCLOUD_PGLITE_PROVIDER_MISSING', `PGlite provider ${local} (from ${origin}) does not exist`, { path: local });
322
+ throw failure('WASMCLOUD_PGLITE_PROVIDER_MISSING', `${component.label} ${local} (from ${origin}) does not exist`, { path: local });
257
323
  let context;
258
324
  if (options.deploy)
259
325
  context = 'deploy';
260
- else if (deps.env.CI)
326
+ else if (isCiEnv(deps.env.CI))
261
327
  context = 'CI';
262
328
  if (context !== undefined && deps.env[ALLOW_LOCAL_PGLITE_ENV] !== '1')
263
- throw failure('WASMCLOUD_PGLITE_LOCAL_REFUSED', `Refusing the unverified local PGlite provider ${local} (from ${origin}) in ${context}; ` +
264
- `pin "pglite.image" by digest, or set ${ALLOW_LOCAL_PGLITE_ENV}=1 to use it anyway`, { path: local, context });
329
+ throw failure('WASMCLOUD_PGLITE_LOCAL_REFUSED', `Refusing the unverified local ${component.label} ${local} (from ${origin}) in ${context}; ` +
330
+ `pin "${component.field}.image" by digest, or set ${ALLOW_LOCAL_PGLITE_ENV}=1 to use it anyway`, { path: local, context });
265
331
  const bytes = readFileSync(local);
266
332
  if (!isWasm(bytes))
267
- throw failure('WASMCLOUD_PGLITE_PROVIDER_INVALID', `PGlite provider ${local} (from ${origin}) is not a WebAssembly binary`, { path: local });
333
+ throw failure('WASMCLOUD_PGLITE_PROVIDER_INVALID', `${component.label} ${local} (from ${origin}) is not a WebAssembly binary`, { path: local });
268
334
  const replaced = config.image ? ` instead of the pinned ${config.image}` : '';
269
- io.stderr.write(`Warning: using the local, unverified PGlite provider ${local} (from ${origin})${replaced}\n`);
335
+ io.stderr.write(`Warning: using the local, unverified ${component.label} ${local} (from ${origin})${replaced}\n`);
270
336
  return { bytes, source: 'local', path: local };
271
337
  }
272
338
  /**
273
339
  * The provider to compose: `DI_FRAMEWORK_PGLITE_WASM`, then `pglite.wasm`, then the
274
340
  * digest-pinned `pglite.image`. Local files are only checked to be WebAssembly, and are
275
341
  * refused in a deploy or on CI without `DI_FRAMEWORK_ALLOW_LOCAL_PGLITE=1`.
342
+ * Note that `buildComponent(..., { deploy: true })` enforces this deploy-time refusal, whereas
343
+ * calling the lower-level `publishComponent` API directly publishes an already-built `.wasm`
344
+ * without re-running provider resolution.
276
345
  */
277
346
  export async function resolvePgliteComponent(config, io, deps, projectRoot, options = {}) {
278
347
  const fromEnv = deps.env[PGLITE_WASM_ENV]?.trim();
@@ -282,22 +351,38 @@ export async function resolvePgliteComponent(config, io, deps, projectRoot, opti
282
351
  return readLocalProvider(config.wasm, 'pglite.wasm', config, io, deps, options);
283
352
  return pullPgliteComponent(config.image, io, deps, projectRoot);
284
353
  }
354
+ /**
355
+ * The encryption layer to plug into the provider, resolved like the provider:
356
+ * `DI_FRAMEWORK_PGLITE_ENCFS_WASM`, then `pglite.encryption.wasm`, then the digest-pinned
357
+ * `pglite.encryption.image`, with the same local-file refusal in a deploy or on CI.
358
+ */
359
+ export async function resolvePgliteEncryption(config, io, deps, projectRoot, options = {}) {
360
+ const fromEnv = deps.env[PGLITE_ENCFS_WASM_ENV]?.trim();
361
+ if (fromEnv)
362
+ return readLocalProvider(resolve(deps.cwd(), fromEnv), PGLITE_ENCFS_WASM_ENV, config, io, deps, options, PGLITE_ENCFS);
363
+ if (config.wasm !== undefined)
364
+ return readLocalProvider(config.wasm, 'pglite.encryption.wasm', config, io, deps, options, PGLITE_ENCFS);
365
+ return pullPgliteComponent(config.image, io, deps, projectRoot, PGLITE_ENCFS);
366
+ }
367
+ function rootsOverlap(a, b) {
368
+ return a === b || a === '' || b === '' || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
369
+ }
285
370
  /**
286
371
  * Members of one workload share one storage directory, mounted at each member's own
287
- * `storageMount`. Two members whose `dataDir` is the same path relative to their mount
288
- * would open the same database from separate instances, which exclusivity cannot stop.
372
+ * `storageMount`. Two members whose `dataDir` is the same or a nested path relative to their mount
373
+ * would open overlapping database directories from separate instances, which exclusivity cannot stop.
289
374
  */
290
375
  export function assertDistinctPgliteRoots(workload, members) {
291
- const owners = new Map();
376
+ const owners = [];
292
377
  for (const member of members) {
293
378
  if (member.workload !== workload || member.pglite === undefined)
294
379
  continue;
295
380
  const root = posix.relative(member.pglite.storageMount, member.pglite.dataDir);
296
- const previous = owners.get(root);
381
+ const previous = owners.find((entry) => rootsOverlap(root, entry.root));
297
382
  if (previous !== undefined)
298
- throw new CommandFailure('WASMCLOUD_PGLITE_DATA_DIR_CONFLICT', `${workload}: ${previous} and ${member.applicationName} would open the same PGlite database ` +
383
+ throw new CommandFailure('WASMCLOUD_PGLITE_DATA_DIR_CONFLICT', `${workload}: ${previous.name} and ${member.applicationName} would open the same PGlite database ` +
299
384
  `(<workload storage>/${root || '.'}); members share one storage directory, so give each a different dataDir relative to its storageMount`, 2, { workload, root });
300
- owners.set(root, member.applicationName);
385
+ owners.push({ root, name: member.applicationName });
301
386
  }
302
387
  }
303
388
  /** Tag fragment of the tenant host image that honours the exclusive opt-in (#140). */
@@ -337,11 +422,10 @@ export async function warnIfHostIgnoresExclusive(project, connection, io, deps)
337
422
  return;
338
423
  }
339
424
  const images = await hostImages(connection, hostgroup, deps, project.projectRoot);
340
- if (images?.some(hasExclusiveTag))
425
+ if (images !== undefined && images.length > 0 && images.every(hasExclusiveTag))
341
426
  return;
342
- const seen = images === undefined || images.length === 0
343
- ? 'could not read its host image'
344
- : `runs ${images[0]}`;
427
+ const nonExclusive = images?.find((img) => !hasExclusiveTag(img));
428
+ const seen = nonExclusive === undefined ? 'could not read its host image' : `runs ${nonExclusive}`;
345
429
  io.stderr.write(`Warning: ${project.applicationName} embeds PGlite and is marked exclusive, but host group ${hostgroup} ` +
346
430
  `${seen}, which does not look like the exclusive build (tagged *${EXCLUSIVE_HOST_IMAGE_MARKER}, set with the platform's tenantHostImage). ${risk}.\n`);
347
431
  }
package/dist/project.d.ts CHANGED
@@ -42,7 +42,14 @@ export type WasmcloudProject = {
42
42
  * component is exclusive and gets persistent storage at `storageMount`.
43
43
  */
44
44
  pglite?: PgliteConfig;
45
+ /**
46
+ * App-owned keys of the `<workload>-control` Secret, from `"controlSecretKeys"`. Deploy keeps
47
+ * them and refuses any other key besides the CLI's own `DI_CONTROL_*` (`writeControlSecret`).
48
+ */
49
+ controlSecretKeys?: string[];
45
50
  };
51
+ /** Why `name` cannot be declared in `controlSecretKeys`, or undefined when it can. */
52
+ export declare function controlSecretKeyProblem(name: unknown): string | undefined;
46
53
  export declare function findUp(startDirectory: string, fileName: string): string | undefined;
47
54
  /** Paths from the config must stay inside the project root. */
48
55
  export declare function resolveInside(projectRoot: string, value: string, label: string, configPath: string): string;
package/dist/project.js CHANGED
@@ -2,9 +2,42 @@ import { accessSync, constants, existsSync, readFileSync, realpathSync } from 'n
2
2
  import { isIP } from 'node:net';
3
3
  import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
4
4
  import { CommandFailure } from '@di-framework/cli-extension';
5
+ import { RENDERED_ENVIRONMENT_KEYS } from './environment-names.js';
5
6
  import { parsePgliteConfig } from './pglite.js';
6
7
  import { discoverWorkloadEntry } from './workload-members.js';
7
8
  export const CONFIG_FILE_NAME = 'di-framework.config.json';
9
+ /** A key the control Secret may carry for the app: an environment variable name. */
10
+ const CONTROL_SECRET_KEY = /^[A-Za-z_][A-Za-z0-9_]{0,252}$/;
11
+ /**
12
+ * The `DI_*` keys a project may declare. Every other `DI_*` name belongs to the framework: the CLI
13
+ * owns it in the control Secret or renders it into the workload's environment config, and a
14
+ * Secret key must not shadow either.
15
+ */
16
+ const DECLARABLE_DI_KEYS = ['DI_PGLITE_KEY', 'DI_PGLITE_KEY_PREVIOUS'];
17
+ /** Why `name` cannot be declared in `controlSecretKeys`, or undefined when it can. */
18
+ export function controlSecretKeyProblem(name) {
19
+ if (typeof name !== 'string' || !CONTROL_SECRET_KEY.test(name))
20
+ return `${JSON.stringify(name)} is not an environment variable name`;
21
+ if (name.startsWith('DI_') && !DECLARABLE_DI_KEYS.includes(name))
22
+ return `${name} is reserved for the framework; of the DI_* names only ${DECLARABLE_DI_KEYS.join(' and ')} may be declared`;
23
+ if (RENDERED_ENVIRONMENT_KEYS.includes(name))
24
+ return `${name} is rendered by the CLI`;
25
+ return undefined;
26
+ }
27
+ function parseControlSecretKeys(value, configPath) {
28
+ if (value === undefined)
29
+ return undefined;
30
+ if (!Array.isArray(value))
31
+ configInvalid(`${CONFIG_FILE_NAME} "controlSecretKeys" must be an array of names`, configPath);
32
+ for (const [index, name] of value.entries()) {
33
+ const problem = controlSecretKeyProblem(name);
34
+ if (problem !== undefined)
35
+ configInvalid(`${CONFIG_FILE_NAME} "controlSecretKeys"[${index}]: ${problem}`, configPath);
36
+ if (value.indexOf(name) !== index)
37
+ configInvalid(`${CONFIG_FILE_NAME} "controlSecretKeys" repeats ${name}`, configPath);
38
+ }
39
+ return value.length > 0 ? [...value] : undefined;
40
+ }
8
41
  export function findUp(startDirectory, fileName) {
9
42
  let previous = '';
10
43
  let current = resolve(startDirectory);
@@ -123,6 +156,7 @@ export function loadProject(startDirectory) {
123
156
  const cronMode = config.cronMode === 'external' ? 'external' : undefined;
124
157
  const persistentStorage = config.persistentStorage === true;
125
158
  const pglite = parsePgliteConfig(config.pglite, configPath, (path) => resolveRealInside(projectRoot, path, 'pglite.wasm', configPath));
159
+ const controlSecretKeys = parseControlSecretKeys(config.controlSecretKeys, configPath);
126
160
  return {
127
161
  applicationName: config.name,
128
162
  ...(workload ? { workload, workloadEntry } : {}),
@@ -131,6 +165,7 @@ export function loadProject(startDirectory) {
131
165
  ...(persistentStorage ? { persistentStorage: true } : {}),
132
166
  ...(config.logs === false ? { logs: false } : {}),
133
167
  ...(pglite ? { pglite } : {}),
168
+ ...(controlSecretKeys ? { controlSecretKeys } : {}),
134
169
  ...(config.allowedIpNameLookups === undefined
135
170
  ? {}
136
171
  : { allowedIpNameLookups: config.allowedIpNameLookups }),
package/dist/publish.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { CliIo } from '@di-framework/cli-extension';
1
+ import { type CliIo, CommandFailure } from '@di-framework/cli-extension';
2
2
  import type { WasmcloudDeps } from './deps.js';
3
3
  import type { WasmcloudProject } from './project.js';
4
4
  import type { ClusterConnection } from './target.js';
@@ -11,5 +11,11 @@ export type PublishedImage = {
11
11
  };
12
12
  export declare function contentDigest(filePath: string): string;
13
13
  export declare function ociReference(registry: string, repository: string, digest: string): string;
14
+ export declare function countCoreWasmModules(wasmBytes: Uint8Array): number;
15
+ export declare function reportCoreInstanceCost(wasmBytes: Uint8Array, io: CliIo, hostPoolSize?: number): {
16
+ coreModules: number;
17
+ maxConcurrentInvocations: number;
18
+ };
19
+ export declare function plainHttpRegistryFailure(pushReference: string, target: string, exitCode?: number): CommandFailure;
14
20
  export declare function publishComponent(project: WasmcloudProject, connection: ClusterConnection, io: CliIo, deps: WasmcloudDeps, deploymentDigest: string): Promise<PublishedImage>;
15
21
  export declare function projectRelativePath(projectRoot: string, path: string): string;
package/dist/publish.js CHANGED
@@ -1,22 +1,51 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { readFileSync } from 'node:fs';
3
3
  import { isAbsolute, join, relative, sep } from 'node:path';
4
+ import { CommandFailure } from '@di-framework/cli-extension';
4
5
  import { registryReferenceHost, registryUsesPlainHttp } from './registry.js';
5
6
  import { toolFailed } from './support.js';
7
+ const CORE_WASM_MAGIC = Buffer.from([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]);
8
+ const PLAIN_HTTP_RESPONSE_RE = /server gave HTTP response to HTTPS client/i;
6
9
  export function contentDigest(filePath) {
7
10
  return createHash('sha256').update(readFileSync(filePath)).digest('hex');
8
11
  }
9
12
  export function ociReference(registry, repository, digest) {
10
13
  return `${registryReferenceHost(registry)}/${repository}:sha256-${digest}`;
11
14
  }
15
+ export function countCoreWasmModules(wasmBytes) {
16
+ const buf = Buffer.from(wasmBytes.buffer, wasmBytes.byteOffset, wasmBytes.byteLength);
17
+ let count = 0;
18
+ let offset = buf.indexOf(CORE_WASM_MAGIC, 0);
19
+ while (offset !== -1) {
20
+ count += 1;
21
+ offset = buf.indexOf(CORE_WASM_MAGIC, offset + CORE_WASM_MAGIC.length);
22
+ }
23
+ return Math.max(1, count);
24
+ }
25
+ export function reportCoreInstanceCost(wasmBytes, io, hostPoolSize = 100) {
26
+ const coreModules = countCoreWasmModules(wasmBytes);
27
+ const maxConcurrentInvocations = Math.floor(hostPoolSize / coreModules);
28
+ if (coreModules > 1) {
29
+ io.stdout.write(`Component instantiates ${coreModules} core WebAssembly modules per invocation (~${maxConcurrentInvocations} concurrent invocations at default WASH_CORE_INSTANCES=${hostPoolSize}).\n`);
30
+ }
31
+ if (maxConcurrentInvocations <= 10) {
32
+ io.stderr.write(`Warning: component requires ${coreModules} core instances per invocation, leaving at most ${maxConcurrentInvocations} concurrent invocations against the host's default WASH_CORE_INSTANCES=${hostPoolSize}; increase WASH_CORE_INSTANCES on the host if higher concurrency is needed.\n`);
33
+ }
34
+ return { coreModules, maxConcurrentInvocations };
35
+ }
36
+ export function plainHttpRegistryFailure(pushReference, target, exitCode = 1) {
37
+ return new CommandFailure('WASMCLOUD_TOOL_FAILED', `oras push failed with exit code ${exitCode}: ${pushReference} answered with plain HTTP to an HTTPS client; prefix the registry push URL with "http://" or set "insecure = true" under [targets.${target}.registry] in di-framework.deploy.toml`, 3, { command: 'oras push', exitCode, target, reference: pushReference });
38
+ }
12
39
  export async function publishComponent(project, connection, io, deps, deploymentDigest) {
13
- const artifactDigest = contentDigest(project.outputPath);
40
+ const wasmBytes = readFileSync(project.outputPath);
41
+ const artifactDigest = createHash('sha256').update(wasmBytes).digest('hex');
14
42
  const pushReference = ociReference(connection.registry.push, project.witName, deploymentDigest);
15
43
  const pullReference = ociReference(connection.registry.pull, project.witName, deploymentDigest);
16
44
  const configPath = join(project.projectRoot, '.di-framework', 'oci-config.json');
17
45
  const componentPath = projectRelativePath(project.projectRoot, project.outputPath);
18
46
  const projectConfigPath = projectRelativePath(project.projectRoot, configPath);
19
47
  io.stdout.write(`Publishing ${componentPath} as ${pushReference}...\n`);
48
+ reportCoreInstanceCost(wasmBytes, io);
20
49
  const transportArgs = registryUsesPlainHttp(connection.registry) ? ['--plain-http'] : [];
21
50
  const existing = await deps.runCaptured('oras', ['manifest', 'fetch', ...transportArgs, '--descriptor', pushReference], { cwd: project.projectRoot });
22
51
  if (existing.exitCode === 0) {
@@ -29,6 +58,9 @@ export async function publishComponent(project, connection, io, deps, deployment
29
58
  reference: pushReference,
30
59
  };
31
60
  }
61
+ if (PLAIN_HTTP_RESPONSE_RE.test(existing.stderr)) {
62
+ throw plainHttpRegistryFailure(pushReference, connection.target, existing.exitCode);
63
+ }
32
64
  const pushed = await deps.runner('oras', [
33
65
  'push',
34
66
  ...transportArgs,
package/dist/service.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { type CliIo, type JsonValue } from '@di-framework/cli-extension';
2
2
  import { type WasmcloudDeps } from './deps.js';
3
+ import { type DeployEnvironment } from './manifest.js';
3
4
  export declare const BACKING_SERVICE_API_VERSION = "platform.di-framework.dev/v1alpha1";
4
5
  export declare const BACKING_SERVICE_KIND = "BackingService";
5
6
  export declare const BACKING_SERVICE_RESOURCE = "backingservices.platform.di-framework.dev";
@@ -38,6 +39,7 @@ export type ServiceCreateOptions = {
38
39
  /** Egress only: hosts the workload may reach. */
39
40
  destinations?: string[];
40
41
  target?: string;
42
+ env?: DeployEnvironment;
41
43
  namespace?: string;
42
44
  context?: string;
43
45
  wait: boolean;
@@ -46,6 +48,7 @@ export type ServiceCreateOptions = {
46
48
  export type ServiceNameOptions = {
47
49
  name?: string;
48
50
  target?: string;
51
+ env?: DeployEnvironment;
49
52
  namespace?: string;
50
53
  context?: string;
51
54
  };
@@ -123,6 +126,27 @@ export declare function parseServiceNameArgs(args: readonly string[], command: s
123
126
  export declare function parseServiceListArgs(args: readonly string[]): ServiceListOptions;
124
127
  export declare function summarizeService(document: BackingServiceDocument): ServiceSummary;
125
128
  export declare function runWasmcloudServiceCreate(args: readonly string[], io: CliIo, deps?: WasmcloudDeps): Promise<{
129
+ data: {
130
+ wait: boolean;
131
+ ready: string;
132
+ createdAt: string;
133
+ resource: {
134
+ apiVersion: string;
135
+ kind: string;
136
+ };
137
+ destinations?: string[] | undefined;
138
+ deletionPolicy?: "Retain" | "Delete" | undefined;
139
+ parameters?: import("./controller/schema.js").ServiceParameters | undefined;
140
+ name: string;
141
+ type: import("./controller/schema.js").ControllerServiceType;
142
+ className: string;
143
+ env: import("./controller/index.js").Env;
144
+ account: string;
145
+ namespace: string;
146
+ target: string;
147
+ };
148
+ text: string;
149
+ } | {
126
150
  data: {
127
151
  resource: {
128
152
  apiVersion: string;
@@ -160,6 +184,16 @@ export declare function runWasmcloudServiceGet(args: readonly string[], _io: Cli
160
184
  text: string;
161
185
  }>;
162
186
  export declare function runWasmcloudServiceDelete(args: readonly string[], io: CliIo, deps?: WasmcloudDeps): Promise<{
187
+ data: {
188
+ name: string;
189
+ env: DeployEnvironment;
190
+ account: string;
191
+ namespace: string;
192
+ target: string;
193
+ deleted: boolean;
194
+ };
195
+ text: string;
196
+ } | {
163
197
  data: {
164
198
  deletionPolicy?: string | undefined;
165
199
  name: string;