@osdlc/wayfinder 0.7.4 → 0.8.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 (121) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/CONTRIBUTING.md +6 -0
  3. package/README.md +295 -150
  4. package/SECURITY.md +19 -5
  5. package/dist/actions.d.ts +23 -0
  6. package/dist/actions.js +97 -0
  7. package/dist/app.d.ts +1 -13
  8. package/dist/app.js +1 -13
  9. package/dist/args.d.ts +11 -6
  10. package/dist/args.js +25 -7
  11. package/dist/cache.d.ts +2 -4
  12. package/dist/cache.js +5 -10
  13. package/dist/catalog.d.ts +30 -3
  14. package/dist/catalog.js +87 -11
  15. package/dist/clean-command.d.ts +65 -36
  16. package/dist/clean-command.js +372 -226
  17. package/dist/cli.d.ts +24 -57
  18. package/dist/cli.js +139 -568
  19. package/dist/commands/browse.d.ts +128 -0
  20. package/dist/commands/browse.js +151 -0
  21. package/dist/commands/index.d.ts +25 -0
  22. package/dist/commands/index.js +71 -0
  23. package/dist/commands/list.d.ts +208 -0
  24. package/dist/commands/list.js +127 -0
  25. package/dist/commands/query.d.ts +166 -0
  26. package/dist/commands/query.js +73 -0
  27. package/dist/commands/run.d.ts +114 -0
  28. package/dist/commands/run.js +139 -0
  29. package/dist/commands/shared.d.ts +152 -0
  30. package/dist/commands/shared.js +209 -0
  31. package/dist/config-command.d.ts +27 -43
  32. package/dist/config-command.js +129 -330
  33. package/dist/config-keys.d.ts +25 -0
  34. package/dist/config-keys.js +29 -0
  35. package/dist/config.d.ts +271 -257
  36. package/dist/config.js +610 -460
  37. package/dist/core/copy-text.d.ts +30 -0
  38. package/dist/core/copy-text.js +50 -0
  39. package/dist/core/filter.d.ts +55 -0
  40. package/dist/core/filter.js +59 -0
  41. package/dist/core/run.d.ts +22 -0
  42. package/dist/core/run.js +59 -0
  43. package/dist/core/saved-view.d.ts +59 -0
  44. package/dist/core/saved-view.js +119 -0
  45. package/dist/core/session.d.ts +262 -0
  46. package/dist/core/session.js +589 -0
  47. package/dist/core/skills.d.ts +53 -0
  48. package/dist/core/skills.js +54 -0
  49. package/dist/core/unknowns.d.ts +72 -0
  50. package/dist/core/unknowns.js +68 -0
  51. package/dist/devlink.d.ts +3 -0
  52. package/dist/devlink.js +5 -2
  53. package/dist/document-schemas.generated.d.ts +22 -0
  54. package/dist/document-schemas.generated.js +916 -0
  55. package/dist/documents.d.ts +432 -0
  56. package/dist/documents.js +163 -0
  57. package/dist/groups.d.ts +22 -26
  58. package/dist/groups.js +13 -29
  59. package/dist/guide.d.ts +26 -13
  60. package/dist/guide.js +119 -103
  61. package/dist/index.d.ts +112 -0
  62. package/dist/index.js +58 -0
  63. package/dist/keys.d.ts +51 -0
  64. package/dist/keys.js +273 -0
  65. package/dist/page.d.ts +18 -8
  66. package/dist/page.js +28 -17
  67. package/dist/providers-command.d.ts +81 -20
  68. package/dist/providers-command.js +33 -75
  69. package/dist/schema.d.ts +48 -0
  70. package/dist/schema.js +61 -0
  71. package/dist/serve/auth.d.ts +46 -0
  72. package/dist/serve/auth.js +82 -0
  73. package/dist/serve/catalog-share.d.ts +51 -0
  74. package/dist/serve/catalog-share.js +116 -0
  75. package/dist/serve/index.d.ts +98 -0
  76. package/dist/serve/index.js +251 -0
  77. package/dist/serve/routes.d.ts +60 -0
  78. package/dist/serve/routes.js +186 -0
  79. package/dist/serve/terminal-input.d.ts +50 -0
  80. package/dist/serve/terminal-input.js +108 -0
  81. package/dist/skills.d.ts +19 -0
  82. package/dist/skills.js +54 -0
  83. package/dist/terminal-text.d.ts +8 -0
  84. package/dist/terminal-text.js +19 -6
  85. package/dist/tool-info.d.ts +24 -0
  86. package/dist/tool-info.js +17 -0
  87. package/dist/trust-command.d.ts +15 -27
  88. package/dist/trust-command.js +110 -208
  89. package/dist/trust-store.d.ts +5 -10
  90. package/dist/trust-store.js +9 -42
  91. package/dist/tui/app.d.ts +180 -0
  92. package/dist/tui/app.js +1278 -0
  93. package/dist/tui/copy.d.ts +29 -0
  94. package/dist/tui/copy.js +39 -0
  95. package/dist/tui/index.d.ts +33 -0
  96. package/dist/tui/index.js +97 -0
  97. package/dist/tui/keys-input.d.ts +27 -0
  98. package/dist/tui/keys-input.js +87 -0
  99. package/dist/tui/settings.d.ts +94 -0
  100. package/dist/tui/settings.js +198 -0
  101. package/dist/tui/style.d.ts +62 -0
  102. package/dist/tui/style.js +77 -0
  103. package/dist/version.d.ts +6 -0
  104. package/dist/version.js +7 -0
  105. package/dist/vocabulary.d.ts +89 -0
  106. package/dist/vocabulary.js +153 -0
  107. package/dist/web/main.js +1965 -568
  108. package/dist/web/page.html +39 -33
  109. package/dist/web/styles.css +457 -329
  110. package/dist/xdg.d.ts +76 -4
  111. package/dist/xdg.js +77 -5
  112. package/package.json +28 -9
  113. package/schema/config.json +133 -0
  114. package/dist/http.d.ts +0 -22
  115. package/dist/http.js +0 -149
  116. package/dist/origin-owner.d.ts +0 -19
  117. package/dist/origin-owner.js +0 -85
  118. package/dist/serve.d.ts +0 -98
  119. package/dist/serve.js +0 -671
  120. package/dist/tui.d.ts +0 -177
  121. package/dist/tui.js +0 -840
