@dooc-dev/dooc 0.0.0-stage → 0.0.2

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 (221) hide show
  1. package/README.md +26 -2
  2. package/dist/cli.d.ts +2 -0
  3. package/dist/cli.js +311 -0
  4. package/dist/code.global.js +285 -0
  5. package/dist/compiler/bundle-urls.d.ts +3 -0
  6. package/dist/compiler/bundle-urls.js +294 -0
  7. package/dist/compiler/bundle.d.ts +2 -0
  8. package/dist/compiler/bundle.js +100 -0
  9. package/dist/compiler/check-prose.d.ts +11 -0
  10. package/dist/compiler/check-prose.js +138 -0
  11. package/dist/compiler/check-types.d.ts +44 -0
  12. package/dist/compiler/check-types.js +1 -0
  13. package/dist/compiler/check.d.ts +5 -0
  14. package/dist/compiler/check.js +450 -0
  15. package/dist/compiler/code-blocks.d.ts +17 -0
  16. package/dist/compiler/code-blocks.js +198 -0
  17. package/dist/compiler/code-languages.d.ts +10 -0
  18. package/dist/compiler/code-languages.js +109 -0
  19. package/dist/compiler/compile.d.ts +95 -0
  20. package/dist/compiler/compile.js +410 -0
  21. package/dist/compiler/config.d.ts +7 -0
  22. package/dist/compiler/config.js +52 -0
  23. package/dist/compiler/dialect.d.ts +24 -0
  24. package/dist/compiler/dialect.js +198 -0
  25. package/dist/compiler/drawio.d.ts +26 -0
  26. package/dist/compiler/drawio.js +176 -0
  27. package/dist/compiler/figures.d.ts +14 -0
  28. package/dist/compiler/figures.js +221 -0
  29. package/dist/compiler/file-cache.d.ts +14 -0
  30. package/dist/compiler/file-cache.js +61 -0
  31. package/dist/compiler/files.d.ts +29 -0
  32. package/dist/compiler/files.js +431 -0
  33. package/dist/compiler/fonts.d.ts +10 -0
  34. package/dist/compiler/fonts.js +54 -0
  35. package/dist/compiler/format.d.ts +1 -0
  36. package/dist/compiler/format.js +42 -0
  37. package/dist/compiler/from-mdast.d.ts +16 -0
  38. package/dist/compiler/from-mdast.js +142 -0
  39. package/dist/compiler/icons.d.ts +14 -0
  40. package/dist/compiler/icons.js +85 -0
  41. package/dist/compiler/language-codes.d.ts +7 -0
  42. package/dist/compiler/language-codes.js +17 -0
  43. package/dist/compiler/locales.d.ts +7 -0
  44. package/dist/compiler/locales.js +67 -0
  45. package/dist/compiler/manifest.d.ts +6 -0
  46. package/dist/compiler/manifest.js +30 -0
  47. package/dist/compiler/ops.d.ts +44 -0
  48. package/dist/compiler/ops.js +362 -0
  49. package/dist/compiler/public-file.d.ts +2 -0
  50. package/dist/compiler/public-file.js +93 -0
  51. package/dist/compiler/serialize.d.ts +3 -0
  52. package/dist/compiler/serialize.js +16 -0
  53. package/dist/compiler/terms.d.ts +9 -0
  54. package/dist/compiler/terms.js +44 -0
  55. package/dist/compiler/textfile-remote.d.ts +12 -0
  56. package/dist/compiler/textfile-remote.js +124 -0
  57. package/dist/compiler/textfile.d.ts +9 -0
  58. package/dist/compiler/textfile.js +113 -0
  59. package/dist/compiler/theme-variants.d.ts +4 -0
  60. package/dist/compiler/theme-variants.js +22 -0
  61. package/dist/compiler/zip.d.ts +6 -0
  62. package/dist/compiler/zip.js +48 -0
  63. package/dist/core/blocks.d.ts +99 -0
  64. package/dist/core/blocks.js +29 -0
  65. package/dist/core/code-file.d.ts +12 -0
  66. package/dist/core/code-file.js +68 -0
  67. package/dist/core/content-metadata.d.ts +48 -0
  68. package/dist/core/content-metadata.js +264 -0
  69. package/dist/core/content-types.d.ts +45 -0
  70. package/dist/core/content-types.js +1 -0
  71. package/dist/core/extension-package.d.ts +34 -0
  72. package/dist/core/extension-package.js +147 -0
  73. package/dist/core/figure-frame.d.ts +12 -0
  74. package/dist/core/figure-frame.js +108 -0
  75. package/dist/core/file-embed.d.ts +13 -0
  76. package/dist/core/file-embed.js +43 -0
  77. package/dist/core/files.d.ts +15 -0
  78. package/dist/core/files.js +59 -0
  79. package/dist/core/flow-base-css.generated.d.ts +1 -0
  80. package/dist/core/flow-base-css.generated.js +4 -0
  81. package/dist/core/flow-css.d.ts +9 -0
  82. package/dist/core/flow-css.js +54 -0
  83. package/dist/core/graph-common.d.ts +32 -0
  84. package/dist/core/graph-common.js +113 -0
  85. package/dist/core/graph.d.ts +117 -0
  86. package/dist/core/graph.js +480 -0
  87. package/dist/core/html.d.ts +29 -0
  88. package/dist/core/html.js +444 -0
  89. package/dist/core/icons.d.ts +2 -0
  90. package/dist/core/icons.js +2 -0
  91. package/dist/core/inline.d.ts +27 -0
  92. package/dist/core/inline.js +42 -0
  93. package/dist/core/language.d.ts +41 -0
  94. package/dist/core/language.js +44 -0
  95. package/dist/core/languages/ja.d.ts +2 -0
  96. package/dist/core/languages/ja.js +5 -0
  97. package/dist/core/markdown.d.ts +27 -0
  98. package/dist/core/markdown.js +154 -0
  99. package/dist/core/previewers.d.ts +37 -0
  100. package/dist/core/previewers.js +103 -0
  101. package/dist/core/routing.d.ts +20 -0
  102. package/dist/core/routing.js +64 -0
  103. package/dist/core/schema-comments.d.ts +14 -0
  104. package/dist/core/schema-comments.js +52 -0
  105. package/dist/core/schema-graph-flow.d.ts +9 -0
  106. package/dist/core/schema-graph-flow.js +379 -0
  107. package/dist/core/schema-graph-mount.d.ts +9 -0
  108. package/dist/core/schema-graph-mount.js +105 -0
  109. package/dist/core/schema-graph.d.ts +254 -0
  110. package/dist/core/schema-graph.js +981 -0
  111. package/dist/core/table-ui.d.ts +2 -0
  112. package/dist/core/table-ui.js +180 -0
  113. package/dist/core/taxonomy.d.ts +12 -0
  114. package/dist/core/taxonomy.js +49 -0
  115. package/dist/core/term-reference.d.ts +5 -0
  116. package/dist/core/term-reference.js +19 -0
  117. package/dist/core/terms-ui.d.ts +6 -0
  118. package/dist/core/terms-ui.js +22 -0
  119. package/dist/core/textfile.d.ts +10 -0
  120. package/dist/core/textfile.js +39 -0
  121. package/dist/core/theme-variants.d.ts +3 -0
  122. package/dist/core/theme-variants.js +37 -0
  123. package/dist/core/toc-ui.d.ts +2 -0
  124. package/dist/core/toc-ui.js +161 -0
  125. package/dist/core/video-ui.d.ts +2 -0
  126. package/dist/core/video-ui.js +253 -0
  127. package/dist/core/workspace.d.ts +15 -0
  128. package/dist/core/workspace.js +28 -0
  129. package/dist/edit.global.js +306 -0
  130. package/dist/flow.global.js +4959 -0
  131. package/dist/index.d.ts +17 -0
  132. package/dist/index.js +31 -0
  133. package/dist/mcp.d.ts +24 -0
  134. package/dist/mcp.js +467 -0
  135. package/dist/plugins/actions.d.ts +45 -0
  136. package/dist/plugins/actions.js +125 -0
  137. package/dist/plugins/blocks.d.ts +93 -0
  138. package/dist/plugins/blocks.js +100 -0
  139. package/dist/plugins/index.d.ts +4 -0
  140. package/dist/plugins/index.js +1 -0
  141. package/dist/plugins/local-storage.d.ts +18 -0
  142. package/dist/plugins/local-storage.js +115 -0
  143. package/dist/plugins/oauth.d.ts +14 -0
  144. package/dist/plugins/oauth.js +170 -0
  145. package/dist/plugins/runtime.d.ts +26 -0
  146. package/dist/plugins/runtime.js +395 -0
  147. package/dist/plugins/types.d.ts +59 -0
  148. package/dist/plugins/types.js +1 -0
  149. package/dist/plugins/view.d.ts +7 -0
  150. package/dist/plugins/view.js +21 -0
  151. package/dist/ui.global.js +78 -0
  152. package/dist/viewer/assets.d.ts +2 -0
  153. package/dist/viewer/assets.js +3 -0
  154. package/dist/viewer/build.d.ts +12 -0
  155. package/dist/viewer/build.js +55 -0
  156. package/dist/viewer/bundle-network.d.ts +2 -0
  157. package/dist/viewer/bundle-network.js +88 -0
  158. package/dist/viewer/code-file.d.ts +20 -0
  159. package/dist/viewer/code-file.js +42 -0
  160. package/dist/viewer/editor-tools.d.ts +38 -0
  161. package/dist/viewer/editor-tools.js +211 -0
  162. package/dist/viewer/extension-pack.d.ts +2 -0
  163. package/dist/viewer/extension-pack.js +36 -0
  164. package/dist/viewer/extensions.d.ts +10 -0
  165. package/dist/viewer/extensions.js +302 -0
  166. package/dist/viewer/file-references.d.ts +14 -0
  167. package/dist/viewer/file-references.js +38 -0
  168. package/dist/viewer/font-picker.d.ts +4 -0
  169. package/dist/viewer/font-picker.js +145 -0
  170. package/dist/viewer/font-settings.d.ts +11 -0
  171. package/dist/viewer/font-settings.js +50 -0
  172. package/dist/viewer/fonts/LICENSE.txt +119 -0
  173. package/dist/viewer/fonts/udev-gothic-regular.woff2 +0 -0
  174. package/dist/viewer/fonts.d.ts +2 -0
  175. package/dist/viewer/fonts.js +13 -0
  176. package/dist/viewer/git-diff.d.ts +3 -0
  177. package/dist/viewer/git-diff.js +33 -0
  178. package/dist/viewer/git-types.d.ts +73 -0
  179. package/dist/viewer/git-types.js +1 -0
  180. package/dist/viewer/git.d.ts +5 -0
  181. package/dist/viewer/git.js +337 -0
  182. package/dist/viewer/hmr.d.ts +53 -0
  183. package/dist/viewer/hmr.js +337 -0
  184. package/dist/viewer/i18n.d.ts +6 -0
  185. package/dist/viewer/i18n.js +65 -0
  186. package/dist/viewer/ja-lint.d.ts +3 -0
  187. package/dist/viewer/ja-lint.js +44 -0
  188. package/dist/viewer/language-picker.d.ts +2 -0
  189. package/dist/viewer/language-picker.js +233 -0
  190. package/dist/viewer/languages.d.ts +11 -0
  191. package/dist/viewer/languages.js +20 -0
  192. package/dist/viewer/locales/eng.json +317 -0
  193. package/dist/viewer/locales/jpn.json +317 -0
  194. package/dist/viewer/locales/zho.json +317 -0
  195. package/dist/viewer/nav-focus.d.ts +2 -0
  196. package/dist/viewer/nav-focus.js +64 -0
  197. package/dist/viewer/plugin-blocks.d.ts +3 -0
  198. package/dist/viewer/plugin-blocks.js +115 -0
  199. package/dist/viewer/plugin-config.d.ts +35 -0
  200. package/dist/viewer/plugin-config.js +57 -0
  201. package/dist/viewer/plugin-view.d.ts +2 -0
  202. package/dist/viewer/plugin-view.js +6 -0
  203. package/dist/viewer/plugins.d.ts +12 -0
  204. package/dist/viewer/plugins.js +267 -0
  205. package/dist/viewer/resize.d.ts +4 -0
  206. package/dist/viewer/resize.js +238 -0
  207. package/dist/viewer/resource-library.d.ts +29 -0
  208. package/dist/viewer/resource-library.js +104 -0
  209. package/dist/viewer/search.d.ts +16 -0
  210. package/dist/viewer/search.js +358 -0
  211. package/dist/viewer/serve.d.ts +210 -0
  212. package/dist/viewer/serve.js +3312 -0
  213. package/dist/viewer/site-icon.d.ts +8 -0
  214. package/dist/viewer/site-icon.js +56 -0
  215. package/dist/viewer/textfile.d.ts +9 -0
  216. package/dist/viewer/textfile.js +50 -0
  217. package/dist/viewer/theme-picker.d.ts +2 -0
  218. package/dist/viewer/theme-picker.js +135 -0
  219. package/dist/viewer/workspace.d.ts +4 -0
  220. package/dist/viewer/workspace.js +47 -0
  221. package/package.json +128 -5
