@yaks/testing 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 (93) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +427 -2
  3. package/_dist/assert.d.ts +40 -0
  4. package/_dist/assert.d.ts.map +1 -0
  5. package/_dist/choose.d.ts +39 -0
  6. package/_dist/choose.d.ts.map +1 -0
  7. package/_dist/clock.d.ts +8 -0
  8. package/_dist/clock.d.ts.map +1 -0
  9. package/_dist/deps.d.ts +113 -0
  10. package/_dist/deps.d.ts.map +1 -0
  11. package/_dist/examples.d.ts +69 -0
  12. package/_dist/examples.d.ts.map +1 -0
  13. package/_dist/find.d.ts +23 -0
  14. package/_dist/find.d.ts.map +1 -0
  15. package/_dist/kept.d.ts +27 -0
  16. package/_dist/kept.d.ts.map +1 -0
  17. package/_dist/lend.d.ts +15 -0
  18. package/_dist/lend.d.ts.map +1 -0
  19. package/_dist/main.d.ts +2 -0
  20. package/_dist/main.d.ts.map +1 -0
  21. package/_dist/mod.d.ts +45 -0
  22. package/_dist/mod.d.ts.map +1 -0
  23. package/_dist/names.d.ts +31 -0
  24. package/_dist/names.d.ts.map +1 -0
  25. package/_dist/own.d.ts +25 -0
  26. package/_dist/own.d.ts.map +1 -0
  27. package/_dist/reads.d.ts +8 -0
  28. package/_dist/reads.d.ts.map +1 -0
  29. package/_dist/suite.d.ts +82 -0
  30. package/_dist/suite.d.ts.map +1 -0
  31. package/_dist/typist.d.ts +24 -0
  32. package/_dist/typist.d.ts.map +1 -0
  33. package/_dist/wait.d.ts +21 -0
  34. package/_dist/wait.d.ts.map +1 -0
  35. package/assert.js +114 -0
  36. package/assert.js.map +1 -0
  37. package/assert.ts +143 -0
  38. package/choose.js +197 -0
  39. package/choose.js.map +1 -0
  40. package/choose.ts +327 -0
  41. package/clock.js +45 -0
  42. package/clock.js.map +1 -0
  43. package/clock.ts +60 -0
  44. package/deno.json +1 -0
  45. package/deps.js +868 -0
  46. package/deps.js.map +1 -0
  47. package/deps.ts +1004 -0
  48. package/drive.js +43 -0
  49. package/drive.js.map +1 -0
  50. package/drive.ts +41 -0
  51. package/examples.js +279 -0
  52. package/examples.js.map +1 -0
  53. package/examples.ts +380 -0
  54. package/find.js +86 -0
  55. package/find.js.map +1 -0
  56. package/find.ts +102 -0
  57. package/kept.js +128 -0
  58. package/kept.js.map +1 -0
  59. package/kept.ts +146 -0
  60. package/lend.js +30 -0
  61. package/lend.js.map +1 -0
  62. package/lend.ts +31 -0
  63. package/load.js +106 -0
  64. package/load.js.map +1 -0
  65. package/load.ts +139 -0
  66. package/main.js +214 -0
  67. package/main.js.map +1 -0
  68. package/main.ts +217 -0
  69. package/mod.js +45 -0
  70. package/mod.js.map +1 -0
  71. package/mod.ts +55 -0
  72. package/names.js +209 -0
  73. package/names.js.map +1 -0
  74. package/names.ts +204 -0
  75. package/own.js +109 -0
  76. package/own.js.map +1 -0
  77. package/own.ts +136 -0
  78. package/package.json +56 -4
  79. package/reads.js +88 -0
  80. package/reads.js.map +1 -0
  81. package/reads.ts +98 -0
  82. package/run.js +306 -0
  83. package/run.js.map +1 -0
  84. package/run.ts +405 -0
  85. package/suite.js +191 -0
  86. package/suite.js.map +1 -0
  87. package/suite.ts +224 -0
  88. package/typist.js +74 -0
  89. package/typist.js.map +1 -0
  90. package/typist.ts +79 -0
  91. package/wait.js +34 -0
  92. package/wait.js.map +1 -0
  93. package/wait.ts +60 -0