@@ -3,30 +3,12 @@
3
3
  * with its roles, its runner kind, its binary and whether that binary is on
4
4
  * an absolute PATH entry. Reads files only; runs nothing.
5
5
  */
6
- import { EXIT } from '@osdlc/cli-tool';
7
6
  import { which } from '@osdlc/command-seam';
8
- import { homeDir, policyExecGate } from '@osdlc/trust-repo';
9
- import { APP, BIN } from "./app.js";
10
- import { ConfigError, loadConfig, trustPolicyFromConfig, trustPolicyOptions, } from "./config.js";
11
- import { jsonText, terminalSafe } from "./terminal-text.js";
12
- import { appTrustStore } from "./trust-store.js";
7
+ import { kit, openSession } from "./commands/shared.js";
8
+ import { ProvidersOutput } from "./documents.js";
9
+ import { terminalSafe } from "./terminal-text.js";
10
+ import { toolSummary } from "./tool-info.js";
13
11
  const ROLE_ORDER = ['runner', 'packageManager', 'toolManager', 'hookManager'];
14
- function usage() {
15
- return `${BIN} providers — the tools ${APP} knows, built-in and your own
16
-
17
- usage: ${BIN} providers [options]
18
-
19
- --config MODULE also load the tools a module exports; repeatable
20
- --json the same rows as a JSON array
21
- -C, --dir PATH the project whose config to read (default: cwd)
22
- -h, --help this text
23
-
24
- A custom tool comes from --config, from "tools" in the user config, or from
25
- "tools" in the project file when the repository is trusted and execution is
26
- allowed. kind is the runner
27
- role's: parse reads files, exec runs the repository's tools and needs trust.
28
- `;
29
- }
30
12
  /** Found on an absolute PATH entry, as detection finds a binary. */
