@thedatagrid/docs-kit 0.1.0 → 0.2.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.
@@ -2,9 +2,34 @@
2
2
  * docs-kit demo cards. Plain CSS on custom properties: sites restyle by
3
3
  * overriding the --dk-* variables (light values on :root, dark ones under
4
4
  * [data-theme='dark']), or any .dk-* rule.
5
+ *
6
+ * The code editor reads --dk-editor-* variables (README → Theming). Only the
7
+ * syntax colors have defaults here; every other --dk-editor-* variable falls
8
+ * back to a card variable:
9
+ * --dk-editor-bg --dk-code-bg
10
+ * --dk-editor-fg --dk-fg
11
+ * --dk-editor-font-family --dk-font-mono
12
+ * --dk-editor-font-size --dk-code-font-size
13
+ * --dk-editor-line-height --dk-code-line-height
14
+ * --dk-editor-cursor --dk-editor-fg
15
+ * --dk-editor-selection-bg (set below)
16
+ * --dk-editor-active-line-bg --dk-accent-soft
17
+ * --dk-editor-gutter-bg --dk-editor-bg
18
+ * --dk-editor-gutter-fg --dk-line-number
19
+ * --dk-editor-gutter-border transparent
20
+ * --dk-editor-active-line-gutter-bg / -fg active line bg / gutter fg
21
+ * --dk-editor-selection-match-bg --dk-accent-soft
22
+ * --dk-editor-bracket-match-bg / -outline --dk-accent-soft / --dk-accent
23
+ * --dk-editor-search-match-bg / -outline --dk-highlight-bg / -border
24
+ * --dk-editor-search-match-selected-bg --dk-accent-soft
25
+ * --dk-editor-tooltip-bg / -fg --dk-editor-panel-bg / -fg
26
+ * --dk-editor-tooltip-selected-bg / -fg --dk-accent-soft / -fg
27
+ * --dk-editor-panel-bg / -fg --dk-surface / -fg (search panel)
28
+ * --dk-editor-border --dk-border
5
29
  */
6
30
  :root {
7
31
  --dk-font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
32
+ --dk-font-sans: system-ui, -apple-system, 'Segoe UI', sans-serif;
8
33
  --dk-radius: 12px;
9
34
  --dk-border: rgb(0 0 0 / 0.12);
10
35
  --dk-surface: #ffffff;
@@ -18,21 +43,29 @@
18
43
  --dk-accent-soft: rgb(9 105 218 / 0.1);
19
44
  --dk-highlight-bg: rgb(9 105 218 / 0.1);
20
45
  --dk-highlight-border: #0969da;
46
+ /* `#highlight label` pills, line numbers */
47
+ --dk-label-bg: rgb(9 105 218 / 0.12);
48
+ --dk-label-fg: #0550ae;
49
+ --dk-line-number: #818b98;
21
50
  --dk-error: #cf222e;
22
51
  --dk-ok: #1a7f37;
23
52
  --dk-shadow: 0 20px 60px rgb(0 0 0 / 0.25);
24
53
  --dk-code-max-height: 560px;
25
- /* editor tokens */
26
- --dk-tok-keyword: #cf222e;
27
- --dk-tok-string: #0a3069;
28
- --dk-tok-number: #0550ae;
29
- --dk-tok-comment: #6e7781;
30
- --dk-tok-type: #953800;
31
- --dk-tok-function: #8250df;
32
- --dk-tok-property: #0550ae;
33
- --dk-tok-tag: #116329;
34
- --dk-tok-attribute: #0550ae;
35
- --dk-selection: rgb(9 105 218 / 0.2);
54
+ --dk-code-font-size: 13.5px;
55
+ --dk-code-line-height: 1.6;
56
+ /* editor syntax colors (github-light, like the static code) */
57
+ --dk-editor-keyword: #cf222e;
58
+ --dk-editor-constant: #0550ae;
59
+ --dk-editor-string: #0a3069;
60
+ --dk-editor-number: #0550ae;
61
+ --dk-editor-comment: #6e7781;
62
+ --dk-editor-type: #953800;
63
+ --dk-editor-function: #8250df;
64
+ --dk-editor-property: #0550ae;
65
+ --dk-editor-tag: #116329;
66
+ --dk-editor-attribute: #0550ae;
67
+ --dk-editor-operator: #cf222e;
68
+ --dk-editor-selection-bg: rgb(9 105 218 / 0.2);
36
69
  }
