@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/frames.js ADDED
@@ -0,0 +1,46 @@
1
+ // Resolve places against the catalog only when its bytes match the failing
2
+ // commit. One catalog read keeps a module and its exports in the same snapshot.
3
+ import { identityEid } from "@yaks/graph/identity";
4
+ import { fileOf } from "@yaks/file";
5
+ let comp = (row, name)=>row?.[name] && typeof row[name] == 'object' ? row[name] : {};
6
+ let appPath = (path, blobs)=>blobs.has(path) && !/(^|\/)(vendor|node_modules)\//.test(path);
7
+ export let resolveFrames = async (catalog, repository, blobs, places)=>{
8
+ let ids = places.map((p)=>fileOf(repository, p.path));
9
+ let symbols = places.map((p, i)=>p.function ? identityEid('symbol', [
10
+ ids[i],
11
+ p.function
12
+ ]) : '');
13
+ let requested = places.flatMap((p, i)=>appPath(p.path, blobs) ? [
14
+ ids[i],
15
+ ...symbols[i] ? [
16
+ symbols[i]
17
+ ] : []
18
+ ] : []);
19
+ let known = new Map((requested.length ? await catalog.get([
20
+ ...new Set(requested)
21
+ ]) : []).map((row)=>[
22
+ row.entity.eid,
23
+ row
24
+ ]));
25
+ return places.map((p, i)=>{
26
+ let app = appPath(p.path, blobs);
27
+ let row = known.get(ids[i]);
28
+ let file = comp(row, 'file');
29
+ if (!app || file.path != p.path || file.root != repository || comp(row, 'module').blob != blobs.get(p.path)) return {
30
+ app
31
+ };
32
+ let symbol = comp(known.get(symbols[i]), 'symbol');
33
+ return {
34
+ app,
35
+ module: ids[i],
36
+ ...symbol.module == ids[i] && symbol.name == p.function && [
37
+ 'function',
38
+ 'variable',
39
+ 'class'
40
+ ].includes(String(symbol.kind)) && typeof symbol.line == 'number' && symbol.line > 0 && (p.line == null || symbol.line <= p.line) ? {
41
+ symbol: symbols[i]
42
+ } : {}
43
+ };
44
+ });
45
+ };
46
+ //# sourceMappingURL=frames.js.map
package/frames.js.map ADDED
@@ -0,0 +1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I,IAAI,KAAK,IAAI,IAAI,cAC5C,KAAK,KAAK,UAAU,IAAI,IAAI,MAAM,GAAG,CAAC,EAAE,IAAI,GAC5C,OAAO;MAAE;IAAI;IACf,IAAI,SAAS,KAAK,MAAM,GAAG,CAAC,OAAO,CAAC,EAAE,GAAG;IACzC,OAAO;MACL;MACA,QAAQ,GAAG,CAAC,EAAE;MACd,GAAG,OAAO,MAAM,IAAI,GAAG,CAAC,EAAE,IAAI,OAAO,IAAI,IAAI,EAAE,QAAQ,IACnD;QAAC;QAAY;QAAY;OAAQ,CAAC,QAAQ,CAAC,OAAO,OAAO,IAAI,MAC7D,OAAO,OAAO,IAAI,IAAI,YAAY,OAAO,IAAI,GAAG,KAChD,CAAC,EAAE,IAAI,IAAI,QAAQ,OAAO,IAAI,IAAI,EAAE,IAAI,IACxC;QAAE,QAAQ,OAAO,CAAC,EAAE;MAAC,IACrB,CAAC,CAAC;IACR;EACF;AACF,EAAC"}
package/frames.ts ADDED
@@ -0,0 +1,54 @@
1
+ // Resolve places against the catalog only when its bytes match the failing
2
+ // commit. One catalog read keeps a module and its exports in the same snapshot.
3
+
4
+ import type { Bundle, Comp } from 'jsr:@yaks/graph@0.2.36'
5
+ import { identityEid } from '@yaks/graph/identity'
6
+ import { fileOf } from '@yaks/file'
7
+
8
+ export type Place = { path: string; function?: string; line?: number }
9
+ export type Catalog = { get: (ids: string[]) => Promise<Bundle[]> }
10
+ export type Resolved = { app: boolean; module?: string; symbol?: string }
11
+ let comp = (row: Bundle | undefined, name: string): Comp =>
12
+ row?.[name] && typeof row[name] == 'object' ? row[name] as Comp : {}
13
+ let appPath = (path: string, blobs: Map<string, string>) =>
14
+ blobs.has(path) && !/(^|\/)(vendor|node_modules)\//.test(path)
15
+
16
+ export let resolveFrames = async (
17
+ catalog: Catalog,
18
+ repository: string,
19
+ blobs: Map<string, string>,
20
+ places: Place[],
21
+ ): Promise<Resolved[]> => {
22
+ let ids = places.map((p) => fileOf(repository, p.path))
23
+ let symbols = places.map((p, i) =>
24
+ p.function ? identityEid('symbol', [ids[i], p.function]) : ''
25
+ )
26
+ let requested = places.flatMap((p, i) =>
27
+ appPath(p.path, blobs) ? [ids[i], ...symbols[i] ? [symbols[i]] : []] : []
28
+ )
29
+ let known = new Map(
30
+ (requested.length ? await catalog.get([...new Set(requested)]) : []).map((
31
+ row,
32
+ ) => [row.entity.eid, row]),
33
+ )
34
+ return places.map((p, i) => {
35
+ let app = appPath(p.path, blobs)
36
+ let row = known.get(ids[i])
37
+ let file = comp(row, 'file')
38
+ if (
39
+ !app || file.path != p.path || file.root != repository ||
40
+ comp(row, 'module').blob != blobs.get(p.path)
41
+ ) return { app }
42
+ let symbol = comp(known.get(symbols[i]), 'symbol')
43
+ return {
44
+ app,
45
+ module: ids[i],
46
+ ...symbol.module == ids[i] && symbol.name == p.function &&
47
+ ['function', 'variable', 'class'].includes(String(symbol.kind)) &&
48
+ typeof symbol.line == 'number' && symbol.line > 0 &&
49
+ (p.line == null || symbol.line <= p.line)
50
+ ? { symbol: symbols[i] }
51
+ : {},
52
+ }
53
+ })
54
+ }
package/mod.js ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * @yaks/code — a codebase, read into a graph.
3
+ *
4
+ * A package per manifest, a module per file, a symbol per export, and an
5
+ * `imports` link per import, each with its text in `doc`, so full-text and
6
+ * vector search find code by what its comments say. A module wears the
7
+ * @yaks/git `file` it was read from, a symbol names its module, and every id
8
+ * is derived from those declared identities, so reading the same tree twice
9
+ * writes one set of entities.
10
+ *
11
+ * ```ts
12
+ * import { codeSync } from '@yaks/code'
13
+ *
14
+ * // await codeSync(graph, '/home/me/project')
15
+ * // '/home/me/project: read 1204 files (6142 exports, …) in 21000 ms.'
16
+ * ```
17
+ *
18
+ * The reading is a read-only @yaks/mirror binding: the files own the code,
19
+ * and a file is read again only when its Git blob moved.
20
+ *
21
+ * @module
22
+ */ export * from "./read.js";
23
+ export * from "./sync.js";
24
+ export * from "./tools.js";
25
+ export * from "./vocab.js";
26
+ //# sourceMappingURL=mod.js.map
package/mod.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.js","sources":["./mod.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;CAqBC,GAED,0BAAyB;AACzB,0BAAyB;AACzB,2BAA0B;AAC1B,2BAA0B"}
package/mod.ts ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * @yaks/code — a codebase, read into a graph.
3
+ *
4
+ * A package per manifest, a module per file, a symbol per export, and an
5
+ * `imports` link per import, each with its text in `doc`, so full-text and
6
+ * vector search find code by what its comments say. A module wears the
7
+ * @yaks/git `file` it was read from, a symbol names its module, and every id
8
+ * is derived from those declared identities, so reading the same tree twice
9
+ * writes one set of entities.
10
+ *
11
+ * ```ts
12
+ * import { codeSync } from '@yaks/code'
13
+ *
14
+ * // await codeSync(graph, '/home/me/project')
15
+ * // '/home/me/project: read 1204 files (6142 exports, …) in 21000 ms.'
16
+ * ```
17
+ *
18
+ * The reading is a read-only @yaks/mirror binding: the files own the code,
19
+ * and a file is read again only when its Git blob moved.
20
+ *
21
+ * @module
22
+ */
23
+
24
+ export * from './read.js'
25
+ export * from './sync.js'
26
+ export * from './tools.js'
27
+ export * from './vocab.js'
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@yaks/code",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.36",
4
+ "homepage": "https://jsr.io/@yaks/code",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./_dist/mod.d.ts",
9
+ "default": "./mod.js"
10
+ },
11
+ "./vocab": {
12
+ "types": "./_dist/vocab.d.ts",
13
+ "default": "./vocab.js"
14
+ },
15
+ "./tools": {
16
+ "types": "./_dist/tools.d.ts",
17
+ "default": "./tools.js"
18
+ },
19
+ "./effects": {
20
+ "types": "./_dist/effects.d.ts",
21
+ "default": "./effects.js"
22
+ },
23
+ "./described": {
24
+ "types": "./_dist/described.d.ts",
25
+ "default": "./described.js"
26
+ },
27
+ "./anatomy": {
28
+ "types": "./_dist/anatomy.d.ts",
29
+ "default": "./anatomy.js"
30
+ },
31
+ "./source": {
32
+ "types": "./_dist/source.d.ts",
33
+ "default": "./source.js"
34
+ },
35
+ "./frames": {
36
+ "types": "./_dist/frames.d.ts",
37
+ "default": "./frames.js"
38
+ }
39
+ },
40
+ "license": "Apache-2.0",
41
+ "dependencies": {
42
+ "@yaks/edge": "0.2.36",
43
+ "@yaks/effects": "0.2.36",
44
+ "@yaks/file": "0.2.36",
45
+ "@yaks/git": "0.2.36",
46
+ "@yaks/graph": "0.2.36",
47
+ "@yaks/mirror": "0.2.36",
48
+ "@yaks/process": "0.2.36",
49
+ "@yaks/query": "0.2.36",
50
+ "@yaks/tools": "0.2.36",
51
+ "@yaks/vocab": "0.2.36",
52
+ "@yaks/yaml": "0.2.36"
53
+ },
54
+ "description": "Reads a codebase into a graph: packages, modules, exported symbols and imports, with their doc comments as searchable text, synced incrementally by Git blob.",
55
+ "repository": "https://github.com/yak-sh/yak.git"
56
+ }
package/read.js ADDED
@@ -0,0 +1,178 @@
1
+ // What a file says about itself, read from its text: the opening comment that
2
+ // says what the file is for, the modules it imports, the title and body of a
3
+ // markdown document, and the exports `deno doc --json` found in it.
4
+ //
5
+ // Everything here is a pure function of text (or of `deno doc`'s JSON), so it
6
+ // runs anywhere and tests without a checkout. ./sync.ts does the reading from
7
+ // disk and the writing to the graph.
8
+ //
9
+ // The opening comment is read here rather than taken from `deno doc`, because
10
+ // `deno doc` only keeps a `/** */` block tagged as the module's, and most files
11
+ // in this repository open with a `//` paragraph instead.
12
+ import { front } from "@yaks/yaml";
13
+ /** Is this a file whose exports `deno doc` can read? */ export let isCode = (path)=>/\.(ts|tsx|js|mjs)$/.test(path);
14
+ /** Is this a markdown document? */ export let isMarkdown = (path)=>path.endsWith('.md');
15
+ // Lines that open a file without saying anything about it: a shebang, a
16
+ // tool's directive, a triple-slash reference.
17
+ let directive = /^(#!|\/\/\/\s*<|\/\/\s*(deno-|@ts-|eslint|prettier))/;
18
+ /**
19
+ * A file's opening comment, as prose: a leading `/** *\/` or `/* *\/` block,
20
+ * or the run of `//` lines the file starts with. Blank comment lines keep the
21
+ * paragraphs apart; the first line of code ends it.
22
+ *
23
+ * ```ts
24
+ * header('// Owns the store.\n//\n// Nothing else.\nlet x = 1')
25
+ * // 'Owns the store.\n\nNothing else.'
26
+ * ```
27
+ */ export let header = (text)=>{
28
+ let lines = text.split('\n');
29
+ let i = 0;
30
+ while(i < lines.length && (!lines[i].trim() || directive.test(lines[i])))i++;
31
+ let first = lines[i]?.trim() ?? '';
32
+ let out = [];
33
+ if (first.startsWith('/*')) {
34
+ for(; i < lines.length; i++){
35
+ let line = lines[i].trim();
36
+ let end = line.includes('*/');
37
+ line = line.replace(/^\/\*\*?/, '').replace(/\*\/.*$/, '').replace(/^\*\s?/, '');
38
+ out.push(line);
39
+ if (end) break;
40
+ }
41
+ } else {
42
+ for(; i < lines.length; i++){
43
+ let line = lines[i].trim();
44
+ if (!line.startsWith('//')) break;
45
+ if (directive.test(line)) continue;
46
+ out.push(line.replace(/^\/\/\s?/, ''));
47
+ }
48
+ }
49
+ return out.join('\n').replace(/^\s*@module\s*$/m, '').trim();
50
+ };
51
+ // An import or re-export statement at the start of a line, so a statement
52
+ // quoted inside a doc comment (` * import { x } from 'y'`) is never read as
53
+ // one: `import x from`, `import * as x from`, `import { a, b } from`,
54
+ // `export * from`, `export { a } from`, `export type { a } from`.
55
+ let statement = /^(?:import|export)\s+(?:type\s+)?(?:[\w$]+\s*,?\s*)?(?:\*(?:\s+as\s+[\w$]+)?\s*)?(?:\{[^}]*\}\s*)?from\s*['"]([^'"\n]+)['"]/gm;
56
+ let bare = /^import\s*['"]([^'"\n]+)['"]/gm;
57
+ /**
58
+ * The specifiers a module imports or re-exports, in the order it names them,
59
+ * each once.
60
+ *
61
+ * ```ts
62
+ * specifiers("import { a } from './a.ts'\nexport * from '@yaks/git'")
63
+ * // ['./a.ts', '@yaks/git']
64
+ * ```
65
+ */ export let specifiers = (text)=>[
66
+ ...new Set([
67
+ ...text.matchAll(statement),
68
+ ...text.matchAll(bare)
69
+ ].sort((a, b)=>a.index - b.index).map((m)=>m[1]))
70
+ ];
71
+ /** Whether a path is a package's manifest: a `package.json`. */ export let manifests = (path)=>/(^|\/)package\.json$/.test(path);
72
+ /** A `package.json`'s package, or nothing when it has no name or is a
73
+ * workspace's root rather than a package. */ export let manifest = (path, text)=>{
74
+ let json;
75
+ try {
76
+ json = JSON.parse(text);
77
+ } catch {
78
+ return undefined;
79
+ }
80
+ if (typeof json.name != 'string' || !json.name) return undefined;
81
+ if (json.workspaces) return undefined;
82
+ let dir = path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '';
83
+ let ex = json.exports;
84
+ let exports = typeof ex == 'string' ? {
85
+ '.': ex
86
+ } : ex && typeof ex == 'object' ? ex : {};
87
+ return {
88
+ path,
89
+ dir,
90
+ name: json.name,
91
+ ...typeof json.version == 'string' ? {
92
+ version: json.version
93
+ } : {},
94
+ ...typeof json.description == 'string' ? {
95
+ description: json.description
96
+ } : {},
97
+ exports
98
+ };
99
+ };
100
+ /** The package a path belongs to: the manifest in its nearest directory. */ export let owner = (path, pkgs)=>pkgs.filter((p)=>!p.dir || path.startsWith(p.dir + '/')).sort((a, b)=>b.dir.length - a.dir.length)[0];
101
+ let join = (dir, rel)=>{
102
+ let parts = dir ? dir.split('/') : [];
103
+ for (let part of rel.split('/')){
104
+ if (part == '..') parts.pop();
105
+ else if (part && part != '.') parts.push(part);
106
+ }
107
+ return parts.join('/');
108
+ };
109
+ let within = (dir, file)=>join(dir, file.replace(/^\.\//, ''));
110
+ /**
111
+ * The repository path a specifier names, from the module at `from`: a relative
112
+ * path, or a package of this repository by its published name and subpath.
113
+ * Anything else — a registry, a URL, a package from elsewhere — names no file
114
+ * here and resolves to nothing.
115
+ *
116
+ * ```ts
117
+ * import { assertEquals } from '@std/assert'
118
+ *
119
+ * let git = {
120
+ * path: 'packages/git/package.json',
121
+ * dir: 'packages/git',
122
+ * name: '@yaks/git',
123
+ * exports: { './cites': './cites.ts' },
124
+ * }
125
+ * assertEquals(resolve('./b.ts', 'src/a.ts', []), 'src/b.ts')
126
+ * assertEquals(
127
+ * resolve('@yaks/git/cites', 'src/a.ts', [git]),
128
+ * 'packages/git/cites.ts',
129
+ * )
130
+ * ```
131
+ */ export let resolve = (spec, from, pkgs)=>{
132
+ if (spec.startsWith('.')) {
133
+ return join(from.slice(0, Math.max(0, from.lastIndexOf('/'))), spec);
134
+ }
135
+ for (let p of pkgs){
136
+ if (spec != p.name && !spec.startsWith(p.name + '/')) continue;
137
+ let sub = '.' + spec.slice(p.name.length);
138
+ let file = p.exports[sub];
139
+ return file ? within(p.dir, file) : undefined;
140
+ }
141
+ return undefined;
142
+ };
143
+ /** A markdown document's title and body: the frontmatter's `doc.title` or
144
+ * the first `#` heading, else the file's name; the body after frontmatter. */ export let markdown = (path, text)=>{
145
+ let body = text;
146
+ let said;
147
+ try {
148
+ let got = front(text, path);
149
+ body = got.body;
150
+ said = got.meta.doc?.title;
151
+ } catch {}
152
+ let heading = body.match(/^#\s+(.+)$/m)?.[1]?.trim();
153
+ let title = typeof said == 'string' && said ? said : heading;
154
+ return {
155
+ title: title || path.slice(path.lastIndexOf('/') + 1),
156
+ body
157
+ };
158
+ };
159
+ /**
160
+ * The exports a module declares itself, from `deno doc --json` output: a
161
+ * re-export belongs to the module that declares it, and an overloaded name
162
+ * is one export at its first declaration. Deno locations are zero-based;
163
+ * symbol lines are one-based.
164
+ */ export let exportsOf = (nodes, url)=>{
165
+ let out = [];
166
+ for (let s of nodes[url]?.symbols ?? []){
167
+ let d = s.declarations?.find((d)=>d.declarationKind == 'export' && d.kind != 'reference' && d.location.filename == url);
168
+ if (!d || out.some((e)=>e.name == s.name)) continue;
169
+ out.push({
170
+ name: s.name,
171
+ kind: d.kind,
172
+ line: d.location.line + 1,
173
+ doc: d.jsDoc?.doc?.trim() ?? ''
174
+ });
175
+ }
176
+ return out;
177
+ };
178
+ //# sourceMappingURL=read.js.map
package/read.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read.js","sources":["./read.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,6EAA6E;AAC7E,oEAAoE;AACpE,EAAE;AACF,8EAA8E;AAC9E,8EAA8E;AAC9E,qCAAqC;AACrC,EAAE;AACF,8EAA8E;AAC9E,gFAAgF;AAChF,yDAAyD;AAEzD,SAAS,KAAK,0BAA+B;AAE7C,sDAAsD,GACtD,OAAO,IAAI,SAAS,CAAC,OAA0B,qBAAqB,IAAI,CAAC,MAAK;AAE9E,iCAAiC,GACjC,OAAO,IAAI,aAAa,CAAC,OAA0B,KAAK,QAAQ,CAAC,OAAM;AAEvE,wEAAwE;AACxE,8CAA8C;AAC9C,IAAI,YAAY;AAEhB;;;;;;;;;CASC,GACD,OAAO,IAAI,SAAS,CAAC;EACnB,IAAI,QAAQ,KAAK,KAAK,CAAC;EACvB,IAAI,IAAI;EACR,MAAO,IAAI,MAAM,MAAM,IAAI,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC,IAAI,MAAM,UAAU,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,EAAG;EAC3E,IAAI,QAAQ,KAAK,CAAC,EAAE,EAAE,UAAU;EAChC,IAAI,MAAgB,EAAE;EACtB,IAAI,MAAM,UAAU,CAAC,OAAO;IAC1B,MAAO,IAAI,MAAM,MAAM,EAAE,IAAK;MAC5B,IAAI,OAAO,KAAK,CAAC,EAAE,CAAC,IAAI;MACxB,IAAI,MAAM,KAAK,QAAQ,CAAC;MACxB,OAAO,KAAK,OAAO,CAAC,YAAY,IAAI,OAAO,CAAC,WAAW,IACpD,OAAO,CAAC,UAAU;MACrB,IAAI,IAAI,CAAC;MACT,IAAI,KAAK;IACX;EACF,OAAO;IACL,MAAO,IAAI,MAAM,MAAM,EAAE,IAAK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AO,EAAE,GAAG,EAAE,QAAQ;EACtC;EACA,OAAO;AACT,EAAC;AAED;4EAC4E,GAC5E,OAAO,IAAI,WAAW,CACpB,MACA;EAEA,IAAI,OAAO;EACX,IAAI;EACJ,IAAI;IACF,IAAI,MAAM,MAAM,MAAM;IACtB,OAAO,IAAI,IAAI;IACf,OAAQ,IAAI,IAAI,CAAC,GAAG,EAAsC;EAC5D,EAAE,OAAM,CAAgD;EACxD,IAAI,UAAU,KAAK,KAAK,CAAC,gBAAgB,CAAC,EAAE,EAAE;EAC9C,IAAI,QAAQ,OAAO,QAAQ,YAAY,OAAO,OAAO;EACrD,OAAO;IAAE,OAAO,SAAS,KAAK,KAAK,CAAC,KAAK,WAAW,CAAC,OAAO;IAAI;EAAK;AACvE,EAAC;AAkBD;;;;;CAKC,GACD,OAAO,IAAI,YAAY,CACrB,OACA;EAEA,IAAI,MAAgB,EAAE;EACtB,KAAK,IAAI,KAAK,KAAK,CAAC,IAAI,EAAE,WAAW,EAAE,CAAE;IACvC,IAAI,IAAI,EAAE,YAAY,EAAE,KAAK,CAAC,IAC5B,EAAE,eAAe,IAAI,YAAY,EAAE,IAAI,IAAI,eAC3C,EAAE,QAAQ,CAAC,QAAQ,IAAI;IAEzB,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC,IAAM,EAAE,IAAI,IAAI,EAAE,IAAI,GAAG;IAC7C,IAAI,IAAI,CAAC;MACP,MAAM,EAAE,IAAI;MACZ,MAAM,EAAE,IAAI;MACZ,MAAM,EAAE,QAAQ,CAAC,IAAI,GAAG;MACxB,KAAK,EAAE,KAAK,EAAE,KAAK,UAAU;IAC/B;EACF;EACA,OAAO;AACT,EAAC"}
package/read.ts ADDED
@@ -0,0 +1,249 @@
1
+ // What a file says about itself, read from its text: the opening comment that
2
+ // says what the file is for, the modules it imports, the title and body of a
3
+ // markdown document, and the exports `deno doc --json` found in it.
4
+ //
5
+ // Everything here is a pure function of text (or of `deno doc`'s JSON), so it
6
+ // runs anywhere and tests without a checkout. ./sync.ts does the reading from
7
+ // disk and the writing to the graph.
8
+ //
9
+ // The opening comment is read here rather than taken from `deno doc`, because
10
+ // `deno doc` only keeps a `/** */` block tagged as the module's, and most files
11
+ // in this repository open with a `//` paragraph instead.
12
+
13
+ import { front } from '@yaks/yaml'
14
+
15
+ /** Is this a file whose exports `deno doc` can read? */
16
+ export let isCode = (path: string): boolean => /\.(ts|tsx|js|mjs)$/.test(path)
17
+
18
+ /** Is this a markdown document? */
19
+ export let isMarkdown = (path: string): boolean => path.endsWith('.md')
20
+
21
+ // Lines that open a file without saying anything about it: a shebang, a
22
+ // tool's directive, a triple-slash reference.
23
+ let directive = /^(#!|\/\/\/\s*<|\/\/\s*(deno-|@ts-|eslint|prettier))/
24
+
25
+ /**
26
+ * A file's opening comment, as prose: a leading `/** *\/` or `/* *\/` block,
27
+ * or the run of `//` lines the file starts with. Blank comment lines keep the
28
+ * paragraphs apart; the first line of code ends it.
29
+ *
30
+ * ```ts
31
+ * header('// Owns the store.\n//\n// Nothing else.\nlet x = 1')
32
+ * // 'Owns the store.\n\nNothing else.'
33
+ * ```
34
+ */
35
+ export let header = (text: string): string => {
36
+ let lines = text.split('\n')
37
+ let i = 0
38
+ while (i < lines.length && (!lines[i].trim() || directive.test(lines[i]))) i++
39
+ let first = lines[i]?.trim() ?? ''
40
+ let out: string[] = []
41
+ if (first.startsWith('/*')) {
42
+ for (; i < lines.length; i++) {
43
+ let line = lines[i].trim()
44
+ let end = line.includes('*/')
45
+ line = line.replace(/^\/\*\*?/, '').replace(/\*\/.*$/, '')
46
+ .replace(/^\*\s?/, '')
47
+ out.push(line)
48
+ if (end) break
49
+ }
50
+ } else {
51
+ for (; i < lines.length; i++) {
52
+ let line = lines[i].trim()
53
+ if (!line.startsWith('//')) break
54
+ if (directive.test(line)) continue
55
+ out.push(line.replace(/^\/\/\s?/, ''))
56
+ }
57
+ }
58
+ return out.join('\n').replace(/^\s*@module\s*$/m, '').trim()
59
+ }
60
+
61
+ // An import or re-export statement at the start of a line, so a statement
62
+ // quoted inside a doc comment (` * import { x } from 'y'`) is never read as
63
+ // one: `import x from`, `import * as x from`, `import { a, b } from`,
64
+ // `export * from`, `export { a } from`, `export type { a } from`.
65
+ let statement =
66
+ /^(?:import|export)\s+(?:type\s+)?(?:[\w$]+\s*,?\s*)?(?:\*(?:\s+as\s+[\w$]+)?\s*)?(?:\{[^}]*\}\s*)?from\s*['"]([^'"\n]+)['"]/gm
67
+ let bare = /^import\s*['"]([^'"\n]+)['"]/gm
68
+
69
+ /**
70
+ * The specifiers a module imports or re-exports, in the order it names them,
71
+ * each once.
72
+ *
73
+ * ```ts
74
+ * specifiers("import { a } from './a.ts'\nexport * from '@yaks/git'")
75
+ * // ['./a.ts', '@yaks/git']
76
+ * ```
77
+ */
78
+ export let specifiers = (text: string): string[] => [
79
+ ...new Set(
80
+ [...text.matchAll(statement), ...text.matchAll(bare)]
81
+ .sort((a, b) => a.index - b.index).map((m) => m[1]),
82
+ ),
83
+ ]
84
+
85
+ /** A package as its manifest describes it: where it is and what it exports. */
86
+ export type Manifest = {
87
+ /** the manifest's own path */
88
+ path: string
89
+ /** the directory it governs, `''` for the repository root */
90
+ dir: string
91
+ name: string
92
+ version?: string
93
+ description?: string
94
+ /** subpath → file, relative to `dir` */
95
+ exports: Record<string, string>
96
+ }
97
+
98
+ /** Whether a path is a package's manifest: a `package.json`. */
99
+ export let manifests = (path: string): boolean =>
100
+ /(^|\/)package\.json$/.test(path)
101
+
102
+ /** A `package.json`'s package, or nothing when it has no name or is a
103
+ * workspace's root rather than a package. */
104
+ export let manifest = (path: string, text: string): Manifest | undefined => {
105
+ let json: Record<string, unknown>
106
+ try {
107
+ json = JSON.parse(text)
108
+ } catch {
109
+ return undefined
110
+ }
111
+ if (typeof json.name != 'string' || !json.name) return undefined
112
+ if (json.workspaces) return undefined
113
+ let dir = path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : ''
114
+ let ex = json.exports
115
+ let exports = typeof ex == 'string'
116
+ ? { '.': ex }
117
+ : ex && typeof ex == 'object'
118
+ ? ex as Record<string, string>
119
+ : {}
120
+ return {
121
+ path,
122
+ dir,
123
+ name: json.name,
124
+ ...(typeof json.version == 'string' ? { version: json.version } : {}),
125
+ ...(typeof json.description == 'string'
126
+ ? { description: json.description }
127
+ : {}),
128
+ exports,
129
+ }
130
+ }
131
+
132
+ /** The package a path belongs to: the manifest in its nearest directory. */
133
+ export let owner = (
134
+ path: string,
135
+ pkgs: Manifest[],
136
+ ): Manifest | undefined =>
137
+ pkgs.filter((p) => !p.dir || path.startsWith(p.dir + '/'))
138
+ .sort((a, b) => b.dir.length - a.dir.length)[0]
139
+
140
+ let join = (dir: string, rel: string): string => {
141
+ let parts = dir ? dir.split('/') : []
142
+ for (let part of rel.split('/')) {
143
+ if (part == '..') parts.pop()
144
+ else if (part && part != '.') parts.push(part)
145
+ }
146
+ return parts.join('/')
147
+ }
148
+
149
+ let within = (dir: string, file: string) => join(dir, file.replace(/^\.\//, ''))
150
+
151
+ /**
152
+ * The repository path a specifier names, from the module at `from`: a relative
153
+ * path, or a package of this repository by its published name and subpath.
154
+ * Anything else — a registry, a URL, a package from elsewhere — names no file
155
+ * here and resolves to nothing.
156
+ *
157
+ * ```ts
158
+ * import { assertEquals } from '@std/assert'
159
+ *
160
+ * let git = {
161
+ * path: 'packages/git/package.json',
162
+ * dir: 'packages/git',
163
+ * name: '@yaks/git',
164
+ * exports: { './cites': './cites.ts' },
165
+ * }
166
+ * assertEquals(resolve('./b.ts', 'src/a.ts', []), 'src/b.ts')
167
+ * assertEquals(
168
+ * resolve('@yaks/git/cites', 'src/a.ts', [git]),
169
+ * 'packages/git/cites.ts',
170
+ * )
171
+ * ```
172
+ */
173
+ export let resolve = (
174
+ spec: string,
175
+ from: string,
176
+ pkgs: Manifest[],
177
+ ): string | undefined => {
178
+ if (spec.startsWith('.')) {
179
+ return join(from.slice(0, Math.max(0, from.lastIndexOf('/'))), spec)
180
+ }
181
+ for (let p of pkgs) {
182
+ if (spec != p.name && !spec.startsWith(p.name + '/')) continue
183
+ let sub = '.' + spec.slice(p.name.length)
184
+ let file = p.exports[sub]
185
+ return file ? within(p.dir, file) : undefined
186
+ }
187
+ return undefined
188
+ }
189
+
190
+ /** A markdown document's title and body: the frontmatter's `doc.title` or
191
+ * the first `#` heading, else the file's name; the body after frontmatter. */
192
+ export let markdown = (
193
+ path: string,
194
+ text: string,
195
+ ): { title: string; body: string } => {
196
+ let body = text
197
+ let said: unknown
198
+ try {
199
+ let got = front(text, path)
200
+ body = got.body
201
+ said = (got.meta.doc as { title?: unknown } | undefined)?.title
202
+ } catch { /* frontmatter that does not parse is text */ }
203
+ let heading = body.match(/^#\s+(.+)$/m)?.[1]?.trim()
204
+ let title = typeof said == 'string' && said ? said : heading
205
+ return { title: title || path.slice(path.lastIndexOf('/') + 1), body }
206
+ }
207
+
208
+ /** One export, as `deno doc` describes it. */
209
+ export type Export = { name: string; kind: string; line: number; doc: string }
210
+
211
+ /** One module in `deno doc --json` output, as far as this package reads it. */
212
+ export type DocNode = {
213
+ symbols?: {
214
+ name: string
215
+ declarations?: {
216
+ location: { filename: string; line: number }
217
+ declarationKind: string
218
+ kind: string
219
+ jsDoc?: { doc?: string }
220
+ }[]
221
+ }[]
222
+ }
223
+
224
+ /**
225
+ * The exports a module declares itself, from `deno doc --json` output: a
226
+ * re-export belongs to the module that declares it, and an overloaded name
227
+ * is one export at its first declaration. Deno locations are zero-based;
228
+ * symbol lines are one-based.
229
+ */
230
+ export let exportsOf = (
231
+ nodes: Record<string, DocNode>,
232
+ url: string,
233
+ ): Export[] => {
234
+ let out: Export[] = []
235
+ for (let s of nodes[url]?.symbols ?? []) {
236
+ let d = s.declarations?.find((d) =>
237
+ d.declarationKind == 'export' && d.kind != 'reference' &&
238
+ d.location.filename == url
239
+ )
240
+ if (!d || out.some((e) => e.name == s.name)) continue
241
+ out.push({
242
+ name: s.name,
243
+ kind: d.kind,
244
+ line: d.location.line + 1,
245
+ doc: d.jsDoc?.doc?.trim() ?? '',
246
+ })
247
+ }
248
+ return out
249
+ }