package/names.js ADDED
@@ -0,0 +1,209 @@
1
+ // Which files name what a change edits: a test importing `fields` from
2
+ // @yaks/fts checks `fields`, where a kernel test reaching the same module
3
+ // through the platform it composes merely loads it. The module graph ranks
4
+ // both alike; the names a file imports, followed through the modules
5
+ // re-exporting them and the declarations saying them, tell the first apart.
6
+ // A change's edits are named by the top-level declaration holding each edited
7
+ // line (`declared`).
8
+ import { location } from "./deps.js";
9
+ // What opens a top-level declaration, and the name it gives.
10
+ let DECLARED = /^(?:export\s+)?(?:default\s+)?(?:declare\s+)?(?:async\s+)?(?:let|const|var|function\*?|class|enum|type|interface)\s+([\w$]+)/;
11
+ // A line going on with what an earlier line opened.
12
+ let GOING_ON = /^[)\]}]/;
13
+ /// let src = ['import { x } from "./x.ts"', '', 'export let a = (', ' n: number,', '): number => {', ' return n', '}', 'let b = 2']
14
+ /// declared(src.join('\n')) -> [undefined, undefined, 'a', 'a', 'a', 'a', 'a', 'b']
15
+ /// declared('let c = [\n 1,\n]\nf(c)') -> ['c', 'c', 'c', undefined]
16
+ /** The top-level declaration each line of formatted source belongs to, by
17
+ * the nearest line above it at no indentation that opens one; none for an
18
+ * import or other top-level code. */ export let declared = (text)=>{
19
+ let at;
20
+ return text.split('\n').map((l)=>{
21
+ if (l && !/^\s/.test(l) && !GOING_ON.test(l)) at = DECLARED.exec(l)?.[1];
22
+ return at;
23
+ });
24
+ };
25
+ let STATEMENT = /^(import|export)\s+(type\s+)?(?:\*\s+as\s+([\w$]+)|(\*)|\{([^}]*)\})\s*from\s*['"]([^'"]+)['"]/gm;
26
+ // A module loaded once the stage is set: `let { a, b: c } = await
27
+ // import('./m.ts')`, or the whole of it under one name.
28
+ let LOADED = /(?:let|const|var)\s+(?:([\w$]+)|\{([^}]*)\})\s*=\s*await\s+import\(\s*['"]([^'"]+)['"]\s*,?\s*\)/gm;
29
+ /// imported("import { a, b as c, type T } from './m.ts'") -> [{ from: './m.ts', names: [['a', 'a'], ['b', 'c']] }]
30
+ /// imported("import type { T } from './m.ts'") -> []
31
+ /// imported("import * as m from '@yaks/m'") -> [{ from: '@yaks/m', names: [], as: 'm' }]
32
+ /// imported("export * from './f.ts'\nexport { g as h } from './g.ts'") -> [{ from: './f.ts', names: [], all: true, exported: true }, { from: './g.ts', names: [['g', 'h']], exported: true }]
33
+ /// imported('import {\n a,\n b,\n} from "x"') -> [{ from: 'x', names: [['a', 'a'], ['b', 'b']] }]
34
+ /// imported("let { a, b: c } = await import('./m.ts')") -> [{ from: './m.ts', names: [['a', 'a'], ['b', 'c']] }]
35
+ /// imported('let m = await import(\n "./m.ts",\n)') -> [{ from: './m.ts', names: [], as: 'm' }]
36
+ /** The values a module imports and re-exports by a specifier, but types,
37
+ * and those it loads with `await import`, as a test that must set its stage
38
+ * first does. */ export let imported = (text)=>[
39
+ ...[
40
+ ...text.matchAll(STATEMENT)
41
+ ].flatMap(([, verb, type, as, star, list, from])=>{
42
+ if (type) return [];
43
+ let exported = verb == 'export' ? {
44
+ exported: true
45
+ } : {};
46
+ if (as) return [
47
+ {
48
+ from,
49
+ names: [],
50
+ as,
51
+ ...exported
52
+ }
53
+ ];
54
+ if (star) return [
55
+ {
56
+ from,
57
+ names: [],
58
+ all: true,
59
+ ...exported
60
+ }
61
+ ];
62
+ let names = list.split(',').map((n)=>n.trim()).filter((n)=>n && !n.startsWith('type ')).map((n)=>n.split(/\s+as\s+/)).map(([n, k])=>[
63
+ n,
64
+ k ?? n
65
+ ]);
66
+ return [
67
+ {
68
+ from,
69
+ names,
70
+ ...exported
71
+ }
72
+ ];
73
+ }),
74
+ ...[
75
+ ...text.matchAll(LOADED)
76
+ ].map(([, as, list, from])=>as ? {
77
+ from,
78
+ names: [],
79
+ as
80
+ } : {
81
+ from,
82
+ names: list.split(',').map((n)=>n.trim()).filter(Boolean).map((n)=>n.split(/\s*:\s*/)).map(([n, k])=>[
83
+ n,
84
+ k ?? n
85
+ ])
86
+ })
87
+ ];
88
+ /** How many public declarations can relay an edited name. Re-exports and
89
+ * references inside private declarations keep the same distance. */ export const STEPS = 2;
90
+ /**
91
+ * Of `files`, how near each is to what a change `edited` (each module's
92
+ * declarations, by checkout path, `*` for its top-level code): 0 for a file
93
+ * importing an edited declaration by name, directly or from a module
94
+ * re-exporting it, or reading it off the whole module (`m.fields`), and for
95
+ * one directly importing a module whose top-level code is edited. A public
96
+ * declaration that uses edited code adds a step, even inside the same
97
+ * module, as does a re-export of a module with edited top-level code; and so on
98
+ * to `steps`. A file naming none is left out. Each file is read for the root it stands for
99
+ * (`root`, an example page's plan module), and modules as `info` resolved
100
+ * them.
101
+ */ export let naming = (info, files, edited, read, root = (f)=>f, steps = STEPS)=>{
102
+ let { url, rel } = location();
103
+ // What each module's specifiers resolve to, and who imports each module.
104
+ let resolved = new Map();
105
+ let importers = new Map();
106
+ for (let m of info.modules){
107
+ let to = new Map();
108
+ for (let d of m.dependencies ?? []){
109
+ let at = d.code?.specifier ?? d.type?.specifier;
110
+ if (!d.specifier || !at) continue;
111
+ to.set(d.specifier, at);
112
+ (importers.get(at) ?? importers.set(at, []).get(at)).push(m.specifier);
113
+ }
114
+ resolved.set(m.specifier, to);
115
+ }
116
+ let texts = new Map();
117
+ let text = (module)=>{
118
+ if (!texts.has(module)) texts.set(module, read(rel(module)) ?? '');
119
+ return texts.get(module);
120
+ };
121
+ let parsed = new Map();
122
+ let of = (module)=>{
123
+ if (!parsed.has(module)) parsed.set(module, imported(text(module)));
124
+ return parsed.get(module);
125
+ };
126
+ let exported = new Map();
127
+ let publicName = (module, name)=>{
128
+ if (!exported.has(module)) {
129
+ let lines = text(module).split('\n').filter((l)=>l.startsWith('export '));
130
+ exported.set(module, new Set(lines.flatMap((l)=>DECLARED.exec(l)?.[1] ?? [])));
131
+ }
132
+ return exported.get(module).has(name);
133
+ };
134
+ // The declarations of a module whose lines say `word`.
135
+ let owners = new Map();
136
+ let saying = (module, word)=>{
137
+ if (!owners.has(module)) owners.set(module, declared(text(module)));
138
+ let of = owners.get(module), said = new Set();
139
+ let re = new RegExp(`(?<![\\w$.])${word.replace(/[$.]/g, '\\$&')}(?![\\w$])`);
140
+ text(module).split('\n').forEach((l, i)=>{
141
+ if (of[i] && re.test(l)) said.add(of[i]);
142
+ });
143
+ return said;
144
+ };
145
+ let roots = new Map(files.map((f)=>[
146
+ url(root(f)),
147
+ f
148
+ ]));
149
+ let near = new Map();
150
+ let seen = new Map();
151
+ // Revisit a declaration only when reached by a shorter path.
152
+ let go = Object.entries(edited).flatMap(([m, names])=>names.map((n)=>({
153
+ m: url(m),
154
+ n,
155
+ step: 0
156
+ })));
157
+ for(let at = 0; at < go.length; at++){
158
+ let { m, n, step } = go[at];
159
+ if ((seen.get(`${m}#${n}`) ?? Infinity) <= step) continue;
160
+ seen.set(`${m}#${n}`, step);
161
+ let next = (module, word)=>{
162
+ for (let d of saying(module, word)){
163
+ if (d == n && module == m) continue;
164
+ let distance = step + Number(publicName(module, d));
165
+ if (distance <= steps) go.push({
166
+ m: module,
167
+ n: d,
168
+ step: distance
169
+ });
170
+ }
171
+ };
172
+ if (n != '*') next(m, n);
173
+ for (let e of importers.get(m) ?? []){
174
+ for (let i of of(e)){
175
+ if (resolved.get(e)?.get(i.from) != m) continue;
176
+ // The module's own code runs for whatever loads it.
177
+ if (n == '*') {
178
+ if (i.exported && step < steps) go.push({
179
+ m: e,
180
+ n,
181
+ step: step + 1
182
+ });
183
+ let f = roots.get(e);
184
+ if (f != undefined) {
185
+ near.set(f, Math.min(near.get(f) ?? Infinity, step));
186
+ }
187
+ continue;
188
+ }
189
+ let words = i.names.filter(([from])=>from == n).map(([, as])=>as);
190
+ if (i.exported) {
191
+ if (i.all) words.push(n);
192
+ for (let w of words)go.push({
193
+ m: e,
194
+ n: w,
195
+ step
196
+ });
197
+ continue;
198
+ }
199
+ if (i.as && text(e).includes(`${i.as}.${n}`)) words.push(`${i.as}.${n}`);
200
+ if (!words.length) continue;
201
+ let f = roots.get(e);
202
+ if (f != undefined) near.set(f, Math.min(near.get(f) ?? Infinity, step));
203
+ for (let w of words)next(e, w);
204
+ }
205
+ }
206
+ }
207
+ return near;
208
+ };
209
+ //# sourceMappingURL=names.js.map
package/names.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"names.js","sources":["./names.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,0EAA0E;AAC1E,2EAA2E;AAC3E,qEAAqE;AACrE,4EAA4E;AAC5E,8EAA8E;AAC9E,qBAAqB;AAErB,SAAS,QAAQ,oBAAmB;AAEpC,6DAA6D;AAC7D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,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,GAAK,QAAQ,GAAG,GAAG,CAAC,CAAC,GAAG,GAAG,GAAK;QAClE,IAAI,EAAE,QAAQ,EAAE;UACd,IAAI,EAAE,GAAG,EAAE,MAAM,IAAI,CAAC;UACtB,KAAK,IAAI,KAAK,MAAO,GAAG,IAAI,CAAC;YAAE,GAAG;YAAG,GAAG;YAAG;UAAK;UAChD;QACF;QACA,IAAI,EAAE,EAAE,IAAI,KAAK,GAAG,QAAQ,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG;QACvE,IAAI,CAAC,MAAM,MAAM,EAAE;QACnB,IAAI,IAAI,MAAM,GAAG,CAAC;QAClB,IAAI,KAAK,WAAW,KAAK,GAAG,CAAC,GAAG,KAAK,GAAG,CAAC,KAAK,GAAG,CAAC,MAAM,UAAU;QAClE,KAAK,IAAI,KAAK,MAAO,KAAK,GAAG;MAC/B;IACF;EACF;EACA,OAAO;AACT,EAAC"}
package/names.ts ADDED
@@ -0,0 +1,204 @@
1
+ // Which files name what a change edits: a test importing `fields` from
2
+ // @yaks/fts checks `fields`, where a kernel test reaching the same module
3
+ // through the platform it composes merely loads it. The module graph ranks
4
+ // both alike; the names a file imports, followed through the modules
5
+ // re-exporting them and the declarations saying them, tell the first apart.
6
+ // A change's edits are named by the top-level declaration holding each edited
7
+ // line (`declared`).
8
+ import type { Info } from 'jsr:@yaks/process@0.2.36/modules'
9
+ import { location } from './deps.js'
10
+
11
+ // What opens a top-level declaration, and the name it gives.
12
+ let DECLARED =
13
+ /^(?:export\s+)?(?:default\s+)?(?:declare\s+)?(?:async\s+)?(?:let|const|var|function\*?|class|enum|type|interface)\s+([\w$]+)/
14
+ // A line going on with what an earlier line opened.
15
+ let GOING_ON = /^[)\]}]/
16
+
17
+ /// let src = ['import { x } from "./x.ts"', '', 'export let a = (', ' n: number,', '): number => {', ' return n', '}', 'let b = 2']
18
+ /// declared(src.join('\n')) -> [undefined, undefined, 'a', 'a', 'a', 'a', 'a', 'b']
19
+ /// declared('let c = [\n 1,\n]\nf(c)') -> ['c', 'c', 'c', undefined]
20
+ /** The top-level declaration each line of formatted source belongs to, by
21
+ * the nearest line above it at no indentation that opens one; none for an
22
+ * import or other top-level code. */
23
+ export let declared = (text: string): (string | undefined)[] => {
24
+ let at: string | undefined
25
+ return text.split('\n').map((l) => {
26
+ if (l && !/^\s/.test(l) && !GOING_ON.test(l)) at = DECLARED.exec(l)?.[1]
27
+ return at
28
+ })
29
+ }
30
+
31
+ /** What a module imports or re-exports from one specifier: each name by the
32
+ * name it has there and the one it is given here, every name (`*`), or the
33
+ * whole module under one name (`as`). */
34
+ export type Imported = {
35
+ from: string
36
+ names: [string, string][]
37
+ all?: boolean
38
+ as?: string
39
+ exported?: boolean
40
+ }
41
+
42
+ let STATEMENT =
43
+ /^(import|export)\s+(type\s+)?(?:\*\s+as\s+([\w$]+)|(\*)|\{([^}]*)\})\s*from\s*['"]([^'"]+)['"]/gm
44
+
45
+ // A module loaded once the stage is set: `let { a, b: c } = await
46
+ // import('./m.ts')`, or the whole of it under one name.
47
+ let LOADED =
48
+ /(?:let|const|var)\s+(?:([\w$]+)|\{([^}]*)\})\s*=\s*await\s+import\(\s*['"]([^'"]+)['"]\s*,?\s*\)/gm
49
+
50
+ /// imported("import { a, b as c, type T } from './m.ts'") -> [{ from: './m.ts', names: [['a', 'a'], ['b', 'c']] }]
51
+ /// imported("import type { T } from './m.ts'") -> []
52
+ /// imported("import * as m from '@yaks/m'") -> [{ from: '@yaks/m', names: [], as: 'm' }]
53
+ /// imported("export * from './f.ts'\nexport { g as h } from './g.ts'") -> [{ from: './f.ts', names: [], all: true, exported: true }, { from: './g.ts', names: [['g', 'h']], exported: true }]
54
+ /// imported('import {\n a,\n b,\n} from "x"') -> [{ from: 'x', names: [['a', 'a'], ['b', 'b']] }]
55
+ /// imported("let { a, b: c } = await import('./m.ts')") -> [{ from: './m.ts', names: [['a', 'a'], ['b', 'c']] }]
56
+ /// imported('let m = await import(\n "./m.ts",\n)') -> [{ from: './m.ts', names: [], as: 'm' }]
57
+ /** The values a module imports and re-exports by a specifier, but types,
58
+ * and those it loads with `await import`, as a test that must set its stage
59
+ * first does. */
60
+ export let imported = (text: string): Imported[] => [
61
+ ...[...text.matchAll(STATEMENT)].flatMap(
62
+ ([, verb, type, as, star, list, from]) => {
63
+ if (type) return []
64
+ let exported = verb == 'export' ? { exported: true } : {}
65
+ if (as) return [{ from, names: [], as, ...exported }]
66
+ if (star) return [{ from, names: [], all: true, ...exported }]
67
+ let names = list.split(',').map((n) => n.trim())
68
+ .filter((n) => n && !n.startsWith('type '))
69
+ .map((n) => n.split(/\s+as\s+/) as [string, string])
70
+ .map(([n, k]) => [n, k ?? n] as [string, string])
71
+ return [{ from, names, ...exported }]
72
+ },
73
+ ),
74
+ ...[...text.matchAll(LOADED)].map(([, as, list, from]) =>
75
+ as ? { from, names: [], as } : {
76
+ from,
77
+ names: list.split(',').map((n) => n.trim()).filter(Boolean)
78
+ .map((n) => n.split(/\s*:\s*/))
79
+ .map(([n, k]) => [n, k ?? n] as [string, string]),
80
+ }
81
+ ),
82
+ ]
83
+
84
+ /** How many public declarations can relay an edited name. Re-exports and
85
+ * references inside private declarations keep the same distance. */
86
+ export const STEPS = 2
87
+
88
+ /**
89
+ * Of `files`, how near each is to what a change `edited` (each module's
90
+ * declarations, by checkout path, `*` for its top-level code): 0 for a file
91
+ * importing an edited declaration by name, directly or from a module
92
+ * re-exporting it, or reading it off the whole module (`m.fields`), and for
93
+ * one directly importing a module whose top-level code is edited. A public
94
+ * declaration that uses edited code adds a step, even inside the same
95
+ * module, as does a re-export of a module with edited top-level code; and so on
96
+ * to `steps`. A file naming none is left out. Each file is read for the root it stands for
97
+ * (`root`, an example page's plan module), and modules as `info` resolved
98
+ * them.
99
+ */
100
+ export let naming = (
101
+ info: Info,
102
+ files: string[],
103
+ edited: Record<string, string[]>,
104
+ read: (path: string) => string | undefined,
105
+ root: (file: string) => string = (f) => f,
106
+ steps: number = STEPS,
107
+ ): Map<string, number> => {
108
+ let { url, rel } = location()
109
+ // What each module's specifiers resolve to, and who imports each module.
110
+ let resolved = new Map<string, Map<string, string>>()
111
+ let importers = new Map<string, string[]>()
112
+ for (let m of info.modules) {
113
+ let to = new Map<string, string>()
114
+ for (let d of m.dependencies ?? []) {
115
+ let at = d.code?.specifier ?? d.type?.specifier
116
+ if (!d.specifier || !at) continue
117
+ to.set(d.specifier, at)
118
+ ;(importers.get(at) ?? importers.set(at, []).get(at)!).push(m.specifier)
119
+ }
120
+ resolved.set(m.specifier, to)
121
+ }
122
+ let texts = new Map<string, string>()
123
+ let text = (module: string) => {
124
+ if (!texts.has(module)) texts.set(module, read(rel(module)) ?? '')
125
+ return texts.get(module)!
126
+ }
127
+ let parsed = new Map<string, Imported[]>()
128
+ let of = (module: string) => {
129
+ if (!parsed.has(module)) parsed.set(module, imported(text(module)))
130
+ return parsed.get(module)!
131
+ }
132
+ let exported = new Map<string, Set<string>>()
133
+ let publicName = (module: string, name: string) => {
134
+ if (!exported.has(module)) {
135
+ let lines = text(module).split('\n').filter((l) =>
136
+ l.startsWith('export ')
137
+ )
138
+ exported.set(
139
+ module,
140
+ new Set(lines.flatMap((l) => DECLARED.exec(l)?.[1] ?? [])),
141
+ )
142
+ }
143
+ return exported.get(module)!.has(name)
144
+ }
145
+ // The declarations of a module whose lines say `word`.
146
+ let owners = new Map<string, (string | undefined)[]>()
147
+ let saying = (module: string, word: string) => {
148
+ if (!owners.has(module)) owners.set(module, declared(text(module)))
149
+ let of = owners.get(module)!, said = new Set<string>()
150
+ let re = new RegExp(
151
+ `(?<![\\w$.])${word.replace(/[$.]/g, '\\$&')}(?![\\w$])`,
152
+ )
153
+ text(module).split('\n').forEach((l, i) => {
154
+ if (of[i] && re.test(l)) said.add(of[i]!)
155
+ })
156
+ return said
157
+ }
158
+ let roots = new Map(files.map((f) => [url(root(f)), f]))
159
+ let near = new Map<string, number>()
160
+ let seen = new Map<string, number>()
161
+ // Revisit a declaration only when reached by a shorter path.
162
+ let go = Object.entries(edited).flatMap(([m, names]) =>
163
+ names.map((n) => ({ m: url(m), n, step: 0 }))
164
+ )
165
+ for (let at = 0; at < go.length; at++) {
166
+ let { m, n, step } = go[at]
167
+ if ((seen.get(`${m}#${n}`) ?? Infinity) <= step) continue
168
+ seen.set(`${m}#${n}`, step)
169
+ let next = (module: string, word: string) => {
170
+ for (let d of saying(module, word)) {
171
+ if (d == n && module == m) continue
172
+ let distance = step + Number(publicName(module, d))
173
+ if (distance <= steps) go.push({ m: module, n: d, step: distance })
174
+ }
175
+ }
176
+ if (n != '*') next(m, n)
177
+ for (let e of importers.get(m) ?? []) {
178
+ for (let i of of(e)) {
179
+ if (resolved.get(e)?.get(i.from) != m) continue
180
+ // The module's own code runs for whatever loads it.
181
+ if (n == '*') {
182
+ if (i.exported && step < steps) go.push({ m: e, n, step: step + 1 })
183
+ let f = roots.get(e)
184
+ if (f != undefined) {
185
+ near.set(f, Math.min(near.get(f) ?? Infinity, step))
186
+ }
187
+ continue
188
+ }
189
+ let words = i.names.filter(([from]) => from == n).map(([, as]) => as)
190
+ if (i.exported) {
191
+ if (i.all) words.push(n)
192
+ for (let w of words) go.push({ m: e, n: w, step })
193
+ continue
194
+ }
195
+ if (i.as && text(e).includes(`${i.as}.${n}`)) words.push(`${i.as}.${n}`)
196
+ if (!words.length) continue
197
+ let f = roots.get(e)
198
+ if (f != undefined) near.set(f, Math.min(near.get(f) ?? Infinity, step))
199
+ for (let w of words) next(e, w)
200
+ }
201
+ }
202
+ }
203
+ return near
204
+ }
package/own.js ADDED
@@ -0,0 +1,109 @@
1
+ import * as io from "@yaks/file/io";
2
+ import * as system from "@yaks/process/system";
3
+ // A process's own time: the wall clock less what the box kept it, or any
4
+ // process it started, waiting for a CPU. Linux keeps, for each thread, the
5
+ // time it ran on a CPU and the time it waited, runnable, for one
6
+ // (/proc/<pid>/task/<tid>/schedstat), and lists the children each thread
7
+ // started (/proc/<pid>/task/<tid>/children). A wait timed by its own time
8
+ // fails when what it waits on hangs, never because the box is busy: a process
9
+ // that stops (a deadlock, a lost wakeup) waits for no CPU, so its own time
10
+ // keeps the wall clock's pace.
11
+ /** What each thread of `pid` and of every process it started has waited for
12
+ * a CPU so far, in ms, by the thread's path under /proc. Empty where the
13
+ * platform does not say. */ export let waits = (pid)=>{
14
+ let found = new Map();
15
+ let visit = (pid)=>{
16
+ for (let task of tasks(pid)){
17
+ let at = `/proc/${pid}/task/${task}`;
18
+ let wait = Number(read(`${at}/schedstat`)?.split(' ')[1]) / 1e6;
19
+ if (Number.isFinite(wait)) found.set(at, wait);
20
+ for (let child of read(`${at}/children`)?.split(' ') ?? []){
21
+ if (child) visit(Number(child));
22
+ }
23
+ }
24
+ };
25
+ visit(pid);
26
+ return found;
27
+ };
28
+ /** What the main thread of every process `pid` started has waited for a CPU
29
+ * so far, in ms, by its path under /proc: the processes `pid`'s main thread
30
+ * started, as Deno starts every child there, and the ones theirs did. A
31
+ * process's other threads are left out, so a look costs two reads a process,
32
+ * and one with no child costs one. */ export let started = (pid = system.pid)=>{
33
+ let found = new Map();
34
+ let visit = (pid)=>{
35
+ for (let child of kids(pid)){
36
+ let at = `/proc/${child}/task/${child}`;
37
+ let wait = Number(read(`${at}/schedstat`)?.split(' ')[1]) / 1e6;
38
+ if (Number.isFinite(wait)) found.set(at, wait);
39
+ visit(child);
40
+ }
41
+ };
42
+ visit(pid);
43
+ return found;
44
+ };
45
+ let kids = (pid)=>(read(`/proc/${pid}/task/${pid}/children`)?.split(' ') ?? []).filter(Boolean).map(Number);
46
+ // A process or thread that ended between two reads has nothing to say, and
47
+ // neither does a platform without /proc or a runtime not let read it. Deno
48
+ // has no class for ESRCH, the error a /proc file of a process that ended
49
+ // gives: a plain Error saying `No such process (os error 3)`, then the call,
50
+ // with no code.
51
+ let gone = (error)=>io.isNotFound(error) || error instanceof Error && error.name == 'NotCapable' || io.isPermissionDenied(error) || /^No such process \(os error 3\)/.test(error?.message ?? '');
52
+ let read = (path)=>{
53
+ try {
54
+ return io.readTextFileSync(path);
55
+ } catch (error) {
56
+ if (gone(error)) return undefined;
57
+ throw error;
58
+ }
59
+ };
60
+ let tasks = (pid)=>{
61
+ try {
62
+ return [
63
+ ...io.readDirSync(`/proc/${pid}/task`)
64
+ ].map((e)=>e.name);
65
+ } catch (error) {
66
+ if (gone(error)) return [];
67
+ throw error;
68
+ }
69
+ };
70
+ /** Looks at what threads have waited for a CPU so far (`look`, as `waits`
71
+ * says it), and says, in ms, how long the box has held them since the first
72
+ * look: between two looks, at least as long as their most-held thread waited,
73
+ * a thread new since the last look having waited all its wait since. */ export let held = (look)=>{
74
+ let was;
75
+ let total = 0;
76
+ return ()=>{
77
+ let is = look();
78
+ let most = 0;
79
+ for (let [thread, wait] of was ? is : []){
80
+ most = Math.max(most, wait - (was.get(thread) ?? 0));
81
+ }
82
+ was = is;
83
+ return total += most;
84
+ };
85
+ };
86
+ /** A clock of `pid`'s own time, in ms since the clock was made: the wall
87
+ * clock's pace, less what the box kept the process, or any process it
88
+ * started, waiting for a CPU (`held`). The first look is `every` ms in and the
89
+ * span before it counts whole, so a clock read only sooner never looks. Where
90
+ * the platform does not say, it is the wall clock (the README has an
91
+ * example). */ export let own = (pid = system.pid, { every = 250, look = waits, time = ()=>performance.now() } = {})=>{
92
+ let start = time();
93
+ let at = start;
94
+ let hold = held(()=>look(pid));
95
+ let kept = 0;
96
+ let last = 0;
97
+ return ()=>{
98
+ let now = time();
99
+ if (now - at >= every) {
100
+ kept = hold();
101
+ at = now;
102
+ }
103
+ // Linux brings a thread's wait up to date only once it is back on a CPU,
104
+ // so a look can take off a wait the clock already counted. A clock never
105
+ // runs back.
106
+ return last = Math.max(last, now - start - kept);
107
+ };
108
+ };
109
+ //# sourceMappingURL=own.js.map
package/own.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"own.js","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AAO;EACX,IAAI,OAAO;EACX,OAAO;IACL,IAAI,MAAM;IACV,IAAI,MAAM,MAAM,OAAO;MACrB,OAAO;MACP,KAAK;IACP;IACA,yEAAyE;IACzE,yEAAyE;IACzE,aAAa;IACb,OAAO,OAAO,KAAK,GAAG,CAAC,MAAM,MAAM,QAAQ;EAC7C;AACF,EAAC"}
package/own.ts ADDED
@@ -0,0 +1,136 @@
1
+ import * as io from '@yaks/file/io'
2
+ import * as system from '@yaks/process/system'
3
+ // A process's own time: the wall clock less what the box kept it, or any
4
+ // process it started, waiting for a CPU. Linux keeps, for each thread, the
5
+ // time it ran on a CPU and the time it waited, runnable, for one
6
+ // (/proc/<pid>/task/<tid>/schedstat), and lists the children each thread
7
+ // started (/proc/<pid>/task/<tid>/children). A wait timed by its own time
8
+ // fails when what it waits on hangs, never because the box is busy: a process
9
+ // that stops (a deadlock, a lost wakeup) waits for no CPU, so its own time
10
+ // keeps the wall clock's pace.
11
+
12
+ /** What each thread of `pid` and of every process it started has waited for
13
+ * a CPU so far, in ms, by the thread's path under /proc. Empty where the
14
+ * platform does not say. */
15
+ export let waits = (pid: number): Map<string, number> => {
16
+ let found = new Map<string, number>()
17
+ let visit = (pid: number) => {
18
+ for (let task of tasks(pid)) {
19
+ let at = `/proc/${pid}/task/${task}`
20
+ let wait = Number(read(`${at}/schedstat`)?.split(' ')[1]) / 1e6
21
+ if (Number.isFinite(wait)) found.set(at, wait)
22
+ for (let child of read(`${at}/children`)?.split(' ') ?? []) {
23
+ if (child) visit(Number(child))
24
+ }
25
+ }
26
+ }
27
+ visit(pid)
28
+ return found
29
+ }
30
+
31
+ /** What the main thread of every process `pid` started has waited for a CPU
32
+ * so far, in ms, by its path under /proc: the processes `pid`'s main thread
33
+ * started, as Deno starts every child there, and the ones theirs did. A
34
+ * process's other threads are left out, so a look costs two reads a process,
35
+ * and one with no child costs one. */
36
+ export let started = (pid: number = system.pid): Map<string, number> => {
37
+ let found = new Map<string, number>()
38
+ let visit = (pid: number) => {
39
+ for (let child of kids(pid)) {
40
+ let at = `/proc/${child}/task/${child}`
41
+ let wait = Number(read(`${at}/schedstat`)?.split(' ')[1]) / 1e6
42
+ if (Number.isFinite(wait)) found.set(at, wait)
43
+ visit(child)
44
+ }
45
+ }
46
+ visit(pid)
47
+ return found
48
+ }
49
+
50
+ let kids = (pid: number) =>
51
+ (read(`/proc/${pid}/task/${pid}/children`)?.split(' ') ?? []).filter(Boolean)
52
+ .map(Number)
53
+
54
+ // A process or thread that ended between two reads has nothing to say, and
55
+ // neither does a platform without /proc or a runtime not let read it. Deno
56
+ // has no class for ESRCH, the error a /proc file of a process that ended
57
+ // gives: a plain Error saying `No such process (os error 3)`, then the call,
58
+ // with no code.
59
+ let gone = (error: unknown) =>
60
+ io.isNotFound(error) ||
61
+ error instanceof Error && error.name == 'NotCapable' ||
62
+ io.isPermissionDenied(error) ||
63
+ /^No such process \(os error 3\)/.test((error as Error)?.message ?? '')
64
+ let read = (path: string): string | undefined => {
65
+ try {
66
+ return io.readTextFileSync(path)
67
+ } catch (error) {
68
+ if (gone(error)) return undefined
69
+ throw error
70
+ }
71
+ }
72
+ let tasks = (pid: number): string[] => {
73
+ try {
74
+ return [...io.readDirSync(`/proc/${pid}/task`)].map((e) => e.name)
75
+ } catch (error) {
76
+ if (gone(error)) return []
77
+ throw error
78
+ }
79
+ }
80
+
81
+ /** How {@link own} looks: how often, at what, and by which clock. */
82
+ export type Looks = {
83
+ /** ms before the first look and between looks; a reading in between keeps
84
+ * the wall clock's pace */
85
+ every?: number
86
+ /** what each thread has waited for a CPU so far, in ms */
87
+ look?: (pid: number) => Map<string, number>
88
+ /** the wall clock, in ms */
89
+ time?: () => number
90
+ }
91
+
92
+ /** Looks at what threads have waited for a CPU so far (`look`, as `waits`
93
+ * says it), and says, in ms, how long the box has held them since the first
94
+ * look: between two looks, at least as long as their most-held thread waited,
95
+ * a thread new since the last look having waited all its wait since. */
96
+ export let held = (look: () => Map<string, number>): () => number => {
97
+ let was: Map<string, number> | undefined
98
+ let total = 0
99
+ return () => {
100
+ let is = look()
101
+ let most = 0
102
+ for (let [thread, wait] of was ? is : []) {
103
+ most = Math.max(most, wait - (was!.get(thread) ?? 0))
104
+ }
105
+ was = is
106
+ return total += most
107
+ }
108
+ }
109
+
110
+ /** A clock of `pid`'s own time, in ms since the clock was made: the wall
111
+ * clock's pace, less what the box kept the process, or any process it
112
+ * started, waiting for a CPU (`held`). The first look is `every` ms in and the
113
+ * span before it counts whole, so a clock read only sooner never looks. Where
114
+ * the platform does not say, it is the wall clock (the README has an
115
+ * example). */
116
+ export let own = (
117
+ pid: number = system.pid,
118
+ { every = 250, look = waits, time = () => performance.now() }: Looks = {},
119
+ ): () => number => {
120
+ let start = time()
121
+ let at = start
122
+ let hold = held(() => look(pid))
123
+ let kept = 0
124
+ let last = 0
125
+ return () => {
126
+ let now = time()
127
+ if (now - at >= every) {
128
+ kept = hold()
129
+ at = now
130
+ }
131
+ // Linux brings a thread's wait up to date only once it is back on a CPU,
132
+ // so a look can take off a wait the clock already counted. A clock never
133
+ // runs back.
134
+ return last = Math.max(last, now - start - kept)
135
+ }
136
+ }