37
70
 
38
71
  [data-theme='dark'] {
@@ -48,30 +81,37 @@
48
81
  --dk-accent-soft: rgb(88 166 255 / 0.14);
49
82
  --dk-highlight-bg: rgb(122 162 247 / 0.14);
50
83
  --dk-highlight-border: #7aa2f7;
84
+ --dk-label-bg: rgb(122 162 247 / 0.28);
85
+ --dk-label-fg: #e3eaff;
86
+ --dk-line-number: #6e7681;
51
87
  --dk-error: #ff7b72;
52
88
  --dk-ok: #3fb950;
53
- --dk-tok-keyword: #bb9af7;
54
- --dk-tok-string: #9ece6a;
55
- --dk-tok-number: #ff9e64;
56
- --dk-tok-comment: #565f89;
57
- --dk-tok-type: #2ac3de;
58
- --dk-tok-function: #7aa2f7;
59
- --dk-tok-property: #73daca;
60
- --dk-tok-tag: #f7768e;
61
- --dk-tok-attribute: #e0af68;
62
- --dk-selection: rgb(122 162 247 / 0.25);
89
+ /* editor syntax colors (tokyo-night, like the static code) */
90
+ --dk-editor-keyword: #bb9af7;
91
+ --dk-editor-constant: #ff9e64;
92
+ --dk-editor-string: #9ece6a;
93
+ --dk-editor-number: #ff9e64;
94
+ --dk-editor-comment: #565f89;
95
+ --dk-editor-type: #2ac3de;
96
+ --dk-editor-function: #7aa2f7;
97
+ --dk-editor-property: #73daca;
98
+ --dk-editor-tag: #f7768e;
99
+ --dk-editor-attribute: #e0af68;
100
+ --dk-editor-operator: #89ddff;
101
+ --dk-editor-punctuation: #9abdf5;
102
+ --dk-editor-selection-bg: rgb(122 162 247 / 0.25);
63
103
  }
64
104
 
65
- /* shiki dual themes (defaultColor: false) */
105
+ /* shiki dual themes (defaultColor: false). Only the text color: the code
106
+ background is --dk-code-bg, and a background on the token spans would paint
107
+ boxes over highlighted lines. */
66
108
  .dk-demo .shiki,
67
109
  .dk-demo .shiki span {
68
110
  color: var(--shiki-light);
69
- background-color: var(--shiki-light-bg);
70
111
  }
71
112
  [data-theme='dark'] .dk-demo .shiki,
72
113
  [data-theme='dark'] .dk-demo .shiki span {
73
114
  color: var(--shiki-dark);
74
- background-color: var(--shiki-dark-bg);
75
115
  }
76
116
 
77
117
  .dk-demo {
@@ -274,8 +314,8 @@
274
314
  border-radius: 0;
275
315
  overflow: visible;
276
316
  font-family: var(--dk-font-mono);
277
- font-size: 13.5px;
278
- line-height: 1.6;
317
+ font-size: var(--dk-code-font-size);
318
+ line-height: var(--dk-code-line-height);
279
319
  tab-size: 2;
280
320
  background-color: var(--dk-code-bg) !important;
281
321
  }
@@ -296,13 +336,28 @@
296
336
  display: flex;
297
337
  gap: 16px;
298
338
  }
339
+ /* `#highlight label`: a pill at the end of the line, left out of text selections */
299
340
  .dk-demo pre.shiki .line-label {
341
+ align-self: center;
300
342
  margin-left: auto;
301
- padding-left: 16px;
343
+ padding: 0 8px;
344
+ border-radius: 999px;
345
+ background: var(--dk-label-bg);
346
+ color: var(--dk-label-fg);
347
+ font-family: var(--dk-font-sans);
302
348
  font-size: 12px;
303
- font-style: italic;
304
- color: var(--dk-accent);
349
+ font-weight: 500;
350
+ line-height: 1.6;
305
351
  white-space: nowrap;
352
+ user-select: none;
353
+ }
354
+ /* a label on a line of its own (`// #highlight label` above the code) */
355
+ .dk-demo pre.shiki .line.label-only {
356
+ gap: 0;
357
+ user-select: none;
358
+ }
359
+ .dk-demo pre.shiki .line.label-only .line-label {
360
+ margin-left: 0;
306
361
  }
