@tomflow/proflow-platform-cli 0.1.1 → 0.1.3

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 (41) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +24 -3
  3. package/dist/deployment/adapter.d.ts +5 -5
  4. package/dist/deployment/descriptor.d.ts +1 -1
  5. package/dist/deployment/descriptor.js +1 -1
  6. package/dist/src/apply/apply.d.ts +2 -0
  7. package/dist/src/apply/apply.js +47 -4
  8. package/dist/src/apply/current.js +14 -0
  9. package/dist/src/apply/driver.d.ts +1 -0
  10. package/dist/src/apply/driver.js +40 -12
  11. package/dist/src/apply/execute.js +28 -0
  12. package/dist/src/binding/global-binding.d.ts +69 -0
  13. package/dist/src/binding/global-binding.js +349 -0
  14. package/dist/src/binding/production-bindings.d.ts +2 -12
  15. package/dist/src/binding/production-bindings.js +18 -4
  16. package/dist/src/cli.d.ts +13 -1
  17. package/dist/src/cli.js +661 -40
  18. package/dist/src/errors.d.ts +1 -1
  19. package/dist/src/errors.js +13 -0
  20. package/dist/src/install/environment.d.ts +2 -1
  21. package/dist/src/install/environment.js +34 -30
  22. package/dist/src/install/install.js +41 -0
  23. package/dist/src/install/package-manager.d.ts +4 -2
  24. package/dist/src/install/package-manager.js +73 -17
  25. package/dist/src/lifecycle/dispatch.js +52 -1
  26. package/dist/src/lifecycle/service-process.js +32 -2
  27. package/dist/src/persistence/guards.js +1 -0
  28. package/dist/src/planner/check.js +12 -1
  29. package/dist/src/planner/plan.d.ts +1 -0
  30. package/dist/src/planner/plan.js +14 -26
  31. package/dist/src/preflight/config.d.ts +1 -0
  32. package/dist/src/preflight/config.js +43 -0
  33. package/dist/src/preflight/preflight.d.ts +2 -0
  34. package/dist/src/preflight/preflight.js +18 -2
  35. package/dist/src/preflight/requirements.d.ts +2 -2
  36. package/dist/src/preflight/requirements.js +16 -9
  37. package/dist/src/registry/npm-registry.d.ts +1 -1
  38. package/dist/src/registry/npm-registry.js +2 -1
  39. package/dist/src/security/lock.js +40 -2
  40. package/package.json +4 -4
  41. package/proflow.module.json +1 -1
