@foliwake/cli 0.0.0-stage → 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.
Files changed (256) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/LICENSE +202 -0
  3. package/README.md +654 -2
  4. package/dist/bin.d.ts +2 -0
  5. package/dist/bin.js +9 -0
  6. package/dist/command-words.d.ts +13 -0
  7. package/dist/command-words.js +53 -0
  8. package/dist/commands/account/keys/create.d.ts +12 -0
  9. package/dist/commands/account/keys/create.js +36 -0
  10. package/dist/commands/account/keys/list.d.ts +9 -0
  11. package/dist/commands/account/keys/list.js +23 -0
  12. package/dist/commands/account/keys/revoke.d.ts +12 -0
  13. package/dist/commands/account/keys/revoke.js +15 -0
  14. package/dist/commands/branch/bootstrap.d.ts +11 -0
  15. package/dist/commands/branch/bootstrap.js +23 -0
  16. package/dist/commands/branch/delete.d.ts +17 -0
  17. package/dist/commands/branch/delete.js +38 -0
  18. package/dist/commands/branch/history.d.ts +14 -0
  19. package/dist/commands/branch/history.js +24 -0
  20. package/dist/commands/branch/list.d.ts +11 -0
  21. package/dist/commands/branch/list.js +15 -0
  22. package/dist/commands/branch/update.d.ts +19 -0
  23. package/dist/commands/branch/update.js +49 -0
  24. package/dist/commands/code/deploy.d.ts +15 -0
  25. package/dist/commands/code/deploy.js +78 -0
  26. package/dist/commands/code/prepare.d.ts +13 -0
  27. package/dist/commands/code/prepare.js +54 -0
  28. package/dist/commands/code/release.d.ts +19 -0
  29. package/dist/commands/code/release.js +51 -0
  30. package/dist/commands/code/rollback.d.ts +17 -0
  31. package/dist/commands/code/rollback.js +38 -0
  32. package/dist/commands/connect.d.ts +19 -0
  33. package/dist/commands/connect.js +100 -0
  34. package/dist/commands/create.d.ts +32 -0
  35. package/dist/commands/create.js +171 -0
  36. package/dist/commands/credential/list.d.ts +10 -0
  37. package/dist/commands/credential/list.js +21 -0
  38. package/dist/commands/credential/rm.d.ts +12 -0
  39. package/dist/commands/credential/rm.js +18 -0
  40. package/dist/commands/credential/set.d.ts +15 -0
  41. package/dist/commands/credential/set.js +58 -0
  42. package/dist/commands/dev.d.ts +30 -0
  43. package/dist/commands/dev.js +144 -0
  44. package/dist/commands/login.d.ts +20 -0
  45. package/dist/commands/login.js +94 -0
  46. package/dist/commands/logout.d.ts +14 -0
  47. package/dist/commands/logout.js +61 -0
  48. package/dist/commands/migration/commit.d.ts +13 -0
  49. package/dist/commands/migration/commit.js +42 -0
  50. package/dist/commands/migration/prepare.d.ts +18 -0
  51. package/dist/commands/migration/prepare.js +53 -0
  52. package/dist/commands/operation/cancel.d.ts +14 -0
  53. package/dist/commands/operation/cancel.js +21 -0
  54. package/dist/commands/operation/get.d.ts +14 -0
  55. package/dist/commands/operation/get.js +26 -0
  56. package/dist/commands/operation/list.d.ts +12 -0
  57. package/dist/commands/operation/list.js +25 -0
  58. package/dist/commands/operation/recover.d.ts +20 -0
  59. package/dist/commands/operation/recover.js +61 -0
  60. package/dist/commands/page/changes.d.ts +13 -0
  61. package/dist/commands/page/changes.js +26 -0
  62. package/dist/commands/page/check.d.ts +12 -0
  63. package/dist/commands/page/check.js +25 -0
  64. package/dist/commands/page/replace.d.ts +13 -0
  65. package/dist/commands/page/replace.js +59 -0
  66. package/dist/commands/page/unpreview.d.ts +17 -0
  67. package/dist/commands/page/unpreview.js +54 -0
  68. package/dist/commands/page/unpublish.d.ts +18 -0
  69. package/dist/commands/page/unpublish.js +36 -0
  70. package/dist/commands/project/preview.d.ts +8 -0
  71. package/dist/commands/project/preview.js +20 -0
  72. package/dist/commands/project/publish.d.ts +16 -0
  73. package/dist/commands/project/publish.js +40 -0
  74. package/dist/commands/project/unpublish.d.ts +16 -0
  75. package/dist/commands/project/unpublish.js +33 -0
  76. package/dist/commands/release/rollback.d.ts +17 -0
  77. package/dist/commands/release/rollback.js +38 -0
  78. package/dist/commands/servers/index.d.ts +20 -0
  79. package/dist/commands/servers/index.js +36 -0
  80. package/dist/commands/servers/use.d.ts +11 -0
  81. package/dist/commands/servers/use.js +30 -0
  82. package/dist/commands/site/adopt.d.ts +11 -0
  83. package/dist/commands/site/adopt.js +21 -0
  84. package/dist/commands/site/create.d.ts +18 -0
  85. package/dist/commands/site/create.js +61 -0
  86. package/dist/commands/site/edit.d.ts +11 -0
  87. package/dist/commands/site/edit.js +56 -0
  88. package/dist/commands/site/history.d.ts +11 -0
  89. package/dist/commands/site/history.js +25 -0
  90. package/dist/commands/site/link.d.ts +15 -0
  91. package/dist/commands/site/link.js +35 -0
  92. package/dist/commands/site/list.d.ts +9 -0
  93. package/dist/commands/site/list.js +29 -0
  94. package/dist/commands/site/reset-storage.d.ts +15 -0
  95. package/dist/commands/site/reset-storage.js +61 -0
  96. package/dist/commands/site/set.d.ts +16 -0
  97. package/dist/commands/site/set.js +45 -0
  98. package/dist/commands/site/show.d.ts +10 -0
  99. package/dist/commands/site/show.js +19 -0
  100. package/dist/commands/site/status.d.ts +11 -0
  101. package/dist/commands/site/status.js +15 -0
  102. package/dist/commands/site/unlink.d.ts +11 -0
  103. package/dist/commands/site/unlink.js +28 -0
  104. package/dist/commands/source/add.d.ts +32 -0
  105. package/dist/commands/source/add.js +103 -0
  106. package/dist/commands/source/adopt-pages.d.ts +14 -0
  107. package/dist/commands/source/adopt-pages.js +30 -0
  108. package/dist/commands/source/check.d.ts +17 -0
  109. package/dist/commands/source/check.js +52 -0
  110. package/dist/commands/source/list.d.ts +11 -0
  111. package/dist/commands/source/list.js +15 -0
  112. package/dist/commands/source/mappings/check.d.ts +13 -0
  113. package/dist/commands/source/mappings/check.js +69 -0
  114. package/dist/commands/source/pending.d.ts +12 -0
  115. package/dist/commands/source/pending.js +25 -0
  116. package/dist/commands/source/plugins.d.ts +6 -0
  117. package/dist/commands/source/plugins.js +17 -0
  118. package/dist/commands/source/sync.d.ts +16 -0
  119. package/dist/commands/source/sync.js +58 -0
  120. package/dist/commands/whoami.d.ts +6 -0
  121. package/dist/commands/whoami.js +22 -0
  122. package/dist/connect-prompts.d.ts +16 -0
  123. package/dist/connect-prompts.js +24 -0
  124. package/dist/connect.d.ts +133 -0
  125. package/dist/connect.js +416 -0
  126. package/dist/core-command.d.ts +99 -0
  127. package/dist/core-command.js +332 -0
  128. package/dist/core-types.d.ts +21 -0
  129. package/dist/core-types.js +1 -0
  130. package/dist/create-connect.d.ts +26 -0
  131. package/dist/create-connect.js +93 -0
  132. package/dist/dev/code-watcher.d.ts +66 -0
  133. package/dist/dev/code-watcher.js +254 -0
  134. package/dist/dev/dev-checks.d.ts +14 -0
  135. package/dist/dev/dev-checks.js +138 -0
  136. package/dist/dev/dev-reload.d.ts +51 -0
  137. package/dist/dev/dev-reload.js +345 -0
  138. package/dist/dev/flags.d.ts +19 -0
  139. package/dist/dev/flags.js +54 -0
  140. package/dist/dev/html.d.ts +30 -0
  141. package/dist/dev/html.js +106 -0
  142. package/dist/dev/kit-files.d.ts +7 -0
  143. package/dist/dev/kit-files.js +33 -0
  144. package/dist/dev/local-code.d.ts +22 -0
  145. package/dist/dev/local-code.js +101 -0
  146. package/dist/dev/remote-config.d.ts +57 -0
  147. package/dist/dev/remote-config.js +100 -0
  148. package/dist/dev/remote-dev.d.ts +41 -0
  149. package/dist/dev/remote-dev.js +527 -0
  150. package/dist/dev/remote-fetch.d.ts +5 -0
  151. package/dist/dev/remote-fetch.js +36 -0
  152. package/dist/dev/remote-html.d.ts +10 -0
  153. package/dist/dev/remote-html.js +60 -0
  154. package/dist/dev/remote-page.d.ts +34 -0
  155. package/dist/dev/remote-page.js +183 -0
  156. package/dist/dev/remote-routes.d.ts +63 -0
  157. package/dist/dev/remote-routes.js +114 -0
  158. package/dist/dev/signal-stop.d.ts +17 -0
  159. package/dist/dev/signal-stop.js +46 -0
  160. package/dist/dev/start.d.ts +18 -0
  161. package/dist/dev/start.js +80 -0
  162. package/dist/index.d.ts +6 -0
  163. package/dist/index.js +8 -0
  164. package/dist/lib/diagnostics.d.ts +15 -0
  165. package/dist/lib/diagnostics.js +12 -0
  166. package/dist/lib/front-matter.d.ts +6 -0
  167. package/dist/lib/front-matter.js +59 -0
  168. package/dist/lib/operation-result.d.ts +3 -0
  169. package/dist/lib/operation-result.js +16 -0
  170. package/dist/lib/problem-groups.d.ts +27 -0
  171. package/dist/lib/problem-groups.js +49 -0
  172. package/dist/lib/problems.d.ts +50 -0
  173. package/dist/lib/problems.js +94 -0
  174. package/dist/lib/prompts.d.ts +38 -0
  175. package/dist/lib/prompts.js +77 -0
  176. package/dist/lib/result-types.d.ts +198 -0
  177. package/dist/lib/result-types.js +3 -0
  178. package/dist/lib/rules.d.ts +15 -0
  179. package/dist/lib/rules.js +26 -0
  180. package/dist/lib/summaries.d.ts +19 -0
  181. package/dist/lib/summaries.js +22 -0
  182. package/dist/lib/sync-problems.d.ts +21 -0
  183. package/dist/lib/sync-problems.js +19 -0
  184. package/dist/local-runtime.d.ts +78 -0
  185. package/dist/local-runtime.js +11 -0
  186. package/dist/local-target.d.ts +6 -0
  187. package/dist/local-target.js +23 -0
  188. package/dist/main.d.ts +2 -0
  189. package/dist/main.js +40 -0
  190. package/dist/project-preview.d.ts +35 -0
  191. package/dist/project-preview.js +156 -0
  192. package/dist/project-publish.d.ts +28 -0
  193. package/dist/project-publish.js +173 -0
  194. package/dist/remote/connection.d.ts +8 -0
  195. package/dist/remote/connection.js +19 -0
  196. package/dist/remote/core-failure.d.ts +8 -0
  197. package/dist/remote/core-failure.js +15 -0
  198. package/dist/remote/credentials.d.ts +15 -0
  199. package/dist/remote/credentials.js +112 -0
  200. package/dist/remote/device-login.d.ts +33 -0
  201. package/dist/remote/device-login.js +161 -0
  202. package/dist/remote/remote-caller.d.ts +14 -0
  203. package/dist/remote/remote-caller.js +52 -0
  204. package/dist/remote/rpc-wire.d.ts +18 -0
  205. package/dist/remote/rpc-wire.js +57 -0
  206. package/dist/remote/servers.d.ts +80 -0
  207. package/dist/remote/servers.js +162 -0
  208. package/dist/remote/session.d.ts +53 -0
  209. package/dist/remote/session.js +132 -0
  210. package/dist/remote/sign-in-here.d.ts +5 -0
  211. package/dist/remote/sign-in-here.js +33 -0
  212. package/dist/remote/sign-in.d.ts +25 -0
  213. package/dist/remote/sign-in.js +55 -0
  214. package/dist/remote/wait-slices.d.ts +16 -0
  215. package/dist/remote/wait-slices.js +21 -0
  216. package/dist/render/add.d.ts +3 -0
  217. package/dist/render/add.js +9 -0
  218. package/dist/render/branch-write.d.ts +9 -0
  219. package/dist/render/branch-write.js +28 -0
  220. package/dist/render/branches.d.ts +5 -0
  221. package/dist/render/branches.js +28 -0
  222. package/dist/render/credentials.d.ts +5 -0
  223. package/dist/render/credentials.js +39 -0
  224. package/dist/render/operation-result.d.ts +16 -0
  225. package/dist/render/operation-result.js +65 -0
  226. package/dist/render/operation.d.ts +7 -0
  227. package/dist/render/operation.js +15 -0
  228. package/dist/render/page-changes.d.ts +3 -0
  229. package/dist/render/page-changes.js +36 -0
  230. package/dist/render/pending.d.ts +3 -0
  231. package/dist/render/pending.js +46 -0
  232. package/dist/render/plugin-list.d.ts +3 -0
  233. package/dist/render/plugin-list.js +30 -0
  234. package/dist/render/probe.d.ts +3 -0
  235. package/dist/render/probe.js +61 -0
  236. package/dist/render/problems.d.ts +35 -0
  237. package/dist/render/problems.js +64 -0
  238. package/dist/render/recovery.d.ts +2 -0
  239. package/dist/render/recovery.js +36 -0
  240. package/dist/render/reset-storage.d.ts +4 -0
  241. package/dist/render/reset-storage.js +70 -0
  242. package/dist/render/site-status.d.ts +2 -0
  243. package/dist/render/site-status.js +81 -0
  244. package/dist/render/source-list.d.ts +2 -0
  245. package/dist/render/source-list.js +37 -0
  246. package/dist/render/sync.d.ts +5 -0
  247. package/dist/render/sync.js +66 -0
  248. package/dist/settings.d.ts +10 -0
  249. package/dist/settings.js +45 -0
  250. package/dist/site-entry-edit.d.ts +5 -0
  251. package/dist/site-entry-edit.js +44 -0
  252. package/dist/source-entry.d.ts +32 -0
  253. package/dist/source-entry.js +89 -0
  254. package/dist/version.d.ts +3 -0
  255. package/dist/version.js +10 -0
  256. package/package.json +112 -3
