@foliwake/cli 0.6.0 → 0.7.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # @foliwake/cli
2
2
 
3
+ ## 0.7.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 3195ef3: `@foliwake/cli/local-runtime`: `registerLocalRuntime()`, the hook the Foliwake engine uses to run this package's
8
+ commands on its own computer as an oclif plugin (`--config`, `--content`, `FOLIWAKE_CONFIG`,
9
+ `./foliwake.config.json` in the engine's server order, `dev` served by the engine, `operation recover --break-lock`,
10
+ phase timings and traces). `chooseTarget()` is exported for it. Without the engine nothing changes, except that
11
+ `dev --remote --content|--config|--site` now says those flags do not apply with `--remote` (as the engine's `dev`
12
+ does) instead of "Nonexistent flag".
13
+
14
+ ### Patch Changes
15
+
16
+ - Updated dependencies [214dd98]
17
+ - create-foliwake@0.7.0
18
+ - @foliwake/block-kit@0.7.0
19
+ - @foliwake/blocks-contract@0.7.0
20
+ - @foliwake/core-contract@0.7.0
21
+ - @foliwake/server@0.7.0
22
+ - @foliwake/site-check@0.7.0
23
+
3
24
  ## 0.6.0
4
25
 
5
26
  ### Minor Changes
package/README.md CHANGED
@@ -92,6 +92,17 @@ block kit (`@foliwake/block-kit`, served from this package's installed copy). De
92
92
  never loaded. With `--watch`, open pages reload after a change to the local code and show the problems the
93
93
  platform's checks (`@foliwake/site-check`) find in it.
94
94
 
95
+ ## Inside the engine
96
+
97
+ The Foliwake engine (its checkout or Docker image) is the same `foliwake` command with this package as an oclif
98
+ plugin: it registers its local runtime with `registerLocalRuntime()` from `@foliwake/cli/local-runtime` before
99
+ oclif loads the commands. Then the same commands also run on that computer: `--server`, then `--config` or
100
+ `FOLIWAKE_CONFIG`, then `.foliwake/connection.json`, then `FOLIWAKE_SERVER`, then `./foliwake.config.json`,
101
+ then the default server, else the local configuration. `--config` and `--content` are shown and work, the engine
102
+ serves `dev` (local content, and `--remote` with its block catalog), `operation recover --break-lock` removes a
103
+ local state lock, and `--timings` reports the engine's phase timings. The hook is for the engine; its shape may
104
+ change with it.
105
+
95
106
  ## Compatibility
96
107
 
97
108
  The CLI speaks core over HTTP as `@foliwake/core-contract` describes it, and names itself to the server in
@@ -24,6 +24,8 @@ export default class Create extends Command {
24
24
  help: import("@oclif/core/interfaces").BooleanFlag<void>;
25
25
  };
26
26
  run(): Promise<void>;
27
+ /** With the engine: it trusts the configuration create wrote, as its own `create` did. */
28
+ private trustLocally;
27
29
  private serverOf;
28
30
  private createProject;
29
31
  private connect;
@@ -105,8 +105,16 @@ At the end it can create or link the site on your Foliwake server (--create-site
105
105
  process.exitCode = result.status;
106
106
  return;
107
107
  }
108
+ await this.trustLocally(result.answers.target);
108
109
  process.exitCode = await this.connect(result, flags, server);
109
110
  }