307
362
  .dk-demo pre.shiki.has-line-numbers .line::before {
308
363
  content: attr(data-line);
@@ -310,7 +365,7 @@
310
365
  width: 2.5em;
311
366
  margin-right: 16px;
312
367
  text-align: right;
313
- color: var(--dk-faint);
368
+ color: var(--dk-line-number);
314
369
  user-select: none;
315
370
  }
316
371
  .dk-demo .dk-file-link {
@@ -370,87 +425,10 @@
370
425
  border-bottom: 1px solid var(--dk-border);
371
426
  }
372
427
  }
428
+ /* the editor's colors and font: --dk-editor-* (editor.ts) */
373
429
  .dk-demo-editor {
374
430
  height: 100%;
375
- background: var(--dk-code-bg);
376
- }
377
- .dk-demo-editor .cm-editor {
378
- height: 100%;
379
- font-size: 13.5px;
380
- background: var(--dk-code-bg);
381
- color: var(--dk-fg);
382
- }
383
- .dk-demo-editor .cm-editor.cm-focused {
384
- outline: none;
385
- }
386
- .dk-demo-editor .cm-scroller {
387
- font-family: var(--dk-font-mono);
388
- line-height: 1.6;
389
- }
390
- .dk-demo-editor .cm-gutters {
391
- border: 0;
392
- background: var(--dk-code-bg);
393
- color: var(--dk-faint);
394
- }
395
- .dk-demo-editor .cm-activeLine,
396
- .dk-demo-editor .cm-activeLineGutter {
397
- background: var(--dk-accent-soft);
398
- }
399
- .dk-demo-editor .cm-content {
400
- caret-color: var(--dk-fg);
401
- }
402
- .dk-demo-editor .cm-cursor {
403
- border-left-color: var(--dk-fg);
404
- }
405
- .dk-demo-editor .cm-selectionBackground,
406
- .dk-demo-editor .cm-focused .cm-selectionBackground,
407
- .dk-demo-editor ::selection {
408
- background: var(--dk-selection) !important;
409
- }
410
- .dk-demo-editor .cm-matchingBracket {
411
- background: var(--dk-accent-soft);
412
- outline: 1px solid var(--dk-accent);
413
- }
414
- .dk-demo-editor .cm-tooltip {
415
- border: 1px solid var(--dk-border);
416
- background: var(--dk-surface);
417
- color: var(--dk-fg);
418
- }
419
- .dk-demo-editor .tok-keyword,
420
- .dk-demo-editor .tok-operatorKeyword,
421
- .dk-demo-editor .tok-modifier {
422
- color: var(--dk-tok-keyword);
423
- }
424
- .dk-demo-editor .tok-string,
425
- .dk-demo-editor .tok-string2 {
426
- color: var(--dk-tok-string);
427
- }
428
- .dk-demo-editor .tok-number,
429
- .dk-demo-editor .tok-bool,
430
- .dk-demo-editor .tok-atom {
431
- color: var(--dk-tok-number);
432
- }
433
- .dk-demo-editor .tok-comment {
434
- color: var(--dk-tok-comment);
435
- font-style: italic;
436
- }
437
- .dk-demo-editor .tok-typeName,
438
- .dk-demo-editor .tok-className,
439
- .dk-demo-editor .tok-namespace {
440
- color: var(--dk-tok-type);
441
- }
442
- .dk-demo-editor .tok-variableName.tok-definition,
443
- .dk-demo-editor .tok-function {
444
- color: var(--dk-tok-function);
445
- }
446
- .dk-demo-editor .tok-propertyName {
447
- color: var(--dk-tok-property);
448
- }
449
- .dk-demo-editor .tok-tagName {
450
- color: var(--dk-tok-tag);
451
- }
452
- .dk-demo-editor .tok-attributeName {
453
- color: var(--dk-tok-attribute);
431
+ background: var(--dk-editor-bg, var(--dk-code-bg));
454
432
  }
