@yaks/code 0.0.0-stage → 0.2.36

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 (55) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +106 -2
  3. package/_dist/anatomy.d.ts +144 -0
  4. package/_dist/anatomy.d.ts.map +1 -0
  5. package/_dist/described.d.ts +31 -0
  6. package/_dist/described.d.ts.map +1 -0
  7. package/_dist/effects.d.ts +9 -0
  8. package/_dist/effects.d.ts.map +1 -0
  9. package/_dist/frames.d.ts +16 -0
  10. package/_dist/frames.d.ts.map +1 -0
  11. package/_dist/mod.d.ts +26 -0
  12. package/_dist/mod.d.ts.map +1 -0
  13. package/_dist/read.d.ts +89 -0
  14. package/_dist/read.d.ts.map +1 -0
  15. package/_dist/source.d.ts +55 -0
  16. package/_dist/source.d.ts.map +1 -0
  17. package/_dist/sync.d.ts +39 -0
  18. package/_dist/sync.d.ts.map +1 -0
  19. package/_dist/tools.d.ts +8 -0
  20. package/_dist/tools.d.ts.map +1 -0
  21. package/_dist/vocab.d.ts +6 -0
  22. package/_dist/vocab.d.ts.map +1 -0
  23. package/anatomy.js +552 -0
  24. package/anatomy.js.map +1 -0
  25. package/anatomy.ts +638 -0
  26. package/deno.json +1 -0
  27. package/described.js +274 -0
  28. package/described.js.map +1 -0
  29. package/described.ts +314 -0
  30. package/effects.js +24 -0
  31. package/effects.js.map +1 -0
  32. package/effects.ts +30 -0
  33. package/frames.js +46 -0
  34. package/frames.js.map +1 -0
  35. package/frames.ts +54 -0
  36. package/mod.js +26 -0
  37. package/mod.js.map +1 -0
  38. package/mod.ts +27 -0
  39. package/package.json +54 -4
  40. package/read.js +178 -0
  41. package/read.js.map +1 -0
  42. package/read.ts +249 -0
  43. package/source.js +238 -0
  44. package/source.js.map +1 -0
  45. package/source.ts +263 -0
  46. package/sync.js +345 -0
  47. package/sync.js.map +1 -0
  48. package/sync.ts +323 -0
  49. package/tools.js +49 -0
  50. package/tools.js.map +1 -0
  51. package/tools.ts +59 -0
  52. package/vocab.js +21 -0
  53. package/vocab.js.map +1 -0
  54. package/vocab.json +143 -0
  55. package/vocab.ts +22 -0