111
+ /** With the engine: it trusts the configuration create wrote, as its own `create` did. */
112
+ async trustLocally(folder) {
113
+ const { localRuntime } = await import('../local-runtime.js');
114
+ const note = await localRuntime()?.created(folder);
115
+ if (note)
116
+ this.logToStderr(note);
117
+ }
110
118
  async serverOf(typed) {
111
119
  if (typed === undefined)
112
120
  return undefined;
@@ -4,6 +4,9 @@ export default class Dev extends Command {
4
4
  static description: string;
5
5
  static examples: string[];
6
6
  static flags: {
7
+ config: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
8
+ site: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
9
+ content: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
7
10
  port: import("@oclif/core/interfaces").OptionFlag<number | undefined, import("@oclif/core/interfaces").CustomOptions>;
8
11
  watch: import("@oclif/core/interfaces").BooleanFlag<boolean>;
9
12
  'watch-polling': import("@oclif/core/interfaces").BooleanFlag<boolean>;
@@ -14,6 +17,8 @@ export default class Dev extends Command {
14
17
  'remote-config': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
15
18
  };
16
19
  run(): Promise<void>;
20
+ /** The engine serves `dev`, local or remote. */
21
+ private serveWithEngine;
17
22
  /** Set by stopOnSignal(): settles when a signal has stopped the server. */
18
23
  private stopped;
19
24
  /** On Ctrl+C or SIGTERM: closes the listeners, waits for the work that runs, exits. */
@@ -2,21 +2,46 @@ import { Command, Errors, Flags } from '@oclif/core';
2
2
  import { NEEDS_ENGINE } from '../core-command.js';
3
3
  import { devProblem, isRemote, withRemoteValue } from '../dev/flags.js';
4
4
  import { UsageError } from '../dev/start.js';
5
+ import { localRuntime } from '../local-runtime.js';
5
6
  const WITHOUT_REMOTE = `\`dev\` without --remote serves local content and ${NEEDS_ENGINE}`;
7
+ /**
8
+ * With the engine registered, the engine serves `dev`: its working files, and with --remote its own remote mode
9
+ * (with the block catalog, which needs its renderer).
10
+ */
11
+ const ENGINE = localRuntime() !== null;
12
+ /** A flag of local mode: with the engine, as it describes it; alone, hidden and refused with NEEDS_ENGINE. */
13
+ const localFlag = (description) => ENGINE ? Flags.string({ description }) : Flags.string({ description, hidden: true });
14
+ const ENGINE_EXAMPLES = [
15
+ '<%= config.bin %> dev',
16
+ '<%= config.bin %> dev --watch',
17
+ '<%= config.bin %> dev --port 3001',
18
+ '<%= config.bin %> dev --config foliwake.config.json --site a',
19
+ ];
6
20
  export default class Dev extends Command {
7
- static summary = 'Develop blocks against a deployed site: its content, this checkout’s code (dev --remote)';
8
- static description = 'A server process, not a core operation: content from the deployed preview (default) or live site, ' +
9
- 'components/, scripts/ and styles/ from this checkout, until Ctrl+C. Serving local content needs the engine.';
21
+ static summary = ENGINE
22
+ ? 'Serve working files with live diagnostics (http://127.0.0.1:3000)'
23
+ : 'Develop blocks against a deployed site: its content, this checkout’s code (dev --remote)';
24
+ static description = ENGINE
25
+ ? "A server process, not a core operation: serves the working files (or the selected snapshot of the site's " +
26
+ 'source) with diagnostics, until Ctrl+C. With --remote: content from the deployed preview (default) or ' +
27
+ 'live site, code from this checkout.'
28
+ : 'A server process, not a core operation: content from the deployed preview (default) or live site, ' +
29
+ 'components/, scripts/ and styles/ from this checkout, until Ctrl+C. Serving local content needs the engine.';
10
30
  static examples = [
31
+ ...(ENGINE ? ENGINE_EXAMPLES : []),
11
32
  '<%= config.bin %> dev --remote --watch # in the frontend checkout: preview content, local code',
12
33
  '<%= config.bin %> dev --remote live --port 3001',
13
34
  '<%= config.bin %> dev --remote-url https://preview.foliwake.example --remote-auth-user owner ' +
14
35
  '--remote-auth-env PREVIEW_PASSWORD',
15
36
  ];
16
37
  static flags = {
38
+ config: localFlag('project configuration (default: $FOLIWAKE_CONFIG, else ./foliwake.config.json in this folder)'),
39
+ site: localFlag('site id from the project configuration (required when it lists several sites)'),
40
+ content: localFlag("this folder instead of the site's content sources; refused when they need the page ledger"),
17
41
  port: Flags.integer({ min: 0, max: 65535, description: 'port to listen on (default 3000)' }),
18
42
  watch: Flags.boolean({
19
- description: 'watch local components/, scripts/, styles/ and reload open browser pages after changes ' +
43
+ description: `watch local components/, scripts/, styles/${ENGINE ? ' and Markdown content' : ''} and reload open ` +
44
+ 'browser pages after changes ' +
20
45
  '(one reload per burst of saves; problems are shown in the page until fixed). Without it, refresh by hand',
21
46
  }),
22
47
  'watch-polling': Flags.boolean({
@@ -45,11 +70,18 @@ export default class Dev extends Command {
45
70
  };
46
71
  async run() {
47
72
  const { flags } = await this.parse(Dev, withRemoteValue(this.argv));
48
- if (!isRemote(flags))
73
+ const engine = localRuntime();
74
+ if (!isRemote(flags) && !engine)
49
75
  this.error(WITHOUT_REMOTE, { exit: 2 });
50
76
  const problem = devProblem(flags);
51
77
  if (problem)
52
78
  throw new UsageError(problem);
79
+ if (engine) {
80
+ const code = await this.serveWithEngine(engine, flags);
81
+ if (code !== 0)
82
+ this.exit(code);
83
+ return;
84
+ }
53
85
  const { startRemoteDev } = await import('../dev/start.js');
54
86
  const options = {
55
87
  remote: flags.remote === 'live' ? 'live' : 'preview',
@@ -63,6 +95,29 @@ export default class Dev extends Command {
63
95
  };
64
96
  await startRemoteDev(options, (line) => this.log(line), (stop) => this.stopOnSignal(stop));
65
97
  }
98
+ /** The engine serves `dev`, local or remote. */
99
+ serveWithEngine(engine, flags) {
100
+ const remote = isRemote(flags)
101
+ ? {
102
+ target: flags.remote === 'live' ? 'live' : 'preview',
103
+ url: flags['remote-url'],
104
+ config: flags['remote-config'],
105
+ authEnv: flags['remote-auth-env'],
106
+ authUser: flags['remote-auth-user'],
107
+ }
108
+ : undefined;
109
+ const options = {
110
+ port: flags.port,
111
+ watch: flags.watch,
112
+ polling: flags['watch-polling'],
113
+ content: flags.content,
114
+ config: flags.config,
115
+ site: flags.site,
116
+ remote,
117
+ };
118
+ const io = { log: (line) => this.log(line), warn: (line) => this.logToStderr(line) };
119
+ return engine.dev(options, io);
120
+ }
66
121
  /** Set by stopOnSignal(): settles when a signal has stopped the server. */
67
122
  stopped = null;
68
123
  /** On Ctrl+C or SIGTERM: closes the listeners, waits for the work that runs, exits. */
@@ -1,15 +1,23 @@
1
1
  import { Flags } from '@oclif/core';
2
2
  import { CoreCommand, NEEDS_ENGINE } from '../../core-command.js';
3
+ import { localRuntime } from '../../local-runtime.js';
3
4
  import { recoveryLines } from '../../render/recovery.js';
4
5
  /**
5
6
  * Exit status of `operation recover --wait` when cache refreshes are still pending at its deadline (they stay
6
7
  * recorded).
7
8
  */
8
9
  export const EXIT_REFRESH_PENDING = 3;
10
+ /** The lock is the engine's, and removing it is the operator's call on the host that runs it. */
11
+ const BREAK_LOCK_HERE = localRuntime()
12
+ ? "needs the site's local configuration; it does not apply with a server."
13
+ : NEEDS_ENGINE;
9
14
  export default class OperationRecover extends CoreCommand {
10
15
  static description = 'Find out what happened to interrupted operations, finish the engine’s interrupted work and pending cache ' +
11
16
  'refreshes; never runs an operation again (core operations.recover)';
12
- static examples = ['<%= config.bin %> operation recover --wait'];
17
+ static examples = [
18
+ '<%= config.bin %> operation recover --wait',
19
+ '<%= config.bin %> operation recover --break-lock --wait # only when the process named by STATE_LOCKED is gone',
20
+ ];
13
21
  static flags = {
14
22
  ...CoreCommand.siteFlags,
15
23
  wait: Flags.boolean({
@@ -18,15 +26,17 @@ export default class OperationRecover extends CoreCommand {
18
26
  }),
19
27
  'wait-timeout': Flags.integer({ min: 0, description: 'limit of --wait in seconds (default: settle delay + 90 s)' }),
20
28
  'break-lock': Flags.boolean({
21
- description: 'remove a state lock left by a process that is gone (on the server: needs the engine there)',
29
+ description: localRuntime()
30
+ ? 'first remove a state lock left by a process that is gone (for example on another host name)'
31
+ : 'remove a state lock left by a process that is gone (on the server: needs the engine there)',
22
32
  }),
23
33
  ...CoreCommand.timingsFlag,
24
34
  ...CoreCommand.inputFlag,
25
35
  };
26
36
  async run() {
27
37
  const { flags } = await this.parse(OperationRecover);
28
- if (flags['break-lock'])
29
- this.error(`--break-lock ${NEEDS_ENGINE}`, { exit: 2 });
38
+ if (flags['break-lock'] && !this.local)
39
+ this.error(`--break-lock ${BREAK_LOCK_HERE}`, { exit: 2 });
30
40
  const input = await this.resolveInput(flags.input, async () => {
31
41
  const { site } = await this.siteInput(flags.site);
32
42
  if (!flags.wait)
@@ -38,6 +48,8 @@ export default class OperationRecover extends CoreCommand {
38
48
  : flags['wait-timeout'] * 1000,
39
49
  };
40
50
  });
51
+ if (flags['break-lock'] && this.local)
52
+ this.log(await this.local.breakLock(input.site));
41
53
  const answer = await this.timed('recover', flags.timings, () => this.core.operations.recover(input));
42
54
  if (!this.jsonEnabled())
43
55
  for (const line of recoveryLines(answer))
@@ -10,9 +10,10 @@ export default class Whoami extends CoreCommand {
10
10
  ];
11
11
  async run() {
12
12
  const grant = await this.core.whoami();
13
- const server = this.target.origin;
13
+ // Locally (the engine on this computer) no server is called.
14
+ const server = this.local ? null : this.target.origin;
14
15
  const organisations = grant.memberships.map(membershipText).join('; ');
15
- this.log(`Server ${serverDisplay(server)}`);
16
+ this.log(`Server ${server ? serverDisplay(server) : 'none (this computer, local configuration)'}`);
16
17
  this.log(`Principal ${grant.principal}`);
17
18
  this.log(`Installation ${grant.installation ? 'yes' : 'no'}`);
18
19
  this.log(`Organisations ${organisations || (grant.installation ? 'all' : 'none')}`);
@@ -1,5 +1,6 @@
1
1
  import { Command } from '@oclif/core';
2
2
  import type { CoreCaller } from '@foliwake/core-contract';
3
+ import { type LocalCore } from './local-runtime.js';
3
4
  import type { Target } from './remote/servers.js';
4
5
  import { type Operation } from './remote/wait-slices.js';
5
6
  /** What a command that needs the engine says, with exit 2. */
@@ -10,7 +11,7 @@ export declare abstract class CoreCommand extends Command {
10
11
  debug: import("@oclif/core/interfaces").BooleanFlag<boolean>;
11
12
  server: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
12
13
  };
13
- /** Accepted so that scripts written for the engine's CLI get a clear answer: a local configuration. */
14
+ /** A local project configuration: the engine's; alone, scripts written for the engine get a clear answer. */
14
15
  static configFlag: {
15
16
  config: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
16
17
  };
@@ -19,7 +20,7 @@ export declare abstract class CoreCommand extends Command {
19
20
  site: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
20
21
  config: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
21
22
  };
22
- /** Reading this computer's working files instead of the site's sources needs the engine. */
23
+ /** Reading this computer's working files instead of the site's sources: the engine's local runtime. */
23
24
  static contentFlag: {
24
25
  content: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
25
26
  };
@@ -44,19 +45,25 @@ export declare abstract class CoreCommand extends Command {
44
45
  timings: import("@oclif/core/interfaces").BooleanFlag<boolean>;
45
46
  };
46
47
  protected core: CoreCaller;
47
- /** The server this command's calls go to. */
48
+ /** The server this command's calls go to; unset when it runs locally (`local`). */
48
49
  protected target: Target;
50
+ /** The engine's core on this computer, when the command runs locally. */
51
+ protected local: LocalCore | null;
49
52
  private coreError;
53
+ protected _run<T>(): Promise<T>;
50
54
  init(): Promise<void>;
51
- private resolveServer;
55
+ /** Runs `choose`; a server address or flag combination it refuses exits 2 with its message. */
56
+ private guarded;
57
+ private serverTarget;
52
58
  protected resolveInput<TInput>(rawInput: string | undefined, fromFlags: () => TInput | Promise<TInput>): Promise<TInput>;
53
- /** The site: `--site`, else the folder's linked site on this server, else the server's only site. */
59
+ /** The site: `--site`, else the folder's linked site on this server, else the server's (or configuration's) only. */
54
60
  protected siteInput(site: string | undefined): Promise<{
55
61
  site: string;
56
62
  }>;
63
+ private onlyLocalSite;
57
64
  private linkedSite;
58
- /** The settle delay that default waits start from; a server's own is not known here, so a fixed one. */
59
- protected settleDelayMs(_siteId: string): Promise<number>;
65
+ /** The settle delay that default waits start from: the site's locally; a server's is not known, so a fixed one. */
66
+ protected settleDelayMs(siteId: string): Promise<number>;
60
67
  /** The `expect.live` of a write: `--expect`, or with `--latest-live` the live release read now. */
61
68
  protected expectedLive(site: string, flags: {
62
69
  expect?: string | undefined;
@@ -77,11 +84,12 @@ export declare abstract class CoreCommand extends Command {
77
84
  wait: boolean;
78
85
  waitTimeout: number | undefined;
79
86
  }): Promise<Operation>;
80
- /** `operations.wait` against a server, in slices under its request timeout. */
87
+ /** `operations.wait`: locally in one call; against a server in slices under its request timeout. */
81
88
  private waitOperation;
82
- /** Runs `fn`; with `--timings` (or FOLIWAKE_TIMINGS=1) reports its total time on stderr. */
89
+ /** Runs `fn`; with `--timings` (or FOLIWAKE_TIMINGS=1) reports its time on stderr (phases: the engine's). */
83
90
  protected timed<T>(name: string, requested: boolean, fn: () => Promise<T>): Promise<T>;
84
91
  private reportTotal;
92
+ finally(error: Error | undefined): Promise<unknown>;
85
93
  protected noteProvisional(provisional: boolean): void;
86
94
  protected toErrorJson(error: unknown): unknown;
87
95
  protected catch(error: Error & {
@@ -1,7 +1,9 @@
1
1
  // Base class of every command that maps to one core operation on a server. A command is a thin wrapper: it
2
2
  // turns flags into the operation's input, calls it, writes text for people with `this.log` and returns the
3
3
  // raw answer, which `--json` prints. Flags, texts and JSON are the engine CLI's own for the same command.
4
+ // With the engine's runtime registered (local-runtime.ts) the same command also runs on this computer.
4
5
  import { Command, Errors, Flags } from '@oclif/core';
6
+ import { localRuntime } from './local-runtime.js';
5
7
  import { CoreFailure, toCoreFailure } from './remote/core-failure.js';
6
8
  import { waitInSlices } from './remote/wait-slices.js';
7
9
  import { COMMAND } from './settings.js';
@@ -14,31 +16,39 @@ const REMOTE_SETTLE_DELAY_MS = 30_000;
14
16
  export const NEEDS_ENGINE = `needs the Foliwake engine: the Docker image (\`${COMMAND} docker install\`) or the ` + `engine checkout.`;
15
17
  const NO_SERVER = `No Foliwake server is named: pass --server, link this folder (\`${COMMAND} site link <id>\`), ` +
16
18
  `set FOLIWAKE_SERVER, or sign in with \`${COMMAND} login\`.`;
17
- const engineOnly = (name, description) => Flags.string({ description: `${description} (${NEEDS_ENGINE.replace(/\.$/, '')})`, hidden: true, name });
19
+ /** Registered before oclif loads the commands, so flags read it when this module loads. */
20
+ const ENGINE = localRuntime() !== null;
21
+ /** With the engine: a flag of local mode. Alone: accepted, hidden, and answered with NEEDS_ENGINE. */
22
+ const localFlag = (name, description, alone) => ENGINE
23
+ ? Flags.string({ description, name })
24
+ : Flags.string({ description: `${alone} (${NEEDS_ENGINE.replace(/\.$/, '')})`, hidden: true, name });
25
+ const SERVER_DEFAULT = "default: the folder's .foliwake/connection.json, then $FOLIWAKE_SERVER, then the last `login`";
26
+ const SERVER_FLAG = ENGINE
27
+ ? `call this Foliwake server (origin or host) instead of the local configuration (${SERVER_DEFAULT})`
28
+ : `call this Foliwake server (origin or host; ${SERVER_DEFAULT})`;
29
+ const SITE_FLAG = ENGINE
30
+ ? 'site id (default: the site this folder is linked to, else the only site of the configuration or server)'
31
+ : 'site id (default: the site this folder is linked to, else the only site on the server)';
32
+ /** The entry name of a command's trace: its words joined by dots (`code:deploy` → `code.deploy`). */
33
+ const commandSpanName = (id) => (id ?? 'command').replaceAll(':', '.');
18
34
  export class CoreCommand extends Command {
19
35
  static enableJsonFlag = true;
20
36
  static baseFlags = {
21
37
  debug: Flags.boolean({ description: 'print the underlying error on stderr', helpGroup: 'GLOBAL' }),
22
- server: Flags.string({
23
- description: "call this Foliwake server (origin or host; default: the folder's .foliwake/connection.json, " +
24
- 'then $FOLIWAKE_SERVER, then the last `login`)',
25
- helpGroup: 'GLOBAL',
26
- }),
38
+ server: Flags.string({ description: SERVER_FLAG, helpGroup: 'GLOBAL' }),
27
39
  };
28
- /** Accepted so that scripts written for the engine's CLI get a clear answer: a local configuration. */
40
+ /** A local project configuration: the engine's; alone, scripts written for the engine get a clear answer. */
29
41
  static configFlag = {
30
- config: engineOnly('config', 'a local project configuration'),
42
+ config: localFlag('config', 'project configuration (default: $FOLIWAKE_CONFIG, else ./foliwake.config.json in this folder)', 'a local project configuration'),
31
43
  };
32
44
  /** For commands that act on a site. Without `--site`: the folder's linked site, else the server's only one. */
33
45
  static siteFlags = {
34
46
  ...CoreCommand.configFlag,
35
- site: Flags.string({
36
- description: 'site id (default: the site this folder is linked to, else the only site on the server)',
37
- }),
47
+ site: Flags.string({ description: SITE_FLAG }),
38
48
  };
39
- /** Reading this computer's working files instead of the site's sources needs the engine. */
49
+ /** Reading this computer's working files instead of the site's sources: the engine's local runtime. */
40
50
  static contentFlag = {
41
- content: engineOnly('content', "this folder instead of the site's content sources"),
51
+ content: localFlag('content', "this folder instead of the site's content sources; refused when they need the page ledger", "this folder instead of the site's content sources"),
42
52
  };
43
53
  /** The whole input of the operation as JSON, for what flags cannot express. Its schema checks it. */
44
54
  static inputFlag = {
@@ -82,23 +92,51 @@ export class CoreCommand extends Command {
82
92
  /** Accepted as in the engine's CLI; only the total time is known here (phase timings need the engine). */
83
93
  static timingsFlag = {
84
94
  timings: Flags.boolean({
85
- description: 'report the total time on stderr (one JSON line with --json); also FOLIWAKE_TIMINGS=1 ' +
86
- '(phase timings need the engine)',
95
+ description: ENGINE
96
+ ? 'report phase timings, request counts and transferred bytes on stderr (one JSON line with --json); ' +
97
+ 'also FOLIWAKE_TIMINGS=1 or FOLIWAKE_TIMINGS_FILE=<file>'
98
+ : 'report the total time on stderr (one JSON line with --json); also FOLIWAKE_TIMINGS=1 ' +
99
+ '(phase timings need the engine)',
87
100
  }),
88
101
  };
89
102
  core;
90
- /** The server this command's calls go to. */
103
+ /** The server this command's calls go to; unset when it runs locally (`local`). */
91
104
  target;
105
+ /** The engine's core on this computer, when the command runs locally. */
106
+ local = null;
92
107
  coreError = null;
108
+ // With the engine, each command is the entry of its trace when traces are exported.
109
+ async _run() {
110
+ const engine = localRuntime();
111
+ if (!engine)
112
+ return super._run();
113
+ return engine.traced(commandSpanName(this.id), () => super._run());
114
+ }
93
115
  async init() {
94
116
  await super.init();
95
117
  // `parse()` without its command cannot type the flags of the subclass.
96
118
  const { flags } = await this.parse();
97
- for (const name of ['config', 'content']) {
98
- if (typeof flags[name] === 'string')
99
- this.error(`--${name} ${NEEDS_ENGINE}`, { exit: 2 });
119
+ const text = (name) => (typeof flags[name] === 'string' ? flags[name] : undefined);
120
+ const engine = localRuntime();
121
+ if (!engine) {
122
+ for (const name of ['config', 'content'])
123
+ if (text(name))
124
+ this.error(`--${name} ${NEEDS_ENGINE}`, { exit: 2 });
125
+ }
126
+ const { chooseTarget } = await import('./local-target.js');
127
+ const choice = await this.guarded(() => chooseTarget({ server: text('server'), config: text('config') }));
128
+ if (choice === 'local' && engine) {
129
+ const content = text('content');
130
+ const { default: path } = await import('node:path');
131
+ const contentFolder = content === undefined ? undefined : path.resolve(process.cwd(), content);
132
+ this.local = engine.open({ config: text('config'), content: contentFolder, debug: flags.debug === true });
133
+ this.core = this.local.core;
134
+ return;
135
+ }
136
+ if (text('content') !== undefined) {
137
+ this.error('--content reads a folder on this computer; it does not apply to a server.', { exit: 2 });
100
138
  }
101
- this.target = await this.resolveServer(typeof flags.server === 'string' ? flags.server : undefined);
139
+ this.target = await this.serverTarget(choice === 'local' ? null : choice);
102
140
  const { SignInMovedError, remoteCallerFor } = await import('./remote/session.js');
103
141
  try {
104
142
  this.core = remoteCallerFor(this.target.origin);
@@ -109,15 +147,11 @@ export class CoreCommand extends Command {
109
147
  throw error;
110
148
  }
111
149
  }
112
- async resolveServer(server) {
113
- const { CLOUD_NOTE, CLOUD_ORIGIN, ServerAddressError, cloudConfigured, resolveTarget } = await import('./remote/servers.js');
150
+ /** Runs `choose`; a server address or flag combination it refuses exits 2 with its message. */
151
+ async guarded(choose) {
152
+ const { ServerAddressError } = await import('./remote/servers.js');
114
153
  try {
115
- const target = resolveTarget({ server });
116
- if (target === null)
117
- this.error(NO_SERVER, { exit: 2 });
118
- if (target.origin === CLOUD_ORIGIN && !cloudConfigured())
119
- this.error(CLOUD_NOTE, { exit: 1 });
120
- return target;
154
+ return choose();
121
155
  }
122
156
  catch (error) {
123
157
  if (error instanceof ServerAddressError)
@@ -125,6 +159,14 @@ export class CoreCommand extends Command {
125
159
  throw error;
126
160
  }
127
161
  }
162
+ async serverTarget(target) {
163
+ const { CLOUD_NOTE, CLOUD_ORIGIN, cloudConfigured } = await import('./remote/servers.js');
164
+ if (target === null)
165
+ this.error(NO_SERVER, { exit: 2 });
166
+ if (target.origin === CLOUD_ORIGIN && !cloudConfigured())
167
+ this.error(CLOUD_NOTE, { exit: 1 });
168
+ return target;
169
+ }
128
170
  async resolveInput(rawInput, fromFlags) {
129
171
  if (rawInput == null)
130
172
  return fromFlags();
@@ -136,10 +178,12 @@ export class CoreCommand extends Command {
136
178
  this.error('--input is not valid JSON.');
137
179
  }
138
180
  }
139
- /** The site: `--site`, else the folder's linked site on this server, else the server's only site. */
181
+ /** The site: `--site`, else the folder's linked site on this server, else the server's (or configuration's) only. */
140
182
  async siteInput(site) {
141
183
  if (site != null)
142
184
  return { site };
185
+ if (this.local)
186
+ return this.onlyLocalSite(this.local);
143
187
  const linked = await this.linkedSite();
144
188
  if (linked !== null)
145
189
  return { site: linked };
@@ -148,6 +192,12 @@ export class CoreCommand extends Command {
148
192
  this.error(`${sites.length} sites are available on this server; choose one with --site.`);
149
193
  return { site: sites[0].id };
150
194
  }
195
+ async onlyLocalSite(local) {
196
+ const sites = await local.sites();
197
+ if (sites.length !== 1)
198
+ this.error(`${sites.length} sites are configured; choose one with --site.`);
199
+ return { site: sites[0].id };
200
+ }
151
201
  async linkedSite() {
152
202
  const { readConnection } = await import('./remote/connection.js');
153
203
  const { nameOrigin } = await import('./remote/servers.js');
@@ -156,9 +206,9 @@ export class CoreCommand extends Command {
156
206
  return null;
157
207
  return connection.site;
158
208
  }
159
- /** The settle delay that default waits start from; a server's own is not known here, so a fixed one. */
160
- async settleDelayMs(_siteId) {
161
- return REMOTE_SETTLE_DELAY_MS;
209
+ /** The settle delay that default waits start from: the site's locally; a server's is not known, so a fixed one. */
210
+ async settleDelayMs(siteId) {
211
+ return this.local ? this.local.settleDelayMs(siteId) : REMOTE_SETTLE_DELAY_MS;
162
212
  }
163
213
  /** The `expect.live` of a write: `--expect`, or with `--latest-live` the live release read now. */
164
214
  async expectedLive(site, flags) {
@@ -201,14 +251,21 @@ export class CoreCommand extends Command {
201
251
  const delivered = await this.waitOperation({ site, id, until: 'delivery', timeoutMs });
202
252
  if (delivered.delivery?.state !== 'pending' || delivered.delivery.reason !== undefined)
203
253
  return delivered;
254
+ // The time is up: locally, stop waiting here, so the row says why it is still pending.
255
+ await this.local?.close();
204
256
  return this.core.operations.get({ site, id });
205
257
  }
206
- /** `operations.wait` against a server, in slices under its request timeout. */
258
+ /** `operations.wait`: locally in one call; against a server in slices under its request timeout. */
207
259
  waitOperation(input) {
260
+ if (this.local)
261
+ return this.core.operations.wait(input);
208
262
  return waitInSlices((sliceMs) => this.core.operations.wait({ ...input, timeoutMs: sliceMs }), input);
209
263
  }
210
- /** Runs `fn`; with `--timings` (or FOLIWAKE_TIMINGS=1) reports its total time on stderr. */
264
+ /** Runs `fn`; with `--timings` (or FOLIWAKE_TIMINGS=1) reports its time on stderr (phases: the engine's). */
211
265
  async timed(name, requested, fn) {
266
+ const engine = localRuntime();
267
+ if (engine)
268
+ return engine.timed(name, { requested, json: this.jsonEnabled() }, fn);
212
269
  if (!requested && process.env.FOLIWAKE_TIMINGS !== '1')
213
270
  return fn();
214
271
  const started = performance.now();
@@ -225,6 +282,11 @@ export class CoreCommand extends Command {
225
282
  : `timings: ${name} ${totalMs} ms in total (phase timings need the engine)`;
226
283
  process.stderr.write(`${line}\n`);
227
284
  }
285
+ // Locally: takes no new work and waits for what runs; a cache refresh still waiting is left to `operation recover`.
286
+ async finally(error) {
287
+ await this.local?.close();
288
+ return super.finally(error);
289
+ }
228
290
  noteProvisional(provisional) {
229
291
  if (!provisional || this.jsonEnabled())
230
292
  return;
@@ -238,7 +300,7 @@ export class CoreCommand extends Command {
238
300
  async catch(error) {
239
301
  if (error instanceof Errors.CLIError)
240
302
  return super.catch(error);
241
- const failure = toCoreFailure(error);
303
+ const failure = await failureOf(error);
242
304
  this.coreError = failure.coreError;
243
305
  if (process.argv.includes('--debug'))
244
306
  this.logToStderr(String(debugStack(failure)));
@@ -246,9 +308,9 @@ export class CoreCommand extends Command {
246
308
  }
247
309
  errorText({ code, message, category, fields = [] }) {
248
310
  const details = fields.map((field) => (field.path ? `${field.path}: ${field.message}` : field.message));
249
- const origin = this.target?.origin;
311
+ const origin = this.local ? undefined : this.target?.origin;
250
312
  const signIn = origin && category === 'unauthorized' ? [`Sign in with \`${COMMAND} login ${origin}\`.`] : [];
251
- const older = code === 'PROCEDURE_UNKNOWN'
313
+ const older = code === 'PROCEDURE_UNKNOWN' && origin
252
314
  ? [
253
315
  `The server is older than this CLI (@foliwake/cli ${cliVersion()}): update the server, or use ` +
254
316
  'an older @foliwake/cli that matches it (`GET /api/version` names its engine).',
@@ -257,6 +319,14 @@ export class CoreCommand extends Command {
257
319
  return [`${code}: ${message}`, ...details, ...signIn, ...older, 'Run again with --debug for details.'].join('\n');
258
320
  }
259
321
  }
322
+ /** What a command threw, as a CoreFailure: the engine maps its own failures; a server's arrive as they are. */
323
+ async function failureOf(error) {
324
+ const engine = localRuntime();
325
+ if (error instanceof CoreFailure || !engine)
326
+ return toCoreFailure(error);
327
+ const { coreError, cause } = await engine.failure(error);
328
+ return new CoreFailure(coreError, cause);
329
+ }
260
330
  function debugStack(failure) {
261
331
  return (failure.cause instanceof Error ? failure.cause : failure).stack;
262
332
  }
@@ -5,6 +5,10 @@ export interface DevFlags {
5
5
  'remote-config'?: string | undefined;
6
6
  'remote-auth-env'?: string | undefined;
7
7
  'remote-auth-user'?: string | undefined;
8
+ /** Local mode only (the engine's): the configuration, site and content folder it serves. */
9
+ content?: string | undefined;
10
+ config?: string | undefined;
11
+ site?: string | undefined;
8
12
  watch?: boolean | undefined;
9
13
  'watch-polling'?: boolean | undefined;
10
14
  }
package/dist/dev/flags.js CHANGED
@@ -20,6 +20,14 @@ function authProblem(flags) {
20
20
  return '--remote-auth-env and --remote-auth-user must be given together.';
21
21
  return null;
22
22
  }
23
+ /** Remote mode reads no site configuration and no content folder. */
24
+ function localProblem(flags) {
25
+ const option = ['content', 'config', 'site'].find((name) => flags[name] !== undefined);
26
+ if (!option)
27
+ return null;
28
+ return (`--${option} does not apply with --remote: remote mode reads no site configuration and no content folder; ` +
29
+ 'it uses ./foliwake.remote.json (or --remote-url) in the frontend checkout.');
30
+ }
23
31
  /** What the command line of `dev` may not combine; the message, or null. */
24
32
  export function devProblem(flags) {
25
33
  const polling = flags['watch-polling'];
@@ -31,6 +39,9 @@ export function devProblem(flags) {
31
39
  if (flags.remote !== undefined && flags.remote !== 'preview' && flags.remote !== 'live') {
32
40
  return `Unknown remote target "${flags.remote}"; use --remote preview (the default) or --remote live.`;
33
41
  }
42
+ const local = localProblem(flags);
43
+ if (local)
44
+ return local;
34
45
  if (flags['remote-config'] !== undefined && flags['remote-url'] !== undefined) {
35
46
  return 'Use either --remote-config or --remote-url, not both.';
36
47
  }
package/dist/index.d.ts CHANGED
@@ -3,3 +3,4 @@ export { type CoreError, CoreFailure } from './remote/core-failure.js';
3
3
  export { remoteCallerFor, tokenFor } from './remote/session.js';
4
4
  export { type Target, resolveTarget, serverOrigin } from './remote/servers.js';
5
5
  export { main } from './main.js';
6
+ export { chooseTarget, type TargetFlags } from './local-target.js';
package/dist/index.js CHANGED
@@ -5,3 +5,4 @@ export { CoreFailure } from './remote/core-failure.js';
5
5
  export { remoteCallerFor, tokenFor } from './remote/session.js';
6
6
  export { resolveTarget, serverOrigin } from './remote/servers.js';
7
7
  export { main } from './main.js';
8
+ export { chooseTarget } from './local-target.js';
@@ -0,0 +1,78 @@
1
+ import type { CoreCaller, CoreError } from '@foliwake/core-contract';
2
+ /** What a command opens the local runtime with. */
3
+ export interface LocalCoreOptions {
4
+ /** `--config`, else undefined: the engine's default ($FOLIWAKE_CONFIG, then ./foliwake.config.json). */
5
+ config: string | undefined;
6
+ /** `--content`: this folder instead of the site's content sources (absolute). */
7
+ content: string | undefined;
8
+ debug: boolean;
9
+ }
10
+ /** The engine's core on this computer, open for one command. */
11
+ export interface LocalCore {
12
+ core: CoreCaller;
13
+ /** The configured sites (the default `--site` is the only one). */
14
+ sites(): Promise<readonly {
15
+ id: string;
16
+ }[]>;
17
+ /** The site's settle delay, which default waits start from. */
18
+ settleDelayMs(site: string): Promise<number>;
19
+ /** Removes a state lock left by a process that is gone; the line to print. */
20
+ breakLock(site: string): Promise<string>;
21
+ /** Takes no new work and waits for what runs. */
22
+ close(): Promise<void>;
23
+ }
24
+ /** `foliwake dev --remote`, served by the engine. */
25
+ export interface LocalDevRemote {
26
+ target: 'preview' | 'live';
27
+ url: string | undefined;
28
+ config: string | undefined;
29
+ authEnv: string | undefined;
30
+ authUser: string | undefined;
31
+ }
32
+ /** `foliwake dev`: local content, or with `remote` the deployed site's. */
33
+ export interface LocalDevOptions {
34
+ port: number | undefined;
35
+ watch: boolean | undefined;
36
+ polling: boolean | undefined;
37
+ content: string | undefined;
38
+ config: string | undefined;
39
+ site: string | undefined;
40
+ remote: LocalDevRemote | undefined;
41
+ }
42
+ export interface LocalDevIo {
43
+ log(line: string): void;
44
+ warn(line: string): void;
45
+ }
46
+ export interface TimedOptions {
47
+ requested: boolean;
48
+ json: boolean;
49
+ }
50
+ /** What the engine gives this CLI. */
51
+ export interface LocalRuntime {
52
+ /** True when this folder has a local configuration (./foliwake.config.json). */
53
+ folderConfig(cwd: string): boolean;
54
+ open(options: LocalCoreOptions): LocalCore;
55
+ /** Anything a command threw, as core's error and its cause (the engine knows its own failures). */
56
+ failure(error: unknown): Promise<{
57
+ coreError: CoreError;
58
+ cause: unknown;
59
+ }>;
60
+ /** Phase timings of a command (`--timings`, FOLIWAKE_TIMINGS); also for calls to a server. */
61
+ timed<T>(name: string, options: TimedOptions, fn: () => Promise<T>): Promise<T>;
62
+ /** The command as the entry of its trace (OTEL_EXPORTER_OTLP_ENDPOINT). */
63
+ traced<T>(name: string, fn: () => Promise<T>): Promise<T>;
64
+ /**
65
+ * Serves `dev` until Ctrl+C or SIGTERM stops it (the engine stops it, as its other servers); prints its own
66
+ * errors. Resolves to the exit code: 0, 1 (failed), 2 (a refused command line).
67
+ */
68
+ dev(options: LocalDevOptions, io: LocalDevIo): Promise<number>;
69
+ /**
70
+ * `create` made a project in `folder`: the engine trusts the configuration it wrote, so `dev` and local
71
+ * commands run there at once. Resolves to a line to print when that failed, else null.
72
+ */
73
+ created(folder: string): Promise<string | null>;
74
+ }
75
+ /** Called by the engine before oclif loads the commands. */
76
+ export declare function registerLocalRuntime(runtime: LocalRuntime): void;
77
+ /** The engine's runtime, or null in the CLI alone. */
78
+ export declare function localRuntime(): LocalRuntime | null;
@@ -0,0 +1,11 @@
1
+ // One registration per process, also when two copies of this module are loaded (a symlinked plugin).
2
+ const KEY = Symbol.for('@foliwake/cli/local-runtime');
3
+ const slot = globalThis;
4
+ /** Called by the engine before oclif loads the commands. */
5
+ export function registerLocalRuntime(runtime) {
6
+ slot[KEY] = runtime;
7
+ }
8
+ /** The engine's runtime, or null in the CLI alone. */
9
+ export function localRuntime() {
10
+ return slot[KEY] ?? null;
11
+ }
@@ -0,0 +1,6 @@
1
+ import { type Target } from './remote/servers.js';
2
+ export interface TargetFlags {
3
+ server: string | undefined;
4
+ config: string | undefined;
5
+ }
6
+ export declare function chooseTarget({ server, config }: TargetFlags, env?: NodeJS.ProcessEnv, cwd?: string): Target | 'local' | null;
@@ -0,0 +1,23 @@
1
+ // Where a core command's calls go: a server, or with the engine's runtime registered, this computer.
2
+ // --server, then --config or $FOLIWAKE_CONFIG (local), then the folder's .foliwake/connection.json, then
3
+ // $FOLIWAKE_SERVER, then ./foliwake.config.json in this folder (local), then the last `login`, else local.
4
+ // Without the engine nothing is local: null when nothing names a server.
5
+ import { localRuntime } from './local-runtime.js';
6
+ import { ServerAddressError, resolveTarget } from './remote/servers.js';
7
+ import { setting } from './settings.js';
8
+ export function chooseTarget({ server, config }, env = process.env, cwd = process.cwd()) {
9
+ const engine = localRuntime();
10
+ if (!engine)
11
+ return resolveTarget({ server }, env, cwd);
12
+ if (server !== undefined && config !== undefined) {
13
+ throw new ServerAddressError('Use either --server or --config, not both.');
14
+ }
15
+ if (server === undefined && (config !== undefined || setting('CONFIG', env)))
16
+ return 'local';
17
+ const target = resolveTarget({ server }, env, cwd);
18
+ if (target && target.from !== 'login')
19
+ return target;
20
+ if (engine.folderConfig(cwd))
21
+ return 'local';
22
+ return target ?? 'local';
23
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foliwake/cli",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "The foliwake command without the engine: sign in to a Foliwake server and run its commands there (site status, sync, preview, publish, code deploy, branches, releases, sources, credentials, CI keys), and develop blocks against a remote preview.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -43,6 +43,10 @@
43
43
  "types": "./dist/bin.d.ts",
44
44
  "default": "./dist/bin.js"
45
45
  },
46
+ "./local-runtime": {
47
+ "types": "./dist/local-runtime.d.ts",
48
+ "default": "./dist/local-runtime.js"
49
+ },
46
50
  "./package.json": "./package.json"
47
51
  },
48
52
  "oclif": {
@@ -94,12 +98,12 @@
94
98
  "@oclif/core": "4.14.0",
95
99
  "chokidar": "6.0.0",
96
100
  "parse5": "7.3.0",
97
- "@foliwake/blocks-contract": "0.6.0",
98
- "@foliwake/core-contract": "0.6.0",
99
- "@foliwake/server": "0.6.0",
100
- "@foliwake/block-kit": "0.6.0",
101
- "create-foliwake": "0.6.0",
102
- "@foliwake/site-check": "0.6.0"
101
+ "@foliwake/blocks-contract": "0.7.0",
102
+ "@foliwake/server": "0.7.0",
103
+ "@foliwake/core-contract": "0.7.0",
104
+ "@foliwake/site-check": "0.7.0",
105
+ "create-foliwake": "0.7.0",
106
+ "@foliwake/block-kit": "0.7.0"
103
107
  },
104
108
  "files": [
105
109
  "dist/",