@di-framework/cli-plugin-platform 6.1.1 → 6.1.2

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.
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Node-shaped argument errors for the overlays. Messages follow Node v22's
3
+ * `ERR_OUT_OF_RANGE` / `ERR_INVALID_ARG_TYPE` / `ERR_INVALID_ARG_VALUE` text, including the
4
+ * `1_000_000` separators Node prints for values beyond 2**32. Do not import WASI from here.
5
+ */
6
+ type CodedError<E extends Error> = E & {
7
+ code: string;
8
+ };
9
+ /** `ERR_OUT_OF_RANGE`: `The value of "<name>" is out of range. It must be <range>. Received …`. */
10
+ export declare function outOfRange(name: string, range: string, received: unknown): CodedError<RangeError>;
11
+ /** `ERR_INVALID_ARG_TYPE`; `expected` is Node's phrase, e.g. `of type number`. */
12
+ export declare function invalidArgType(name: string, expected: string, received: unknown): CodedError<TypeError>;
13
+ /** `ERR_INVALID_ARG_VALUE`: `The argument '<name>' <reason>. Received …`. */
14
+ export declare function invalidArgValue(name: string, reason: string, received: string): CodedError<TypeError>;
15
+ /**
16
+ * Node's `validateInteger(value, name, min)`: a number, an integer, and within
17
+ * `[min, Number.MAX_SAFE_INTEGER]`.
18
+ */
19
+ export declare function validateInteger(value: unknown, name: string, min?: number): number;
20
+ export {};
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Node-shaped argument errors for the overlays. Messages follow Node v22's
3
+ * `ERR_OUT_OF_RANGE` / `ERR_INVALID_ARG_TYPE` / `ERR_INVALID_ARG_VALUE` text, including the
4
+ * `1_000_000` separators Node prints for values beyond 2**32. Do not import WASI from here.
5
+ */
6
+ function coded(error, code) {
7
+ return Object.assign(error, { code });
8
+ }
9
+ function addNumericalSeparator(value) {
10
+ let result = '';
11
+ let i = value.length;
12
+ const start = value.startsWith('-') ? 1 : 0;
13
+ for (; i >= start + 4; i -= 3)
14
+ result = `_${value.slice(i - 3, i)}${result}`;
15
+ return `${value.slice(0, i)}${result}`;
16
+ }
17
+ function formatRangeReceived(value) {
18
+ if (typeof value === 'number' && Number.isInteger(value) && Math.abs(value) > 2 ** 32) {
19
+ return addNumericalSeparator(String(value));
20
+ }
21
+ if (typeof value === 'bigint') {
22
+ const text = String(value);
23
+ return `${value > 2n ** 32n || value < -(2n ** 32n) ? addNumericalSeparator(text) : text}n`;
24
+ }
25
+ return String(value);
26
+ }
27
+ function formatTypeReceived(value) {
28
+ if (value === null || value === undefined)
29
+ return `Received ${value}`;
30
+ if (typeof value === 'function')
31
+ return `Received function ${value.name}`;
32
+ if (typeof value === 'object') {
33
+ const name = value.constructor?.name;
34
+ return name ? `Received an instance of ${name}` : 'Received [Object: null prototype] {}';
35
+ }
36
+ let shown;
37
+ if (typeof value === 'string') {
38
+ shown = `'${value.length > 28 ? `${value.slice(0, 25)}...` : value}'`;
39
+ }
40
+ else if (typeof value === 'bigint') {
41
+ shown = `${value}n`;
42
+ }
43
+ else {
44
+ shown = String(value);
45
+ }
46
+ return `Received type ${typeof value} (${shown})`;
47
+ }
48
+ /** `ERR_OUT_OF_RANGE`: `The value of "<name>" is out of range. It must be <range>. Received …`. */
49
+ export function outOfRange(name, range, received) {
50
+ return coded(new RangeError(`The value of "${name}" is out of range. It must be ${range}. Received ${formatRangeReceived(received)}`), 'ERR_OUT_OF_RANGE');
51
+ }
52
+ /** `ERR_INVALID_ARG_TYPE`; `expected` is Node's phrase, e.g. `of type number`. */
53
+ export function invalidArgType(name, expected, received) {
54
+ return coded(new TypeError(`The "${name}" argument must be ${expected}. ${formatTypeReceived(received)}`), 'ERR_INVALID_ARG_TYPE');
55
+ }
56
+ /** `ERR_INVALID_ARG_VALUE`: `The argument '<name>' <reason>. Received …`. */
57
+ export function invalidArgValue(name, reason, received) {
58
+ return coded(new TypeError(`The argument '${name}' ${reason}. Received ${received}`), 'ERR_INVALID_ARG_VALUE');
59
+ }
60
+ /**
61
+ * Node's `validateInteger(value, name, min)`: a number, an integer, and within
62
+ * `[min, Number.MAX_SAFE_INTEGER]`.
63
+ */
64
+ export function validateInteger(value, name, min = Number.MIN_SAFE_INTEGER) {
65
+ if (typeof value !== 'number')
66
+ throw invalidArgType(name, 'of type number', value);
67
+ if (!Number.isInteger(value))
68
+ throw outOfRange(name, 'an integer', value);
69
+ if (value < min || value > Number.MAX_SAFE_INTEGER) {
70
+ throw outOfRange(name, `>= ${min} && <= ${Number.MAX_SAFE_INTEGER}`, value);
71
+ }
72
+ return value;
73
+ }
@@ -12,8 +12,8 @@ export type WasiDescriptor = {
12
12
  write?: boolean;
13
13
  mutateDirectory?: boolean;
14
14
  }): WasiDescriptor;