455
433
  .dk-demo-editor-error {
456
434
  margin: 0;
@@ -0,0 +1,23 @@
1
+ # docs-kit links
2
+
3
+ Cmd/Ctrl+click the `file="…"` of a code fence in a docs page to open that file.
4
+ When the fence has `region="name"`, the file opens at its `#region name` line.
5
+
6
+ ````md
7
+ ```tsx file="basic.demo.tsx" live
8
+ ```
9
+
10
+ ```ts file="/docs/learn/sorting/sorting.snippet.tsx" region="sort-info"
11
+ ```
12
+ ````
13
+
14
+ The paths resolve like they do in `@thedatagrid/docs-kit`'s `remarkDemoFences`:
15
+ `x.demo.tsx` resolves from the page's folder, and `/docs/…` from the site's
16
+ content root. The content root is `docsKit.contentDir`, or else
17
+ `docsRoot.source`, in the nearest `package.json` that has one.
18
+
19
+ Install it from a project that depends on `@thedatagrid/docs-kit`:
20
+
21
+ ```sh
22
+ npx docs-kit editor install # VS Code and/or Cursor, whichever are installed
23
+ ```
@@ -0,0 +1,40 @@
1
+ // @ts-check
2
+ /**
3
+ * docs-kit links for VS Code and Cursor: Cmd/Ctrl+click the `file="…"` of a
4
+ * docs code fence to open that file, at its `region="…"` when one is set.
5
+ * Installed with `docs-kit editor install` (README → Editor extension).
6
+ */
7
+ const vscode = require('vscode');
8
+ const { fenceLinks } = require('./links.js');
9
+
10
+ /** @type {import('vscode').DocumentLinkProvider} */
11
+ const provider = {
12
+ provideDocumentLinks(document) {
13
+ return fenceLinks(document.getText(), document.fileName).map((link) => {
14
+ const target = vscode.Uri.file(link.target).with({
15
+ fragment: link.targetLine == null ? '' : `L${link.targetLine + 1}`,
16
+ });
17
+ const documentLink = new vscode.DocumentLink(
18
+ new vscode.Range(link.line, link.start, link.line, link.end),
19
+ target,
20
+ );
21
+ documentLink.tooltip = link.tooltip;
22
+ return documentLink;
23
+ });
24
+ },
25
+ };
26
+
27
+ /** @param {import('vscode').ExtensionContext} context */
28
+ function activate(context) {
29
+ context.subscriptions.push(
30
+ vscode.languages.registerDocumentLinkProvider(
31
+ [
32
+ { scheme: 'file', language: 'markdown' },
33
+ { scheme: 'file', language: 'mdx' },
34
+ ],
35
+ provider,
36
+ ),
37
+ );
38
+ }
39
+
40
+ module.exports = { activate, deactivate() {} };
@@ -0,0 +1,137 @@
1
+ // @ts-check
2
+ /**
3
+ * Fence links for the docs-kit editor extension, without the `vscode` API (so
4
+ * it can be unit tested). Same rules as `remarkDemoFences`:
5
+ *
6
+ * - `file="x.demo.tsx"` resolves from the page's folder;
7
+ * - `file="/docs/a/x.demo.tsx"` resolves from the site's content root;
8
+ * - `region="name"` targets the line of that region's `#region name` marker.
9
+ *
10
+ * The content root is `docsKit.contentDir` or `docsRoot.source` (the
11
+ * generate-docs-meta config) of the nearest package.json that has one.
12
+ */
13
+ const fs = require('node:fs');
14
+ const path = require('node:path');
15
+
16
+ /** A fence opener with an info string: ```lang meta (or ~~~). */
17
+ const FENCE_RE = /^(\s*(?:`{3,}|~{3,})[^\s`]*[ \t]+)(.*)$/;
18
+
19
+ /** @param {string} name */
20
+ function attributeRe(name) {
21
+ return new RegExp(`(^|\\s)${name}=(?:"([^"]*)"|'([^']*)'|([^\\s"']+))`);
22
+ }
23
+ const FILE_RE = attributeRe('file');
24
+ const REGION_RE = attributeRe('region');
25
+
26
+ /** @param {string} file */
27
+ function isFile(file) {
28
+ try {
29
+ return fs.statSync(file).isFile();
30
+ } catch {
31
+ return false;
32
+ }
33
+ }
34
+
35
+ /**
36
+ * The content root of the docs site `fromDir` is in, or null.
37
+ * @param {string} fromDir
38
+ */
39
+ function contentRootOf(fromDir) {
40
+ for (let dir = fromDir; ; dir = path.dirname(dir)) {
41
+ const manifest = path.join(dir, 'package.json');
42
+ if (isFile(manifest)) {
43
+ try {
44
+ const json = JSON.parse(fs.readFileSync(manifest, 'utf8'));
45
+ const source = json.docsKit?.contentDir ?? json.docsRoot?.source;
46
+ if (typeof source === 'string') return path.resolve(dir, source);
47
+ } catch {
48
+ // not JSON: keep looking further up
49
+ }
50
+ }
51
+ if (path.dirname(dir) === dir) return null;
52
+ }
53
+ }
54
+
55
+ /** @param {string} text */
56
+ const escapeRe = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
57
+
58
+ /**
59
+ * 0-based line of the `#region <name>` marker in `file`, or null. Matches the
60
+ * markers `sliceRegion` accepts: `// #region`, `/* #region *\/`,
61
+ * `{/* #region *\/}` and `<!-- #region -->`.
62
+ * @param {string} file
63
+ * @param {string} name
64
+ */
65
+ function regionLine(file, name) {
66
+ const n = escapeRe(name);
67
+ const markers = [
68
+ new RegExp(`^\\s*//\\s*#?region\\s+${n}\\s*$`),
69
+ new RegExp(`^\\s*\\{?/\\*\\s*#region\\s+${n}\\s*\\*/\\}?\\s*$`),
70
+ new RegExp(`^\\s*<!--\\s*#?region\\s+${n}\\s*-->`),
71
+ ];
72
+ const lines = fs.readFileSync(file, 'utf8').split('\n');
73
+ const index = lines.findIndex((line) => markers.some((marker) => marker.test(line)));
74
+ return index === -1 ? null : index;
75
+ }
76
+
77
+ /**
78
+ * @typedef {{
79
+ * line: number, start: number, end: number,
80
+ * target: string, targetLine: number | null, tooltip: string,
81
+ * }} FenceLink
82
+ * `line`/`start`/`end`: 0-based position of the `file` value on the page;
83
+ * `targetLine`: 0-based line to open the target at.
84
+ */
85
+
86
+ /**
87
+ * Links for the `file="…"` values of the fences in a page. Files that don't
88
+ * exist get no link.
89
+ * @param {string} text the page source
90
+ * @param {string} fileName the page's absolute path
91
+ * @returns {FenceLink[]}
92
+ */
93
+ function fenceLinks(text, fileName) {
94
+ const pageDir = path.dirname(fileName);
95
+ /** @type {string | null | undefined} */
96
+ let contentRoot;
97
+ /** @type {FenceLink[]} */
98
+ const links = [];
99
+ text.split('\n').forEach((lineText, line) => {
100
+ const fence = FENCE_RE.exec(lineText.replace(/\r$/, ''));
101
+ if (!fence) return;
102
+ const [, opener, meta] = fence;
103
+ const file = FILE_RE.exec(meta);
104
+ if (!file) return;
105
+ const value = file[2] ?? file[3] ?? file[4];
106
+ if (!value) return;
107
+ let target;
108
+ if (value.startsWith('/')) {
109
+ if (contentRoot === undefined) contentRoot = contentRootOf(pageDir);
110
+ if (!contentRoot) return;
111
+ target = path.join(contentRoot, value);
112
+ } else {
113
+ target = path.resolve(pageDir, value);
114
+ }
115
+ if (!isFile(target)) return;
116
+
117
+ const start = opener.length + file.index + file[0].indexOf(value, file[1].length + 'file='.length);
118
+ const region = REGION_RE.exec(meta);
119
+ const regionName = region ? (region[2] ?? region[3] ?? region[4]) : undefined;
120
+ const targetLine = regionName ? regionLine(target, regionName) : null;
121
+ links.push({
122
+ line,
123
+ start,
124
+ end: start + value.length,
125
+ target,
126
+ targetLine,
127
+ tooltip: regionName
128
+ ? targetLine == null
129
+ ? `Open ${value} (no #region ${regionName} in it)`
130
+ : `Open ${value} at #region ${regionName}`
131
+ : `Open ${value}`,
132
+ });
133
+ });
134
+ return links;
135
+ }
136
+
137
+ module.exports = { fenceLinks, contentRootOf, regionLine };
@@ -0,0 +1,19 @@
1
+ {
2
+ "name": "docs-kit-links",
3
+ "displayName": "docs-kit links",
4
+ "description": "Cmd/Ctrl+click file=\"…\" in a docs code fence to open the file, at its region=\"…\" when set. Part of @thedatagrid/docs-kit.",
5
+ "version": "0.0.0",
6
+ "publisher": "thedatagrid",
7
+ "license": "MIT",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/thedatagrid/docs-kit.git"
11
+ },
12
+ "engines": {
13
+ "vscode": "^1.80.0"
14
+ },
15
+ "categories": ["Other"],
16
+ "main": "./extension.js",
17
+ "activationEvents": ["onLanguage:markdown", "onLanguage:mdx"],
18
+ "contributes": {}
19
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thedatagrid/docs-kit",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Docs tooling: type-checked file snippets with regions and highlights, prebuilt and editable live demos, CodeSandbox forks",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -58,6 +58,7 @@
58
58
  "files": [
59
59
  "dist",
60
60
  "src",
61
+ "editor-extension",
61
62
  "README.md",
62
63
  "CHANGELOG.md"
63
64
  ],
package/src/demos/cli.ts CHANGED
@@ -5,24 +5,57 @@
5
5
  * Loads `docs-kit.config.{mjs,js,ts}` from the current folder (or `--config`)
6
6
  * and prebuilds the demos. The config's default export is a `DocsKitConfig`
7
7
  * or a (sync/async) function returning one.
8
+ *
9
+ * `docs-kit editor install [code] [cursor]` installs the docs-kit links
10
+ * extension (cmd+click `file="…"` in fences) into VS Code and/or Cursor;
11
+ * `docs-kit editor package [--out <file>]` only builds its .vsix.
8
12
  */
9
13
  import fs from 'node:fs';
10
14
  import path from 'node:path';
11
15
  import { pathToFileURL } from 'node:url';
12
16
 
17
+ import { installExtension, packageExtension, type Editor } from '../editor/install.ts';
13
18
  import { buildDemos } from './build.ts';
14
19
  import type { DocsKitConfig } from './config.ts';
15
20
 
16
21
  const CONFIG_NAMES = ['docs-kit.config.mjs', 'docs-kit.config.js', 'docs-kit.config.ts'];
17
22
 
18
23
  function usage(): never {
19
- console.error('usage: docs-kit demos [build] [--watch] [--config <file>]');
24
+ console.error(
25
+ [
26
+ 'usage: docs-kit demos [build] [--watch] [--config <file>]',
27
+ ' docs-kit editor install [code] [cursor]',
28
+ ' docs-kit editor package [--out <file>]',
29
+ ].join('\n'),
30
+ );
20
31
  process.exit(1);
21
32
  }
22
33
 
34
+ function editorCommand(args: string[]) {
35
+ const sub = args.shift();
36
+ if (sub === 'install') {
37
+ const only = args.map((arg) => (arg === 'code' || arg === 'cursor' ? (arg as Editor) : usage()));
38
+ const { installed } = installExtension(only);
39
+ if (only.length && installed.length < only.length) process.exit(1);
40
+ return;
41
+ }
42
+ if (sub === 'package') {
43
+ let out: string | undefined;
44
+ while (args.length) {
45
+ const arg = args.shift()!;
46
+ if (arg === '--out' || arg === '-o') out = args.shift() ?? usage();
47
+ else usage();
48
+ }
49
+ console.log(packageExtension(out));
50
+ return;
51
+ }
52
+ usage();
53
+ }
54
+
23
55
  async function main(argv: string[]) {
24
56
  const args = [...argv];
25
57
  const command = args.shift();
58
+ if (command === 'editor') return editorCommand(args);
26
59
  if (command !== 'demos') usage();
27
60
  if (args[0] === 'build') args.shift();
28
61
 
@@ -0,0 +1,85 @@
1
+ /**
2
+ * `docs-kit editor install|package`: packages the docs-kit links extension
3
+ * (`editor-extension/` in this package) into a .vsix with @vscode/vsce and
4
+ * installs it into VS Code and/or Cursor.
5
+ */
6
+ import { spawnSync } from 'node:child_process';
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+
12
+ /** Same folder from `src/editor/` (local mode) and `dist/editor/` (the package). */
13
+ const packageRoot = fileURLToPath(new URL('../../', import.meta.url));
14
+ export const EXTENSION_DIR = path.join(packageRoot, 'editor-extension');
15
+ const VSCE = '@vscode/vsce@4.1.0';
16
+ const FILES = ['package.json', 'extension.js', 'links.js', 'README.md'];
17
+
18
+ export type Editor = 'code' | 'cursor';
19
+
20
+ const APP_BINARIES: Record<Editor, string[]> = {
21
+ code: ['/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code'],
22
+ cursor: ['/Applications/Cursor.app/Contents/Resources/app/bin/cursor'],
23
+ };
24
+
25
+ function onPath(command: string): string | null {
26
+ const result = spawnSync(process.platform === 'win32' ? 'where' : 'which', [command], { encoding: 'utf8' });
27
+ return result.status === 0 ? result.stdout.split(/\r?\n/)[0].trim() || null : null;
28
+ }
29
+
30
+ /** The CLI of each editor that is installed (`code`, `cursor`). */
31
+ export function findEditors(only?: Editor[]): { editor: Editor; bin: string }[] {
32
+ return (Object.keys(APP_BINARIES) as Editor[])
33
+ .filter((editor) => !only?.length || only.includes(editor))
34
+ .flatMap((editor) => {
35
+ const bin = onPath(editor) ?? APP_BINARIES[editor].find((file) => fs.existsSync(file));
36
+ return bin ? [{ editor, bin }] : [];
37
+ });
38
+ }
39
+
40
+ /** Packages the extension, versioned like this docs-kit, into `outFile` (default: a temp file). */
41
+ export function packageExtension(outFile?: string): string {
42
+ const { version } = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf8')) as {
43
+ version: string;
44
+ };
45
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), 'docs-kit-editor-'));
46
+ for (const file of FILES) fs.copyFileSync(path.join(EXTENSION_DIR, file), path.join(work, file));
47
+ const manifest = JSON.parse(fs.readFileSync(path.join(work, 'package.json'), 'utf8')) as { version: string };
48
+ manifest.version = version;
49
+ fs.writeFileSync(path.join(work, 'package.json'), `${JSON.stringify(manifest, null, 2)}\n`);
50
+
51
+ const out = path.resolve(outFile ?? path.join(work, `docs-kit-links-${version}.vsix`));
52
+ const result = spawnSync(
53
+ 'npx',
54
+ ['--yes', VSCE, 'package', '--no-dependencies', '--skip-license', '--allow-missing-repository', '-o', out],
55
+ { cwd: work, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8', shell: process.platform === 'win32' },
56
+ );
57
+ if (result.status !== 0 || !fs.existsSync(out)) {
58
+ throw new Error(`[docs-kit] packaging the editor extension failed:\n${result.stdout}${result.stderr}`);
59
+ }
60
+ return out;
61
+ }
62
+
63
+ /** Packages the extension and installs it into each editor found (or the ones in `only`). */
64
+ export function installExtension(only?: Editor[], log: (message: string) => void = console.log) {
65
+ const editors = findEditors(only);
66
+ const vsix = packageExtension();
67
+ if (!editors.length) {
68
+ log(
69
+ `[docs-kit] no VS Code or Cursor CLI found. Install ${vsix} from the editor ` +
70
+ '(Extensions → … → Install from VSIX).',
71
+ );
72
+ return { vsix, installed: [] as Editor[] };
73
+ }
74
+ const installed: Editor[] = [];
75
+ for (const { editor, bin } of editors) {
76
+ const result = spawnSync(bin, ['--install-extension', vsix, '--force'], { encoding: 'utf8' });
77
+ if (result.status === 0) {
78
+ installed.push(editor);
79
+ log(`[docs-kit] installed the docs-kit links extension in ${editor}. Reload its windows to use it.`);
80
+ } else {
81
+ log(`[docs-kit] installing in ${editor} failed:\n${result.stdout}${result.stderr}`);
82
+ }
83
+ }
84
+ return { vsix, installed };
85
+ }