package/sync.js ADDED
@@ -0,0 +1,345 @@
1
+ import * as io from "@yaks/file/io";
2
+ import { command as processCommand } from "@yaks/process/command";
3
+ import { localFilesystem } from "@yaks/git/host";
4
+ import { identities } from "@yaks/graph/identity";
5
+ import { signed } from "@yaks/graph/provenance";
6
+ import { line } from "@yaks/query";
7
+ import { link, unlink } from "@yaks/edge";
8
+ import { blobOf } from "@yaks/mirror";
9
+ import { exportsOf, header, isCode, isMarkdown, manifest, manifests, markdown, owner, resolve, specifiers } from "./read.js";
10
+ let str = (v)=>v == null ? '' : String(v);
11
+ let comp = (b, name)=>b[name];
12
+ /** Run a command in a directory and return its stdout; a failure throws with
13
+ * its stderr. */ let run = async (cmd, args, cwd)=>{
14
+ let out = await processCommand(cmd, {
15
+ args,
16
+ cwd,
17
+ stdout: 'piped',
18
+ stderr: 'piped'
19
+ }).output();
20
+ let err = new TextDecoder().decode(out.stderr);
21
+ if (!out.success) throw new Error(`${cmd} ${args[0]}: ${err.trim()}`);
22
+ return new TextDecoder().decode(out.stdout);
23
+ };
24
+ /** The checkout `cwd` is in: its root, and its repository's common Git
25
+ * directory, both canonical. */ export let checkout = async (cwd)=>{
26
+ let [top, git] = (await run('git', [
27
+ 'rev-parse',
28
+ '--path-format=absolute',
29
+ '--show-toplevel',
30
+ '--git-common-dir'
31
+ ], cwd)).trim().split('\n');
32
+ return {
33
+ root: await io.realPath(top),
34
+ common: await io.realPath(git)
35
+ };
36
+ };
37
+ /** Which tracked files are code: TS/JS modules, markdown, package manifests
38
+ * and vocabularies, outside any `vendor` directory. */ export let covered = (path)=>!/(^|\/)(vendor|node_modules)\//.test(path) && (isCode(path) || isMarkdown(path) || /(^|\/)(deno|package|vocab)\.json$/.test(path));
39
+ /**
40
+ * The exports of many modules at once. `deno doc` refuses a whole batch when
41
+ * one module in it cannot be resolved, so a refused module is set aside —
42
+ * named in `refused`, read for everything but its exports — and the rest are
43
+ * asked again.
44
+ */ export let exported = async (root, paths)=>{
45
+ let refused = [];
46
+ let left = paths.filter(isCode);
47
+ while(left.length){
48
+ let out = await processCommand('deno', {
49
+ args: [
50
+ 'doc',
51
+ '--json',
52
+ '-q',
53
+ ...left
54
+ ],
55
+ cwd: root,
56
+ env: {
57
+ NO_COLOR: '1'
58
+ },
59
+ stdout: 'piped',
60
+ stderr: 'piped'
61
+ }).output();
62
+ if (out.success) {
63
+ let json = JSON.parse(new TextDecoder().decode(out.stdout));
64
+ return {
65
+ nodes: json.nodes ?? {},
66
+ refused
67
+ };
68
+ }
69
+ // deno doc names the module it could not resolve from as a file URL.
70
+ let err = new TextDecoder().decode(out.stderr);
71
+ let bad = [
72
+ ...err.matchAll(/from 'file:\/\/([^']+)'/g)
73
+ ].map((m)=>m[1].slice(root.length + 1)).find((p)=>left.includes(p));
74
+ if (!bad) throw new Error(`deno doc: ${err.trim()}`);
75
+ refused.push(bad);
76
+ left = left.filter((p)=>p != bad);
77
+ }
78
+ return {
79
+ nodes: {},
80
+ refused
81
+ };
82
+ };
83
+ /** The most bundles one transaction carries. */ let BATCH = 1000;
84
+ /**
85
+ * The binding for one checkout. `full` forgets what was read, so every file
86
+ * is read again; `read` accumulates what the reads found into `said`.
87
+ */ export let codeMirror = async (g, cwd, opts = {})=>{
88
+ let { root, common } = await checkout(cwd);
89
+ let derive = identities(g.vocab);
90
+ // The id a component's declared identity gives these values; a graph whose
91
+ // vocabulary declares no such identity cannot hold a codebase.
92
+ let ids = (name, c)=>{
93
+ let d = derive[name];
94
+ if (!d) throw new Error(`this graph declares no identity for ${name}`);
95
+ return d(c, {
96
+ entity: {
97
+ eid: ''
98
+ },
99
+ [name]: c
100
+ });
101
+ };
102
+ let workspace = (await localFilesystem(g)).entity.eid;
103
+ let repository = ids('repository', {
104
+ workspace,
105
+ common
106
+ });
107
+ let apply = async (bundles)=>{
108
+ for(let i = 0; i < bundles.length; i += BATCH){
109
+ await g.apply(signed(bundles.slice(i, i + BATCH), opts.actor ?? null), {
110
+ trusted: true
111
+ });
112
+ }
113
+ };
114
+ await apply([
115
+ {
116
+ entity: {
117
+ eid: repository
118
+ },
119
+ repository: {
120
+ workspace,
121
+ common
122
+ }
123
+ }
124
+ ]);
125
+ // Regular files only: a symlink's blob is the path it points at, and a
126
+ // submodule is somebody else's tree.
127
+ let tracked = (await run('git', [
128
+ 'ls-files',
129
+ '-s',
130
+ '-z'
131
+ ], root)).split('\0').filter((l)=>/^100/.test(l)).map((l)=>l.slice(l.indexOf('\t') + 1)).filter(covered);
132
+ let isTracked = new Set(tracked);
133
+ let text = (path)=>io.readTextFileSync(`${root}/${path}`);
134
+ let pkgs = tracked.filter(manifests).flatMap((p)=>{
135
+ try {
136
+ return [
137
+ manifest(p, text(p))
138
+ ].filter((m)=>!!m);
139
+ } catch {
140
+ return [];
141
+ }
142
+ });
143
+ let moduleOf = (path)=>ids('file', {
144
+ path,
145
+ root: repository
146
+ });
147
+ let packageOf = (name)=>ids('package', {
148
+ name
149
+ });
150
+ // What the graph read last time, kept for the read below: every module of
151
+ // this repository, by path.
152
+ let known = new Map();
153
+ let said = {
154
+ modules: 0,
155
+ symbols: 0,
156
+ imports: 0,
157
+ packages: 0,
158
+ refused: []
159
+ };
160
+ let read = async (paths, gone)=>{
161
+ let here = paths.filter((p)=>!gone.includes(p));
162
+ let mods = new Set([
163
+ ...paths.map(moduleOf)
164
+ ]);
165
+ let { nodes, refused } = await exported(root, here);
166
+ said.refused = refused;
167
+ let bundles = [];
168
+ let later = [];
169
+ // Packages first, so a module's reference to one lands on an entity that
170
+ // exists; and each manifest that moved clears the package it used to be.
171
+ let wasPkgs = await g.read('.package');
172
+ for (let path of paths.filter(manifests)){
173
+ let m = moduleOf(path);
174
+ let now = pkgs.find((p)=>p.path == path && !gone.includes(path));
175
+ for (let old of wasPkgs){
176
+ let c = comp(old, 'package');
177
+ if (c.manifest == m && c.name != now?.name) {
178
+ bundles.push({
179
+ entity: old.entity,
180
+ package: null,
181
+ doc: null
182
+ });
183
+ }
184
+ }
185
+ if (!now) continue;
186
+ said.packages++;
187
+ bundles.push({
188
+ entity: {
189
+ eid: packageOf(now.name)
190
+ },
191
+ package: {
192
+ name: now.name,
193
+ version: now.version ?? null,
194
+ manifest: m
195
+ },
196
+ doc: {
197
+ title: now.name,
198
+ body: now.description ?? null
199
+ }
200
+ });
201
+ }
202
+ let pkgOf = (path)=>{
203
+ let p = owner(path, pkgs);
204
+ return p ? packageOf(p.name) : null;
205
+ };
206
+ // The exports and imports each module had, so what it no longer has is
207
+ // cleared rather than left behind.
208
+ let wasSyms = (await g.read('.symbol')).filter((b)=>mods.has(str(comp(b, 'symbol')?.module)));
209
+ let wasLinks = (await g.read('.imports&?edge')).filter((b)=>mods.has(str(comp(b, 'edge')?.from)));
210
+ let keep = new Set();
211
+ for (let path of paths){
212
+ let m = moduleOf(path);
213
+ if (gone.includes(path)) {
214
+ bundles.push({
215
+ entity: {
216
+ eid: m
217
+ },
218
+ file: null,
219
+ module: null,
220
+ doc: null
221
+ });
222
+ continue;
223
+ }
224
+ let body = text(path);
225
+ let md = isMarkdown(path) ? markdown(path, body) : undefined;
226
+ said.modules++;
227
+ bundles.push({
228
+ entity: {
229
+ eid: m
230
+ },
231
+ file: {
232
+ path,
233
+ root: repository
234
+ },
235
+ module: {
236
+ blob: await blobOf(body),
237
+ package: pkgOf(path)
238
+ },
239
+ doc: md ?? {
240
+ title: path,
241
+ body: header(body) || null
242
+ }
243
+ });
244
+ for (let e of exportsOf(nodes, `file://${root}/${path}`)){
245
+ let s = ids('symbol', {
246
+ module: m,
247
+ name: e.name
248
+ });
249
+ keep.add(s);
250
+ said.symbols++;
251
+ later.push({
252
+ entity: {
253
+ eid: s
254
+ },
255
+ symbol: {
256
+ module: m,
257
+ name: e.name,
258
+ kind: e.kind,
259
+ line: e.line
260
+ },
261
+ doc: {
262
+ title: e.name,
263
+ body: e.doc || null
264
+ }
265
+ });
266
+ }
267
+ if (!isCode(path)) continue;
268
+ for (let spec of specifiers(body)){
269
+ let to = resolve(spec, path, pkgs);
270
+ if (!to || to == path || !isTracked.has(to)) continue;
271
+ let l = link(m, 'imports', moduleOf(to));
272
+ keep.add(l.entity.eid);
273
+ said.imports++;
274
+ later.push(l);
275
+ }
276
+ }
277
+ for (let b of wasSyms){
278
+ if (!keep.has(b.entity.eid)) {
279
+ later.push({
280
+ entity: b.entity,
281
+ symbol: null,
282
+ doc: null
283
+ });
284
+ }
285
+ }
286
+ for (let b of wasLinks){
287
+ if (!keep.has(b.entity.eid)) {
288
+ let e = comp(b, 'edge');
289
+ later.push(unlink(str(e.from), 'imports', str(e.to)));
290
+ }
291
+ }
292
+ // A manifest that came or went moves every file under it: re-point the
293
+ // modules nobody read this time.
294
+ if (paths.some(manifests)) {
295
+ for (let [path, b] of known){
296
+ if (mods.has(b.entity.eid)) continue;
297
+ let want = pkgOf(path);
298
+ if (str(comp(b, 'module')?.package) != str(want)) {
299
+ bundles.push({
300
+ entity: b.entity,
301
+ module: {
302
+ package: want
303
+ }
304
+ });
305
+ }
306
+ }
307
+ }
308
+ await apply([
309
+ ...bundles,
310
+ ...later
311
+ ]);
312
+ };
313
+ let binding = {
314
+ name: 'code',
315
+ files: async ()=>{
316
+ let out = new Map();
317
+ for (let path of tracked)out.set(path, await blobOf(text(path)));
318
+ return out;
319
+ },
320
+ read,
321
+ agreed: async ()=>{
322
+ known.clear();
323
+ for (let b of (await g.read(line`.file.root=${repository}&?module`))){
324
+ let path = str(comp(b, 'file')?.path);
325
+ if (path && comp(b, 'module')) known.set(path, b);
326
+ }
327
+ // A full read forgets every blob, so every file reads as moved, while a
328
+ // file that is gone is still known to have been here.
329
+ return new Map([
330
+ ...known
331
+ ].map(([path, b])=>[
332
+ path,
333
+ {
334
+ blob: opts.full ? '' : str(comp(b, 'module')?.blob)
335
+ }
336
+ ]));
337
+ }
338
+ };
339
+ return {
340
+ binding,
341
+ said,
342
+ root
343
+ };
344
+ };
345
+ //# sourceMappingURL=sync.js.map
package/sync.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sync.js","sources":["./sync.ts"],"names":[],"mappings":"AAAA,YAAY,6BAAkC;AAC9C,SAAS,WAAW,cAAc,qCAA0C;AAoB5E,SAAS,eAAe,8BAAmC;AAC3D,SAAS,UAAU,oCAAyC;AAC5D,SAAS,MAAM,sCAA2C;AAE1D,SAAS,IAAI,2BAAgC;AAC7C,SAAS,IAAI,EAAE,MAAM,0BAA+B;AAEpD,SAAS,MAAM,4BAAiC;AAChD,SAEE,SAAS,EACT,MAAM,EACN,MAAM,EACN,UAAU,EAEV,QAAQ,EACR,SAAS,EACT,QAAQ,EACR,KAAK,EACL,OAAO,EACP,UAAU,oBACM;AAElB,IAAI,MAAM,CAAC,IAAe,KAAK,OAAO,KAAK,OAAO;AAClD,IAAI,OAAO,CAAC,GAAW,OAAiB,CAAC,CAAC,KAAK;AAE/C;eACe,GACf,IAAI,MAAM,OAAO,KAAa,MAAgB;EAC5C,IAAI,MAAM,MAAM,eAAe,KAAK;IAClC;IACA;IACA,QAAQ;IACR,QAAQ;EACV,GAAG,MAAM;EACT,IAAI,MAAM,IAAI,cAAc,MAAM,CAAC,IAAI,MAAM;EAC7C,IAAI,CAAC,IAAI,OAAO,EAAE,MAAM,IAAI,MAAM,GAAG,IAAI,CAAC,EAAE,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE,IAAI,IAAI,IAAI;EACpE,OAAO,IAAI,cAAc,MAAM,CAAC,IAAI,MAAM;AAC5C;AAEA;8BAC8B,GAC9B,OAAO,IAAI,WAAW,OACpB;EAEA,IAAI,CAAC,KAAK,IAAI,GAAG,CAAC,MAAM,IAAI,OAAO;IACjC;IACA;IACA;IACA;GACD,EAAE,IAAI,EAAE,IAAI,GAAG,KAAK,CAAC;EACtB,OAAO;IAAE,MAAM,MAAM,GAAG,QAAQ,CAAC;IAAM,QAAQ,MAAM,GAAG,QA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AAG;QAC5B,IAAI,OAAO,MAAM;QACjB,IAAI,IAAI,KAAK,GAAG,WAAW,YAAY,IAAI,OAAO;UAChD,QAAQ,IAAI,CAAC;YAAE,QAAQ,EAAE,MAAM;YAAE,QAAQ;cAAE,SAAS;YAAK;UAAE;QAC7D;MACF;IACF;IACA,MAAM,MAAM;SAAI;SAAY;KAAM;EACpC;EAEA,IAAI,UAAmB;IACrB,MAAM;IACN,OAAO;MACL,IAAI,MAAM,IAAI;MACd,KAAK,IAAI,QAAQ,QAAS,IAAI,GAAG,CAAC,MAAM,MAAM,OAAO,KAAK;MAC1D,OAAO;IACT;IACA;IACA,QAAQ;MACN,MAAM,KAAK;MACX,KAAK,IAAI,KAAK,CAAA,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,WAAW,QAAQ,CAAC,CAAA,EAAG;QAClE,IAAI,OAAO,IAAI,KAAK,GAAG,SAAS;QAChC,IAAI,QAAQ,KAAK,GAAG,WAAW,MAAM,GAAG,CAAC,MAAM;MACjD;MACA,wEAAwE;MACxE,sDAAsD;MACtD,OAAO,IAAI,IACT;WAAI;OAAM,CAAC,GAAG,CAAC,CACb,CAAC,MAAM,EAAE,GACN;UAAC;UAAM;YAAE,MAAM,KAAK,IAAI,GAAG,KAAK,IAAI,KAAK,GAAG,WAAW;UAAM;SAAE;IAExE;EACF;EACA,OAAO;IAAE;IAAS;IAAM;EAAK;AAC/B,EAAC"}
package/sync.ts ADDED
@@ -0,0 +1,323 @@
1
+ import * as io from '@yaks/file/io'
2
+ import { command as processCommand } from '@yaks/process/command'
3
+ // The codebase, read into a graph: a read-only @yaks/mirror binding over the
4
+ // files Git tracks in one checkout.
5
+ //
6
+ // The files own the code, so the binding only reads. What it remembers of each
7
+ // file is the blob id its module records, which is also what makes a sync
8
+ // incremental: a file whose blob still matches is not read again, and a full
9
+ // read of an unchanged tree writes nothing.
10
+ //
11
+ // Every id is derived from the vocabulary's declared identities (@yaks/graph
12
+ // `identities`): a module is its `file{path, root}` (@yaks/file), rooted in the
13
+ // repository, a symbol its module and name, a package its name. So reading the same tree twice is one set of
14
+ // entities, and nothing here invents an id.
15
+ //
16
+ // Nothing is ever deleted. A path or an export name comes back often, so what
17
+ // is gone has its components cleared instead: the entity stays, empty, and a
18
+ // later read fills it in.
19
+ // Import links are cleared the same way, with @yaks/edge's `unlink`.
20
+
21
+ import type { Bundle, Comp, Eid, Graph } from 'jsr:@yaks/graph@0.2.36'
22
+ import { localFilesystem } from '@yaks/git/host'
23
+ import { identities } from '@yaks/graph/identity'
24
+ import { signed } from '@yaks/graph/provenance'
25
+ import type { Actor } from 'jsr:@yaks/graph@0.2.36'
26
+ import { line } from '@yaks/query'
27
+ import { link, unlink } from '@yaks/edge'
28
+ import type { Binding } from '@yaks/mirror'
29
+ import { blobOf } from '@yaks/mirror'
30
+ import {
31
+ type DocNode,
32
+ exportsOf,
33
+ header,
34
+ isCode,
35
+ isMarkdown,
36
+ type Manifest,
37
+ manifest,
38
+ manifests,
39
+ markdown,
40
+ owner,
41
+ resolve,
42
+ specifiers,
43
+ } from './read.js'
44
+
45
+ let str = (v: unknown) => v == null ? '' : String(v)
46
+ let comp = (b: Bundle, name: string) => b[name] as Comp | undefined
47
+
48
+ /** Run a command in a directory and return its stdout; a failure throws with
49
+ * its stderr. */
50
+ let run = async (cmd: string, args: string[], cwd: string) => {
51
+ let out = await processCommand(cmd, {
52
+ args,
53
+ cwd,
54
+ stdout: 'piped',
55
+ stderr: 'piped',
56
+ }).output()
57
+ let err = new TextDecoder().decode(out.stderr)
58
+ if (!out.success) throw new Error(`${cmd} ${args[0]}: ${err.trim()}`)
59
+ return new TextDecoder().decode(out.stdout)
60
+ }
61
+
62
+ /** The checkout `cwd` is in: its root, and its repository's common Git
63
+ * directory, both canonical. */
64
+ export let checkout = async (
65
+ cwd: string,
66
+ ): Promise<{ root: string; common: string }> => {
67
+ let [top, git] = (await run('git', [
68
+ 'rev-parse',
69
+ '--path-format=absolute',
70
+ '--show-toplevel',
71
+ '--git-common-dir',
72
+ ], cwd)).trim().split('\n')
73
+ return { root: await io.realPath(top), common: await io.realPath(git) }
74
+ }
75
+
76
+ /** Which tracked files are code: TS/JS modules, markdown, package manifests
77
+ * and vocabularies, outside any `vendor` directory. */
78
+ export let covered = (path: string): boolean =>
79
+ !/(^|\/)(vendor|node_modules)\//.test(path) &&
80
+ (isCode(path) || isMarkdown(path) ||
81
+ /(^|\/)(deno|package|vocab)\.json$/.test(path))
82
+
83
+ /**
84
+ * The exports of many modules at once. `deno doc` refuses a whole batch when
85
+ * one module in it cannot be resolved, so a refused module is set aside —
86
+ * named in `refused`, read for everything but its exports — and the rest are
87
+ * asked again.
88
+ */
89
+ export let exported = async (
90
+ root: string,
91
+ paths: string[],
92
+ ): Promise<{ nodes: Record<string, DocNode>; refused: string[] }> => {
93
+ let refused: string[] = []
94
+ let left = paths.filter(isCode)
95
+ while (left.length) {
96
+ let out = await processCommand('deno', {
97
+ args: ['doc', '--json', '-q', ...left],
98
+ cwd: root,
99
+ env: { NO_COLOR: '1' },
100
+ stdout: 'piped',
101
+ stderr: 'piped',
102
+ }).output()
103
+ if (out.success) {
104
+ let json = JSON.parse(new TextDecoder().decode(out.stdout))
105
+ return { nodes: json.nodes ?? {}, refused }
106
+ }
107
+ // deno doc names the module it could not resolve from as a file URL.
108
+ let err = new TextDecoder().decode(out.stderr)
109
+ let bad = [...err.matchAll(/from 'file:\/\/([^']+)'/g)]
110
+ .map((m) => m[1].slice(root.length + 1))
111
+ .find((p) => left.includes(p))
112
+ if (!bad) throw new Error(`deno doc: ${err.trim()}`)
113
+ refused.push(bad)
114
+ left = left.filter((p) => p != bad)
115
+ }
116
+ return { nodes: {}, refused }
117
+ }
118
+
119
+ /** What a sync of one checkout did, beyond what the mirror reports. */
120
+ export type Read = {
121
+ modules: number
122
+ symbols: number
123
+ imports: number
124
+ packages: number
125
+ refused: string[]
126
+ }
127
+
128
+ /** The most bundles one transaction carries. */
129
+ let BATCH = 1000
130
+
131
+ /**
132
+ * The binding for one checkout. `full` forgets what was read, so every file
133
+ * is read again; `read` accumulates what the reads found into `said`.
134
+ */
135
+ export let codeMirror = async (
136
+ g: Graph,
137
+ cwd: string,
138
+ opts: { full?: boolean; actor?: Actor | null } = {},
139
+ ): Promise<{ binding: Binding; said: Read; root: string }> => {
140
+ let { root, common } = await checkout(cwd)
141
+ let derive = identities(g.vocab)
142
+ // The id a component's declared identity gives these values; a graph whose
143
+ // vocabulary declares no such identity cannot hold a codebase.
144
+ let ids = (name: string, c: Comp): Eid => {
145
+ let d = derive[name]
146
+ if (!d) throw new Error(`this graph declares no identity for ${name}`)
147
+ return d(c, { entity: { eid: '' }, [name]: c })
148
+ }
149
+ let workspace = (await localFilesystem(g)).entity.eid
150
+ let repository = ids('repository', { workspace, common })
151
+ let apply = async (bundles: Bundle[]) => {
152
+ for (let i = 0; i < bundles.length; i += BATCH) {
153
+ await g.apply(signed(bundles.slice(i, i + BATCH), opts.actor ?? null), {
154
+ trusted: true,
155
+ })
156
+ }
157
+ }
158
+ await apply([{
159
+ entity: { eid: repository },
160
+ repository: { workspace, common },
161
+ }])
162
+
163
+ // Regular files only: a symlink's blob is the path it points at, and a
164
+ // submodule is somebody else's tree.
165
+ let tracked = (await run('git', ['ls-files', '-s', '-z'], root)).split('\0')
166
+ .filter((l) => /^100/.test(l)).map((l) => l.slice(l.indexOf('\t') + 1))
167
+ .filter(covered)
168
+ let isTracked = new Set(tracked)
169
+ let text = (path: string) => io.readTextFileSync(`${root}/${path}`)
170
+ let pkgs = tracked.filter(manifests).flatMap((p) => {
171
+ try {
172
+ return [manifest(p, text(p))].filter((m): m is Manifest => !!m)
173
+ } catch {
174
+ return []
175
+ }
176
+ })
177
+ let moduleOf = (path: string): Eid => ids('file', { path, root: repository })
178
+ let packageOf = (name: string): Eid => ids('package', { name })
179
+
180
+ // What the graph read last time, kept for the read below: every module of
181
+ // this repository, by path.
182
+ let known = new Map<string, Bundle>()
183
+ let said: Read = {
184
+ modules: 0,
185
+ symbols: 0,
186
+ imports: 0,
187
+ packages: 0,
188
+ refused: [],
189
+ }
190
+
191
+ let read = async (paths: string[], gone: string[]) => {
192
+ let here = paths.filter((p) => !gone.includes(p))
193
+ let mods = new Set([...paths.map(moduleOf)])
194
+ let { nodes, refused } = await exported(root, here)
195
+ said.refused = refused
196
+ let bundles: Bundle[] = []
197
+ let later: Bundle[] = []
198
+
199
+ // Packages first, so a module's reference to one lands on an entity that
200
+ // exists; and each manifest that moved clears the package it used to be.
201
+ let wasPkgs = await g.read('.package')
202
+ for (let path of paths.filter(manifests)) {
203
+ let m = moduleOf(path)
204
+ let now = pkgs.find((p) => p.path == path && !gone.includes(path))
205
+ for (let old of wasPkgs) {
206
+ let c = comp(old, 'package')!
207
+ if (c.manifest == m && c.name != now?.name) {
208
+ bundles.push({ entity: old.entity, package: null, doc: null })
209
+ }
210
+ }
211
+ if (!now) continue
212
+ said.packages++
213
+ bundles.push({
214
+ entity: { eid: packageOf(now.name) },
215
+ package: { name: now.name, version: now.version ?? null, manifest: m },
216
+ doc: { title: now.name, body: now.description ?? null },
217
+ })
218
+ }
219
+ let pkgOf = (path: string) => {
220
+ let p = owner(path, pkgs)
221
+ return p ? packageOf(p.name) : null
222
+ }
223
+ // The exports and imports each module had, so what it no longer has is
224
+ // cleared rather than left behind.
225
+ let wasSyms = (await g.read('.symbol')).filter((b) =>
226
+ mods.has(str(comp(b, 'symbol')?.module))
227
+ )
228
+ let wasLinks = (await g.read('.imports&?edge')).filter((b) =>
229
+ mods.has(str(comp(b, 'edge')?.from))
230
+ )
231
+ let keep = new Set<Eid>()
232
+
233
+ for (let path of paths) {
234
+ let m = moduleOf(path)
235
+ if (gone.includes(path)) {
236
+ bundles.push({
237
+ entity: { eid: m },
238
+ file: null,
239
+ module: null,
240
+ doc: null,
241
+ })
242
+ continue
243
+ }
244
+ let body = text(path)
245
+ let md = isMarkdown(path) ? markdown(path, body) : undefined
246
+ said.modules++
247
+ bundles.push({
248
+ entity: { eid: m },
249
+ file: { path, root: repository },
250
+ module: { blob: await blobOf(body), package: pkgOf(path) },
251
+ doc: md ?? { title: path, body: header(body) || null },
252
+ })
253
+ for (let e of exportsOf(nodes, `file://${root}/${path}`)) {
254
+ let s = ids('symbol', { module: m, name: e.name })
255
+ keep.add(s)
256
+ said.symbols++
257
+ later.push({
258
+ entity: { eid: s },
259
+ symbol: { module: m, name: e.name, kind: e.kind, line: e.line },
260
+ doc: { title: e.name, body: e.doc || null },
261
+ })
262
+ }
263
+ if (!isCode(path)) continue
264
+ for (let spec of specifiers(body)) {
265
+ let to = resolve(spec, path, pkgs)
266
+ if (!to || to == path || !isTracked.has(to)) continue
267
+ let l = link(m, 'imports', moduleOf(to))
268
+ keep.add(l.entity.eid)
269
+ said.imports++
270
+ later.push(l)
271
+ }
272
+ }
273
+ for (let b of wasSyms) {
274
+ if (!keep.has(b.entity.eid)) {
275
+ later.push({ entity: b.entity, symbol: null, doc: null })
276
+ }
277
+ }
278
+ for (let b of wasLinks) {
279
+ if (!keep.has(b.entity.eid)) {
280
+ let e = comp(b, 'edge')!
281
+ later.push(unlink(str(e.from), 'imports', str(e.to)))
282
+ }
283
+ }
284
+
285
+ // A manifest that came or went moves every file under it: re-point the
286
+ // modules nobody read this time.
287
+ if (paths.some(manifests)) {
288
+ for (let [path, b] of known) {
289
+ if (mods.has(b.entity.eid)) continue
290
+ let want = pkgOf(path)
291
+ if (str(comp(b, 'module')?.package) != str(want)) {
292
+ bundles.push({ entity: b.entity, module: { package: want } })
293
+ }
294
+ }
295
+ }
296
+ await apply([...bundles, ...later])
297
+ }
298
+
299
+ let binding: Binding = {
300
+ name: 'code',
301
+ files: async () => {
302
+ let out = new Map<string, string>()
303
+ for (let path of tracked) out.set(path, await blobOf(text(path)))
304
+ return out
305
+ },
306
+ read,
307
+ agreed: async () => {
308
+ known.clear()
309
+ for (let b of await g.read(line`.file.root=${repository}&?module`)) {
310
+ let path = str(comp(b, 'file')?.path)
311
+ if (path && comp(b, 'module')) known.set(path, b)
312
+ }
313
+ // A full read forgets every blob, so every file reads as moved, while a
314
+ // file that is gone is still known to have been here.
315
+ return new Map(
316
+ [...known].map((
317
+ [path, b],
318
+ ) => [path, { blob: opts.full ? '' : str(comp(b, 'module')?.blob) }]),
319
+ )
320
+ },
321
+ }
322
+ return { binding, said, root }
323
+ }