@@ -0,0 +1,349 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { access, chmod, mkdir, open, readFile, realpath, rm, stat, unlink, } from "node:fs/promises";
4
+ import { homedir } from "node:os";
5
+ import { dirname, join, resolve } from "node:path";
6
+ import { PlatformError } from "../errors.js";
7
+ import { atomicWrite } from "../paths.js";
8
+ export const GLOBAL_BINDING_CONTRACT = "deployment.global-binding.v1";
9
+ export const WORKSPACE_INSTANCE_CONTRACT = "deployment.workspace-instance.v1";
10
+ export function globalPlatformPaths(globalRoot) {
11
+ const root = globalRoot ??
12
+ process.env.PROFLOW_GLOBAL_HOME ??
13
+ join(homedir(), ".proflow", "platform");
14
+ return {
15
+ root,
16
+ bindingJson: join(root, "binding.json"),
17
+ bindingLock: join(root, "binding.lock"),
18
+ operationLock: join(root, "operation.lock"),
19
+ };
20
+ }
21
+ export async function canonicalizeWorkspace(workspace) {
22
+ const workspacePath = resolve(workspace);
23
+ let info;
24
+ try {
25
+ info = await stat(workspacePath);
26
+ }
27
+ catch {
28
+ throw new PlatformError("WORKSPACE_NOT_FOUND", `workspace does not exist: ${workspacePath}`);
29
+ }
30
+ if (!info.isDirectory()) {
31
+ throw new PlatformError("WORKSPACE_NOT_FOUND", `workspace is not a directory: ${workspacePath}`);
32
+ }
33
+ try {
34
+ await access(workspacePath, constants.R_OK | constants.W_OK);
35
+ }
36
+ catch {
37
+ throw new PlatformError("WORKSPACE_NOT_WRITABLE", `workspace is not readable and writable: ${workspacePath}`);
38
+ }
39
+ return { workspacePath, workspaceRealPath: await realpath(workspacePath) };
40
+ }
41
+ export async function loadGlobalBinding(globalRoot) {
42
+ const paths = globalPlatformPaths(globalRoot);
43
+ try {
44
+ const raw = await readFile(paths.bindingJson, "utf8");
45
+ const parsed = JSON.parse(raw);
46
+ if (!isGlobalWorkspaceBinding(parsed)) {
47
+ throw new PlatformError("GLOBAL_BINDING_INVALID", `global binding is invalid: ${paths.bindingJson}`);
48
+ }
49
+ return parsed;
50
+ }
51
+ catch (error) {
52
+ if (isMissingFile(error))
53
+ return undefined;
54
+ if (error instanceof PlatformError)
55
+ throw error;
56
+ throw new PlatformError("GLOBAL_BINDING_INVALID", `cannot read global binding ${paths.bindingJson}: ${errorMessage(error)}`);
57
+ }
58
+ }
59
+ export async function observeBoundWorkspace(globalRoot) {
60
+ const binding = await loadGlobalBinding(globalRoot);
61
+ if (binding === undefined)
62
+ return undefined;
63
+ return {
64
+ binding,
65
+ workspaceExists: await directoryExists(binding.workspaceRealPath),
66
+ };
67
+ }
68
+ export async function requireBoundWorkspace(globalRoot) {
69
+ const observation = await observeBoundWorkspace(globalRoot);
70
+ if (observation === undefined) {
71
+ throw new PlatformError("WORKSPACE_NOT_BOUND", "no ProFlow Workspace is currently installed/bound");
72
+ }
73
+ if (!observation.workspaceExists) {
74
+ throw new PlatformError("BOUND_WORKSPACE_MISSING", `bound Workspace no longer exists: ${observation.binding.workspaceRealPath}`);
75
+ }
76
+ return observation.binding;
77
+ }
78
+ export async function claimWorkspaceBinding(options) {
79
+ const requested = await canonicalizeWorkspace(options.workspace);
80
+ const paths = globalPlatformPaths(options.globalRoot);
81
+ const lock = await acquireGlobalBindingLock(paths);
82
+ try {
83
+ const current = await loadGlobalBinding(options.globalRoot);
84
+ if (current !== undefined) {
85
+ if (current.workspaceRealPath !== requested.workspaceRealPath) {
86
+ throw new PlatformError("WORKSPACE_ALREADY_BOUND", `ProFlow is already bound to ${current.workspaceRealPath}; uninstall it before installing ${requested.workspaceRealPath}`);
87
+ }
88
+ return { binding: current, alreadyBound: true };
89
+ }
90
+ const existingMarker = await loadWorkspaceInstanceMarker(requested.workspaceRealPath);
91
+ const now = new Date().toISOString();
92
+ const binding = {
93
+ contract: GLOBAL_BINDING_CONTRACT,
94
+ state: "INSTALLING",
95
+ workspacePath: requested.workspacePath,
96
+ workspaceRealPath: requested.workspaceRealPath,
97
+ workspaceInstanceId: existingMarker?.workspaceInstanceId ?? randomUUID(),
98
+ createdAt: existingMarker?.createdAt ?? now,
99
+ updatedAt: now,
100
+ };
101
+ await saveGlobalBinding(paths, binding);
102
+ if (existingMarker === undefined) {
103
+ try {
104
+ await writeWorkspaceInstanceMarker(binding);
105
+ }
106
+ catch (error) {
107
+ const broken = withBindingState(binding, "BROKEN", {
108
+ code: "WORKSPACE_INSTANCE_WRITE_FAILED",
109
+ message: errorMessage(error),
110
+ });
111
+ await saveGlobalBinding(paths, broken);
112
+ throw new PlatformError("GLOBAL_BINDING_INVALID", `failed to materialize Workspace instance identity: ${errorMessage(error)}`);
113
+ }
114
+ }
115
+ return { binding, alreadyBound: false };
116
+ }
117
+ finally {
118
+ await lock.release();
119
+ }
120
+ }
121
+ export async function updateGlobalBindingState(options) {
122
+ const paths = globalPlatformPaths(options.globalRoot);
123
+ const lock = await acquireGlobalBindingLock(paths);
124
+ try {
125
+ const current = await loadGlobalBinding(options.globalRoot);
126
+ if (current === undefined) {
127
+ throw new PlatformError("WORKSPACE_NOT_BOUND", "cannot update global binding because no Workspace is bound");
128
+ }
129
+ if (current.workspaceInstanceId !== options.workspaceInstanceId) {
130
+ throw new PlatformError("GLOBAL_BINDING_INVALID", "global binding instance identity changed during the operation");
131
+ }
132
+ const next = withBindingState(current, options.state, options.failure);
133
+ await saveGlobalBinding(paths, next);
134
+ return next;
135
+ }
136
+ finally {
137
+ await lock.release();
138
+ }
139
+ }
140
+ export async function clearGlobalBinding(options) {
141
+ const paths = globalPlatformPaths(options.globalRoot);
142
+ const lock = await acquireGlobalBindingLock(paths);
143
+ try {
144
+ const current = await loadGlobalBinding(options.globalRoot);
145
+ if (current === undefined)
146
+ return;
147
+ if (current.workspaceInstanceId !== options.workspaceInstanceId) {
148
+ throw new PlatformError("GLOBAL_BINDING_INVALID", "refusing to clear a different Workspace binding");
149
+ }
150
+ await rm(paths.bindingJson, { force: true });
151
+ if (options.removeWorkspaceMarker === true) {
152
+ await rm(workspaceInstanceMarkerPath(current.workspaceRealPath), {
153
+ force: true,
154
+ });
155
+ }
156
+ }
157
+ finally {
158
+ await lock.release();
159
+ }
160
+ }
161
+ export async function forgetMissingWorkspaceBinding(options) {
162
+ const paths = globalPlatformPaths(options.globalRoot);
163
+ const lock = await acquireGlobalBindingLock(paths);
164
+ try {
165
+ const current = await loadGlobalBinding(options.globalRoot);
166
+ if (current === undefined) {
167
+ throw new PlatformError("WORKSPACE_NOT_BOUND", "no ProFlow Workspace binding exists to forget");
168
+ }
169
+ if (await directoryExists(current.workspaceRealPath)) {
170
+ throw new PlatformError("INVALID_REQUEST", "bound Workspace still exists; use normal platform uninstall instead of forget");
171
+ }
172
+ await rm(paths.bindingJson, { force: true });
173
+ return current;
174
+ }
175
+ finally {
176
+ await lock.release();
177
+ }
178
+ }
179
+ export async function acquireGlobalBindingLock(paths) {
180
+ return acquireExclusiveGlobalLock(paths.root, paths.bindingLock, "GLOBAL_BINDING_LOCKED", "another process is mutating the global Workspace binding");
181
+ }
182
+ export async function acquireGlobalOperationLock(globalRoot) {
183
+ const paths = globalPlatformPaths(globalRoot);
184
+ return acquireExclusiveGlobalLock(paths.root, paths.operationLock, "GLOBAL_OPERATION_LOCKED", "another Platform install/uninstall operation is already running");
185
+ }
186
+ async function acquireExclusiveGlobalLock(root, file, code, message) {
187
+ await mkdir(root, { recursive: true });
188
+ for (let attempt = 0; attempt < 2; attempt += 1) {
189
+ try {
190
+ const handle = await open(file, "wx", 0o600);
191
+ try {
192
+ await handle.writeFile(`${JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString() })}\n`, "utf8");
193
+ }
194
+ finally {
195
+ await handle.close();
196
+ }
197
+ return {
198
+ async release() {
199
+ try {
200
+ await unlink(file);
201
+ }
202
+ catch (error) {
203
+ if (!isMissingFile(error))
204
+ throw error;
205
+ }
206
+ },
207
+ };
208
+ }
209
+ catch (error) {
210
+ if (!isAlreadyExists(error))
211
+ throw error;
212
+ const record = await readLockRecord(file);
213
+ if (record !== undefined && !pidIsAlive(record.pid)) {
214
+ await rm(file, { force: true });
215
+ continue;
216
+ }
217
+ throw new PlatformError(code, `${message}: ${file}`);
218
+ }
219
+ }
220
+ throw new PlatformError(code, `${message}: ${file}`);
221
+ }
222
+ function workspaceInstanceMarkerPath(workspaceRoot) {
223
+ return join(workspaceRoot, ".proflow", "deployment", "instance.json");
224
+ }
225
+ async function loadWorkspaceInstanceMarker(workspaceRoot) {
226
+ const path = workspaceInstanceMarkerPath(workspaceRoot);
227
+ try {
228
+ const parsed = JSON.parse(await readFile(path, "utf8"));
229
+ if (!isWorkspaceInstanceMarker(parsed)) {
230
+ throw new PlatformError("WORKSPACE_INSTANCE_INVALID", `Workspace instance marker is invalid: ${path}`);
231
+ }
232
+ if (parsed.workspaceRealPath !== workspaceRoot) {
233
+ throw new PlatformError("WORKSPACE_INSTANCE_INVALID", `Workspace instance marker belongs to ${parsed.workspaceRealPath}, not ${workspaceRoot}`);
234
+ }
235
+ return parsed;
236
+ }
237
+ catch (error) {
238
+ if (isMissingFile(error))
239
+ return undefined;
240
+ if (error instanceof PlatformError)
241
+ throw error;
242
+ throw new PlatformError("WORKSPACE_INSTANCE_INVALID", `cannot read Workspace instance marker ${path}: ${errorMessage(error)}`);
243
+ }
244
+ }
245
+ function isWorkspaceInstanceMarker(value) {
246
+ if (!isRecord(value))
247
+ return false;
248
+ return (value.contract === WORKSPACE_INSTANCE_CONTRACT &&
249
+ typeof value.workspaceInstanceId === "string" &&
250
+ value.workspaceInstanceId.length > 0 &&
251
+ typeof value.workspaceRealPath === "string" &&
252
+ typeof value.createdAt === "string");
253
+ }
254
+ async function writeWorkspaceInstanceMarker(binding) {
255
+ const path = workspaceInstanceMarkerPath(binding.workspaceRealPath);
256
+ const marker = {
257
+ contract: WORKSPACE_INSTANCE_CONTRACT,
258
+ workspaceInstanceId: binding.workspaceInstanceId,
259
+ workspaceRealPath: binding.workspaceRealPath,
260
+ createdAt: binding.createdAt,
261
+ };
262
+ await mkdir(dirname(path), { recursive: true });
263
+ await atomicWrite(path, `${JSON.stringify(marker, null, 2)}\n`);
264
+ await chmod(path, 0o600);
265
+ }
266
+ async function saveGlobalBinding(paths, binding) {
267
+ await mkdir(paths.root, { recursive: true });
268
+ await atomicWrite(paths.bindingJson, `${JSON.stringify(binding, null, 2)}\n`);
269
+ await chmod(paths.bindingJson, 0o600);
270
+ }
271
+ function withBindingState(binding, state, failure) {
272
+ const { failure: _previousFailure, ...base } = binding;
273
+ return {
274
+ ...base,
275
+ state,
276
+ updatedAt: new Date().toISOString(),
277
+ ...(failure === undefined ? {} : { failure }),
278
+ };
279
+ }
280
+ function isGlobalWorkspaceBinding(value) {
281
+ if (!isRecord(value))
282
+ return false;
283
+ if (value.contract !== GLOBAL_BINDING_CONTRACT)
284
+ return false;
285
+ if (!isBindingState(value.state))
286
+ return false;
287
+ return (typeof value.workspacePath === "string" &&
288
+ typeof value.workspaceRealPath === "string" &&
289
+ typeof value.workspaceInstanceId === "string" &&
290
+ typeof value.createdAt === "string" &&
291
+ typeof value.updatedAt === "string" &&
292
+ (value.failure === undefined ||
293
+ (isRecord(value.failure) &&
294
+ typeof value.failure.code === "string" &&
295
+ typeof value.failure.message === "string")));
296
+ }
297
+ function isBindingState(value) {
298
+ return (value === "INSTALLING" ||
299
+ value === "INSTALLED" ||
300
+ value === "UNINSTALLING" ||
301
+ value === "BROKEN");
302
+ }
303
+ async function directoryExists(path) {
304
+ try {
305
+ return (await stat(path)).isDirectory();
306
+ }
307
+ catch {
308
+ return false;
309
+ }
310
+ }
311
+ async function readLockRecord(path) {
312
+ try {
313
+ const parsed = JSON.parse(await readFile(path, "utf8"));
314
+ if (isRecord(parsed) &&
315
+ typeof parsed.pid === "number" &&
316
+ Number.isInteger(parsed.pid) &&
317
+ parsed.pid > 0) {
318
+ return { pid: parsed.pid };
319
+ }
320
+ return undefined;
321
+ }
322
+ catch {
323
+ return undefined;
324
+ }
325
+ }
326
+ function pidIsAlive(pid) {
327
+ try {
328
+ process.kill(pid, 0);
329
+ return true;
330
+ }
331
+ catch (error) {
332
+ return isPermissionError(error);
333
+ }
334
+ }
335
+ function isRecord(value) {
336
+ return typeof value === "object" && value !== null && !Array.isArray(value);
337
+ }
338
+ function isMissingFile(error) {
339
+ return isRecord(error) && error.code === "ENOENT";
340
+ }
341
+ function isAlreadyExists(error) {
342
+ return isRecord(error) && error.code === "EEXIST";
343
+ }
344
+ function isPermissionError(error) {
345
+ return isRecord(error) && error.code === "EPERM";
346
+ }
347
+ function errorMessage(error) {
348
+ return error instanceof Error ? error.message : String(error);
349
+ }
@@ -2,6 +2,7 @@ import type { ResolvedModule } from "../contracts.ts";
2
2
  type ResolvedSource = ResolvedModule["source"];