31
13
  function onPath(binary, env) {
32
14
  const lookup = { absolutePathOnly: true, env: { PATH: env['PATH'], PATHEXT: env['PATHEXT'] } };
@@ -36,6 +18,7 @@ function onPath(binary, env) {
36
18
  export function providerRows(tools, custom, env) {
37
19
  return tools.map((t) => {
38
20
  const from = custom.find((c) => c.def === t);
21
+ const info = toolSummary(t);
39
22
  return {
40
23
  id: t.id,
41
24
  roles: ROLE_ORDER.filter((r) => t.roles[r] !== undefined),
@@ -44,6 +27,10 @@ export function providerRows(tools, custom, env) {
44
27
  onPath: t.binary === undefined ? null : onPath(t.binary, env),
45
28
  source: from === undefined ? 'built-in' : 'custom',
46
29
  ...(from !== undefined ? { module: from.module } : {}),
30
+ homepage: info.homepage,
31
+ description: info.description,
32
+ ecosystem: info.ecosystem,
33
+ language: info.language,
47
34
  };
48
35
  });
49
36
  }
@@ -55,9 +42,11 @@ function table(rows) {
55
42
  r.kind ?? '-',
56
43
  r.binary ?? '-',
57
44
  r.onPath === null ? '-' : r.onPath ? 'yes' : 'no',
45
+ r.language,
58
46
  r.source === 'custom' && r.module !== undefined ? `custom ${r.module}` : r.source,
47
+ r.homepage ?? '-',
59
48
  ].map((cell) => terminalSafe(cell)));
60
- const head = ['tool', 'roles', 'kind', 'binary', 'on PATH', 'source'];
49
+ const head = ['tool', 'roles', 'kind', 'binary', 'on PATH', 'language', 'source', 'homepage'];
61
50
  const widths = head.map((h, i) => Math.max(h.length, ...cells.map((c) => c[i].length)));
62
51
  const fmt = (c) => c
63
52
  .map((v, i) => (i === c.length - 1 ? v : v.padEnd(widths[i])))
@@ -65,56 +54,25 @@ function table(rows) {
65
54
  .trimEnd();
66
55
  return [fmt(head), ...cells.map(fmt)].join('\n') + '\n';
67
56
  }
68
- /** `way providers …`. Returns the exit code. */
69
- export async function runProvidersCommand(root, argv, io) {
70
- const env = io.env ?? process.env;
71
- const home = io.home ?? homeDir();
72
- let json = false;
73
- const modules = [];
74
- for (let i = 0; i < argv.length; i++) {
75
- const arg = argv[i];
76
- if (arg === '-h' || arg === '--help') {
77
- io.stdout(usage());
78
- return EXIT.ok;
79
- }
80
- else if (arg === '--json')
81
- json = true;
82
- else if (arg === '--config' || arg.startsWith('--config=')) {
83
- const value = arg === '--config' ? argv[++i] : arg.slice('--config='.length);
84
- if (value === undefined || value === '') {
85
- io.stderr(`${APP}: --config needs a module path\n\n${usage()}`);
86
- return EXIT.usage;
87
- }
88
- modules.push(value);
89
- }
90
- else {
91
- io.stderr(`${APP}: unknown option: ${arg}\n\n${usage()}`);
92
- return EXIT.usage;
93
- }
94
- }
95
- let cfg;
96
- try {
97
- cfg = await loadConfig(root, env, home);
98
- }
99
- catch (err) {
100
- if (err instanceof ConfigError) {
101
- io.stderr(`${APP}: ${err.message}\n`);
102
- return EXIT.error;
103
- }
104
- throw err;
105
- }
106
- for (const warning of cfg.warnings)
107
- io.stderr(`warning: ${warning}\n`);
108
- // The same gate `way` applies: project modules need trust and execution allowed.
109
- const gate = await policyExecGate(appTrustStore({ env, home }), trustPolicyFromConfig(cfg.effective), { root, configured: io.configuredAllowExec(cfg) }, trustPolicyOptions(home));
110
- const built = await io.load(cfg, modules, gate.trusted && gate.allowExec);
111
- if ('error' in built) {
112
- io.stderr(`${APP}: ${built.error}\n`);
113
- return EXIT.error;
114
- }
115
- for (const warning of built.warnings)
116
- io.stderr(`warning: ${warning}\n`);
117
- const rows = providerRows(built.project.tools, built.tools, env);
118
- io.stdout(json ? `${jsonText(rows, 2)}\n` : table(rows));
119
- return EXIT.ok;
57
+ /** Make the `providers` command. */
58
+ export function providersCommand(home) {
59
+ return kit.command({
60
+ summary: 'the registered tools, built-in and your own',
61
+ description: 'Every tool wayfinder knows, with its roles, its runner kind, its binary and whether that ' +
62
+ 'binary is on an absolute PATH entry. Reads files only; runs nothing. A custom tool comes ' +
63
+ 'from --config, from "tools" in the user config, or from "tools" in the project file when ' +
64
+ "the repository is trusted and execution is allowed. kind is the runner role's: parse " +
65
+ "reads files, exec runs the repository's tools and needs trust. Each tool has its " +
66
+ 'language and homepage; --json adds its description.',
67
+ output: ProvidersOutput,
68
+ kind: 'providers',
69
+ readOnly: true,
70
+ async run({ globals }, ctx) {
71
+ const session = await openSession(globals, ctx, home);
72
+ return { providers: providerRows(session.project.tools, session.tools, ctx.env) };
73
+ },
74
+ text(output) {
75
+ return table(output.providers);
76
+ },
77
+ });
120
78
  }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * `@osdlc/wayfinder/schema`: JSON Schemas (draft 2020-12) for every document
3
+ * `way` prints with `--json`, keyed by each document's `kind`. Every document
4
+ * is an object with `schemaVersion` and `kind` first. `way schema` prints the
5
+ * same schemas with each command's input.
6
+ *
7
+ * The task, report and catalog shapes are `@osdlc/system-model/schema`'s,
8
+ * re-exported here. Browser-safe: no Node built-in.
9
+ */
10
+ import { z } from 'zod';
11
+ import { GENERATED_VERSIONS } from './document-schemas.generated.ts';
12
+ export { CATALOG_SCHEMA_VERSION, catalogSchema, paramSchema, runnerReportSchema, taskSchema, toolInfoSchema, } from '@osdlc/system-model/schema';
13
+ /** A JSON Schema document, as a plain object. */
14
+ export type JsonSchema = Readonly<Record<string, unknown>>;
15
+ /**
16
+ * The `kind` of each document `way` prints: `catalog` (`list`), `query`,
17
+ * `run`, `providers`, `config-<name>` for each `config` subcommand, `trust`,
18
+ * `guide`, `clean`, `help`, `schema`, `error` for a failure and `version`
19
+ * for `--version`.
20
+ */
21
+ export type DocumentKind = keyof typeof GENERATED_VERSIONS;
22
+ /** Every {@link DocumentKind}. */
23
+ export declare const DOCUMENT_KINDS: readonly DocumentKind[];
24
+ /**
25
+ * The `schemaVersion` of each document, as each command declares it. Raised
26
+ * when a document changes incompatibly.
27
+ */
28
+ export declare const DOCUMENT_VERSIONS: Readonly<Record<DocumentKind, number>>;
29
+ /**
30
+ * The Zod schema of a whole document: `schemaVersion` and `kind`, then the
31
+ * command's output. The same envelope `@osdlc/cli-tool` prints. A document
32
+ * wayfinder does not declare itself is read from its JSON Schema.
33
+ */
34
+ export declare function documentZod(kind: DocumentKind): z.ZodObject;
35
+ /** `way list --json`: the catalog with its groups, cache verdicts and unknowns. */
36
+ export declare const catalogDocumentSchema: JsonSchema;
37
+ /** `way query --json`: the matching tasks, best first. */
38
+ export declare const queryDocumentSchema: JsonSchema;
39
+ /** `way providers --json`: every registered tool. */
40
+ export declare const providersDocumentSchema: JsonSchema;
41
+ /** `way run --json`: what ran, or with `--dry-run` what would. */
42
+ export declare const runDocumentSchema: JsonSchema;
43
+ /** `way trust --json`: what a grant, a removal, `--show` or `--list` found. */
44
+ export declare const trustDocumentSchema: JsonSchema;
45
+ /** `way clean --json`: what was removed, or with `--dry-run` what would be. */
46
+ export declare const cleanDocumentSchema: JsonSchema;
47
+ /** Every document schema, by `kind`. */
48
+ export declare const DOCUMENT_SCHEMAS: Readonly<Record<DocumentKind, JsonSchema>>;
package/dist/schema.js ADDED
@@ -0,0 +1,61 @@
1
+ /**
2
+ * `@osdlc/wayfinder/schema`: JSON Schemas (draft 2020-12) for every document
3
+ * `way` prints with `--json`, keyed by each document's `kind`. Every document
4
+ * is an object with `schemaVersion` and `kind` first. `way schema` prints the
5
+ * same schemas with each command's input.
6
+ *
7
+ * The task, report and catalog shapes are `@osdlc/system-model/schema`'s,
8
+ * re-exported here. Browser-safe: no Node built-in.
9
+ */
10
+ import { z } from 'zod';
11
+ import { GENERATED_SCHEMAS, GENERATED_VERSIONS } from "./document-schemas.generated.js";
12
+ import { CatalogOutput, ProvidersOutput, QueryOutput, RunOutput } from "./documents.js";
13
+ export { CATALOG_SCHEMA_VERSION, catalogSchema, paramSchema, runnerReportSchema, taskSchema, toolInfoSchema, } from '@osdlc/system-model/schema';
14
+ /** Every {@link DocumentKind}. */
15
+ export const DOCUMENT_KINDS = Object.keys(GENERATED_VERSIONS);
16
+ /**
17
+ * The `schemaVersion` of each document, as each command declares it. Raised
18
+ * when a document changes incompatibly.
19
+ */
20
+ export const DOCUMENT_VERSIONS = GENERATED_VERSIONS;
21
+ /** The documents wayfinder declares itself, as Zod. */
22
+ const OUTPUTS = {
23
+ catalog: CatalogOutput,
24
+ query: QueryOutput,
25
+ providers: ProvidersOutput,
26
+ run: RunOutput,
27
+ };
28
+ /**
29
+ * The Zod schema of a whole document: `schemaVersion` and `kind`, then the
30
+ * command's output. The same envelope `@osdlc/cli-tool` prints. A document
31
+ * wayfinder does not declare itself is read from its JSON Schema.
32
+ */
33
+ export function documentZod(kind) {
34
+ const output = OUTPUTS[kind];
35
+ if (output === undefined) {
36
+ return z.fromJSONSchema(GENERATED_SCHEMAS[kind]);
37
+ }
38
+ return z
39
+ .object({ schemaVersion: z.literal(DOCUMENT_VERSIONS[kind]), kind: z.literal(kind) })
40
+ .extend(output.shape);
41
+ }
42
+ function jsonSchema(kind) {
43
+ const generated = GENERATED_SCHEMAS[kind];
44
+ if (generated !== undefined)
45
+ return generated;
46
+ return z.toJSONSchema(documentZod(kind), { io: 'input', unrepresentable: 'any' });
47
+ }
48
+ /** `way list --json`: the catalog with its groups, cache verdicts and unknowns. */
49
+ export const catalogDocumentSchema = jsonSchema('catalog');
50
+ /** `way query --json`: the matching tasks, best first. */
51
+ export const queryDocumentSchema = jsonSchema('query');
52
+ /** `way providers --json`: every registered tool. */
53
+ export const providersDocumentSchema = jsonSchema('providers');
54
+ /** `way run --json`: what ran, or with `--dry-run` what would. */
55
+ export const runDocumentSchema = jsonSchema('run');
56
+ /** `way trust --json`: what a grant, a removal, `--show` or `--list` found. */
57
+ export const trustDocumentSchema = jsonSchema('trust');
58
+ /** `way clean --json`: what was removed, or with `--dry-run` what would be. */
59
+ export const cleanDocumentSchema = jsonSchema('clean');
60
+ /** Every document schema, by `kind`. */
61
+ export const DOCUMENT_SCHEMAS = Object.fromEntries(DOCUMENT_KINDS.map((kind) => [kind, jsonSchema(kind)]));
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Signing a browser in to the web view.
3
+ *
4
+ * The command tree is served by cli-tool's HTTP adapter, which owns the
5
+ * bearer token and the Host and Origin checks. What it leaves to the app is
6
+ * how its own page gets that token.
7
+ *
8
+ * Other local users can reach 127.0.0.1 and can read a process's argv while
9
+ * it runs. So the bearer token never appears in a URL, an argv or the page
10
+ * itself. The URL the server prints or opens carries a boot token instead.
11
+ * The page sends it once, in a JSON body to `POST /session`, and gets the
12
+ * bearer token back. The boot token works once and expires a minute after
13
+ * the URL is shown, so it is only usable between opening the browser and the
14
+ * page loading.
15
+ *
16
+ * The boot token is in the browser opener's argv while it runs, so another
17
+ * local user could redeem it first. The right boot token sent a second time
18
+ * is refused, and the server warns in its terminal (see `onReplay`). Sessions
19
+ * already signed in keep working; a new link comes from {@link SignIn.renew}.
20
+ *
21
+ * A JSON body from another origin needs a CORS preflight, which the server
22
+ * never answers, so a website cannot redeem the boot token either.
23
+ */
24
+ /** The one-shot boot token. */
25
+ export interface SignIn {
26
+ /** Put this in the URL the person opens. The latest one {@link renew} made. */
27
+ readonly bootToken: string;
28
+ /**
29
+ * Start the expiry timer. Call it when the URL is shown: the first probe
30
+ * runs before that, and on a cold tree it can use up much of the minute.
31
+ */
32
+ arm(): void;
33
+ /** True once, for the first unexpired `candidate` that matches. */
34
+ redeem(candidate: unknown): boolean;
35
+ /**
36
+ * Replace the boot token with a new one, armed, and return it. The old one
37
+ * stops working. Bearer tokens already handed out keep working.
38
+ */
39
+ renew(): string;
40
+ }
41
+ /**
42
+ * Make a boot token. `now` is injectable for tests. `onReplay` is called when
43
+ * the right boot token arrives after it was redeemed: a second tab, or
44
+ * another program that read the link.
45
+ */
46
+ export declare function createSignIn(now?: () => number, onReplay?: () => void): SignIn;
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Signing a browser in to the web view.
3
+ *
4
+ * The command tree is served by cli-tool's HTTP adapter, which owns the
5
+ * bearer token and the Host and Origin checks. What it leaves to the app is
6
+ * how its own page gets that token.
7
+ *
8
+ * Other local users can reach 127.0.0.1 and can read a process's argv while
9
+ * it runs. So the bearer token never appears in a URL, an argv or the page
10
+ * itself. The URL the server prints or opens carries a boot token instead.
11
+ * The page sends it once, in a JSON body to `POST /session`, and gets the
12
+ * bearer token back. The boot token works once and expires a minute after
13
+ * the URL is shown, so it is only usable between opening the browser and the
14
+ * page loading.
15
+ *
16
+ * The boot token is in the browser opener's argv while it runs, so another
17
+ * local user could redeem it first. The right boot token sent a second time
18
+ * is refused, and the server warns in its terminal (see `onReplay`). Sessions
19
+ * already signed in keep working; a new link comes from {@link SignIn.renew}.
20
+ *
21
+ * A JSON body from another origin needs a CORS preflight, which the server
22
+ * never answers, so a website cannot redeem the boot token either.
23
+ */
24
+ /** How long the boot token stays usable once the URL is shown. */
25
+ const BOOT_TTL_MS = 60_000;
26
+ /** 128 bits, hex, from a secure source. */
27
+ function secret() {
28
+ const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));
29
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
30
+ }
31
+ /** Compared without an early exit, so a near miss takes as long as a far one. */
32
+ function tokenEquals(a, b) {
33
+ if (a.length !== b.length)
34
+ return false;
35
+ let diff = 0;
36
+ for (let i = 0; i < a.length; i++)
37
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
38
+ return diff === 0;
39
+ }
40
+ /**
41
+ * Make a boot token. `now` is injectable for tests. `onReplay` is called when
42
+ * the right boot token arrives after it was redeemed: a second tab, or
43
+ * another program that read the link.
44
+ */
45
+ export function createSignIn(now = Date.now, onReplay) {
46
+ let bootToken = secret();
47
+ let live = true;
48
+ let redeemed = false;
49
+ let expiresAt = Number.POSITIVE_INFINITY;
50
+ return {
51
+ get bootToken() {
52
+ return bootToken;
53
+ },
54
+ arm() {
55
+ expiresAt = now() + BOOT_TTL_MS;
56
+ },
57
+ redeem(candidate) {
58
+ if (typeof candidate !== 'string')
59
+ return false;
60
+ if (redeemed && tokenEquals(candidate, bootToken))
61
+ onReplay?.();
62
+ if (!live)
63
+ return false;
64
+ if (now() > expiresAt) {
65
+ live = false;
66
+ return false;
67
+ }
68
+ if (!tokenEquals(candidate, bootToken))
69
+ return false;
70
+ live = false;
71
+ redeemed = true;
72
+ return true;
73
+ },
74
+ renew() {
75
+ bootToken = secret();
76
+ live = true;
77
+ redeemed = false;
78
+ expiresAt = now() + BOOT_TTL_MS;
79
+ return bootToken;
80
+ },
81
+ };
82
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * The catalog the web view's server holds between requests.
3
+ *
4
+ * Each request opens its own session, as a CLI run does. Without this, the
5
+ * page's first `list --cached` would read the store again (seconds on a large
6
+ * repository) right after `serve` read it, and every poll would start its
7
+ * own probe. With it:
8
+ *
9
+ * - `list --cached` answers with the newest catalog the server holds, marked
10
+ * `source: "cached"`.
11
+ * - `list --join` (the page's first read and its polls) joins a probe
12
+ * already running. A plain `list` (Refresh) always starts a probe, so it
13
+ * never answers with one that began before an edit.
14
+ *
15
+ * A shared probe runs on a signal this module owns. A request that stops
16
+ * waiting (a closed tab) leaves on its own; the probe stops only when nobody
17
+ * waits for it, or when the server stops. A failed probe fails every waiter
18
+ * and is forgotten, so the next request starts again.
19
+ *
20
+ * An entry is used only by a request whose session has the same view key
21
+ * (trust and settings), so a trust grant or a saved setting is never answered
22
+ * with rows from before it. Only unfiltered listings are shared.
23
+ */
24
+ import type { CatalogBody } from '../commands/list.ts';
25
+ /** See the module comment. One per command tree; `serve` turns it on. */
26
+ export interface CatalogShare {
27
+ /** True once `serve` has started, until it stops. The command line never shares. */
28
+ readonly active: boolean;
29
+ /** Aborted when the server stops. Sessions that run shared probes use it. */
30
+ readonly signal: AbortSignal;
31
+ activate(): void;
32
+ /** Stop every shared probe and share nothing more. */
33
+ stop(): void;
34
+ /** Keep `body` as the newest catalog for `key`. */
35
+ remember(key: string, body: CatalogBody): void;
36
+ /** The newest catalog for `key`, marked as cached, or null. */
37
+ cached(key: string): CatalogBody | null;
38
+ /**
39
+ * A fresh catalog for `key`. With `join`, the probe already running for it
40
+ * when there is one; otherwise `probe` starts now. `probe` gets the
41
+ * share's signal, not the caller's. `signal` is the caller's own: when it
42
+ * aborts, this call rejects and the probe goes on for the other waiters.
43
+ */
44
+ fresh(key: string, probe: (signal: AbortSignal) => Promise<CatalogBody>, opts: {
45
+ join: boolean;
46
+ signal?: AbortSignal | undefined;
47
+ }): Promise<CatalogBody>;
48
+ /** How many callers wait on the running probe for `key`. For tests. */
49
+ waiting(key: string): number;
50
+ }
51
+ export declare function createCatalogShare(): CatalogShare;
@@ -0,0 +1,116 @@
1
+ /**
2
+ * The catalog the web view's server holds between requests.
3
+ *
4
+ * Each request opens its own session, as a CLI run does. Without this, the
5
+ * page's first `list --cached` would read the store again (seconds on a large
6
+ * repository) right after `serve` read it, and every poll would start its
7
+ * own probe. With it:
8
+ *
9
+ * - `list --cached` answers with the newest catalog the server holds, marked
10
+ * `source: "cached"`.
11
+ * - `list --join` (the page's first read and its polls) joins a probe
12
+ * already running. A plain `list` (Refresh) always starts a probe, so it
13
+ * never answers with one that began before an edit.
14
+ *
15
+ * A shared probe runs on a signal this module owns. A request that stops
16
+ * waiting (a closed tab) leaves on its own; the probe stops only when nobody
17
+ * waits for it, or when the server stops. A failed probe fails every waiter
18
+ * and is forgotten, so the next request starts again.
19
+ *
20
+ * An entry is used only by a request whose session has the same view key
21
+ * (trust and settings), so a trust grant or a saved setting is never answered
22
+ * with rows from before it. Only unfiltered listings are shared.
23
+ */
24
+ export function createCatalogShare() {
25
+ let active = false;
26
+ const stopper = new AbortController();
27
+ let latest = null;
28
+ let running = null;
29
+ let seq = 0;
30
+ const start = (key, probe) => {
31
+ const controller = new AbortController();
32
+ const onStop = () => controller.abort(stopper.signal.reason);
33
+ stopper.signal.addEventListener('abort', onStop, { once: true });
34
+ const run = {
35
+ key,
36
+ seq: ++seq,
37
+ controller,
38
+ promise: Promise.resolve().then(() => probe(controller.signal)),
39
+ waiters: 0,
40
+ settled: false,
41
+ };
42
+ running = run;
43
+ const done = () => {
44
+ run.settled = true;
45
+ stopper.signal.removeEventListener('abort', onStop);
46
+ if (running === run)
47
+ running = null;
48
+ };
49
+ run.promise.then((body) => {
50
+ done();
51
+ if (!controller.signal.aborted && (latest === null || latest.seq < run.seq)) {
52
+ latest = { key, seq: run.seq, body };
53
+ }
54
+ }, done);
55
+ return run;
56
+ };
57
+ const wait = (run, signal) => new Promise((resolve, reject) => {
58
+ let left = false;
59
+ run.waiters++;
60
+ const leave = () => {
61
+ if (left)
62
+ return;
63
+ left = true;
64
+ run.waiters--;
65
+ signal?.removeEventListener('abort', onAbort);
66
+ if (run.waiters === 0 && !run.settled)
67
+ run.controller.abort(new Error('nobody is waiting'));
68
+ };
69
+ const onAbort = () => {
70
+ leave();
71
+ reject(signal?.reason ?? new Error('aborted'));
72
+ };
73
+ if (signal?.aborted === true)
74
+ return onAbort();
75
+ signal?.addEventListener('abort', onAbort, { once: true });
76
+ run.promise.then((body) => {
77
+ leave();
78
+ resolve(body);
79
+ }, (err) => {
80
+ leave();
81
+ reject(err);
82
+ });
83
+ });
84
+ return {
85
+ get active() {
86
+ return active && !stopper.signal.aborted;
87
+ },
88
+ signal: stopper.signal,
89
+ activate() {
90
+ active = true;
91
+ },
92
+ stop() {
93
+ active = false;
94
+ stopper.abort(new Error('the server stopped'));
95
+ },
96
+ remember(key, body) {
97
+ latest = { key, seq: latest?.seq ?? 0, body };
98
+ },
99
+ cached(key) {
100
+ if (latest === null || latest.key !== key)
101
+ return null;
102
+ const body = latest.body;
103
+ return body.source === 'cached'
104
+ ? body
105
+ : { ...body, source: 'cached', storedAt: body.generatedAt };
106
+ },
107
+ fresh(key, probe, opts) {
108
+ const joinable = running !== null && running.key === key && !running.settled;
109
+ const run = opts.join && joinable ? running : start(key, probe);
110
+ return wait(run, opts.signal);
111
+ },
112
+ waiting(key) {
113
+ return running !== null && running.key === key ? running.waiters : 0;
114
+ },
115
+ };
116
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * The web view: the same catalog as a page you can search in a browser.
3
+ *
4
+ * It is a server rather than a generated file, because a file goes out of date
5
+ * as soon as a task is added. The page calls the command tree over cli-tool's
6
+ * HTTP adapter (`routes.ts`), so each request reads the repository as it is
7
+ * now, with the same rules as the command line. The catalog the server holds
8
+ * between those requests is `catalog-share.ts`. The page signs in with a
9
+ * one-shot boot token (`auth.ts`).
10
+ */
11
+ import type { App } from '@osdlc/cli-tool/command';
12
+ import { type HttpServer } from '@osdlc/cli-tool/http';
13
+ import { type HandOffResult } from '../core/run.ts';
14
+ import type { CatalogSnapshot, Session } from '../core/session.ts';
15
+ import type { RunDocumentBody } from '../documents.ts';
16
+ import { type SignIn } from './auth.ts';
17
+ import type { CatalogShare } from './catalog-share.ts';
18
+ import { type JobSignals } from './terminal-input.ts';
19
+ /** What {@link startServer} and {@link serve} need. */
20
+ export interface ServeOptions {
21
+ /** The session `serve` opened: its root, environment and first catalog. */
22
+ session: Session;
23
+ /** The command tree the page calls. */
24
+ app: App;
25
+ /**
26
+ * The catalog `app`'s `list` shares between requests. `serve` fills it
27
+ * with its first catalog and starts a probe, so the page's first two
28
+ * calls wait on neither a second store read nor a second probe.
29
+ */
30
+ share?: CatalogShare | undefined;
31
+ /**
32
+ * The global flag values every call runs with, fixed at start. `dir` is
33
+ * set to the session's root.
34
+ */
35
+ globals: Record<string, unknown>;
36
+ /** The working directory commands run with. */
37
+ cwd: string;
38
+ /** A fixed port. Default: one the system picks. */
39
+ port?: number | undefined;
40
+ /** Open a browser. Default true. */
41
+ open?: boolean | undefined;
42
+ /** Stops the server when aborted, such as on Ctrl-C. */
43
+ signal?: AbortSignal | undefined;
44
+ /** Where the startup lines go. */
45
+ stdout(text: string): void;
46
+ /** Where the handed-off command line goes, as `way run` prints it. */
47
+ stderr(text: string): void;
48
+ /**
49
+ * The terminal's input, when stdin is a terminal. Each line read from it
50
+ * (Enter) prints a new sign-in link, for a new tab or another browser. It
51
+ * is read only while the process is in the foreground.
52
+ */
53
+ input?: NodeJS.ReadableStream | undefined;
54
+ /** Whether the process may read `input` now. Tests inject one. Default: a `ps` check. */
55
+ foreground?: (() => Promise<boolean>) | undefined;
56
+ /** The job-control signals the reader follows. Tests inject a stand-in. */
57
+ jobSignals?: JobSignals | null | undefined;
58
+ /** Gives the terminal to a task. Tests inject one. Default: the core's `handOff`. */
59
+ handOff?: ((plan: Pick<RunDocumentBody, 'argv' | 'env' | 'cwd'>) => HandOffResult) | undefined;
60
+ }
61
+ /** A running web view. */
62
+ export interface WebServer {
63
+ server: HttpServer;
64
+ /** The boot token and its timer. */
65
+ signIn: SignIn;
66
+ /**
67
+ * Settles when the server has stopped: with the task's exit code after a
68
+ * run took the terminal, or null when it was stopped otherwise.
69
+ */
70
+ finished: Promise<number | null>;
71
+ /** Settles as soon as the server stops listening, before a run starts. */
72
+ stopped: Promise<void>;
73
+ /** Stop the server. */
74
+ stop(): Promise<void>;
75
+ }
76
+ /**
77
+ * Bind the port and return the server, without printing or opening anything.
78
+ * Split from {@link serve} so a test can bind a port, send real requests and
79
+ * stop again.
80
+ */
81
+ export declare function startServer(options: ServeOptions): Promise<WebServer>;
82
+ /**
83
+ * The first lines `serve` prints: the address, the root, what was collected
84
+ * and what came from the store. Repository text in them is terminal-safe.
85
+ */
86
+ export declare function startupSummary(address: string, first: Omit<CatalogSnapshot, 'origin'> & {
87
+ origin?: CatalogSnapshot['origin'];
88
+ }): string;
89
+ /** The program that opens a URL in the default browser on `platform`, before the URL. */
90
+ export declare function browserOpener(platform: NodeJS.Platform): {
91
+ binary: string;
92
+ args: string[];
93
+ };
94
+ /**
95
+ * Serve the page until the signal aborts or a run takes the terminal. Returns
96
+ * the task's exit code after a run, or null when the server was stopped.
97
+ */
98
+ export declare function serve(options: ServeOptions): Promise<number | null>;