15
- read(length: number, offset: number): [Uint8Array | number[], boolean];
16
- write(buffer: Uint8Array, offset: number): number;
15
+ read(length: number, offset: number | bigint): [Uint8Array | number[], boolean];
16
+ write(buffer: Uint8Array, offset: number): number | bigint;
17
17
  setSize(size: number): void;
18
18
  stat(): WasiStat;
19
19
  statAt(pathFlags: {
@@ -70,7 +70,7 @@ export declare function createStorage(preopens: () => Preopen[], prefixes?: type
70
70
  readFile(path: string): Uint8Array;
71
71
  writeFile(path: string, bytes: Uint8Array): void;
72
72
  appendFile(path: string, bytes: Uint8Array): void;
73
- readAt(path: string, length: number, offset: number): Uint8Array;
73
+ readAt(path: string, length: number, offset: number | bigint): Uint8Array;
74
74
  writeAt(path: string, bytes: Uint8Array, offset: number | "end"): number;
75
75
  truncate(path: string): void;
76
76
  stat: (path: string) => StorageStat;
@@ -1,2 +1,22 @@
1
- /** Guest CSPRNG from WASI 0.3 `wasi:random/random`. */
1
+ /** Node's `kMaxPossibleLength` for `crypto.randomBytes` / `randomFillSync` sizes: 2**31 - 1. */
2
+ export declare const RANDOM_SIZE_MAX: number;
3
+ /**
4
+ * Largest `max-len` one `wasi:random` call asks for. Bigger requests are filled in
5
+ * chunks so the host never allocates more than this per call (it matches the Web
6
+ * Crypto `getRandomValues` quota).
7
+ */
8
+ export declare const RANDOM_CHUNK = 65536;
9
+ /**
10
+ * Validates a byte count exactly as Node v22's `crypto.randomBytes` does: a number
11
+ * (`ERR_INVALID_ARG_TYPE` otherwise, BigInt included) in `[0, 2**31 - 1]`
12
+ * (`ERR_OUT_OF_RANGE` otherwise, NaN included). Like Node, fractional sizes are
13
+ * accepted and truncated (`1.5` gives one byte). Returns the truncated count.
14
+ */
15
+ export declare function validateRandomSize(size: unknown, name?: string): number;
16
+ /**
17
+ * Fills `target` from the guest CSPRNG in calls of at most {@link RANDOM_CHUNK} bytes.
18
+ * Callers validate the length first.
19
+ */
20
+ export declare function fillRandom(target: Uint8Array): Uint8Array;
21
+ /** Guest CSPRNG from WASI 0.3 `wasi:random/random`, validated like `crypto.randomBytes`. */
2
22
  export declare function getRandomBytes(size: number): Uint8Array;
@@ -1,5 +1,14 @@
1
1
  import { getRandomBytes as wasiGetRandomBytes } from 'wasi:random/random@0.3.0';
2
2
  import { toBytes } from './bytes.js';
3
+ import { invalidArgType, outOfRange } from './node-errors.js';
4
+ /** Node's `kMaxPossibleLength` for `crypto.randomBytes` / `randomFillSync` sizes: 2**31 - 1. */
5
+ export const RANDOM_SIZE_MAX = 2 ** 31 - 1;
6
+ /**
7
+ * Largest `max-len` one `wasi:random` call asks for. Bigger requests are filled in
8
+ * chunks so the host never allocates more than this per call (it matches the Web
9
+ * Crypto `getRandomValues` quota).
10
+ */
11
+ export const RANDOM_CHUNK = 65_536;
3
12
  function unwrapRandom(value) {
4
13
  if (value !== null && typeof value === 'object' && 'tag' in value) {
5
14
  const result = value;
@@ -9,17 +18,41 @@ function unwrapRandom(value) {
9
18
  }
10
19
  return toBytes(value);
11
20
  }
12
- /** Guest CSPRNG from WASI 0.3 `wasi:random/random`. */
13
- export function getRandomBytes(size) {
14
- if (!Number.isFinite(size) || size < 0) {
15
- throw new RangeError(`getRandomBytes size must be a non-negative integer, received ${size}`);
21
+ /**
22
+ * Validates a byte count exactly as Node v22's `crypto.randomBytes` does: a number
23
+ * (`ERR_INVALID_ARG_TYPE` otherwise, BigInt included) in `[0, 2**31 - 1]`
24
+ * (`ERR_OUT_OF_RANGE` otherwise, NaN included). Like Node, fractional sizes are
25
+ * accepted and truncated (`1.5` gives one byte). Returns the truncated count.
26
+ */
27
+ export function validateRandomSize(size, name = 'size') {
28
+ if (typeof size !== 'number')
29
+ throw invalidArgType(name, 'of type number', size);
30
+ if (Number.isNaN(size) || size < 0 || size > RANDOM_SIZE_MAX) {
31
+ throw outOfRange(name, `>= 0 && <= ${RANDOM_SIZE_MAX}`, size);
32
+ }
33
+ return Math.trunc(size);
34
+ }
35
+ function requestRandom(length) {
36
+ // `max-len` is a WIT u64; BigInt is the canonical JS representation, and
37
+ // componentize-qjs 0.4.4-di.5+ traps on a Number that is not a safe integer.
38
+ const bytes = unwrapRandom(wasiGetRandomBytes(BigInt(length)));
39
+ if (bytes.length < length) {
40
+ throw new Error(`wasi:random returned ${bytes.length} bytes, expected ${length}`);
16
41
  }
17
- if (size === 0)
18
- return new Uint8Array();
19
- const bytes = unwrapRandom(wasiGetRandomBytes(size));
20
- if (bytes.length === size)
21
- return bytes.slice();
22
- if (bytes.length > size)
23
- return bytes.slice(0, size);
24
- throw new Error(`wasi:random returned ${bytes.length} bytes, expected ${size}`);
42
+ return bytes.length === length ? bytes : bytes.subarray(0, length);
43
+ }
44
+ /**
45
+ * Fills `target` from the guest CSPRNG in calls of at most {@link RANDOM_CHUNK} bytes.
46
+ * Callers validate the length first.
47
+ */
48
+ export function fillRandom(target) {
49
+ for (let offset = 0; offset < target.length; offset += RANDOM_CHUNK) {
50
+ target.set(requestRandom(Math.min(RANDOM_CHUNK, target.length - offset)), offset);
51
+ }
52
+ return target;
53
+ }
54
+ /** Guest CSPRNG from WASI 0.3 `wasi:random/random`, validated like `crypto.randomBytes`. */
55
+ export function getRandomBytes(size) {
56
+ const length = validateRandomSize(size);
57
+ return fillRandom(new Uint8Array(length));
25
58
  }
@@ -0,0 +1,106 @@
1
+ import { type CliIo } from '@di-framework/cli-extension';
2
+ import type { WasmcloudDeps } from './deps.js';
3
+ import type { ClusterConnection } from './target.js';
4
+ export { DI_PGLITE_PACKAGE, DI_PGLITE_VERSION, PGLITE_SOURCE } from './wit.js';
5
+ /**
6
+ * Embedded PostgreSQL provider (`di-framework:pglite`), published by di-framework/platform
7
+ * as `ghcr.io/di-framework/pglite-component`. A guest that imports its `database` interface
8
+ * gets the provider plugged in after componentize; the deployed component is then marked
9
+ * exclusive and given persistent storage, because the engine tolerates exactly one opener
10
+ * of its data directory.
11
+ */
12
+ export declare const PGLITE_REPOSITORY = "ghcr.io/di-framework/pglite-component";
13
+ /** Absolute (or cwd-relative) path of a local provider build; wins over the config. */
14
+ export declare const PGLITE_WASM_ENV = "DI_FRAMEWORK_PGLITE_WASM";
15
+ /** Root of the CLI's download cache. Defaults to `$XDG_CACHE_HOME/di-framework`. */
16
+ export declare const CACHE_DIR_ENV = "DI_FRAMEWORK_CACHE_DIR";
17
+ /** Guest environment entry naming the database root the guest passes to `open`. */
18
+ export declare const PGLITE_DATA_DIR_ENV = "DI_PGLITE_DATA_DIR";
19
+ /**
20
+ * `localResources.config` entry the patched tenant host reads (di-framework/platform#140).
21
+ * Components only: platform admission rejects it on the service.
22
+ */
23
+ export declare const EXCLUSIVE_INSTANCE_KEY = "di-framework.dev/exclusive-instance";
24
+ export declare const DEFAULT_PGLITE_STORAGE_MOUNT = "/data";
25
+ /** File name of the provider inside a cache entry. */
26
+ export declare const PGLITE_WASM_FILE = "di-framework-pglite.wasm";
27
+ /** `pglite` in di-framework.config.json, resolved. */
28
+ export type PgliteConfig = {
29
+ /** `<repository>@sha256:<hex>`; the manifest digest the platform publish job records. */
30
+ image?: string;
31
+ /** Absolute path of a local provider build, used instead of `image`. */
32
+ wasm?: string;
33
+ /** Guest preopen for the workload's persistent directory. */
34
+ storageMount: string;
35
+ /** Database root the guest opens; at or under `storageMount`. */
36
+ dataDir: string;
37
+ };
38
+ export type ResolvedPglite = {
39
+ /** Verified provider bytes; the build plugs a private copy of these. */
40
+ bytes: Buffer;
41
+ source: 'local' | 'cache' | 'registry';
42
+ /** The digest pin, when the bytes came from the registry or the cache. */
43
+ image?: string;
44
+ /** The local file, when the bytes came from one. */
45
+ path?: string;
46
+ };
47
+ export declare function parseDigestReference(reference: string): {
48
+ repository: string;
49
+ digest: string;
50
+ };
51
+ /** True when `path` is `directory` or below it (both normalized guest paths). */
52
+ export declare function isWithin(path: string, directory: string): boolean;
53
+ /** Validates `pglite` from the config. `resolveFile` keeps `wasm` inside the project. */
54
+ export declare function parsePgliteConfig(value: unknown, configPath: string, resolveFile: (path: string) => string): PgliteConfig | undefined;
55
+ export declare function cacheRoot(env: Record<string, string | undefined>): string;
56
+ /** Where a digest-pinned provider is cached: `<cache>/oci/sha256/<hex>/`. */
57
+ export declare function cacheEntry(env: Record<string, string | undefined>, digest: string): string;
58
+ /**
59
+ * The manifest bytes must hash to the pinned digest; then the single `application/wasm`
60
+ * layer names the blob digest the provider bytes must hash to.
61
+ */
62
+ export declare function verifyManifest(bytes: Uint8Array, image: string): string;
63
+ export declare function verifyLayer(bytes: Uint8Array, image: string, layerDigest: string): void;
64
+ /** Staging directories older than this were left by a killed build and are removed. */
65
+ export declare const STALE_STAGING_MS: number;
66
+ /**
67
+ * Pulls the provider by digest with `oras`, verifying the manifest digest and the layer
68
+ * digest, into the cache. A cached entry is re-verified on every use; a corrupt one is
69
+ * pulled again. Returns the verified bytes, so later readers never see a swapped file.
70
+ */
71
+ export declare function pullPgliteComponent(image: string, io: CliIo, deps: WasmcloudDeps, cwd: string): Promise<ResolvedPglite>;
72
+ /** Set to `1` to let `deploy` or a CI build use a local, unverified provider. */
73
+ export declare const ALLOW_LOCAL_PGLITE_ENV = "DI_FRAMEWORK_ALLOW_LOCAL_PGLITE";
74
+ export type ResolvePgliteOptions = {
75
+ /** A deploy ships the provider, so a local file needs the explicit opt-in. */
76
+ deploy?: boolean;
77
+ };
78
+ /**
79
+ * The provider to compose: `DI_FRAMEWORK_PGLITE_WASM`, then `pglite.wasm`, then the
80
+ * digest-pinned `pglite.image`. Local files are only checked to be WebAssembly, and are
81
+ * refused in a deploy or on CI without `DI_FRAMEWORK_ALLOW_LOCAL_PGLITE=1`.
82
+ */
83
+ export declare function resolvePgliteComponent(config: PgliteConfig, io: CliIo, deps: WasmcloudDeps, projectRoot: string, options?: ResolvePgliteOptions): Promise<ResolvedPglite>;
84
+ /**
85
+ * Members of one workload share one storage directory, mounted at each member's own
86
+ * `storageMount`. Two members whose `dataDir` is the same path relative to their mount
87
+ * would open the same database from separate instances, which exclusivity cannot stop.
88
+ */
89
+ export declare function assertDistinctPgliteRoots(workload: string, members: Iterable<{
90
+ applicationName: string;
91
+ workload?: string;
92
+ pglite?: PgliteConfig;
93
+ }>): void;
94
+ /** Tag fragment of the tenant host image that honours the exclusive opt-in (#140). */
95
+ export declare const EXCLUSIVE_HOST_IMAGE_MARKER = "-exclusive";
96
+ /**
97
+ * Stock wash ignores `di-framework.dev/exclusive-instance`: when its pool saturates or an
98
+ * instance drains, it builds a second store, which opens the same data directory. Warn when
99
+ * a tenant host group's image is not the exclusive build; elsewhere the CLI cannot see the
100
+ * host, so say what the opt-in depends on.
101
+ */
102
+ export declare function warnIfHostIgnoresExclusive(project: {
103
+ applicationName: string;
104
+ projectRoot: string;
105
+ pglite?: PgliteConfig;
106
+ }, connection: ClusterConnection, io: CliIo, deps: WasmcloudDeps): Promise<void>;
package/dist/pglite.js ADDED
@@ -0,0 +1,347 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, statSync, } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { join, posix, resolve } from 'node:path';
5
+ import { CommandFailure } from '@di-framework/cli-extension';
6
+ import { captureKubectl } from './kubernetes.js';
7
+ import { DI_PGLITE_VERSION } from './wit.js';
8
+ export { DI_PGLITE_PACKAGE, DI_PGLITE_VERSION, PGLITE_SOURCE } from './wit.js';
9
+ /**
10
+ * Embedded PostgreSQL provider (`di-framework:pglite`), published by di-framework/platform
11
+ * as `ghcr.io/di-framework/pglite-component`. A guest that imports its `database` interface
12
+ * gets the provider plugged in after componentize; the deployed component is then marked
13
+ * exclusive and given persistent storage, because the engine tolerates exactly one opener
14
+ * of its data directory.
15
+ */
16
+ export const PGLITE_REPOSITORY = 'ghcr.io/di-framework/pglite-component';
17
+ /** Absolute (or cwd-relative) path of a local provider build; wins over the config. */
18
+ export const PGLITE_WASM_ENV = 'DI_FRAMEWORK_PGLITE_WASM';
19
+ /** Root of the CLI's download cache. Defaults to `$XDG_CACHE_HOME/di-framework`. */
20
+ export const CACHE_DIR_ENV = 'DI_FRAMEWORK_CACHE_DIR';
21
+ /** Guest environment entry naming the database root the guest passes to `open`. */
22
+ export const PGLITE_DATA_DIR_ENV = 'DI_PGLITE_DATA_DIR';
23
+ /**
24
+ * `localResources.config` entry the patched tenant host reads (di-framework/platform#140).
25
+ * Components only: platform admission rejects it on the service.
26
+ */
27
+ export const EXCLUSIVE_INSTANCE_KEY = 'di-framework.dev/exclusive-instance';
28
+ export const DEFAULT_PGLITE_STORAGE_MOUNT = '/data';
29
+ /** File name of the provider inside a cache entry. */
30
+ export const PGLITE_WASM_FILE = 'di-framework-pglite.wasm';
31
+ const WASM_LAYER_MEDIA_TYPE = 'application/wasm';
32
+ const SHA256_DIGEST = /^sha256:[0-9a-f]{64}$/;
33
+ const DIGEST_REFERENCE = /^([a-z0-9]+(?:[.:-][a-z0-9]+)*(?:\/[a-z0-9]+(?:[._-][a-z0-9]+)*)+)@(.+)$/;
34
+ const CONFIG_KEYS = ['image', 'wasm', 'storageMount', 'dataDir'];
35
+ function configInvalid(message, configPath) {
36
+ throw new CommandFailure('WASMCLOUD_CONFIG_INVALID', message, 2, { configPath });
37
+ }
38
+ export function parseDigestReference(reference) {
39
+ const match = DIGEST_REFERENCE.exec(reference);
40
+ const digest = match?.[2] ?? '';
41
+ 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`);
43
+ }
44
+ return { repository: match[1], digest };
45
+ }
46
+ function absoluteGuestPath(value, label, configPath) {
47
+ if (typeof value !== 'string' || !value.startsWith('/'))
48
+ configInvalid(`pglite.${label} must be an absolute guest path`, configPath);
49
+ const normalized = posix.normalize(value);
50
+ return normalized.length > 1 && normalized.endsWith('/') ? normalized.slice(0, -1) : normalized;
51
+ }
52
+ /** `image` must be a digest pin and `wasm` a path; at least one of them is required. */
53
+ function validateProviderSource(entry, configPath) {
54
+ if (entry.image !== undefined) {
55
+ if (typeof entry.image !== 'string')
56
+ configInvalid('pglite.image must be a string', configPath);
57
+ try {
58
+ parseDigestReference(entry.image);
59
+ }
60
+ catch (error) {
61
+ configInvalid(`pglite.image: ${error.message}`, configPath);
62
+ }
63
+ }
64
+ if (entry.wasm !== undefined && (typeof entry.wasm !== 'string' || entry.wasm.trim() === ''))
65
+ configInvalid('pglite.wasm must be a non-empty path', configPath);
66
+ if (entry.image === undefined && entry.wasm === undefined)
67
+ configInvalid(`pglite needs "image" (${PGLITE_REPOSITORY}@sha256:<digest>) or a local "wasm" path`, configPath);
68
+ }
69
+ /** True when `path` is `directory` or below it (both normalized guest paths). */
70
+ export function isWithin(path, directory) {
71
+ return path === directory || path.startsWith(directory === '/' ? '/' : `${directory}/`);
72
+ }
73
+ /** Validates `pglite` from the config. `resolveFile` keeps `wasm` inside the project. */
74
+ export function parsePgliteConfig(value, configPath, resolveFile) {
75
+ if (value === undefined)
76
+ return undefined;
77
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
78
+ configInvalid('pglite must be an object', configPath);
79
+ const entry = value;
80
+ const unknown = Object.keys(entry).filter((key) => !CONFIG_KEYS.includes(key));
81
+ if (unknown.length > 0)
82
+ configInvalid(`pglite has unsupported fields: ${unknown.join(', ')}. Use ${CONFIG_KEYS.join(', ')}`, configPath);
83
+ validateProviderSource(entry, configPath);
84
+ const storageMount = entry.storageMount === undefined
85
+ ? DEFAULT_PGLITE_STORAGE_MOUNT
86
+ : absoluteGuestPath(entry.storageMount, 'storageMount', configPath);
87
+ const dataDir = entry.dataDir === undefined
88
+ ? posix.join(storageMount, 'pglite')
89
+ : absoluteGuestPath(entry.dataDir, 'dataDir', configPath);
90
+ if (!isWithin(dataDir, storageMount))
91
+ configInvalid(`pglite.dataDir ${dataDir} must be inside storageMount ${storageMount}; only that directory is persistent`, configPath);
92
+ return {
93
+ ...(entry.image === undefined ? {} : { image: entry.image }),
94
+ ...(entry.wasm === undefined ? {} : { wasm: resolveFile(entry.wasm) }),
95
+ storageMount,
96
+ dataDir,
97
+ };
98
+ }
99
+ export function cacheRoot(env) {
100
+ const explicit = env[CACHE_DIR_ENV]?.trim();
101
+ if (explicit)
102
+ return resolve(explicit);
103
+ const xdg = env.XDG_CACHE_HOME?.trim();
104
+ return xdg ? join(xdg, 'di-framework') : join(env.HOME ?? homedir(), '.cache', 'di-framework');
105
+ }
106
+ /** Where a digest-pinned provider is cached: `<cache>/oci/sha256/<hex>/`. */
107
+ export function cacheEntry(env, digest) {
108
+ return join(cacheRoot(env), 'oci', 'sha256', digest.slice('sha256:'.length));
109
+ }
110
+ function sha256(bytes) {
111
+ return `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
112
+ }
113
+ function failure(code, message, details = {}) {
114
+ return new CommandFailure(code, message, 3, details);
115
+ }
116
+ /**
117
+ * The manifest bytes must hash to the pinned digest; then the single `application/wasm`
118
+ * layer names the blob digest the provider bytes must hash to.
119
+ */
120
+ export function verifyManifest(bytes, image) {
121
+ const { digest } = parseDigestReference(image);
122
+ const actual = sha256(bytes);
123
+ if (actual !== digest)
124
+ throw failure('WASMCLOUD_PGLITE_DIGEST_MISMATCH', `Manifest pulled for ${image} hashes to ${actual}, not the pinned ${digest}`, { image, expected: digest, actual });
125
+ let manifest;
126
+ try {
127
+ manifest = JSON.parse(Buffer.from(bytes).toString('utf8'));
128
+ }
129
+ catch {
130
+ throw failure('WASMCLOUD_PGLITE_MANIFEST_INVALID', `Manifest for ${image} is not JSON`, {
131
+ image,
132
+ });
133
+ }
134
+ if (manifest.manifests !== undefined)
135
+ throw failure('WASMCLOUD_PGLITE_MANIFEST_INVALID', `${image} is an image index; pin the digest of the wasm artifact manifest instead`, { image });
136
+ const layers = (manifest.layers ?? []).filter((layer) => layer.mediaType === WASM_LAYER_MEDIA_TYPE);
137
+ const layer = layers[0];
138
+ if (layers.length !== 1 || typeof layer?.digest !== 'string' || !SHA256_DIGEST.test(layer.digest))
139
+ throw failure('WASMCLOUD_PGLITE_MANIFEST_INVALID', `Manifest for ${image} must have exactly one ${WASM_LAYER_MEDIA_TYPE} layer with a sha256 digest`, { image });
140
+ return layer.digest;
141
+ }
142
+ function isWasm(bytes) {
143
+ return (bytes.length >= 4 &&
144
+ bytes[0] === 0 &&
145
+ bytes[1] === 0x61 &&
146
+ bytes[2] === 0x73 &&
147
+ bytes[3] === 0x6d);
148
+ }
149
+ export function verifyLayer(bytes, image, layerDigest) {
150
+ const actual = sha256(bytes);
151
+ if (actual !== layerDigest)
152
+ throw failure('WASMCLOUD_PGLITE_DIGEST_MISMATCH', `Provider layer of ${image} hashes to ${actual}, not ${layerDigest} from its manifest`, { image, expected: layerDigest, actual });
153
+ if (!isWasm(bytes))
154
+ throw failure('WASMCLOUD_PGLITE_MANIFEST_INVALID', `Provider layer of ${image} is not a WebAssembly binary`, { image });
155
+ }
156
+ /** The verified provider bytes of a cache entry, or undefined when it is absent or stale. */
157
+ function readVerifiedEntry(directory, image) {
158
+ const manifestPath = join(directory, 'manifest.json');
159
+ const wasmPath = join(directory, PGLITE_WASM_FILE);
160
+ if (!existsSync(manifestPath) || !existsSync(wasmPath))
161
+ return undefined;
162
+ try {
163
+ const bytes = readFileSync(wasmPath);
164
+ verifyLayer(bytes, image, verifyManifest(readFileSync(manifestPath), image));
165
+ return bytes;
166
+ }
167
+ catch {
168
+ return undefined;
169
+ }
170
+ }
171
+ /** Staging directories older than this were left by a killed build and are removed. */
172
+ export const STALE_STAGING_MS = 24 * 60 * 60 * 1000;
173
+ function sweepStaleStaging(root, now) {
174
+ for (const name of readdirSync(root)) {
175
+ if (!name.startsWith('.pull-'))
176
+ continue;
177
+ const path = join(root, name);
178
+ try {
179
+ if (now - statSync(path).mtimeMs > STALE_STAGING_MS)
180
+ rmSync(path, { recursive: true, force: true });
181
+ }
182
+ catch {
183
+ // Another build removed it first.
184
+ }
185
+ }
186
+ }
187
+ async function oras(deps, args, image, cwd) {
188
+ const result = await deps.runCaptured('oras', args, { cwd });
189
+ if (result.exitCode === 0)
190
+ return;
191
+ const reason = (result.stderr || result.stdout).trim();
192
+ const detail = reason ? `: ${reason}` : '';
193
+ 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) });
195
+ }
196
+ /**
197
+ * Stores a verified staging directory as the cache entry. A concurrent build may have
198
+ * stored the same digest first; its entry is used when it verifies.
199
+ */
200
+ function storeEntry(staging, entry, image, bytes) {
201
+ mkdirSync(join(entry, '..'), { recursive: true });
202
+ try {
203
+ renameSync(staging, entry);
204
+ return bytes;
205
+ }
206
+ catch (error) {
207
+ const winner = readVerifiedEntry(entry, image);
208
+ if (winner !== undefined)
209
+ return winner;
210
+ throw failure('WASMCLOUD_PGLITE_CACHE_CONFLICT', `Could not store ${image} in the cache at ${entry} (${error.code ?? 'unknown error'}), ` +
211
+ `and the entry there does not verify; remove ${entry} and retry`, { image, entry });
212
+ }
213
+ }
214
+ /**
215
+ * Pulls the provider by digest with `oras`, verifying the manifest digest and the layer
216
+ * digest, into the cache. A cached entry is re-verified on every use; a corrupt one is
217
+ * pulled again. Returns the verified bytes, so later readers never see a swapped file.
218
+ */
219
+ export async function pullPgliteComponent(image, io, deps, cwd) {
220
+ const { repository, digest } = parseDigestReference(image);
221
+ const entry = cacheEntry(deps.env, digest);
222
+ const cached = readVerifiedEntry(entry, image);
223
+ if (cached !== undefined) {
224
+ io.stdout.write(`Using cached ${image}\n`);
225
+ return { bytes: cached, source: 'cache', image };
226
+ }
227
+ if (existsSync(entry)) {
228
+ io.stderr.write(`Cached ${image} failed verification; pulling it again\n`);
229
+ rmSync(entry, { recursive: true, force: true });
230
+ }
231
+ 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' });
233
+ const root = cacheRoot(deps.env);
234
+ mkdirSync(root, { recursive: true });
235
+ sweepStaleStaging(root, Date.now());
236
+ const staging = mkdtempSync(join(root, '.pull-'));
237
+ try {
238
+ io.stdout.write(`Pulling ${image}...\n`);
239
+ const manifestPath = join(staging, 'manifest.json');
240
+ await oras(deps, ['manifest', 'fetch', '--output', manifestPath, image], image, cwd);
241
+ 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);
244
+ const bytes = readFileSync(stagedWasm);
245
+ verifyLayer(bytes, image, layerDigest);
246
+ return { bytes: storeEntry(staging, entry, image, bytes), source: 'registry', image };
247
+ }
248
+ finally {
249
+ rmSync(staging, { recursive: true, force: true });
250
+ }
251
+ }
252
+ /** Set to `1` to let `deploy` or a CI build use a local, unverified provider. */
253
+ export const ALLOW_LOCAL_PGLITE_ENV = 'DI_FRAMEWORK_ALLOW_LOCAL_PGLITE';
254
+ function readLocalProvider(local, origin, config, io, deps, options) {
255
+ if (!existsSync(local))
256
+ throw failure('WASMCLOUD_PGLITE_PROVIDER_MISSING', `PGlite provider ${local} (from ${origin}) does not exist`, { path: local });
257
+ let context;
258
+ if (options.deploy)
259
+ context = 'deploy';
260
+ else if (deps.env.CI)
261
+ context = 'CI';
262
+ 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 });
265
+ const bytes = readFileSync(local);
266
+ if (!isWasm(bytes))
267
+ throw failure('WASMCLOUD_PGLITE_PROVIDER_INVALID', `PGlite provider ${local} (from ${origin}) is not a WebAssembly binary`, { path: local });
268
+ 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`);
270
+ return { bytes, source: 'local', path: local };
271
+ }
272
+ /**
273
+ * The provider to compose: `DI_FRAMEWORK_PGLITE_WASM`, then `pglite.wasm`, then the
274
+ * digest-pinned `pglite.image`. Local files are only checked to be WebAssembly, and are
275
+ * refused in a deploy or on CI without `DI_FRAMEWORK_ALLOW_LOCAL_PGLITE=1`.
276
+ */
277
+ export async function resolvePgliteComponent(config, io, deps, projectRoot, options = {}) {
278
+ const fromEnv = deps.env[PGLITE_WASM_ENV]?.trim();
279
+ if (fromEnv)
280
+ return readLocalProvider(resolve(deps.cwd(), fromEnv), PGLITE_WASM_ENV, config, io, deps, options);
281
+ if (config.wasm !== undefined)
282
+ return readLocalProvider(config.wasm, 'pglite.wasm', config, io, deps, options);
283
+ return pullPgliteComponent(config.image, io, deps, projectRoot);
284
+ }
285
+ /**
286
+ * 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.
289
+ */
290
+ export function assertDistinctPgliteRoots(workload, members) {
291
+ const owners = new Map();
292
+ for (const member of members) {
293
+ if (member.workload !== workload || member.pglite === undefined)
294
+ continue;
295
+ const root = posix.relative(member.pglite.storageMount, member.pglite.dataDir);
296
+ const previous = owners.get(root);
297
+ if (previous !== undefined)
298
+ throw new CommandFailure('WASMCLOUD_PGLITE_DATA_DIR_CONFLICT', `${workload}: ${previous} and ${member.applicationName} would open the same PGlite database ` +
299
+ `(<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);
301
+ }
302
+ }
303
+ /** Tag fragment of the tenant host image that honours the exclusive opt-in (#140). */
304
+ export const EXCLUSIVE_HOST_IMAGE_MARKER = '-exclusive';
305
+ function hasExclusiveTag(image) {
306
+ const tag = image.split('@')[0]?.split('/').pop()?.split(':')[1];
307
+ return tag?.includes(EXCLUSIVE_HOST_IMAGE_MARKER) === true;
308
+ }
309
+ async function hostImages(connection, hostgroup, deps, cwd) {
310
+ const runtime = { ...connection, namespace: `di-runtime-${hostgroup.slice('tenant-'.length)}` };
311
+ const result = await captureKubectl(deps, runtime, ['get', 'pods', '-l', `wasmcloud.com/hostgroup=${hostgroup}`, '-o', 'json'], cwd);
312
+ if (result.exitCode !== 0)
313
+ return undefined;
314
+ try {
315
+ const list = JSON.parse(result.stdout);
316
+ return (list.items ?? []).flatMap((pod) => (pod.spec?.containers ?? []).flatMap((container) => typeof container.image === 'string' ? [container.image] : []));
317
+ }
318
+ catch {
319
+ return undefined;
320
+ }
321
+ }
322
+ /**
323
+ * Stock wash ignores `di-framework.dev/exclusive-instance`: when its pool saturates or an
324
+ * instance drains, it builds a second store, which opens the same data directory. Warn when
325
+ * a tenant host group's image is not the exclusive build; elsewhere the CLI cannot see the
326
+ * host, so say what the opt-in depends on.
327
+ */
328
+ export async function warnIfHostIgnoresExclusive(project, connection, io, deps) {
329
+ if (project.pglite === undefined)
330
+ return;
331
+ const risk = 'Without it a second instance can open the same PGlite data directory and corrupt it';
332
+ const hostgroup = connection.hostgroup;
333
+ if (!hostgroup?.startsWith('tenant-')) {
334
+ const group = hostgroup ?? connection.storageHostgroup ?? 'storage';
335
+ io.stderr.write(`Note: ${project.applicationName} embeds PGlite and is marked exclusive; host group ${group} ` +
336
+ `must run a wash image built with the exclusive patch (tagged *${EXCLUSIVE_HOST_IMAGE_MARKER}). ${risk}.\n`);
337
+ return;
338
+ }
339
+ const images = await hostImages(connection, hostgroup, deps, project.projectRoot);
340
+ if (images?.some(hasExclusiveTag))
341
+ return;
342
+ const seen = images === undefined || images.length === 0
343
+ ? 'could not read its host image'
344
+ : `runs ${images[0]}`;
345
+ io.stderr.write(`Warning: ${project.applicationName} embeds PGlite and is marked exclusive, but host group ${hostgroup} ` +
346
+ `${seen}, which does not look like the exclusive build (tagged *${EXCLUSIVE_HOST_IMAGE_MARKER}, set with the platform's tenantHostImage). ${risk}.\n`);
347
+ }