3
3
  export interface DeploymentAdapterBinding {
4
4
  behaviorAdapter: Record<string, unknown>;
5
+ materializeProductionConfig?: (...args: unknown[]) => unknown;
5
6
  }
6
7
  export type ProductionBindingFactory = (input: {
7
8
  moduleRef: string;
@@ -29,17 +30,6 @@ export interface ProductionBindingOptions {
29
30
  configByModuleRef: ReadonlyMap<string, Record<string, string>>;
30
31
  importAdapter: (packageName: string, source: ResolvedSource) => Promise<Record<string, unknown>>;
31
32
  }
32
- export declare function importRawAdapter(packageName: string, source: ResolvedSource): Promise<Record<string, unknown>>;
33
- /**
34
- * The shipped Platform CLI production binding factory. For every discovered
35
- * module it imports the module's own `deployment/adapter.ts` and, when that
36
- * adapter exposes a `createProductionBinding` factory, invokes it with the
37
- * module's materialized config to obtain a real bound adapter. A module without
38
- * a production factory — or whose import/factory fails, or which has no
39
- * materialized config the adapter accepts — is left out of the map, so the
40
- * catalog falls back to the module's unbound default, which must fail-closed
41
- * (ACTION_REQUIRED / NOT_READY). Platform CLI never invents a service or
42
- * resource reality: it only relays the adapter's own current reality.
43
- */
33
+ export declare function importRawAdapter(packageName: string, source: ResolvedSource, workspaceRoot: string): Promise<Record<string, unknown>>;
44
34
  export declare function buildProductionBindings(options: ProductionBindingOptions): Promise<ReadonlyMap<string, DeploymentAdapterBinding>>;
45
35
  export {};
@@ -6,6 +6,7 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
6
6
  }
7
7
  return path;
8
8
  };