@@ -0,0 +1,119 @@
1
+ # Licensing
2
+
3
+ - Source fonts are licensed under SIL OPEN FONT LICENSE Version 1.1.
4
+ For more information, see "LICENSE_<FontName>" file contained in the "source" directory.
5
+ - "UDEV Gothic" are licensed under SIL OPEN FONT LICENSE Version 1.1.
6
+
7
+ ## "UDEV Gothic" licensing
8
+
9
+ Copyright (c) 2022 Yuko OTAWARA. with Reserved Font Name "UDEV Gothic"
10
+
11
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
12
+ This license is copied below, and is also available with a FAQ at:
13
+ https://scripts.sil.org/OFL
14
+
15
+
16
+ -----------------------------------------------------------
17
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
18
+ -----------------------------------------------------------
19
+
20
+ PREAMBLE
21
+ The goals of the Open Font License (OFL) are to stimulate worldwide
22
+ development of collaborative font projects, to support the font creation
23
+ efforts of academic and linguistic communities, and to provide a free and
24
+ open framework in which fonts may be shared and improved in partnership
25
+ with others.
26
+
27
+ The OFL allows the licensed fonts to be used, studied, modified and
28
+ redistributed freely as long as they are not sold by themselves. The
29
+ fonts, including any derivative works, can be bundled, embedded,
30
+ redistributed and/or sold with any software provided that any reserved
31
+ names are not used by derivative works. The fonts and derivatives,
32
+ however, cannot be released under any other type of license. The
33
+ requirement for fonts to remain under this license does not apply
34
+ to any document created using the fonts or their derivatives.
35
+
36
+ DEFINITIONS
37
+ "Font Software" refers to the set of files released by the Copyright
38
+ Holder(s) under this license and clearly marked as such. This may
39
+ include source files, build scripts and documentation.
40
+
41
+ "Reserved Font Name" refers to any names specified as such after the
42
+ copyright statement(s).
43
+
44
+ "Original Version" refers to the collection of Font Software components as
45
+ distributed by the Copyright Holder(s).
46
+
47
+ "Modified Version" refers to any derivative made by adding to, deleting,
48
+ or substituting -- in part or in whole -- any of the components of the
49
+ Original Version, by changing formats or by porting the Font Software to a
50
+ new environment.
51
+
52
+ "Author" refers to any designer, engineer, programmer, technical
53
+ writer or other person who contributed to the Font Software.
54
+
55
+ PERMISSION & CONDITIONS
56
+ Permission is hereby granted, free of charge, to any person obtaining
57
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
58
+ redistribute, and sell modified and unmodified copies of the Font
59
+ Software, subject to the following conditions:
60
+
61
+ 1) Neither the Font Software nor any of its individual components,
62
+ in Original or Modified Versions, may be sold by itself.
63
+
64
+ 2) Original or Modified Versions of the Font Software may be bundled,
65
+ redistributed and/or sold with any software, provided that each copy
66
+ contains the above copyright notice and this license. These can be
67
+ included either as stand-alone text files, human-readable headers or
68
+ in the appropriate machine-readable metadata fields within text or
69
+ binary files as long as those fields can be easily viewed by the user.
70
+
71
+ 3) No Modified Version of the Font Software may use the Reserved Font
72
+ Name(s) unless explicit written permission is granted by the corresponding
73
+ Copyright Holder. This restriction only applies to the primary font name as
74
+ presented to the users.
75
+
76
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
77
+ Software shall not be used to promote, endorse or advertise any
78
+ Modified Version, except to acknowledge the contribution(s) of the
79
+ Copyright Holder(s) and the Author(s) or with their explicit written
80
+ permission.
81
+
82
+ 5) The Font Software, modified or unmodified, in part or in whole,
83
+ must be distributed entirely under this license, and must not be
84
+ distributed under any other license. The requirement for fonts to
85
+ remain under this license does not apply to any document created
86
+ using the Font Software.
87
+
88
+ TERMINATION
89
+ This license becomes null and void if any of the above conditions are
90
+ not met.
91
+
92
+ DISCLAIMER
93
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
94
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
95
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
96
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
97
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
98
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
99
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
100
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
101
+ OTHER DEALINGS IN THE FONT SOFTWARE.
102
+
103
+
104
+ ## Included font copyrights
105
+
106
+ [JetBrains Mono]
107
+ Copyright 2020 The JetBrains Mono Project Authors https://github.com/JetBrains/JetBrainsMono
108
+
109
+ [BIZ UDGothic]
110
+ Copyright 2022 The BIZ UDGothic Project Authors https://github.com/googlefonts/morisawa-biz-ud-mincho
111
+
112
+ [Nerd Fonts]
113
+ Copyright (c) 2014, Ryan L McIntyre https://ryanlmcintyre.com
114
+
115
+ [UDEV Gothic]
116
+ Copyright 2022 Yuko Otawara
117
+
118
+ Source: https://github.com/yuru7/udev-gothic/releases/tag/v2.2.0
119
+ UDEVGothic-Regular.ttf (standard 1:2 width, no ligatures), packaged as WOFF2.
@@ -0,0 +1,2 @@
1
+ export declare const readFont: (name: string) => Buffer | undefined;
2
+ export declare function fontCss(inline: boolean): string;
@@ -0,0 +1,13 @@
1
+ import { readViewerAsset } from "./assets.js";
2
+ const fontName = "udev-gothic-regular.woff2";
3
+ const font = readViewerAsset(`fonts/${fontName}`);
4
+ const license = readViewerAsset("fonts/LICENSE.txt").toString("utf8").replaceAll("*/", "* /");
5
+ const face = (url) => `@font-face { font-family:'UDEV Gothic'; font-style:normal; font-weight:400; font-display:swap; src:url(${url}) format('woff2'); }`;
6
+ let embedded;
7
+ export const readFont = (name) => name === fontName ? font : undefined;
8
+ export function fontCss(inline) {
9
+ if (!inline)
10
+ return face(`/assets/fonts/${fontName}`);
11
+ embedded ??= `/* ${license} */\n${face(`data:font/woff2;base64,${font.toString("base64")}`)}`;
12
+ return embedded;
13
+ }
@@ -0,0 +1,3 @@
1
+ /** Compare against HEAD so saving or staging does not clear the editor's changes. */
2
+ export declare const gitBaseText: (root: string, file: string) => string | null;
3
+ export declare const gitBaseBody: (root: string, file: string) => string | null;
@@ -0,0 +1,33 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { parseDoc } from "../compiler/dialect.js";
3
+ import { textfilePath } from "../compiler/textfile.js";
4
+ /** Compare against HEAD so saving or staging does not clear the editor's changes. */
5
+ export const gitBaseText = (root, file) => {
6
+ const git = (...args) => execFileSync("git", ["-C", root, ...args], {
7
+ encoding: "utf8",
8
+ stdio: ["ignore", "pipe", "ignore"],
9
+ timeout: 2_000,
10
+ maxBuffer: 5_000_000,
11
+ });
12
+ try {
13
+ textfilePath(root, file);
14
+ let head;
15
+ try {
16
+ head = git("rev-parse", "--verify", "--quiet", "HEAD").trim();
17
+ }
18
+ catch (error) {
19
+ return error.status === 1 ? "" : null;
20
+ }
21
+ if (!git("ls-tree", "-z", head, "--", `:(literal)${file}`))
22
+ return "";
23
+ return git("show", `${head}:./${file}`);
24
+ }
25
+ catch {
26
+ // Missing Git or unreadable history must leave the editor usable.
27
+ return null;
28
+ }
29
+ };
30
+ export const gitBaseBody = (root, file) => {
31
+ const raw = gitBaseText(root, file);
32
+ return raw === null ? null : parseDoc(raw).body;
33
+ };
@@ -0,0 +1,73 @@
1
+ export interface GitContext {
2
+ root: string;
3
+ branch: string;
4
+ head: string;
5
+ }
6
+ export interface GitPullRequest {
7
+ number: number;
8
+ title: string;
9
+ body: string;
10
+ url: string;
11
+ head: string;
12
+ base: string;
13
+ headCommit: string;
14
+ draft: boolean;
15
+ status: string;
16
+ }
17
+ export interface GitOriginState {
18
+ url: string;
19
+ defaultBranch: string;
20
+ pullRequests: GitPullRequest[];
21
+ }
22
+ export type GitOriginAction = {
23
+ action: "fetch" | "pull" | "push";
24
+ } | {
25
+ action: "createPr";
26
+ title: string;
27
+ body: string;
28
+ base: string;
29
+ draft: boolean;
30
+ } | {
31
+ action: "updatePr";
32
+ number: number;
33
+ title: string;
34
+ body: string;
35
+ previous: GitPullRequest;
36
+ } | {
37
+ action: "mergePr";
38
+ number: number;
39
+ method: "merge" | "squash" | "rebase";
40
+ previous: GitPullRequest;
41
+ };
42
+ /** Injected by the host, never by dooc.yaml. The host owns credentials and remote policy. */
43
+ export interface GitOrigin {
44
+ name: string;
45
+ capabilities: readonly GitOriginAction["action"][];
46
+ read(context: GitContext): Promise<GitOriginState>;
47
+ execute(context: GitContext, request: GitOriginAction): Promise<void>;
48
+ }
49
+ export interface GitChange {
50
+ path: string;
51
+ index: string;
52
+ worktree: string;
53
+ }
54
+ export interface GitState {
55
+ repo: string;
56
+ branch: string;
57
+ head: string;
58
+ version: string;
59
+ branches: string[];
60
+ changes: GitChange[];
61
+ stash?: {
62
+ id: string;
63
+ label: string;
64
+ };
65
+ upstream: string;
66
+ ahead: number;
67
+ behind: number;
68
+ origin?: GitOriginState & {
69
+ name: string;
70
+ capabilities: readonly GitOriginAction["action"][];
71
+ };
72
+ originError?: string;
73
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,5 @@
1
+ import type { GitChange, GitOrigin } from "./git-types.js";
2
+ export declare const parseGitChanges: (status: string) => GitChange[];
3
+ export declare const validateGitOrigin: (value: unknown) => GitOrigin;
4
+ /** Serialize UI operations; Git's own locks still arbitrate with other Git clients. */
5
+ export declare const createGitHandler: (documentRoot: string, getOrigin: () => GitOrigin | undefined) => (input: Record<string, unknown> | undefined) => Promise<unknown>;
@@ -0,0 +1,337 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { lstat, readFile, readlink } from "node:fs/promises";
4
+ import { basename, join } from "node:path";
5
+ const git = (root, args, input = "") => new Promise((resolve, reject) => {
6
+ const child = execFile("git",
7
+ // Stash uses pathspec magic internally when cleaning its saved untracked files.
8
+ [
9
+ args[0] === "stash" ? "--no-literal-pathspecs" : "--literal-pathspecs",
10
+ "-C",
11
+ root,
12
+ ...args,
13
+ ], {
14
+ encoding: "utf8",
15
+ timeout: 30_000,
16
+ maxBuffer: 8 * 1024 * 1024,
17
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0" },
18
+ }, (error, stdout, stderr) => {
19
+ if (error)
20
+ reject(new Error(stderr.trim().slice(0, 2000) || "Git command failed"));
21
+ else
22
+ resolve(stdout);
23
+ });
24
+ child.stdin?.on("error", () => {
25
+ /* execFile reports process failures. */
26
+ });
27
+ child.stdin?.end(input);
28
+ });
29
+ export const parseGitChanges = (status) => {
30
+ const records = status.split("\0");
31
+ const changes = [];
32
+ for (let i = 0; i < records.length; i++) {
33
+ const record = records[i];
34
+ if (!record)
35
+ continue;
36
+ const index = record[0] ?? " ";
37
+ const worktree = record[1] ?? " ";
38
+ changes.push({ path: record.slice(3), index, worktree });
39
+ if (/[RC]/.test(index + worktree))
40
+ i++;
41
+ }
42
+ return changes;
43
+ };
44
+ const text = (value, limit, empty = false) => {
45
+ if (typeof value !== "string" ||
46
+ value.length > limit ||
47
+ value.includes("\0") ||
48
+ (!empty && !value.trim()))
49
+ throw new Error("Invalid Git request text");
50
+ return value;
51
+ };
52
+ export const validateGitOrigin = (value) => {
53
+ const origin = value;
54
+ if (!origin ||
55
+ typeof origin !== "object" ||
56
+ typeof origin.name !== "string" ||
57
+ !origin.name.trim() ||
58
+ typeof origin.read !== "function" ||
59
+ typeof origin.execute !== "function" ||
60
+ !Array.isArray(origin.capabilities) ||
61
+ origin.capabilities.some((action) => !["fetch", "pull", "push", "createPr", "updatePr", "mergePr"].includes(action)))
62
+ throw new Error("Git origin requires a name, capabilities, read and execute handlers");
63
+ return origin;
64
+ };
65
+ /** Serialize UI operations; Git's own locks still arbitrate with other Git clients. */
66
+ export const createGitHandler = (documentRoot, getOrigin) => {
67
+ let busy = false;
68
+ let lastOrigin = getOrigin();
69
+ let originRevision = 0;
70
+ const snapshot = async () => {
71
+ if (lastOrigin !== getOrigin()) {
72
+ lastOrigin = getOrigin();
73
+ originRevision++;
74
+ }
75
+ const root = (await git(documentRoot, ["rev-parse", "--show-toplevel"])).trim();
76
+ const [branch, head, status, branches, upstream, remote, unstaged, staged, stash] = await Promise.all([
77
+ git(root, ["symbolic-ref", "--quiet", "--short", "HEAD"]).then((s) => s.trim(), () => ""),
78
+ git(root, ["rev-parse", "--verify", "HEAD"]).then((s) => s.trim(), () => ""),
79
+ git(root, [
80
+ "status",
81
+ "--porcelain=v1",
82
+ "-z",
83
+ "--untracked-files=all",
84
+ "--no-renames",
85
+ ]),
86
+ git(root, ["for-each-ref", "--format=%(refname:short)", "refs/heads"]),
87
+ git(root, ["rev-parse", "--abbrev-ref", "@{upstream}"]).then((s) => s.trim(), () => ""),
88
+ git(root, ["config", "--get-regexp", "^remote\\.origin\\."]).catch(() => ""),
89
+ git(root, ["diff", "--raw", "--no-abbrev", "--no-renames"]),
90
+ git(root, ["diff", "--cached", "--raw", "--no-abbrev", "--no-renames"]),
91
+ git(root, ["stash", "list", "-1", "--format=%H%x00%gs"]),
92
+ ]);
93
+ const changes = parseGitChanges(status);
94
+ const hash = createHash("sha256").update(JSON.stringify([
95
+ root,
96
+ branch,
97
+ head,
98
+ status,
99
+ remote,
100
+ unstaged,
101
+ staged,
102
+ stash,
103
+ originRevision,
104
+ ]));
105
+ for (const change of changes) {
106
+ const path = join(root, change.path);
107
+ try {
108
+ const stat = await lstat(path);
109
+ // Index object IDs cover staged content; timestamps also cover untracked and binary files.
110
+ hash.update(JSON.stringify([change.path, stat.size, stat.mtimeMs, stat.ctimeMs]));
111
+ }
112
+ catch (error) {
113
+ if (error.code !== "ENOENT")
114
+ throw error;
115
+ hash.update(`deleted:${change.path}`);
116
+ }
117
+ }
118
+ const counts = upstream && head
119
+ ? (await git(root, ["rev-list", "--left-right", "--count", "HEAD...@{upstream}"]))
120
+ .trim()
121
+ .split(/\s+/)
122
+ : [];
123
+ return {
124
+ context: { root, branch, head },
125
+ state: {
126
+ repo: basename(root),
127
+ branch,
128
+ head,
129
+ version: hash.digest("hex"),
130
+ branches: branches.trim().split("\n").filter(Boolean),
131
+ changes,
132
+ ...(stash
133
+ ? {
134
+ stash: {
135
+ id: stash.split("\0")[0] ?? "",
136
+ label: stash.split("\0")[1]?.trim() ?? "",
137
+ },
138
+ }
139
+ : {}),
140
+ upstream,
141
+ ahead: Number(counts[0] ?? 0),
142
+ behind: Number(counts[1] ?? 0),
143
+ },
144
+ };
145
+ };
146
+ return async (input) => {
147
+ if (!input || typeof input.action !== "string")
148
+ throw new Error("Invalid Git action");
149
+ if (busy)
150
+ throw new Error("A Git operation is running. Reload when it finishes.");
151
+ busy = true;
152
+ try {
153
+ const { state, context } = await snapshot();
154
+ const origin = getOrigin();
155
+ if (input.action === "read" || input.action === "branches") {
156
+ if (origin && input.action === "read") {
157
+ try {
158
+ state.origin = {
159
+ ...(await origin.read(context)),
160
+ name: origin.name,
161
+ capabilities: origin.capabilities,
162
+ };
163
+ }
164
+ catch (error) {
165
+ state.originError =
166
+ error instanceof Error ? error.message : "Origin unavailable";
167
+ }
168
+ }
169
+ return state;
170
+ }
171
+ if (input.version !== state.version)
172
+ throw new Error("Repository changed. Reload before continuing.");
173
+ const stashChanges = async () => {
174
+ if (state.stash)
175
+ throw new Error("Stash is occupied. Restore it before stashing more changes.");
176
+ if (!context.head)
177
+ throw new Error("Create the first commit before stashing changes.");
178
+ if (!state.changes.length)
179
+ throw new Error("No changes to stash");
180
+ await git(context.root, [
181
+ "stash",
182
+ "push",
183
+ "--include-untracked",
184
+ "--message",
185
+ "dooc",
186
+ ]);
187
+ if ((await git(context.root, [
188
+ "status",
189
+ "--porcelain=v1",
190
+ "--untracked-files=all",
191
+ ])).trim())
192
+ throw new Error("Some changes could not be stashed. The saved stash has been kept.");
193
+ };
194
+ if (["diff", "stage", "unstage"].includes(input.action)) {
195
+ const path = text(input.path, 4096);
196
+ const change = state.changes.find((item) => item.path === path);
197
+ if (!change)
198
+ throw new Error("Changed file not found");
199
+ if (input.action === "diff") {
200
+ if (change.index === "?") {
201
+ const absolute = join(context.root, path);
202
+ const stat = await lstat(absolute);
203
+ if (stat.size > 1024 * 1024)
204
+ return { diff: "File too large to preview" };
205
+ const data = stat.isSymbolicLink()
206
+ ? Buffer.from(await readlink(absolute))
207
+ : await readFile(absolute);
208
+ return { diff: data.includes(0) ? "Binary file" : data.toString("utf8") };
209
+ }
210
+ const args = ["--no-ext-diff", "--no-textconv", "--", path];
211
+ const [staged, working] = await Promise.all([
212
+ git(context.root, ["diff", "--cached", ...args]),
213
+ git(context.root, ["diff", ...args]),
214
+ ]);
215
+ return { diff: `${staged}${working}` };
216
+ }
217
+ await git(context.root, input.action === "stage"
218
+ ? ["add", "--", path]
219
+ : context.head
220
+ ? ["restore", "--staged", "--", path]
221
+ : ["rm", "--cached", "--", path]);
222
+ }
223
+ else if (input.action === "stash") {
224
+ await stashChanges();
225
+ }
226
+ else if (input.action === "restoreStash") {
227
+ if (!state.stash)
228
+ throw new Error("Stash is empty");
229
+ if (state.changes.length)
230
+ throw new Error("Commit changes before restoring the stash");
231
+ // Git keeps the stash when restoration conflicts, including staged and untracked files.
232
+ try {
233
+ await git(context.root, ["stash", "pop", "--index", "stash@{0}"]);
234
+ }
235
+ catch (error) {
236
+ throw new Error(`Stash restore failed; the stash has been kept. ${error instanceof Error ? error.message : ""}`);
237
+ }
238
+ }
239
+ else if (input.action === "commit") {
240
+ const message = text(input.message, 65_536);
241
+ if (!state.changes.some((change) => ![" ", "?"].includes(change.index)))
242
+ throw new Error("No staged changes");
243
+ await git(context.root, ["commit", "--file=-"], message);
244
+ }
245
+ else if (input.action === "switch" || input.action === "branch") {
246
+ const branch = text(input.branch, 256);
247
+ if (branch.startsWith("-") || branch.includes("\n"))
248
+ throw new Error("Invalid branch");
249
+ await git(context.root, ["check-ref-format", `refs/heads/${branch}`]);
250
+ if (input.action === "switch" && !state.branches.includes(branch))
251
+ throw new Error("Branch not found");
252
+ if (input.action === "switch" && branch === state.branch)
253
+ return { ok: true };
254
+ const stash = input.action === "switch" && state.changes.length > 0;
255
+ if (stash) {
256
+ if (input.stash !== true)
257
+ throw new Error("Commit changes or stash them before switching branches");
258
+ await stashChanges();
259
+ }
260
+ try {
261
+ await git(context.root, input.action === "branch"
262
+ ? ["switch", "-c", branch]
263
+ : ["switch", "--no-guess", branch]);
264
+ }
265
+ catch (error) {
266
+ if (!stash)
267
+ throw error;
268
+ throw new Error(`Branch switch failed; your changes remain in the stash. ${error instanceof Error ? error.message : ""}`);
269
+ }
270
+ }
271
+ else {
272
+ if (!origin?.capabilities.includes(input.action))
273
+ throw new Error("Origin operation is not available");
274
+ let request;
275
+ if (input.action === "fetch" ||
276
+ input.action === "pull" ||
277
+ input.action === "push") {
278
+ if (input.action !== "fetch" && (!context.branch || !context.head))
279
+ throw new Error("A committed branch is required");
280
+ if (input.action === "pull" && state.changes.length)
281
+ throw new Error("Commit changes before pulling");
282
+ request = { action: input.action };
283
+ }
284
+ else if (input.action === "createPr") {
285
+ if (!context.branch || !context.head)
286
+ throw new Error("A committed branch is required");
287
+ if (typeof input.draft !== "boolean")
288
+ throw new Error("Invalid draft setting");
289
+ request = {
290
+ action: "createPr",
291
+ title: text(input.title, 256),
292
+ body: text(input.body, 65_536, true),
293
+ base: text(input.base, 256),
294
+ draft: input.draft,
295
+ };
296
+ }
297
+ else if (input.action === "updatePr" || input.action === "mergePr") {
298
+ if (!Number.isSafeInteger(input.number) || Number(input.number) < 1)
299
+ throw new Error("Invalid pull request number");
300
+ const previous = (await origin.read(context)).pullRequests.find((pr) => pr.number === input.number);
301
+ if (!previous || JSON.stringify(previous) !== input.revision)
302
+ throw new Error("Pull request changed. Reload before continuing.");
303
+ if (input.action === "updatePr") {
304
+ request = {
305
+ action: "updatePr",
306
+ number: previous.number,
307
+ previous,
308
+ title: text(input.title, 256),
309
+ body: text(input.body, 65_536, true),
310
+ };
311
+ }
312
+ else {
313
+ if (!["merge", "squash", "rebase"].includes(String(input.method)))
314
+ throw new Error("Invalid merge method");
315
+ if (previous.draft)
316
+ throw new Error("Draft pull requests cannot be merged");
317
+ request = {
318
+ action: "mergePr",
319
+ number: previous.number,
320
+ previous,
321
+ method: input.method,
322
+ };
323
+ }
324
+ }
325
+ else
326
+ throw new Error("Invalid Git action");
327
+ if (getOrigin() !== origin)
328
+ throw new Error("Origin changed. Reload before continuing.");
329
+ await origin.execute(context, request);
330
+ }
331
+ return { ok: true };
332
+ }
333
+ finally {
334
+ busy = false;
335
+ }
336
+ };
337
+ };
@@ -0,0 +1,53 @@
1
+ import type { ServerResponse } from "node:http";
2
+ import type { ServeMode } from "./serve.js";
3
+ /** SSE endpoint. SoT for the server route and the client script's connection target. */
4
+ export declare const HMR_PATH = "/api/hmr";
5
+ /** Kind of change — content = main data, client = edit's client bundle (needs a reload). */
6
+ export type HmrKind = "content" | "client";
7
+ /**
8
+ * Changed path (repo-root relative) → HMR kind. undefined for out-of-scope files
9
+ * (dist output, temp files etc.).
10
+ */
11
+ export declare const classifyChange: (rel: string) => HmrKind | undefined;
12
+ /** One SSE frame (in the format the client's EventSource reads). */
13
+ export declare const sseFrame: (event: string, data: unknown) => string;
14
+ /**
15
+ * Notification hooks the client script puts on `window.__docsHmr` (contract with edit-client.ts).
16
+ * setDirty = shares the unsaved state,
17
+ * onContent = hook for applying content changes in place (registered by edit-client.ts; falls
18
+ * back to a reload if unregistered).
19
+ */
20
+ export interface HmrBridge {
21
+ setDirty: (v: boolean) => void;
22
+ onContent?: (files: string[]) => void;
23
+ updatePreview?: (target: HTMLElement, source: HTMLElement) => void;
24
+ }
25
+ export interface HmrHub {
26
+ /** GET /api/hmr — holds the connection and keeps pushing broadcasts to it. */
27
+ handle: (res: ServerResponse) => void;
28
+ broadcast: (kind: HmrKind, files: string[]) => void;
29
+ }
30
+ export declare const createHmrHub: (bootId: string) => HmrHub;
31
+ /**
32
+ * Folders to watch. The docs-side ones are relative to docsRoot, src to pkgRoot (only files that
33
+ * classifyChange marks "client" count).
34
+ */
35
+ /**
36
+ * Notifies data-side changes batched by kind. An editor save fires multiple events
37
+ * (rename + change), so debounce collapses them into one. Referenced text files can be added
38
+ * as drafts are compiled; close() releases all watchers.
39
+ */
40
+ export declare const watchProject: (docsRoot: string, pkgRoot: string, onChange: (kind: HmrKind, files: string[]) => void, debounceMs?: number) => {
41
+ close: () => void;
42
+ watchTextfiles: (files: Iterable<string>) => void;
43
+ };
44
+ /**
45
+ * Client script injected into page(). How changes are applied depends on mode:
46
+ * preview = swap the main <main> + nav (keeping scroll / sidebar state).
47
+ * edit = delegate content changes to `window.__docsHmr.onContent` (registered by
48
+ * edit-client.ts) without reloading (pages without it, e.g. the new page, reload).
49
+ * Changes to the client bundle (`src/viewer/edit-client.ts` / `src/core/*.tsx`) and
50
+ * a bootId difference in `hello` (= the server itself restarted) reload. While there
51
+ * are unsaved (dirty) changes, the reload is downgraded to a badge and waits.
52
+ */
53
+ export declare const hmrClientScript: (mode: ServeMode) => string;