kryptheon 0.1.68 → 0.1.70

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.
@@ -1,222 +1,222 @@
1
- // What changed in a project since Kryptheon last looked, and what that means
2
- // for which checks have to run.
3
- //
4
- // A snapshot is a content hash of every file that is the project's own - its
5
- // source, its database migrations, its dependency list - kept in the store,
6
- // never in the project. Comparing two snapshots answers the first question a
7
- // person has after an AI tool says "done": what did it actually touch?
8
- //
9
- // Content, not timestamps and not git: an editor that saves a file unchanged
10
- // is not a change, and a landing page with no git repository still has one.
11
- //
12
- // Each changed file is put in a part of the app (frontend, backend, database,
13
- // tests, dependencies, config, docs), and each part names the checks that
14
- // can speak to it. The mapping is written here, once, and deliberately
15
- // plain: a path-based guess that is right for how most projects are laid
16
- // out, and said as a guess ("likely affected") rather than a proof.
17
-
18
- const fs = require('fs');
19
- const path = require('path');
20
- const crypto = require('crypto');
21
-
22
- const SKIP_DIRS = new Set([
23
- 'node_modules', '.git', 'dist', 'build', 'out', '.next', '.nuxt', '.svelte-kit', 'coverage',
24
- '.vercel', '.netlify', '.turbo', '.cache', 'test-results', 'playwright-report', '.kryptheon',
25
- ]);
26
- const MAX_BYTES = 5 * 1024 * 1024;
27
-
28
- // Where a file sits in the app. The first rule that matches wins, so the
29
- // specific ones come first: a .sql file inside backend/ is a database change.
30
- const PARTS = [
31
- { part: 'dependencies', test: (p) => /(^|\/)(package\.json|package-lock\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lockb?|requirements\.txt|poetry\.lock|Gemfile\.lock|go\.sum)$/i.test(p) },
32
- { part: 'database', test: (p) => /\.sql$/i.test(p) || /(^|\/)(migrations|supabase|prisma|drizzle|db\/schema)(\/|$)/i.test(p) || /(^|\/)schema\.prisma$/i.test(p) },
33
- { part: 'tests', test: (p) => /(^|\/)(tests?|__tests__|e2e|cypress)\//i.test(p) || /\.(spec|test)\.[cm]?[jt]sx?$/i.test(p) },
34
- { part: 'docs', test: (p) => /\.(md|mdx|txt|rst)$/i.test(p) || /(^|\/)docs\//i.test(p) },
35
- { part: 'config', test: (p) => /(^|\/)(\.env\.example|\.env\.sample|tsconfig[^/]*\.json|jsconfig\.json|vercel\.json|netlify\.toml|dockerfile|docker-compose[^/]*\.ya?ml)$/i.test(p) || /\.config\.[cm]?[jt]s$/i.test(p) || /(^|\/)\.github\//i.test(p) },
36
- { part: 'backend', test: (p) => /(^|\/)(server|backend|api|routes|controllers|services|middleware|functions|workers|jobs|lib\/server)(\/|\.[cm]?[jt]s$)/i.test(p) || /(^|\/)(server|app|index)\.[cm]?[jt]s$/i.test(p) && !/(^|\/)(src|public|frontend|client|pages|components)\//i.test(p) },
37
- { part: 'frontend', test: (p) => /\.(html?|css|scss|sass|less|jsx|tsx|vue|svelte|astro)$/i.test(p) || /(^|\/)(frontend|client|public|src|pages|components|app|views|static)\//i.test(p) && /\.[cm]?[jt]s$/i.test(p) },
38
- { part: 'assets', test: (p) => /\.(png|jpe?g|gif|svg|webp|ico|woff2?|ttf|otf|mp4|webm|mp3|pdf)$/i.test(p) },
39
- ];
40
-
41
- // Which checks can speak to a change in each part. Ids are the dashboard's.
42
- const CHECKS_FOR = {
43
- frontend: ['frontend', 'regression'],
44
- backend: ['backend', 'api', 'regression'],
45
- database: ['data', 'regression'],
46
- dependencies: ['dependency', 'build', 'regression'],
47
- tests: ['regression'],
48
- config: ['build', 'regression'],
49
- code: ['regression'],
50
- docs: [],
51
- assets: [],
52
- };
53
-
54
- function partOf(rel) {
55
- const p = rel.split(path.sep).join('/');
56
- const hit = PARTS.find((r) => r.test(p));
57
- if (hit) return hit.part;
58
- return /\.[cm]?[jt]sx?$/i.test(p) ? 'code' : 'other';
59
- }
60
-
61
- /** Every file that is the project's own, as relative paths with forward slashes. */
62
- function listFiles(root) {
63
- const out = [];
64
- (function walk(dir) {
65
- let entries;
66
- try {
67
- entries = fs.readdirSync(dir, { withFileTypes: true });
68
- } catch (err) {
69
- return;
70
- }
71
- for (const entry of entries) {
72
- const full = path.join(dir, entry.name);
73
- if (entry.isDirectory()) {
74
- if (!SKIP_DIRS.has(entry.name)) walk(full);
75
- } else if (entry.isFile()) {
76
- // A real .env holds secrets; its content is never hashed or kept.
77
- if (/^\.env(\..+)?$/i.test(entry.name) && !/\.(example|sample)$/i.test(entry.name)) continue;
78
- out.push(path.relative(root, full).split(path.sep).join('/'));
79
- }
80
- }
81
- })(root);
82
- return out.sort();
83
- }
84
-
85
- /** The dependency lists of package.json, kept so a change can say which package moved. */
86
- function dependenciesOf(root) {
87
- try {
88
- const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
89
- return Object.assign({}, pkg.dependencies || {}, pkg.devDependencies || {});
90
- } catch (err) {
91
- return null;
92
- }
93
- }
94
-
95
- /**
96
- * The project as it is now. Files whose size and modified time match the
97
- * previous snapshot keep its hash without being read again - on a large
98
- * project that is the difference between milliseconds and seconds, and an
99
- * unchanged size and time is the same bytes for every editor that exists.
100
- */
101
- function takeSnapshot(root, previous) {
102
- const before = (previous && previous.files) || {};
103
- const files = {};
104
- for (const rel of listFiles(root)) {
105
- let stat;
106
- try {
107
- stat = fs.statSync(path.join(root, rel));
108
- } catch (err) {
109
- continue;
110
- }
111
- const old = before[rel];
112
- if (old && old.size === stat.size && old.mtimeMs === stat.mtimeMs) {
113
- files[rel] = old;
114
- continue;
115
- }
116
- let hash;
117
- if (stat.size > MAX_BYTES) {
118
- hash = 'size:' + stat.size + ':' + stat.mtimeMs;
119
- } else {
120
- try {
121
- hash = crypto.createHash('sha1').update(fs.readFileSync(path.join(root, rel))).digest('hex');
122
- } catch (err) {
123
- continue;
124
- }
125
- }
126
- files[rel] = { hash: hash, size: stat.size, mtimeMs: stat.mtimeMs };
127
- }
128
- return { takenAt: new Date().toISOString(), files: files, dependencies: dependenciesOf(root) };
129
- }
130
-
131
- /** Packages added, removed or moved to another version between two snapshots. */
132
- function dependencyChanges(before, after) {
133
- const a = (before && before.dependencies) || {};
134
- const b = (after && after.dependencies) || {};
135
- const out = [];
136
- for (const name of new Set(Object.keys(a).concat(Object.keys(b)))) {
137
- if (!(name in a)) out.push({ name: name, change: 'added', to: b[name] });
138
- else if (!(name in b)) out.push({ name: name, change: 'removed', from: a[name] });
139
- else if (a[name] !== b[name]) out.push({ name: name, change: 'changed', from: a[name], to: b[name] });
140
- }
141
- return out.sort((x, y) => x.name.localeCompare(y.name));
142
- }
143
-
144
- /**
145
- * What changed between two snapshots, by part of the app, and which checks
146
- * that calls for. With no earlier snapshot there is nothing to compare, and
147
- * that is said - it is not reported as "everything changed".
148
- */
149
- function compare(before, after) {
150
- if (!before) return { first: true, files: [], parts: [], checks: [], dependencies: [] };
151
- const files = [];
152
- const a = before.files || {};
153
- const b = after.files || {};
154
- for (const rel of Object.keys(b)) {
155
- if (!a[rel]) files.push({ path: rel, state: 'added' });
156
- else if (a[rel].hash !== b[rel].hash) files.push({ path: rel, state: 'modified' });
157
- }
158
- for (const rel of Object.keys(a)) if (!b[rel]) files.push({ path: rel, state: 'deleted' });
159
- files.sort((x, y) => x.path.localeCompare(y.path));
160
- for (const f of files) f.part = partOf(f.path);
161
-
162
- const parts = [];
163
- for (const f of files) if (!parts.includes(f.part)) parts.push(f.part);
164
- const checks = [];
165
- for (const part of parts) for (const id of CHECKS_FOR[part] || []) if (!checks.includes(id)) checks.push(id);
166
- return {
167
- first: false,
168
- files: files,
169
- parts: parts,
170
- checks: checks,
171
- dependencies: dependencyChanges(before, after),
172
- };
173
- }
174
-
175
- /**
176
- * Findings that were not there last time. Keyed by what they are about rather
177
- * than by line number: a line added above a known finding moves it, and a
178
- * moved finding reported as new would teach a person to ignore this list.
179
- */
180
- //
181
- // The detail is part of what a finding is only for the code read, where it is
182
- // the expression itself. For a recorded flow or a database finding it is the
183
- // account of how it broke this time - "ended up somewhere different", "could
184
- // not be opened" - and a flow that is still broken in a new way is the same
185
- // finding, not a fixed one and a new one.
186
- function findingKey(f) {
187
- return [
188
- f.check || '',
189
- f.where ? String(f.where).replace(/:\d+$/, '') : '',
190
- f.headline ? String(f.headline).replace(/:\d+\b/g, '') : '',
191
- f.check === 'frontend' ? f.detail || '' : '',
192
- ].join('|');
193
- }
194
-
195
- /** A short, stable name for a finding: what a person types to re-check it. */
196
- function findingId(f) {
197
- return crypto.createHash('sha1').update(findingKey(f)).digest('hex').slice(0, 8);
198
- }
199
-
200
- function newFindings(before, after) {
201
- const seen = new Set((before || []).map(findingKey));
202
- return (after || []).filter((f) => !seen.has(findingKey(f)));
203
- }
204
-
205
- function goneFindings(before, after) {
206
- const now = new Set((after || []).map(findingKey));
207
- return (before || []).filter((f) => !now.has(findingKey(f)));
208
- }
209
-
210
- module.exports = {
211
- PARTS: PARTS,
212
- CHECKS_FOR: CHECKS_FOR,
213
- partOf: partOf,
214
- listFiles: listFiles,
215
- takeSnapshot: takeSnapshot,
216
- compare: compare,
217
- dependencyChanges: dependencyChanges,
218
- findingKey: findingKey,
219
- findingId: findingId,
220
- newFindings: newFindings,
221
- goneFindings: goneFindings,
222
- };
1
+ // What changed in a project since Kryptheon last looked, and what that means
2
+ // for which checks have to run.
3
+ //
4
+ // A snapshot is a content hash of every file that is the project's own - its
5
+ // source, its database migrations, its dependency list - kept in the store,
6
+ // never in the project. Comparing two snapshots answers the first question a
7
+ // person has after an AI tool says "done": what did it actually touch?
8
+ //
9
+ // Content, not timestamps and not git: an editor that saves a file unchanged
10
+ // is not a change, and a landing page with no git repository still has one.
11
+ //
12
+ // Each changed file is put in a part of the app (frontend, backend, database,
13
+ // tests, dependencies, config, docs), and each part names the checks that
14
+ // can speak to it. The mapping is written here, once, and deliberately
15
+ // plain: a path-based guess that is right for how most projects are laid
16
+ // out, and said as a guess ("likely affected") rather than a proof.
17
+
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+ const crypto = require('crypto');
21
+
22
+ const SKIP_DIRS = new Set([
23
+ 'node_modules', '.git', 'dist', 'build', 'out', '.next', '.nuxt', '.svelte-kit', 'coverage',
24
+ '.vercel', '.netlify', '.turbo', '.cache', 'test-results', 'playwright-report', '.kryptheon',
25
+ ]);
26
+ const MAX_BYTES = 5 * 1024 * 1024;
27
+
28
+ // Where a file sits in the app. The first rule that matches wins, so the
29
+ // specific ones come first: a .sql file inside backend/ is a database change.
30
+ const PARTS = [
31
+ { part: 'dependencies', test: (p) => /(^|\/)(package\.json|package-lock\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lockb?|requirements\.txt|poetry\.lock|Gemfile\.lock|go\.sum)$/i.test(p) },
32
+ { part: 'database', test: (p) => /\.sql$/i.test(p) || /(^|\/)(migrations|supabase|prisma|drizzle|db\/schema)(\/|$)/i.test(p) || /(^|\/)schema\.prisma$/i.test(p) },
33
+ { part: 'tests', test: (p) => /(^|\/)(tests?|__tests__|e2e|cypress)\//i.test(p) || /\.(spec|test)\.[cm]?[jt]sx?$/i.test(p) },
34
+ { part: 'docs', test: (p) => /\.(md|mdx|txt|rst)$/i.test(p) || /(^|\/)docs\//i.test(p) },
35
+ { part: 'config', test: (p) => /(^|\/)(\.env\.example|\.env\.sample|tsconfig[^/]*\.json|jsconfig\.json|vercel\.json|netlify\.toml|dockerfile|docker-compose[^/]*\.ya?ml)$/i.test(p) || /\.config\.[cm]?[jt]s$/i.test(p) || /(^|\/)\.github\//i.test(p) },
36
+ { part: 'backend', test: (p) => /(^|\/)(server|backend|api|routes|controllers|services|middleware|functions|workers|jobs|lib\/server)(\/|\.[cm]?[jt]s$)/i.test(p) || /(^|\/)(server|app|index)\.[cm]?[jt]s$/i.test(p) && !/(^|\/)(src|public|frontend|client|pages|components)\//i.test(p) },
37
+ { part: 'frontend', test: (p) => /\.(html?|css|scss|sass|less|jsx|tsx|vue|svelte|astro)$/i.test(p) || /(^|\/)(frontend|client|public|src|pages|components|app|views|static)\//i.test(p) && /\.[cm]?[jt]s$/i.test(p) },
38
+ { part: 'assets', test: (p) => /\.(png|jpe?g|gif|svg|webp|ico|woff2?|ttf|otf|mp4|webm|mp3|pdf)$/i.test(p) },
39
+ ];
40
+
41
+ // Which checks can speak to a change in each part. Ids are the dashboard's.
42
+ const CHECKS_FOR = {
43
+ frontend: ['frontend', 'regression'],
44
+ backend: ['backend', 'api', 'regression'],
45
+ database: ['data', 'regression'],
46
+ dependencies: ['dependency', 'build', 'regression'],
47
+ tests: ['regression'],
48
+ config: ['build', 'regression'],
49
+ code: ['regression'],
50
+ docs: [],
51
+ assets: [],
52
+ };
53
+
54
+ function partOf(rel) {
55
+ const p = rel.split(path.sep).join('/');
56
+ const hit = PARTS.find((r) => r.test(p));
57
+ if (hit) return hit.part;
58
+ return /\.[cm]?[jt]sx?$/i.test(p) ? 'code' : 'other';
59
+ }
60
+
61
+ /** Every file that is the project's own, as relative paths with forward slashes. */
62
+ function listFiles(root) {
63
+ const out = [];
64
+ (function walk(dir) {
65
+ let entries;
66
+ try {
67
+ entries = fs.readdirSync(dir, { withFileTypes: true });
68
+ } catch (err) {
69
+ return;
70
+ }
71
+ for (const entry of entries) {
72
+ const full = path.join(dir, entry.name);
73
+ if (entry.isDirectory()) {
74
+ if (!SKIP_DIRS.has(entry.name)) walk(full);
75
+ } else if (entry.isFile()) {
76
+ // A real .env holds secrets; its content is never hashed or kept.
77
+ if (/^\.env(\..+)?$/i.test(entry.name) && !/\.(example|sample)$/i.test(entry.name)) continue;
78
+ out.push(path.relative(root, full).split(path.sep).join('/'));
79
+ }
80
+ }
81
+ })(root);
82
+ return out.sort();
83
+ }
84
+
85
+ /** The dependency lists of package.json, kept so a change can say which package moved. */
86
+ function dependenciesOf(root) {
87
+ try {
88
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
89
+ return Object.assign({}, pkg.dependencies || {}, pkg.devDependencies || {});
90
+ } catch (err) {
91
+ return null;
92
+ }
93
+ }
94
+
95
+ /**
96
+ * The project as it is now. Files whose size and modified time match the
97
+ * previous snapshot keep its hash without being read again - on a large
98
+ * project that is the difference between milliseconds and seconds, and an
99
+ * unchanged size and time is the same bytes for every editor that exists.
100
+ */
101
+ function takeSnapshot(root, previous) {
102
+ const before = (previous && previous.files) || {};
103
+ const files = {};
104
+ for (const rel of listFiles(root)) {
105
+ let stat;
106
+ try {
107
+ stat = fs.statSync(path.join(root, rel));
108
+ } catch (err) {
109
+ continue;
110
+ }
111
+ const old = before[rel];
112
+ if (old && old.size === stat.size && old.mtimeMs === stat.mtimeMs) {
113
+ files[rel] = old;
114
+ continue;
115
+ }
116
+ let hash;
117
+ if (stat.size > MAX_BYTES) {
118
+ hash = 'size:' + stat.size + ':' + stat.mtimeMs;
119
+ } else {
120
+ try {
121
+ hash = crypto.createHash('sha1').update(fs.readFileSync(path.join(root, rel))).digest('hex');
122
+ } catch (err) {
123
+ continue;
124
+ }
125
+ }
126
+ files[rel] = { hash: hash, size: stat.size, mtimeMs: stat.mtimeMs };
127
+ }
128
+ return { takenAt: new Date().toISOString(), files: files, dependencies: dependenciesOf(root) };
129
+ }
130
+
131
+ /** Packages added, removed or moved to another version between two snapshots. */
132
+ function dependencyChanges(before, after) {
133
+ const a = (before && before.dependencies) || {};
134
+ const b = (after && after.dependencies) || {};
135
+ const out = [];
136
+ for (const name of new Set(Object.keys(a).concat(Object.keys(b)))) {
137
+ if (!(name in a)) out.push({ name: name, change: 'added', to: b[name] });
138
+ else if (!(name in b)) out.push({ name: name, change: 'removed', from: a[name] });
139
+ else if (a[name] !== b[name]) out.push({ name: name, change: 'changed', from: a[name], to: b[name] });
140
+ }
141
+ return out.sort((x, y) => x.name.localeCompare(y.name));
142
+ }
143
+
144
+ /**
145
+ * What changed between two snapshots, by part of the app, and which checks
146
+ * that calls for. With no earlier snapshot there is nothing to compare, and
147
+ * that is said - it is not reported as "everything changed".
148
+ */
149
+ function compare(before, after) {
150
+ if (!before) return { first: true, files: [], parts: [], checks: [], dependencies: [] };
151
+ const files = [];
152
+ const a = before.files || {};
153
+ const b = after.files || {};
154
+ for (const rel of Object.keys(b)) {
155
+ if (!a[rel]) files.push({ path: rel, state: 'added' });
156
+ else if (a[rel].hash !== b[rel].hash) files.push({ path: rel, state: 'modified' });
157
+ }
158
+ for (const rel of Object.keys(a)) if (!b[rel]) files.push({ path: rel, state: 'deleted' });
159
+ files.sort((x, y) => x.path.localeCompare(y.path));
160
+ for (const f of files) f.part = partOf(f.path);
161
+
162
+ const parts = [];
163
+ for (const f of files) if (!parts.includes(f.part)) parts.push(f.part);
164
+ const checks = [];
165
+ for (const part of parts) for (const id of CHECKS_FOR[part] || []) if (!checks.includes(id)) checks.push(id);
166
+ return {
167
+ first: false,
168
+ files: files,
169
+ parts: parts,
170
+ checks: checks,
171
+ dependencies: dependencyChanges(before, after),
172
+ };
173
+ }
174
+
175
+ /**
176
+ * Findings that were not there last time. Keyed by what they are about rather
177
+ * than by line number: a line added above a known finding moves it, and a
178
+ * moved finding reported as new would teach a person to ignore this list.
179
+ */
180
+ //
181
+ // The detail is part of what a finding is only for the code read, where it is
182
+ // the expression itself. For a recorded flow or a database finding it is the
183
+ // account of how it broke this time - "ended up somewhere different", "could
184
+ // not be opened" - and a flow that is still broken in a new way is the same
185
+ // finding, not a fixed one and a new one.
186
+ function findingKey(f) {
187
+ return [
188
+ f.check || '',
189
+ f.where ? String(f.where).replace(/:\d+$/, '') : '',
190
+ f.headline ? String(f.headline).replace(/:\d+\b/g, '') : '',
191
+ f.check === 'frontend' ? f.detail || '' : '',
192
+ ].join('|');
193
+ }
194
+
195
+ /** A short, stable name for a finding: what a person types to re-check it. */
196
+ function findingId(f) {
197
+ return crypto.createHash('sha1').update(findingKey(f)).digest('hex').slice(0, 8);
198
+ }
199
+
200
+ function newFindings(before, after) {
201
+ const seen = new Set((before || []).map(findingKey));
202
+ return (after || []).filter((f) => !seen.has(findingKey(f)));
203
+ }
204
+
205
+ function goneFindings(before, after) {
206
+ const now = new Set((after || []).map(findingKey));
207
+ return (before || []).filter((f) => !now.has(findingKey(f)));
208
+ }
209
+
210
+ module.exports = {
211
+ PARTS: PARTS,
212
+ CHECKS_FOR: CHECKS_FOR,
213
+ partOf: partOf,
214
+ listFiles: listFiles,
215
+ takeSnapshot: takeSnapshot,
216
+ compare: compare,
217
+ dependencyChanges: dependencyChanges,
218
+ findingKey: findingKey,
219
+ findingId: findingId,
220
+ newFindings: newFindings,
221
+ goneFindings: goneFindings,
222
+ };
@@ -0,0 +1,192 @@
1
+ // The daily check: "Check my app" by itself, once a day at the time the person chose, while the laptop is on - and a
2
+ // note in the corner of the screen when it is done, saying what is new since the last time.
3
+ //
4
+ // Rules (kept here and by kryptheon-daily.check.js):
5
+ // - once a day: the day it ran is written down BEFORE it starts, so a crash or a second dashboard never runs it twice;
6
+ // - a laptop asleep at the time runs it once when it wakes, never once for every missed day;
7
+ // - one run at a time: while any run is going (the person's own, say), it waits and tries again a minute later;
8
+ // - a "Check my app" the person started themselves after today's time counts as today's: no second run;
9
+ // - checks that add test data to the app run only if the person ticked that, once, for this app; a step that opens
10
+ // an address that is not this computer never runs by itself;
11
+ // - the app not answering is said in the note, not hidden.
12
+ // The schedule lives in its own file next to the dashboard's settings (daily.json), so a change of any other setting
13
+ // never wipes it.
14
+
15
+ const fs = require('fs');
16
+ const path = require('path');
17
+ const { spawn } = require('child_process');
18
+
19
+ const FILE = 'daily.json';
20
+ const AT = /^([01]\d|2[0-3]):([0-5]\d)$/;
21
+
22
+ const fileOf = (paths) => path.join(path.dirname(paths.config), FILE);
23
+ const dayOf = (d) => d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
24
+
25
+ function read(paths) {
26
+ try {
27
+ const j = JSON.parse(fs.readFileSync(fileOf(paths), 'utf8'));
28
+ return Object.assign({ on: false, at: '09:00', addsData: false }, j && typeof j === 'object' ? j : {});
29
+ } catch (err) {
30
+ return { on: false, at: '09:00', addsData: false };
31
+ }
32
+ }
33
+
34
+ function write(paths, value) {
35
+ const file = fileOf(paths);
36
+ fs.mkdirSync(path.dirname(file), { recursive: true });
37
+ const tmp = file + '.' + process.pid + '.tmp';
38
+ fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + '\n', 'utf8');
39
+ fs.renameSync(tmp, file);
40
+ }
41
+
42
+ /** Saves the person's choice. { on, at: 'HH:MM', addsData }. */
43
+ function set(paths, input) {
44
+ const now = read(paths);
45
+ const at = input && typeof input.at === 'string' ? input.at.trim() : now.at;
46
+ if (!AT.test(at)) return { ok: false, why: 'a time like 09:00' };
47
+ const next = Object.assign({}, now, { on: Boolean(input && input.on), at, addsData: Boolean(input && input.addsData) });
48
+ // a new time later today than now, after today's run already happened earlier: it does not run again today
49
+ write(paths, next);
50
+ return { ok: true, daily: next };
51
+ }
52
+
53
+ /** Today's time to run, as a Date. */
54
+ function dueAt(schedule, now) {
55
+ const [h, m] = schedule.at.split(':').map(Number);
56
+ const d = new Date(now.getTime());
57
+ d.setHours(h, m, 0, 0);
58
+ return d;
59
+ }
60
+
61
+ /** Whether to start now, and why not. */
62
+ function decide(schedule, now, busy) {
63
+ if (!schedule.on) return { run: false, why: 'switched off' };
64
+ if (!AT.test(schedule.at)) return { run: false, why: 'no time set' };
65
+ const due = dueAt(schedule, now);
66
+ if (now < due) return { run: false, why: 'not time yet' };
67
+ if (schedule.lastDay === dayOf(now)) return { run: false, why: 'already ran today' };
68
+ if (schedule.lastFullRun && new Date(schedule.lastFullRun) >= due) return { run: false, why: 'you ran Check my app yourself after today\'s time' };
69
+ if (busy) return { run: false, why: 'another run is going - trying again in a minute' };
70
+ return { run: true };
71
+ }
72
+
73
+ /** The steps the daily run may take, from "Check my app"'s own plan: never a step that opens another computer's address. */
74
+ function stepsFor(plan, schedule) {
75
+ const steps = (plan.steps || []).filter((s) => !s.live && (schedule.addsData || !s.addsData));
76
+ const left = (plan.steps || []).filter((s) => !steps.includes(s)).map((s) => ({ id: s.id, label: s.label,
77
+ why: s.live ? 'it opens an address that is not this computer - it runs only when you start it' : 'it adds test data to your app - tick that in Every day to include it' }))
78
+ .concat(plan.skipped || []);
79
+ return { steps, left };
80
+ }
81
+
82
+ /** What changed between two lists of findings: { added: [headline], gone: [headline], still: n }. */
83
+ function compare(before, after) {
84
+ const key = (f) => String(f.id || f.key || f.headline || '');
85
+ const had = new Map((before || []).map((f) => [key(f), f]));
86
+ const has = new Map((after || []).map((f) => [key(f), f]));
87
+ return {
88
+ added: Array.from(has.keys()).filter((k) => !had.has(k)).map((k) => has.get(k).headline || k),
89
+ gone: Array.from(had.keys()).filter((k) => !has.has(k)).map((k) => had.get(k).headline || k),
90
+ still: Array.from(has.keys()).filter((k) => had.has(k)).length,
91
+ };
92
+ }
93
+
94
+ /** The note's two lines, in plain words. */
95
+ function noteOf(diff, result, left) {
96
+ if (result && result.ok === false) return { title: 'Kryptheon: today\'s check did not finish', body: String(result.why || 'it stopped').slice(0, 180) };
97
+ const parts = [];
98
+ if (diff.added.length) parts.push(diff.added.length + ' new problem' + (diff.added.length === 1 ? '' : 's'));
99
+ if (diff.gone.length) parts.push(diff.gone.length + ' fixed');
100
+ const title = 'Kryptheon: ' + (parts.length ? parts.join(', ') : diff.still ? 'nothing new' : 'all clear');
101
+ const body = diff.added.length ? 'New: ' + String(diff.added[0]).slice(0, 140) : diff.still ? diff.still + ' known problem' + (diff.still === 1 ? '' : 's') + ' still open.' : 'No problems found.';
102
+ return { title, body: body + (left && left.length ? ' (' + left.length + ' check' + (left.length === 1 ? '' : 's') + ' not run - see the dashboard)' : '') };
103
+ }
104
+
105
+ /**
106
+ * A note in the corner of the screen. The words go in through the environment, never into the command line, so a
107
+ * finding's text cannot become a command. Windows: a toast; macOS: osascript; Linux: notify-send. Never throws.
108
+ */
109
+ function notifyDesktop(note) {
110
+ try {
111
+ const env = Object.assign({}, process.env, { KX_NOTE_TITLE: String(note.title).slice(0, 120), KX_NOTE_BODY: String(note.body).slice(0, 240) });
112
+ if (process.platform === 'win32') {
113
+ const ps = [
114
+ '$t=[Security.SecurityElement]::Escape($env:KX_NOTE_TITLE);$b=[Security.SecurityElement]::Escape($env:KX_NOTE_BODY)',
115
+ '[Windows.UI.Notifications.ToastNotificationManager,Windows.UI.Notifications,ContentType=WindowsRuntime]|Out-Null',
116
+ '[Windows.Data.Xml.Dom.XmlDocument,Windows.Data.Xml.Dom.XmlDocument,ContentType=WindowsRuntime]|Out-Null',
117
+ '$x=New-Object Windows.Data.Xml.Dom.XmlDocument',
118
+ '$x.LoadXml("<toast><visual><binding template=`"ToastGeneric`"><text>$t</text><text>$b</text></binding></visual></toast>")',
119
+ '$id=\'{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe\'',
120
+ '[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($id).Show([Windows.UI.Notifications.ToastNotification]::new($x))',
121
+ ].join(';');
122
+ const kid = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', ps], { env, stdio: 'ignore', windowsHide: true });
123
+ kid.on('error', () => {});
124
+ return true;
125
+ }
126
+ if (process.platform === 'darwin') {
127
+ const kid = spawn('osascript', ['-e', 'display notification (system attribute "KX_NOTE_BODY") with title (system attribute "KX_NOTE_TITLE")'], { env, stdio: 'ignore' });
128
+ kid.on('error', () => {});
129
+ return true;
130
+ }
131
+ const kid = spawn('notify-send', [env.KX_NOTE_TITLE, env.KX_NOTE_BODY], { stdio: 'ignore' });
132
+ kid.on('error', () => {});
133
+ return true;
134
+ } catch (err) {
135
+ return false;
136
+ }
137
+ }
138
+
139
+ /**
140
+ * The clock. deps: { paths, jobs, plan(): everything plan, findings(): open findings, everything(steps, say, control, info),
141
+ * notify(note), now() }. tick() is called every minute; it returns what it did, for the checks.
142
+ */
143
+ function createDaily(deps) {
144
+ const now = deps.now || (() => new Date());
145
+ return {
146
+ tick() {
147
+ const schedule = read(deps.paths);
148
+ const at = now();
149
+ const d = decide(schedule, at, deps.jobs.busy());
150
+ if (!d.run) return { started: false, why: d.why };
151
+ const plan = deps.plan();
152
+ const { steps, left } = stepsFor(plan, schedule);
153
+ // written down before anything starts: once a day, whatever happens next
154
+ write(deps.paths, Object.assign({}, schedule, { lastDay: dayOf(at), lastStartedAt: at.toISOString() }));
155
+ if (!steps.length) {
156
+ const note = { title: 'Kryptheon: today\'s check could not run', body: String((left[0] && left[0].label + ': ' + left[0].why) || 'nothing can run from here yet').slice(0, 200) };
157
+ write(deps.paths, Object.assign(read(deps.paths), { lastResult: { at: at.toISOString(), note } }));
158
+ deps.notify(note);
159
+ return { started: false, why: 'nothing could run', note };
160
+ }
161
+ const before = deps.findings();
162
+ const job = deps.jobs.start('everything', 'Daily check (automatic)', 'started by itself at ' + schedule.at, (say, control) =>
163
+ Promise.resolve(deps.everything(steps, say, control, { origin: plan.origin, confirmed: [], skipped: left, daily: true })).then((result) => {
164
+ const diff = compare(before, deps.findings());
165
+ const note = noteOf(diff, result, left);
166
+ write(deps.paths, Object.assign(read(deps.paths), { lastResult: { at: new Date().toISOString(), note, added: diff.added.length, gone: diff.gone.length, still: diff.still } }));
167
+ deps.notify(note);
168
+ return result;
169
+ }));
170
+ return { started: Boolean(job), steps: steps.map((s) => s.id), left };
171
+ },
172
+ };
173
+ }
174
+
175
+ /** The person started "Check my app" themselves: today's daily run is then not needed after it. */
176
+ function markFullRun(paths, at) {
177
+ try { write(paths, Object.assign(read(paths), { lastFullRun: (at || new Date()).toISOString() })); } catch (err) { /* only a convenience */ }
178
+ }
179
+
180
+ /** For the page: the schedule, the next time, and the last result. */
181
+ function stateOf(paths, at) {
182
+ const s = read(paths);
183
+ const now = at || new Date();
184
+ let next = null;
185
+ if (s.on && AT.test(s.at)) {
186
+ const due = dueAt(s, now);
187
+ next = s.lastDay === dayOf(now) || now >= due ? new Date(due.getTime() + 24 * 3600 * 1000) : due;
188
+ }
189
+ return { on: s.on, at: s.at, addsData: s.addsData, next: next ? next.toISOString() : null, last: s.lastResult || null };
190
+ }
191
+
192
+ module.exports = { createDaily, decide, stepsFor, compare, noteOf, notifyDesktop, set, read, stateOf, markFullRun, dayOf, FILE };