@@ -0,0 +1,332 @@
1
+ // Base class of every command that maps to one core operation on a server. A command is a thin wrapper: it
2
+ // turns flags into the operation's input, calls it, writes text for people with `this.log` and returns the
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.
5
+ import { Command, Errors, Flags } from '@oclif/core';
6
+ import { localRuntime } from './local-runtime.js';
7
+ import { CoreFailure, toCoreFailure } from './remote/core-failure.js';
8
+ import { waitInSlices } from './remote/wait-slices.js';
9
+ import { COMMAND } from './settings.js';
10
+ import { cliVersion } from './version.js';
11
+ /** Commit or end: a long sync or publication finishes long before; the wait stops nothing. */
12
+ const COMMIT_WAIT_MS = 24 * 60 * 60 * 1000;
13
+ /** Default waits start from this settle delay (the server's own is not known here). */
14
+ const REMOTE_SETTLE_DELAY_MS = 30_000;
15
+ /** What a command that needs the engine says, with exit 2. */
16
+ export const NEEDS_ENGINE = `needs the Foliwake engine: the Docker image (\`${COMMAND} docker install\`) or the ` + `engine checkout.`;
17
+ const NO_SERVER = `No Foliwake server is named: pass --server, link this folder (\`${COMMAND} site link <id>\`), ` +
18
+ `set FOLIWAKE_SERVER, or sign in with \`${COMMAND} login\`.`;
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(':', '.');
34
+ export class CoreCommand extends Command {
35
+ static enableJsonFlag = true;
36
+ static baseFlags = {
37
+ debug: Flags.boolean({ description: 'print the underlying error on stderr', helpGroup: 'GLOBAL' }),
38
+ server: Flags.string({ description: SERVER_FLAG, helpGroup: 'GLOBAL' }),
39
+ };
40
+ /** A local project configuration: the engine's; alone, scripts written for the engine get a clear answer. */
41
+ static configFlag = {
42
+ config: localFlag('config', 'project configuration (default: $FOLIWAKE_CONFIG, else ./foliwake.config.json in this folder)', 'a local project configuration'),
43
+ };
44
+ /** For commands that act on a site. Without `--site`: the folder's linked site, else the server's only one. */
45
+ static siteFlags = {
46
+ ...CoreCommand.configFlag,
47
+ site: Flags.string({ description: SITE_FLAG }),
48
+ };
49
+ /** Reading this computer's working files instead of the site's sources: the engine's local runtime. */
50
+ static contentFlag = {
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"),
52
+ };
53
+ /** The whole input of the operation as JSON, for what flags cannot express. Its schema checks it. */
54
+ static inputFlag = {
55
+ input: Flags.string({ description: 'raw JSON for the full operation input; overrides the other input flags' }),
56
+ };
57
+ static refreshWaitFlag = {
58
+ 'wait-timeout': Flags.integer({
59
+ min: 0,
60
+ description: "limit of the wait for this write's cache refresh, in seconds (default: settle delay + 30 s); " +
61
+ 'still pending then: exit 3, `operation recover` finishes it',
62
+ }),
63
+ };
64
+ static expectLiveFlags = {
65
+ expect: Flags.string({
66
+ description: 'the live site release you saw (sr_…, as `site status` shows it); refused when live is another one',
67
+ exclusive: ['latest-live'],
68
+ }),
69
+ 'latest-live': Flags.boolean({
70
+ description: 'expect the live release as it is now (read once, before the request)',
71
+ exclusive: ['expect'],
72
+ }),
73
+ };
74
+ static expectBranchFlags = {
75
+ expect: Flags.string({
76
+ helpValue: 'sel_…|none',
77
+ description: 'the selection of the branch you saw (`branch list --json` shows it; `none`: the branch had no preview); ' +
78
+ 'refused when it is another one',
79
+ exclusive: ['latest-selection', 'sequence'],
80
+ }),
81
+ 'latest-selection': Flags.boolean({
82
+ description: "expect the branch's selection as it is now (read once, before the request)",
83
+ exclusive: ['expect', 'sequence'],
84
+ }),
85
+ sequence: Flags.integer({
86
+ min: 1,
87
+ description: 'deployment ordering (a positive integer such as the CI run id), instead of --expect: refused as ' +
88
+ 'superseded when a request with a higher sequence already updated or deleted this branch',
89
+ exclusive: ['expect', 'latest-selection'],
90
+ }),
91
+ };
92
+ /** Accepted as in the engine's CLI; only the total time is known here (phase timings need the engine). */
93
+ static timingsFlag = {
94
+ timings: Flags.boolean({
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)',
100
+ }),
101
+ };
102
+ core;
103
+ /** The server this command's calls go to; unset when it runs locally (`local`). */
104
+ target;
105
+ /** The engine's core on this computer, when the command runs locally. */
106
+ local = null;
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
+ }
115
+ async init() {
116
+ await super.init();
117
+ // `parse()` without its command cannot type the flags of the subclass.
118
+ const { flags } = await this.parse();
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 });
138
+ }
139
+ this.target = await this.serverTarget(choice === 'local' ? null : choice);
140
+ const { SignInMovedError, remoteCallerFor } = await import('./remote/session.js');
141
+ try {
142
+ this.core = remoteCallerFor(this.target.origin);
143
+ }
144
+ catch (error) {
145
+ if (error instanceof SignInMovedError)
146
+ this.error(error.message, { exit: 1 });
147
+ throw error;
148
+ }
149
+ }
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');
153
+ try {
154
+ return choose();
155
+ }
156
+ catch (error) {
157
+ if (error instanceof ServerAddressError)
158
+ this.error(error.message, { exit: 2 });
159
+ throw error;
160
+ }
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
+ }
170
+ async resolveInput(rawInput, fromFlags) {
171
+ if (rawInput == null)
172
+ return fromFlags();
173
+ try {
174
+ // The untyped boundary: the operation's own schema checks what the JSON holds.
175
+ return JSON.parse(rawInput);
176
+ }
177
+ catch {
178
+ this.error('--input is not valid JSON.');
179
+ }
180
+ }
181
+ /** The site: `--site`, else the folder's linked site on this server, else the server's (or configuration's) only. */
182
+ async siteInput(site) {
183
+ if (site != null)
184
+ return { site };
185
+ if (this.local)
186
+ return this.onlyLocalSite(this.local);
187
+ const linked = await this.linkedSite();
188
+ if (linked !== null)
189
+ return { site: linked };
190
+ const { sites } = await this.core.sites.list();
191
+ if (sites.length !== 1)
192
+ this.error(`${sites.length} sites are available on this server; choose one with --site.`);
193
+ return { site: sites[0].id };
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
+ }
201
+ async linkedSite() {
202
+ const { readConnection } = await import('./remote/connection.js');
203
+ const { nameOrigin } = await import('./remote/servers.js');
204
+ const connection = readConnection(process.cwd());
205
+ if (!connection || nameOrigin(connection.server) !== this.target.origin)
206
+ return null;
207
+ return connection.site;
208
+ }
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;
212
+ }
213
+ /** The `expect.live` of a write: `--expect`, or with `--latest-live` the live release read now. */
214
+ async expectedLive(site, flags) {
215
+ if (flags.expect !== undefined)
216
+ return flags.expect;
217
+ if (!flags['latest-live']) {
218
+ this.error('Name the live release you expect: --expect <sr_…> (as `site status` shows it), or --latest-live.', {
219
+ exit: 2,
220
+ });
221
+ }
222
+ const { live } = await this.core.sites.status({ site });
223
+ if (!live)
224
+ this.error('This site has no live release yet.');
225
+ return live.site_release;
226
+ }
227
+ /** The `expect` of a branch write: `--sequence`, `--expect`, or with `--latest-selection` the selection now. */
228
+ async expectedBranch(site, branch, flags) {
229
+ if (flags.sequence !== undefined)
230
+ return { sequence: flags.sequence };
231
+ if (flags.expect !== undefined)
232
+ return { selection: flags.expect === 'none' ? null : flags.expect };
233
+ if (!flags['latest-selection']) {
234
+ this.error('Name the branch selection you expect: --expect <sel_…|none> (as `branch list --json` shows it), ' +
235
+ '--latest-selection, or --sequence <n> for a deployment.', { exit: 2 });
236
+ }
237
+ const rows = await this.core.branches.list({ site });
238
+ const row = rows.find((candidate) => candidate.branch === branch);
239
+ return { selection: row && row.retired === null ? row.selection : null };
240
+ }
241
+ /** Follows an accepted operation to its commit (or end) and, with `--wait`, its cache refresh. */
242
+ async follow(operation, { wait, waitTimeout }) {
243
+ const { site, id } = operation;
244
+ const committed = await this.waitOperation({ site, id, until: 'commit', timeoutMs: COMMIT_WAIT_MS });
245
+ if (!wait || committed.delivery?.state !== 'pending')
246
+ return committed;
247
+ const timeoutMs = waitTimeout === undefined ? (await this.settleDelayMs(site)) + 30_000 : waitTimeout * 1000;
248
+ const seconds = Math.ceil(timeoutMs / 1000);
249
+ if (!this.jsonEnabled())
250
+ this.log(`Cache refresh pending; waiting up to ${seconds} s for it…`);
251
+ const delivered = await this.waitOperation({ site, id, until: 'delivery', timeoutMs });
252
+ if (delivered.delivery?.state !== 'pending' || delivered.delivery.reason !== undefined)
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();
256
+ return this.core.operations.get({ site, id });
257
+ }
258
+ /** `operations.wait`: locally in one call; against a server in slices under its request timeout. */
259
+ waitOperation(input) {
260
+ if (this.local)
261
+ return this.core.operations.wait(input);
262
+ return waitInSlices((sliceMs) => this.core.operations.wait({ ...input, timeoutMs: sliceMs }), input);
263
+ }
264
+ /** Runs `fn`; with `--timings` (or FOLIWAKE_TIMINGS=1) reports its time on stderr (phases: the engine's). */
265
+ async timed(name, requested, fn) {
266
+ const engine = localRuntime();
267
+ if (engine)
268
+ return engine.timed(name, { requested, json: this.jsonEnabled() }, fn);
269
+ if (!requested && process.env.FOLIWAKE_TIMINGS !== '1')
270
+ return fn();
271
+ const started = performance.now();
272
+ try {
273
+ return await fn();
274
+ }
275
+ finally {
276
+ this.reportTotal(name, Math.round(performance.now() - started));
277
+ }
278
+ }
279
+ reportTotal(name, totalMs) {
280
+ const line = this.jsonEnabled()
281
+ ? JSON.stringify({ timings: { command: name, totalMs } })
282
+ : `timings: ${name} ${totalMs} ms in total (phase timings need the engine)`;
283
+ process.stderr.write(`${line}\n`);
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
+ }
290
+ noteProvisional(provisional) {
291
+ if (!provisional || this.jsonEnabled())
292
+ return;
293
+ this.logToStderr('Note: page IDs of new pages are provisional here (the published pages were not consulted); ' +
294
+ 'preview/publish decide them.');
295
+ }
296
+ toErrorJson(error) {
297
+ return { error: this.coreError ?? { message: error instanceof Error ? error.message : String(error) } };
298
+ }
299
+ // Anything that is not oclif's own goes through core's error shape and exits 1. Parse errors keep exit 2.
300
+ async catch(error) {
301
+ if (error instanceof Errors.CLIError)
302
+ return super.catch(error);
303
+ const failure = await failureOf(error);
304
+ this.coreError = failure.coreError;
305
+ if (process.argv.includes('--debug'))
306
+ this.logToStderr(String(debugStack(failure)));
307
+ return super.catch(new Errors.CLIError(this.errorText(failure.coreError), { exit: 1 }));
308
+ }
309
+ errorText({ code, message, category, fields = [] }) {
310
+ const details = fields.map((field) => (field.path ? `${field.path}: ${field.message}` : field.message));
311
+ const origin = this.local ? undefined : this.target?.origin;
312
+ const signIn = origin && category === 'unauthorized' ? [`Sign in with \`${COMMAND} login ${origin}\`.`] : [];
313
+ const older = code === 'PROCEDURE_UNKNOWN' && origin
314
+ ? [
315
+ `The server is older than this CLI (@foliwake/cli ${cliVersion()}): update the server, or use ` +
316
+ 'an older @foliwake/cli that matches it (`GET /api/version` names its engine).',
317
+ ]
318
+ : [];
319
+ return [`${code}: ${message}`, ...details, ...signIn, ...older, 'Run again with --debug for details.'].join('\n');
320
+ }
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
+ }
330
+ function debugStack(failure) {
331
+ return (failure.cause instanceof Error ? failure.cause : failure).stack;
332
+ }
@@ -0,0 +1,21 @@
1
+ import type { CoreOutput } from '@foliwake/core-contract';
2
+ export type { CoreCaller } from '@foliwake/core-contract';
3
+ export type { BranchResultCore, OperationResult, ResetStorageResult, SiteCreateResult, SyncResultCore, } from './lib/result-types.js';
4
+ export type Grant = CoreOutput<'whoami'>;
5
+ export type Operation = CoreOutput<'operations.get'>;
6
+ export type Recovery = CoreOutput<'operations.recover'>;
7
+ export type SiteStatus = CoreOutput<'sites.status'>;
8
+ export type SiteList = CoreOutput<'sites.list'>;
9
+ export type ResetStoragePlan = CoreOutput<'sites.resetStoragePlan'>;
10
+ export type SourceList = CoreOutput<'sources.list'>;
11
+ export type PluginList = CoreOutput<'sources.plugins'>;
12
+ export type PendingAnswer = CoreOutput<'sources.pending'>;
13
+ export type ProbeAnswer = CoreOutput<'sources.probe'>;
14
+ export type AddAnswer = CoreOutput<'sources.add'>;
15
+ export type BranchList = CoreOutput<'branches.list'>;
16
+ export type BranchHistory = CoreOutput<'branches.history'>;
17
+ export type Changes = CoreOutput<'content.changes'>;
18
+ export type Validation = CoreOutput<'content.validate'>;
19
+ export type CredentialList = CoreOutput<'credentials.list'>;
20
+ export type CredentialSetResult = CoreOutput<'credentials.set'>;
21
+ export type CredentialRemoveResult = CoreOutput<'credentials.remove'>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,26 @@
1
+ import { type ConnectIO } from './connect.js';
2
+ import { type PromptStreams } from './lib/prompts.js';
3
+ export interface ConnectStep {
4
+ /** The project folder, as created. */
5
+ target: string;
6
+ /** The site id the answers named, if any. */
7
+ siteId: string | null;
8
+ /** The project has its first commit (a new site gets its code from it). */
9
+ committed: boolean;
10
+ interactive: boolean;
11
+ createSite: boolean;
12
+ linkSite: string | undefined;
13
+ /** An origin, from --server. */
14
+ server: string | undefined;
15
+ relink: boolean;
16
+ prompts: PromptStreams;
17
+ signIn: (origin: string) => Promise<boolean>;
18
+ /** Told the server and site the folder was linked to (`connect --json`). */
19
+ onLinked?: (linked: {
20
+ server: string | null;
21
+ site: string;
22
+ created: boolean;
23
+ }) => void;
24
+ }
25
+ /** The connect step; its exit status, or null when nothing ran (not now, a failed sign-in, no answer). */
26
+ export declare function connectStep(step: ConnectStep, io: ConnectIO): Promise<number | null>;
@@ -0,0 +1,93 @@
1
+ // The last step of `foliwake create`: «Connect to a Foliwake server?». In a terminal: which server (each
2
+ // signed in to, those signed out of, another one, or not now; not asked with --server or FOLIWAKE_SERVER), the
3
+ // sign-in when it is needed (as `login`), then a new site (offered to admins), an existing one, or not now.
4
+ // Without a terminal: only --create-site or --link-site, on the server `site create` would choose. Runs the
5
+ // same code as `site create` and `site link` in the new folder.
6
+ import { localSiteId } from 'create-foliwake';
7
+ import { connectChoices, createSite, knownServers, linkSite } from './connect.js';
8
+ import { terminalQuestions } from './connect-prompts.js';
9
+ import { askConnect, askServer } from './lib/prompts.js';
10
+ import { cloudConfigured, serverOrigin } from './remote/servers.js';
11
+ import { COMMAND, setting } from './settings.js';
12
+ function relinkOf(step) {
13
+ const ask = terminalQuestions({ input: process.stdin, output: process.stdout }, { ask: step.interactive });
14
+ return { relink: step.relink, confirmRelink: ask.confirmRelink };
15
+ }
16
+ function runner(step, io, site) {
17
+ const base = { cwd: step.target, env: process.env, ...relinkOf(step) };
18
+ return async (server) => {
19
+ const on = server ?? undefined;
20
+ if (step.linkSite) {
21
+ const linked = await linkSite({ ...base, site: step.linkSite, server: on }, io);
22
+ if (linked.exit === 0)
23
+ step.onLinked?.({ server: linked.server, site: step.linkSite, created: false });
24
+ return linked.exit;
25
+ }
26
+ const created = await createSite({ ...base, site, server: on, code: true }, io);
27
+ if (created.exit === 0)
28
+ step.onLinked?.({ server: created.server, site, created: true });
29
+ return created.exit;
30
+ };
31
+ }
32
+ /** FOLIWAKE_SERVER as an origin, or null (a value that is no address is said and not used). */
33
+ function presetServer() {
34
+ const typed = setting('SERVER', process.env);
35
+ if (!typed)
36
+ return null;
37
+ try {
38
+ return serverOrigin(typed);
39
+ }
40
+ catch (error) {
41
+ process.stderr.write(`FOLIWAKE_SERVER is not used: ${error.message}\n`);
42
+ return null;
43
+ }
44
+ }
45
+ async function choicesOn(server, io) {
46
+ try {
47
+ const { mayCreate, sites } = await connectChoices({ server, env: process.env }, io);
48
+ return { mayCreate, sites };
49
+ }
50
+ catch (error) {
51
+ const code = error.coreError?.code ?? error.message;
52
+ const later = `connect later with \`${COMMAND} site create\` or \`site link\``;
53
+ process.stderr.write(`${server} could not list your sites (${code}); ${later}.\n`);
54
+ return null;
55
+ }
56
+ }
57
+ /** The connect step; its exit status, or null when nothing ran (not now, a failed sign-in, no answer). */
58
+ export async function connectStep(step, io) {
59
+ const site = localSiteId(step.siteId, step.target);
60
+ const run = runner(step, io, site);
61
+ const asked = step.createSite || step.linkSite !== undefined;
62
+ if (!step.interactive)
63
+ return asked ? run(step.server ?? null) : null;
64
+ const known = await knownServers(process.env, { withCloud: cloudConfigured() });
65
+ const server = step.server ?? presetServer() ?? (await askServer(step.prompts, known, (typed) => serverOrigin(typed)));
66
+ if (server === null)
67
+ return null;
68
+ if (!known.some((entry) => entry.origin === server && entry.signedIn)) {
69
+ io.out(`\nSigning in to ${server} (as \`${COMMAND} login ${server}\`).`);
70
+ if (!(await step.signIn(server)))
71
+ return null;
72
+ }
73
+ if (asked)
74
+ return run(server);
75
+ if (!step.committed) {
76
+ io.out(`There is no first commit: a new site gets no code until \`${COMMAND} code prepare\` on the server.`);
77
+ }
78
+ const choices = await choicesOn(server, io);
79
+ if (!choices)
80
+ return null;
81
+ const answer = await askConnect(step.prompts, { server, site, ...choices });
82
+ if (!answer)
83
+ return null;
84
+ io.out('');
85
+ return 'create' in answer ? run(server) : linkWith(step, io, answer.link, server);
86
+ }
87
+ async function linkWith(step, io, site, server) {
88
+ const request = { cwd: step.target, env: process.env, site, server, ...relinkOf(step) };
89
+ const linked = await linkSite(request, io);
90
+ if (linked.exit === 0)
91
+ step.onLinked?.({ server: linked.server, site, created: false });
92
+ return linked.exit;
93
+ }
@@ -0,0 +1,66 @@
1
+ /** The code directories served (and watched) under the code root. */
2
+ export declare const CODE_DIRECTORIES: readonly ["components", "scripts", "styles", "templates"];
3
+ /** The file types served from them. */
4
+ export declare const CODE_EXTENSIONS: readonly string[];
5
+ /** Default polling interval (ms) when polling is chosen. */
6
+ export declare const DEFAULT_CODE_POLLING_INTERVAL_MS = 1000;
7
+ export interface CodeWatcherOptions {
8
+ /** absolute code root */
9
+ cwd: string;
10
+ /** called with the changed cwd-relative posix paths (added, changed or removed) */
11
+ onChange: (files: string[]) => void;
12
+ onError?: (error: unknown) => void;
13
+ /** stat polling (true) or native fs.watch events (false); see resolveWatchPolling */
14
+ usePolling: boolean;
15
+ /** polling interval in ms (default 1000; polling only) */
16
+ pollingIntervalMs?: number;
17
+ /** quiet window that merges watcher events into one batch (default 50) */
18
+ eventDelayMs?: number;
19
+ }
20
+ export interface CodeWatcher {
21
+ start(): Promise<void>;
22
+ /** Re-reads every known and watched code file now; resolves with the files that changed. */
23
+ rescan(): Promise<string[]>;
24
+ stop(): Promise<void>;
25
+ /** The backend Chokidar actually runs ('polling' or 'auto'); null before start / after stop. */
26
+ backend(): string | null;
27
+ }
28
+ export type WatchModeSource = 'option' | 'env' | 'chokidar-env' | 'platform';
29
+ export interface WatchModeChoice {
30
+ usePolling: boolean;
31
+ /** which setting decided */
32
+ source: WatchModeSource;
33
+ /** one line for the start-up log: the mode, what decided it and what it overrode */
34
+ description: string;
35
+ /** a FOLIWAKE_WATCH_POLLING value that is not recognised (ignored) */
36
+ invalid?: string;
37
+ /** environment variables that were set but did not decide (lower precedence) */
38
+ overridden: string[];
39
+ }
40
+ /**
41
+ * Chooses polling or native events for the code watcher. Precedence (first that is set wins):
42
+ * 1. the command line: `dev --watch --watch-polling` / `--no-watch-polling`;
43
+ * 2. FOLIWAKE_WATCH_POLLING=1|true|yes or 0|false|no (any other value is ignored and reported);
44
+ * 3. CHOKIDAR_USEPOLLING (Chokidar's own variable; same reading as Chokidar);
45
+ * 4. the platform: polling on macOS (native directory events / FSEvents were measured silent
46
+ * on a development Mac), native events elsewhere (Linux measured; Windows not measured).
47
+ * The watcher is always created with this decision: createCodeWatcher hides CHOKIDAR_USEPOLLING
48
+ * and CHOKIDAR_INTERVAL from Chokidar, which would otherwise override it.
49
+ */
50
+ export declare function resolveWatchPolling({ option, env, platform, }?: {
51
+ option?: boolean;
52
+ env?: NodeJS.ProcessEnv;
53
+ platform?: NodeJS.Platform;
54
+ }): WatchModeChoice;
55
+ /** Whether a cwd-relative posix path is watched code (no dot segments, served extension) or a block example. */
56
+ export declare function isCodeFile(relative: string): boolean;
57
+ export declare function createCodeWatcher({ cwd, onChange, onError, usePolling, pollingIntervalMs, eventDelayMs, }: CodeWatcherOptions): CodeWatcher;
58
+ /**
59
+ * The code watcher of `dev --watch` (local and remote mode): decides polling vs native events
60
+ * (resolveWatchPolling, `polling` = the CLI flag), logs the decision and what it overrode, and
61
+ * creates the watcher. `log` receives one line without the command tag.
62
+ */
63
+ export declare function createLiveCodeWatcher({ polling, log, ...options }: Omit<CodeWatcherOptions, 'usePolling'> & {
64
+ polling?: boolean;
65
+ log: (line: string) => void;
66
+ }): CodeWatcher;