9
+ import { createRequire } from "node:module";
9
10
  import { join } from "node:path";
10
11
  import { pathToFileURL } from "node:url";
11
12
  import { managedServiceStatus, restartManagedService, startManagedService, stopManagedService, } from "../lifecycle/service-process.js";
@@ -21,15 +22,16 @@ function managedServiceAdapter(workspaceRoot, module, serviceProcess, probeAdapt
21
22
  uninstall: () => stopManagedService(paths, module),
22
23
  };
23
24
  }
24
- export async function importRawAdapter(packageName, source) {
25
+ export async function importRawAdapter(packageName, source, workspaceRoot) {
25
26
  if (source.type === "workspace") {
26
27
  if (source.path === undefined)
27
28
  return {};
28
29
  const url = pathToFileURL(join(source.path, "deployment", "adapter.ts"));
29
30
  return (await /* architecture-allow-local-file-url-import */ import(__rewriteRelativeImportExtension(url.href)));
30
31
  }
31
- const resolved = import.meta.resolve(`${packageName}/deployment/adapter`);
32
- const url = new URL(resolved);
32
+ const workspaceRequire = createRequire(pathToFileURL(join(workspaceRoot, "package.json")));
33
+ const resolved = workspaceRequire.resolve(`${packageName}/deployment/adapter`);
34
+ const url = pathToFileURL(resolved);
33
35
  return (await /* architecture-allow-local-file-url-import */ import(__rewriteRelativeImportExtension(url.href)));
34
36
  }
35
37
  /**
@@ -43,6 +45,14 @@ export async function importRawAdapter(packageName, source) {
43
45
  * (ACTION_REQUIRED / NOT_READY). Platform CLI never invents a service or
44
46
  * resource reality: it only relays the adapter's own current reality.
45
47
  */
48
+ function materializerBinding(namespace) {
49
+ const materializer = namespace.materializeProductionConfig;
50
+ return typeof materializer === "function"
51
+ ? {
52
+ materializeProductionConfig: materializer,
53
+ }
54
+ : {};
55
+ }
46
56
  export async function buildProductionBindings(options) {
47
57
  const bindings = new Map();
48
58
  for (const module of options.modules) {
@@ -67,6 +77,7 @@ export async function buildProductionBindings(options) {
67
77
  : {});
68
78
  bindings.set(module.packageName, {
69
79
  behaviorAdapter: managedServiceAdapter(options.workspaceRoot, module, processBinding.serviceProcess, probeAdapter),
80
+ ...materializerBinding(namespace),
70
81
  });
71
82
  }
72
83
  // A formal service package that exposes the process seam must never fall
@@ -90,7 +101,10 @@ export async function buildProductionBindings(options) {
90
101
  binding !== null &&
91
102
  typeof binding.behaviorAdapter === "object" &&
92
103
  binding.behaviorAdapter !== null) {
93
- bindings.set(module.packageName, binding);
104
+ bindings.set(module.packageName, {
105
+ ...binding,
106
+ ...materializerBinding(namespace),
107
+ });
94
108
  }
95
109
  }
96
110
  catch {
package/dist/src/cli.d.ts CHANGED
@@ -1,12 +1,24 @@
1
1
  #!/usr/bin/env node
2
+ import { type GlobalWorkspaceBinding } from "./binding/global-binding.ts";
2
3
  export type CliStatus = "SUCCEEDED" | "ACTION_REQUIRED" | "BLOCKED" | "FAILED";
4
+ export interface CliWorkspaceSummary {
5
+ boundWorkspace: string;
6
+ workspaceInstanceId: string;
7
+ bindingState: GlobalWorkspaceBinding["state"];
8
+ }
3
9
  export interface CliOutcome {
4
10
  command: string;
5
11
  status: CliStatus;
6
12
  data?: unknown;
13
+ workspace?: CliWorkspaceSummary;
7
14
  error?: {
8
15
  code: string;
9
16
  message: string;
10
17
  };
11
18
  }
12
- export declare function runCli(argv: readonly string[]): Promise<string>;
19
+ export interface CliRuntimeOptions {
20
+ cwd?: string;
21
+ globalRoot?: string;
22
+ }
23
+ export declare function renderHumanResult(machineOutput: string): string;
24
+ export declare function runCli(argv: readonly string[], runtime?: CliRuntimeOptions): Promise<string>;