@mainwave/cli 0.10.0 → 0.12.0
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.
- package/README.md +176 -13
- package/dist/adapters/claude-code.js +5 -4
- package/dist/adapters/claude-desktop.js +35 -1
- package/dist/adapters/copilot-chat.js +7 -13
- package/dist/adapters/copilot-cli.js +9 -12
- package/dist/adapters/cursor.js +7 -2
- package/dist/adapters/kiro.js +13 -8
- package/dist/commands.js +217 -0
- package/dist/core/apply.js +13 -5
- package/dist/core/auth-commands.js +2 -1
- package/dist/core/codecs/kiro-hooks-json.js +1 -1
- package/dist/core/doctor.js +71 -8
- package/dist/core/entry-script.js +9 -4
- package/dist/core/format.js +0 -1
- package/dist/core/hook-copies.js +157 -0
- package/dist/core/install-hooks.js +148 -10
- package/dist/core/interview.js +8 -2
- package/dist/core/markers.js +90 -24
- package/dist/core/post-setup.js +5 -22
- package/dist/core/redaction.js +179 -0
- package/dist/core/skills.js +6 -14
- package/dist/core/status.js +21 -1
- package/dist/core/store.js +255 -5
- package/dist/core/url.js +1 -0
- package/dist/core/wizard.js +101 -7
- package/dist/main.js +163 -162
- package/hooks/git-commit-marker.mjs +406 -0
- package/hooks/kiro-otlp.mjs +10 -1
- package/hooks/mainwave-hook.mjs +17 -5
- package/hooks/marker-core.mjs +56 -2
- package/hooks/matchers.json +20 -3
- package/hooks/redaction-data.mjs +201 -0
- package/hooks/redaction-json.mjs +215 -0
- package/hooks/redaction-pattern.mjs +503 -0
- package/hooks/redaction.d.mts +84 -0
- package/hooks/redaction.mjs +701 -0
- package/hooks/vocabulary.d.mts +13 -0
- package/hooks/vocabulary.mjs +42 -1
- package/package.json +9 -7
- package/skills/mainwave-instrument/SKILL.md +24 -6
- package/skills/mainwave-instrument/reference/frameworks.md +4 -2
- package/skills/mainwave-instrument/reference/troubleshooting.md +4 -0
- package/skills/mainwave-instrument-node/SKILL.md +81 -30
- package/skills/mainwave-instrument-node/reference/api.md +3 -3
- package/skills/mainwave-instrument-node/reference/frameworks.md +42 -25
- package/skills/mainwave-instrument-node/reference/troubleshooting.md +11 -7
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { isAbsolute, resolve } from 'node:path';
|
|
2
|
+
import { loadHookRedaction, readRedactionFile, recordedOrgPacks, REDACTION_PACKS, } from '../../hooks/redaction.mjs';
|
|
3
|
+
import { tildify } from './post-setup.js';
|
|
4
|
+
export const canonicalPacks = (names) => {
|
|
5
|
+
if (names.length === 0)
|
|
6
|
+
throw new Error('no redaction pack named');
|
|
7
|
+
const known = REDACTION_PACKS;
|
|
8
|
+
const seen = new Set();
|
|
9
|
+
for (const name of names) {
|
|
10
|
+
if (!known.includes(name)) {
|
|
11
|
+
throw new Error(`unknown redaction pack ${JSON.stringify(name)} (known: ${REDACTION_PACKS.join(', ')})`);
|
|
12
|
+
}
|
|
13
|
+
if (seen.has(name))
|
|
14
|
+
throw new Error(`redaction pack ${JSON.stringify(name)} is named twice`);
|
|
15
|
+
seen.add(name);
|
|
16
|
+
}
|
|
17
|
+
return REDACTION_PACKS.filter((name) => seen.has(name));
|
|
18
|
+
};
|
|
19
|
+
export const packOrder = (names) => {
|
|
20
|
+
const known = REDACTION_PACKS;
|
|
21
|
+
return [
|
|
22
|
+
...known.filter((name) => names.includes(name)),
|
|
23
|
+
...new Set(names.filter((name) => !known.includes(name))),
|
|
24
|
+
];
|
|
25
|
+
};
|
|
26
|
+
export const parseRedactionPacks = (value) => {
|
|
27
|
+
if (value === undefined || value.trim() === '') {
|
|
28
|
+
throw new Error(`--redaction-packs requires a comma-separated list of packs (${REDACTION_PACKS.join(', ')})`);
|
|
29
|
+
}
|
|
30
|
+
try {
|
|
31
|
+
return canonicalPacks(value.split(',').map((name) => name.trim()));
|
|
32
|
+
}
|
|
33
|
+
catch (err) {
|
|
34
|
+
throw new Error(`--redaction-packs: ${err instanceof Error ? err.message : String(err)}`);
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
export const redactionView = ({ configDir } = {}) => {
|
|
38
|
+
const loaded = loadHookRedaction({ configDir });
|
|
39
|
+
const configDirs = recordedOrgPacks();
|
|
40
|
+
const scoped = configDir === undefined
|
|
41
|
+
? packOrder(Object.values(configDirs).flat())
|
|
42
|
+
: packOrder(Object.entries(configDirs)
|
|
43
|
+
.filter(([dir]) => isAbsolute(dir) && resolve(dir) === resolve(configDir))
|
|
44
|
+
.flatMap(([, packs]) => packs));
|
|
45
|
+
const org = Object.keys(configDirs).length === 0
|
|
46
|
+
? {}
|
|
47
|
+
: {
|
|
48
|
+
org: {
|
|
49
|
+
setBy: 'managed-settings',
|
|
50
|
+
packs: scoped,
|
|
51
|
+
...(configDir === undefined ? {} : { configDir }),
|
|
52
|
+
configDirs,
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
if (loaded.state === 'off')
|
|
56
|
+
return { state: 'off', reason: 'secrets-off', ...org };
|
|
57
|
+
if (loaded.state === 'error') {
|
|
58
|
+
return {
|
|
59
|
+
state: 'error',
|
|
60
|
+
...(loaded.file === undefined ? {} : { file: loaded.file }),
|
|
61
|
+
...(loaded.org === true ? { cause: 'org' } : {}),
|
|
62
|
+
reason: loaded.reason,
|
|
63
|
+
...org,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
return {
|
|
67
|
+
state: 'on',
|
|
68
|
+
source: loaded.source,
|
|
69
|
+
...(loaded.source === 'file' ? { file: loaded.file } : {}),
|
|
70
|
+
packs: loaded.redactor.packs,
|
|
71
|
+
summary: loaded.redactor.summary,
|
|
72
|
+
...org,
|
|
73
|
+
};
|
|
74
|
+
};
|
|
75
|
+
export const hasRulesFile = (view) => view.state === 'error' || (view.state === 'on' && view.source === 'file');
|
|
76
|
+
export const checkRedactionFile = (path) => {
|
|
77
|
+
const file = resolve(path);
|
|
78
|
+
readRedactionFile(file);
|
|
79
|
+
return file;
|
|
80
|
+
};
|
|
81
|
+
export const nextRedactionChoice = (current, change) => {
|
|
82
|
+
if (change.file === undefined && change.noRedaction !== true && change.secrets === undefined) {
|
|
83
|
+
return undefined;
|
|
84
|
+
}
|
|
85
|
+
const base = typeof current === 'object' && current !== null && !Array.isArray(current);
|
|
86
|
+
const next = base ? { ...current } : {};
|
|
87
|
+
if (change.file !== undefined)
|
|
88
|
+
next.file = change.file;
|
|
89
|
+
else if (change.noRedaction === true)
|
|
90
|
+
delete next.file;
|
|
91
|
+
if (change.secrets === false)
|
|
92
|
+
next.secrets = false;
|
|
93
|
+
else if (change.secrets === true)
|
|
94
|
+
delete next.secrets;
|
|
95
|
+
return Object.keys(next).length === 0 ? null : next;
|
|
96
|
+
};
|
|
97
|
+
const SET_BY_ORG = "set by your organization's managed settings";
|
|
98
|
+
const orgLines = (org, indent) => {
|
|
99
|
+
if (org === undefined)
|
|
100
|
+
return [];
|
|
101
|
+
if (org.configDir !== undefined) {
|
|
102
|
+
return org.packs.length === 0
|
|
103
|
+
? []
|
|
104
|
+
: [`${indent} organization packs: ${org.packs.join(', ')} (${SET_BY_ORG})`];
|
|
105
|
+
}
|
|
106
|
+
const dirs = Object.entries(org.configDirs);
|
|
107
|
+
return [
|
|
108
|
+
`${indent} organization packs (${SET_BY_ORG}), by Claude config dir:`,
|
|
109
|
+
...dirs.map(([dir, packs]) => `${indent} ${tildify(dir)}: ${packs.join(', ')}`),
|
|
110
|
+
];
|
|
111
|
+
};
|
|
112
|
+
export const redactionLines = (view, indent = '') => {
|
|
113
|
+
if (view.state === 'off') {
|
|
114
|
+
return [
|
|
115
|
+
`${indent}off (secrets turned off)`,
|
|
116
|
+
`${indent} credentials are not stripped; run setup with --redact-secrets to turn the default back on`,
|
|
117
|
+
...orgLines(view.org, indent),
|
|
118
|
+
];
|
|
119
|
+
}
|
|
120
|
+
if (view.state === 'error') {
|
|
121
|
+
return [
|
|
122
|
+
`${indent}error — hooks send nothing until it is fixed`,
|
|
123
|
+
...(view.file === undefined ? [] : [`${indent} rules file: ${tildify(view.file)}`]),
|
|
124
|
+
`${indent} ${view.reason}`,
|
|
125
|
+
...orgLines(view.org, indent),
|
|
126
|
+
];
|
|
127
|
+
}
|
|
128
|
+
return [
|
|
129
|
+
view.file === undefined && (view.org?.packs.length ?? 0) === 0
|
|
130
|
+
? `${indent}on (default)`
|
|
131
|
+
: `${indent}on`,
|
|
132
|
+
...(view.file === undefined ? [] : [`${indent} rules file: ${tildify(view.file)}`]),
|
|
133
|
+
`${indent} packs: ${view.packs.length > 0 ? view.packs.join(', ') : 'none'}`,
|
|
134
|
+
...orgLines(view.org, indent),
|
|
135
|
+
`${indent} summary: ${view.summary}`,
|
|
136
|
+
];
|
|
137
|
+
};
|
|
138
|
+
const PROBE = {
|
|
139
|
+
collectorUrl: 'https://collector.invalid',
|
|
140
|
+
apiKey: 'redaction-probe',
|
|
141
|
+
};
|
|
142
|
+
const carriesOptIns = (adapter) => {
|
|
143
|
+
const all = (on) => ({
|
|
144
|
+
userPrompts: on,
|
|
145
|
+
toolDetails: on,
|
|
146
|
+
toolContent: on,
|
|
147
|
+
repository: on,
|
|
148
|
+
});
|
|
149
|
+
const build = (on) => JSON.stringify(adapter.buildEnv({ ...PROBE, optIns: all(on) }));
|
|
150
|
+
return build(true) !== build(false);
|
|
151
|
+
};
|
|
152
|
+
const exportsNatively = (adapter) => adapter.bundledHookScripts === undefined;
|
|
153
|
+
export const sendsUnredactedContent = (adapter, optIns) => {
|
|
154
|
+
if (!exportsNatively(adapter))
|
|
155
|
+
return false;
|
|
156
|
+
if (!carriesOptIns(adapter))
|
|
157
|
+
return true;
|
|
158
|
+
if (optIns === undefined)
|
|
159
|
+
return false;
|
|
160
|
+
return (optIns.userPrompts || optIns.toolDetails || optIns.toolContent || optIns.repository === true);
|
|
161
|
+
};
|
|
162
|
+
const list = (names) => names.length <= 2 ? names.join(' and ') : `${names.slice(0, -1).join(', ')} and ${names.at(-1)}`;
|
|
163
|
+
export const uncoveredNotice = (uncovered) => {
|
|
164
|
+
const names = uncovered.map((a) => a.displayName);
|
|
165
|
+
const switchable = uncovered.filter(carriesOptIns).map((a) => a.displayName);
|
|
166
|
+
const fixed = uncovered.filter((a) => !carriesOptIns(a)).map((a) => a.displayName);
|
|
167
|
+
return [
|
|
168
|
+
`Redaction covers the spans mainwave-cli's hooks send. ${list(names)} ` +
|
|
169
|
+
`${names.length === 1 ? 'exports' : 'export'} content through ` +
|
|
170
|
+
`${names.length === 1 ? 'its' : 'their'} own OpenTelemetry exporter, which the CLI is not in the ` +
|
|
171
|
+
'path of, so that content is not redacted.',
|
|
172
|
+
...(switchable.length > 0
|
|
173
|
+
? [`Run setup with --opt-in none to stop ${list(switchable)} sending content.`]
|
|
174
|
+
: []),
|
|
175
|
+
...(fixed.length > 0
|
|
176
|
+
? [`${list(fixed)}: what it exports is set where its export is configured, not by --opt-in.`]
|
|
177
|
+
: []),
|
|
178
|
+
].join(' ');
|
|
179
|
+
};
|
package/dist/core/skills.js
CHANGED
|
@@ -11,7 +11,7 @@ export const SKILL_NAMES = [
|
|
|
11
11
|
'mainwave-instrument-node',
|
|
12
12
|
];
|
|
13
13
|
export const packagedSkillsDir = () => fileURLToPath(new URL('../../skills/', import.meta.url));
|
|
14
|
-
|
|
14
|
+
const installedSkillsDir = () => join(homedir(), '.mainwave', 'skills');
|
|
15
15
|
export const copySkillBundle = async (name, srcRoot = packagedSkillsDir(), destRoot = installedSkillsDir()) => {
|
|
16
16
|
const src = join(srcRoot, name);
|
|
17
17
|
const dest = join(destRoot, name);
|
|
@@ -34,7 +34,7 @@ export const copySkillBundle = async (name, srcRoot = packagedSkillsDir(), destR
|
|
|
34
34
|
}
|
|
35
35
|
return dest;
|
|
36
36
|
};
|
|
37
|
-
|
|
37
|
+
const copyAllSkills = async (names = SKILL_NAMES, srcRoot = packagedSkillsDir(), destRoot = installedSkillsDir()) => {
|
|
38
38
|
const out = [];
|
|
39
39
|
for (const name of names)
|
|
40
40
|
out.push(await copySkillBundle(name, srcRoot, destRoot));
|
|
@@ -57,15 +57,7 @@ export const renderBlock = (version, skillsDir, names = SKILL_NAMES) => {
|
|
|
57
57
|
];
|
|
58
58
|
return lines.join('\n');
|
|
59
59
|
};
|
|
60
|
-
|
|
61
|
-
export const installedBlockVersion = (body) => {
|
|
62
|
-
for (const line of body.split('\n')) {
|
|
63
|
-
if (!isBlockOpen(line))
|
|
64
|
-
continue;
|
|
65
|
-
return /@([^\s]+) -->/.exec(line.slice(BLOCK_OPEN.length))?.[1];
|
|
66
|
-
}
|
|
67
|
-
return undefined;
|
|
68
|
-
};
|
|
60
|
+
const isBlockOpen = (line) => line.startsWith(BLOCK_OPEN);
|
|
69
61
|
export const stripBlocks = (body) => {
|
|
70
62
|
const out = [];
|
|
71
63
|
let inside = false;
|
|
@@ -132,8 +124,8 @@ export const planBlockRemoval = async (path) => {
|
|
|
132
124
|
note: `${path}: remove Mainwave's instructions, keep the rest`,
|
|
133
125
|
};
|
|
134
126
|
};
|
|
135
|
-
export const installToSurface = async (adapterName, surface,
|
|
136
|
-
const target =
|
|
127
|
+
export const installToSurface = async (adapterName, surface, version, srcRoot = packagedSkillsDir(), installedRoot = installedSkillsDir(), names = SKILL_NAMES) => {
|
|
128
|
+
const target = surface.global;
|
|
137
129
|
if (surface.kind === 'skill-dir') {
|
|
138
130
|
for (const name of names)
|
|
139
131
|
await copySkillBundle(name, srcRoot, target);
|
|
@@ -171,7 +163,7 @@ export const installSkillsPayload = async (adapters, version, srcRoot = packaged
|
|
|
171
163
|
if (seen.has(surface.global))
|
|
172
164
|
continue;
|
|
173
165
|
seen.add(surface.global);
|
|
174
|
-
installs.push(await installToSurface(adapter.name, surface,
|
|
166
|
+
installs.push(await installToSurface(adapter.name, surface, version, srcRoot, installedRoot, names));
|
|
175
167
|
}
|
|
176
168
|
return { installs, noOps, bundleDir: join(installedRoot) };
|
|
177
169
|
};
|
package/dist/core/status.js
CHANGED
|
@@ -4,6 +4,8 @@ import { adapterNames, adapters } from '../adapters/index.js';
|
|
|
4
4
|
import { color, maskSecret } from './format.js';
|
|
5
5
|
import { nativeIdentityReason } from './effective-settings.js';
|
|
6
6
|
import { tildify } from './post-setup.js';
|
|
7
|
+
import { copyAdvice, unredactedHookCopies } from './hook-copies.js';
|
|
8
|
+
import { hasRulesFile, redactionLines, redactionView } from './redaction.js';
|
|
7
9
|
import { ignoredKeysAt, policyState } from './layer-policy.js';
|
|
8
10
|
import { readExistingEnv } from './settings.js';
|
|
9
11
|
import { emitJson } from './ui.js';
|
|
@@ -260,11 +262,29 @@ const statusJsonFor = async (adapter) => {
|
|
|
260
262
|
};
|
|
261
263
|
export const runStatus = async (adapter, options = {}) => {
|
|
262
264
|
const targets = adapter !== undefined ? [adapter] : adapterNames().map((n) => adapters[n]);
|
|
265
|
+
const redaction = redactionView();
|
|
266
|
+
const unredacted = redaction.state === 'off'
|
|
267
|
+
? []
|
|
268
|
+
: await unredactedHookCopies(undefined, redaction.org !== undefined);
|
|
263
269
|
if (options.json) {
|
|
264
|
-
emitJson({
|
|
270
|
+
emitJson({
|
|
271
|
+
redaction: redaction.state === 'off' ? redaction : { ...redaction, unredactedHooks: unredacted },
|
|
272
|
+
adapters: await Promise.all(targets.map(statusJsonFor)),
|
|
273
|
+
});
|
|
265
274
|
return 0;
|
|
266
275
|
}
|
|
267
276
|
console.log(color.bold('mainwave-cli — current configuration'));
|
|
277
|
+
const [state, ...detail] = redactionLines(redaction);
|
|
278
|
+
console.log('');
|
|
279
|
+
console.log(`${color.bold('Redaction:')} ${state}`);
|
|
280
|
+
for (const line of detail)
|
|
281
|
+
console.log(color.dim(line));
|
|
282
|
+
for (const copy of unredacted) {
|
|
283
|
+
const serious = hasRulesFile(redaction) || copy.orgPacks === true;
|
|
284
|
+
console.log((serious ? color.red : color.yellow)(copy.orgPacks === true
|
|
285
|
+
? ` ✗ ${copy.what} in ${tildify(copy.path)} predate your organization's redaction packs and send spans without them. ${copyAdvice(copy)}`
|
|
286
|
+
: ` ${serious ? '✗' : '!'} ${copy.what} in ${tildify(copy.path)} predate redaction and send spans without it. ${copyAdvice(copy)}`));
|
|
287
|
+
}
|
|
268
288
|
for (const a of targets) {
|
|
269
289
|
for (const line of await renderAdapter(a)) {
|
|
270
290
|
console.log(line);
|
package/dist/core/store.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
1
2
|
import { promises as fs } from 'node:fs';
|
|
2
3
|
import { homedir } from 'node:os';
|
|
3
|
-
import { dirname, join } from 'node:path';
|
|
4
|
+
import { dirname, isAbsolute, join } from 'node:path';
|
|
4
5
|
import { isErrnoCode } from './settings.js';
|
|
5
|
-
|
|
6
|
+
import { trimSlash } from './url.js';
|
|
7
|
+
const mainwaveDir = () => join(homedir(), '.mainwave');
|
|
6
8
|
export const settingsPath = () => join(mainwaveDir(), 'settings.json');
|
|
7
9
|
export const credentialsPath = () => join(mainwaveDir(), 'credentials.json');
|
|
8
10
|
export const DEFAULTS = {
|
|
@@ -11,6 +13,7 @@ export const DEFAULTS = {
|
|
|
11
13
|
collectorUrl: 'https://collector.mainwave.com',
|
|
12
14
|
};
|
|
13
15
|
const FILE_MODE = 0o600;
|
|
16
|
+
const isPlainObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
14
17
|
const readJson = async (path) => {
|
|
15
18
|
let body;
|
|
16
19
|
try {
|
|
@@ -23,7 +26,7 @@ const readJson = async (path) => {
|
|
|
23
26
|
}
|
|
24
27
|
try {
|
|
25
28
|
const parsed = JSON.parse(body);
|
|
26
|
-
return
|
|
29
|
+
return isPlainObject(parsed) ? parsed : null;
|
|
27
30
|
}
|
|
28
31
|
catch {
|
|
29
32
|
return null;
|
|
@@ -41,8 +44,120 @@ const writeJson = async (path, value) => {
|
|
|
41
44
|
throw err;
|
|
42
45
|
}
|
|
43
46
|
};
|
|
47
|
+
const LOCK_WAIT_MS = 15_000;
|
|
48
|
+
const LOCK_STALE_MS = 10_000;
|
|
49
|
+
const LOCK_RETRY_MS = 25;
|
|
50
|
+
const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
|
|
51
|
+
const lockNonce = () => `${process.pid}.${randomBytes(8).toString('hex')}`;
|
|
52
|
+
const readLockOwner = async (lock) => {
|
|
53
|
+
try {
|
|
54
|
+
return await fs.readFile(lock, 'utf8');
|
|
55
|
+
}
|
|
56
|
+
catch (err) {
|
|
57
|
+
if (isErrnoCode(err, 'ENOENT'))
|
|
58
|
+
return undefined;
|
|
59
|
+
throw err;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
const takeOverStaleLock = async (lock, owner) => {
|
|
63
|
+
const taken = `${lock}.stale.${process.pid}.${Date.now()}`;
|
|
64
|
+
await fs.rename(lock, taken);
|
|
65
|
+
try {
|
|
66
|
+
if ((await readLockOwner(taken)) !== owner) {
|
|
67
|
+
await fs.link(taken, lock).catch((err) => {
|
|
68
|
+
if (!isErrnoCode(err, 'EEXIST'))
|
|
69
|
+
throw err;
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
finally {
|
|
74
|
+
await fs.rm(taken, { force: true });
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
export const withFileLock = async (path, work) => {
|
|
78
|
+
const lock = `${path}.lock`;
|
|
79
|
+
await fs.mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
80
|
+
const nonce = lockNonce();
|
|
81
|
+
const started = Date.now();
|
|
82
|
+
const deadline = started + LOCK_WAIT_MS;
|
|
83
|
+
for (;;) {
|
|
84
|
+
try {
|
|
85
|
+
const handle = await fs.open(lock, 'wx', FILE_MODE);
|
|
86
|
+
try {
|
|
87
|
+
await handle.writeFile(nonce);
|
|
88
|
+
}
|
|
89
|
+
finally {
|
|
90
|
+
await handle.close();
|
|
91
|
+
}
|
|
92
|
+
break;
|
|
93
|
+
}
|
|
94
|
+
catch (err) {
|
|
95
|
+
if (!isErrnoCode(err, 'EEXIST'))
|
|
96
|
+
throw err;
|
|
97
|
+
}
|
|
98
|
+
try {
|
|
99
|
+
const owner = await readLockOwner(lock);
|
|
100
|
+
if (owner === undefined)
|
|
101
|
+
continue;
|
|
102
|
+
const { mtimeMs } = await fs.stat(lock);
|
|
103
|
+
const age = Date.now() - mtimeMs;
|
|
104
|
+
if (age > LOCK_STALE_MS || (age < 0 && Date.now() - started > LOCK_STALE_MS)) {
|
|
105
|
+
await takeOverStaleLock(lock, owner);
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
catch (err) {
|
|
110
|
+
if (isErrnoCode(err, 'ENOENT'))
|
|
111
|
+
continue;
|
|
112
|
+
throw err;
|
|
113
|
+
}
|
|
114
|
+
if (Date.now() >= deadline) {
|
|
115
|
+
throw new Error(`${path} is being written by another mainwave-cli run (${lock} is held). ` +
|
|
116
|
+
'Run the command again; if no other run is active, remove that file.');
|
|
117
|
+
}
|
|
118
|
+
await sleep(LOCK_RETRY_MS);
|
|
119
|
+
}
|
|
120
|
+
try {
|
|
121
|
+
return await work();
|
|
122
|
+
}
|
|
123
|
+
finally {
|
|
124
|
+
if ((await readLockOwner(lock).catch(() => undefined)) === nonce) {
|
|
125
|
+
await fs.rm(lock, { force: true });
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
};
|
|
44
129
|
export const readSettings = async () => (await readJson(settingsPath())) ?? {};
|
|
45
|
-
export
|
|
130
|
+
export class SettingsFileError extends Error {
|
|
131
|
+
path;
|
|
132
|
+
constructor(path) {
|
|
133
|
+
super(`${path} is not valid JSON, but it mentions "redaction", so the CLI will not overwrite it ` +
|
|
134
|
+
'and risk dropping your redaction setting. Fix the file, or remove it, then run the command again.');
|
|
135
|
+
this.name = 'SettingsFileError';
|
|
136
|
+
this.path = path;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
export const assertSettingsWritable = async () => {
|
|
140
|
+
const path = settingsPath();
|
|
141
|
+
let body;
|
|
142
|
+
try {
|
|
143
|
+
body = await fs.readFile(path, 'utf8');
|
|
144
|
+
}
|
|
145
|
+
catch (err) {
|
|
146
|
+
if (isErrnoCode(err, 'ENOENT') || isErrnoCode(err, 'ENOTDIR'))
|
|
147
|
+
return;
|
|
148
|
+
throw err;
|
|
149
|
+
}
|
|
150
|
+
try {
|
|
151
|
+
if (isPlainObject(JSON.parse(body)))
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
}
|
|
156
|
+
if (body.includes('"redaction"'))
|
|
157
|
+
throw new SettingsFileError(path);
|
|
158
|
+
};
|
|
159
|
+
export const updateSettings = async (patch) => withFileLock(settingsPath(), async () => {
|
|
160
|
+
await assertSettingsWritable();
|
|
46
161
|
const current = await readSettings();
|
|
47
162
|
const next = { ...current };
|
|
48
163
|
for (const [key, value] of Object.entries(patch)) {
|
|
@@ -51,8 +166,144 @@ export const updateSettings = async (patch) => {
|
|
|
51
166
|
else if (value !== undefined)
|
|
52
167
|
Object.assign(next, { [key]: value });
|
|
53
168
|
}
|
|
169
|
+
if (patch.redaction !== undefined && isPlainObject(current.redaction)) {
|
|
170
|
+
const { org } = current.redaction;
|
|
171
|
+
if (org !== undefined)
|
|
172
|
+
next.redaction = { ...next.redaction, org };
|
|
173
|
+
}
|
|
54
174
|
await writeJson(settingsPath(), next);
|
|
55
175
|
return next;
|
|
176
|
+
});
|
|
177
|
+
export const KEEP_ORG_PACKS = 'keep';
|
|
178
|
+
export const hasOrgEntry = async (configDir, path) => orgDirsIn(await readSettingsText(path)).includes(configDir);
|
|
179
|
+
const sameList = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
|
|
180
|
+
const dirIsGone = async (dir) => {
|
|
181
|
+
try {
|
|
182
|
+
await fs.stat(dir);
|
|
183
|
+
return false;
|
|
184
|
+
}
|
|
185
|
+
catch (err) {
|
|
186
|
+
if (!isErrnoCode(err, 'ENOENT') && !isErrnoCode(err, 'ENOTDIR'))
|
|
187
|
+
return false;
|
|
188
|
+
}
|
|
189
|
+
try {
|
|
190
|
+
return (await fs.stat(dirname(dir))).isDirectory();
|
|
191
|
+
}
|
|
192
|
+
catch {
|
|
193
|
+
return false;
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
const goneEntries = async (dirs, configDir) => {
|
|
197
|
+
const gone = [];
|
|
198
|
+
for (const dir of dirs) {
|
|
199
|
+
if (dir !== configDir && isAbsolute(dir) && (await dirIsGone(dir)))
|
|
200
|
+
gone.push(dir);
|
|
201
|
+
}
|
|
202
|
+
return gone;
|
|
203
|
+
};
|
|
204
|
+
const readSettingsText = async (path) => {
|
|
205
|
+
try {
|
|
206
|
+
return await fs.readFile(path, 'utf8');
|
|
207
|
+
}
|
|
208
|
+
catch (err) {
|
|
209
|
+
if (!isErrnoCode(err, 'ENOENT') && !isErrnoCode(err, 'ENOTDIR'))
|
|
210
|
+
throw err;
|
|
211
|
+
return undefined;
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
const orgDirsIn = (body) => {
|
|
215
|
+
if (body === undefined)
|
|
216
|
+
return [];
|
|
217
|
+
try {
|
|
218
|
+
const redaction = JSON.parse(body)?.redaction;
|
|
219
|
+
const org = isPlainObject(redaction) ? redaction.org : undefined;
|
|
220
|
+
return isPlainObject(org) ? Object.keys(org) : [];
|
|
221
|
+
}
|
|
222
|
+
catch {
|
|
223
|
+
return [];
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
const planOrgSync = (body, path, configDir, packs, gone) => {
|
|
227
|
+
const keep = packs === KEEP_ORG_PACKS;
|
|
228
|
+
const set = keep ? undefined : packs;
|
|
229
|
+
let doc = {};
|
|
230
|
+
if (body !== undefined) {
|
|
231
|
+
let parsed;
|
|
232
|
+
try {
|
|
233
|
+
parsed = JSON.parse(body);
|
|
234
|
+
}
|
|
235
|
+
catch {
|
|
236
|
+
parsed = undefined;
|
|
237
|
+
}
|
|
238
|
+
if (isPlainObject(parsed))
|
|
239
|
+
doc = parsed;
|
|
240
|
+
else {
|
|
241
|
+
if (set === undefined)
|
|
242
|
+
return { result: 'unchanged' };
|
|
243
|
+
if (body.includes('"redaction"'))
|
|
244
|
+
throw new SettingsFileError(path);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
const redaction = doc.redaction;
|
|
248
|
+
if (redaction !== undefined && !isPlainObject(redaction)) {
|
|
249
|
+
if (set === undefined)
|
|
250
|
+
return { result: 'unchanged' };
|
|
251
|
+
throw new Error(`${path}: redaction is not an object, so your organization's redaction packs cannot be recorded. ` +
|
|
252
|
+
'Fix the file, then start a new session.');
|
|
253
|
+
}
|
|
254
|
+
const current = (redaction ?? {});
|
|
255
|
+
const org = isPlainObject(current.org) ? current.org : {};
|
|
256
|
+
const entry = org[configDir];
|
|
257
|
+
const recorded = isPlainObject(entry) && Array.isArray(entry.packs)
|
|
258
|
+
? entry.packs
|
|
259
|
+
: undefined;
|
|
260
|
+
const malformed = !keep && current.org !== undefined && !isPlainObject(current.org);
|
|
261
|
+
const goneNow = gone.filter((dir) => dir !== configDir && Object.hasOwn(org, dir));
|
|
262
|
+
const sameEntry = keep
|
|
263
|
+
? true
|
|
264
|
+
: set === undefined
|
|
265
|
+
? entry === undefined
|
|
266
|
+
: recorded !== undefined && sameList(recorded, set);
|
|
267
|
+
if (sameEntry && !malformed && goneNow.length === 0)
|
|
268
|
+
return { result: 'unchanged' };
|
|
269
|
+
const nextOrg = { ...org };
|
|
270
|
+
for (const dir of goneNow)
|
|
271
|
+
delete nextOrg[dir];
|
|
272
|
+
if (set === undefined) {
|
|
273
|
+
if (!keep)
|
|
274
|
+
delete nextOrg[configDir];
|
|
275
|
+
}
|
|
276
|
+
else
|
|
277
|
+
nextOrg[configDir] = { packs: [...set] };
|
|
278
|
+
const nextRedaction = { ...current };
|
|
279
|
+
if (Object.keys(nextOrg).length === 0)
|
|
280
|
+
delete nextRedaction.org;
|
|
281
|
+
else
|
|
282
|
+
nextRedaction.org = nextOrg;
|
|
283
|
+
const next = { ...doc };
|
|
284
|
+
if (Object.keys(nextRedaction).length === 0)
|
|
285
|
+
delete next.redaction;
|
|
286
|
+
else
|
|
287
|
+
next.redaction = nextRedaction;
|
|
288
|
+
return {
|
|
289
|
+
result: sameEntry && !malformed ? 'pruned' : set === undefined ? 'cleared' : 'set',
|
|
290
|
+
next,
|
|
291
|
+
};
|
|
292
|
+
};
|
|
293
|
+
export const syncOrgRedaction = async (configDir, packs, path = settingsPath()) => {
|
|
294
|
+
const first = await readSettingsText(path);
|
|
295
|
+
const candidates = await goneEntries(orgDirsIn(first), configDir);
|
|
296
|
+
if (planOrgSync(first, path, configDir, packs, candidates).result === 'unchanged') {
|
|
297
|
+
return 'unchanged';
|
|
298
|
+
}
|
|
299
|
+
return withFileLock(path, async () => {
|
|
300
|
+
const body = await readSettingsText(path);
|
|
301
|
+
const plan = planOrgSync(body, path, configDir, packs, await goneEntries(candidates, configDir));
|
|
302
|
+
if (plan.result === 'unchanged')
|
|
303
|
+
return 'unchanged';
|
|
304
|
+
await writeJson(path, plan.next);
|
|
305
|
+
return plan.result;
|
|
306
|
+
});
|
|
56
307
|
};
|
|
57
308
|
export const readCredentials = async () => (await readJson(credentialsPath())) ?? {};
|
|
58
309
|
export const writeCredentials = async (credentials) => {
|
|
@@ -76,7 +327,6 @@ export const rememberKey = async (orgId, key) => {
|
|
|
76
327
|
const credentials = await readCredentials();
|
|
77
328
|
await writeCredentials({ ...credentials, keys: { ...credentials.keys, [orgId]: key } });
|
|
78
329
|
};
|
|
79
|
-
const trimSlash = (url) => url.replace(/\/+$/, '');
|
|
80
330
|
export const resolveEndpoints = (settings, overrides = {}, env = process.env) => ({
|
|
81
331
|
apiUrl: trimSlash(overrides.apiUrl ?? env.MAINWAVE_API_URL ?? settings.apiUrl ?? DEFAULTS.apiUrl),
|
|
82
332
|
appUrl: trimSlash(overrides.appUrl ?? env.MAINWAVE_APP_URL ?? settings.appUrl ?? DEFAULTS.appUrl),
|
package/dist/core/url.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const trimSlash = (url) => url.replace(/\/+$/, '');
|