toolcrib 0.1.1 → 0.2.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 +10 -0
- package/package.json +1 -1
- package/src/commands/doctor.js +56 -1
- package/src/commands/init.js +50 -6
- package/src/index.js +16 -3
- package/src/lib/fences.js +27 -12
- package/src/lib/patchFallback.js +15 -0
- package/src/lib/project.js +11 -0
- package/src/lib/zip.js +28 -5
package/README.md
CHANGED
|
@@ -141,6 +141,16 @@ anything. It reports:
|
|
|
141
141
|
needs a `'use client'` directive, since Next's App Router treats
|
|
142
142
|
components as server-only by default.
|
|
143
143
|
|
|
144
|
+
**`--reprint-managed-block [docId]`** re-prints the current managed block(s)
|
|
145
|
+
to stdout instead of running the checks above — for re-injecting the
|
|
146
|
+
primer into an agent session that's lost it to context compaction,
|
|
147
|
+
without starting a new session:
|
|
148
|
+
|
|
149
|
+
```bash
|
|
150
|
+
toolcrib doctor --reprint-managed-block # every block found
|
|
151
|
+
toolcrib doctor --reprint-managed-block core # just one docId
|
|
152
|
+
```
|
|
153
|
+
|
|
144
154
|
### `toolcrib merge`
|
|
145
155
|
|
|
146
156
|
Stages an upgrade from your currently installed version to another.
|
package/package.json
CHANGED
package/src/commands/doctor.js
CHANGED
|
@@ -92,14 +92,69 @@ export async function checkManagedBlocks(projectRoot, installedRelease) {
|
|
|
92
92
|
return messages;
|
|
93
93
|
}
|
|
94
94
|
|
|
95
|
+
/**
|
|
96
|
+
* Every managed block currently sitting in AGENTS.md/CLAUDE.md, available
|
|
97
|
+
* to reprint on demand — no network access, no lockfile requirement, just
|
|
98
|
+
* `listManagedBlocks` over whatever's already on disk. `docIdFilter`
|
|
99
|
+
* narrows to one docId; omitted, every block found across both files is
|
|
100
|
+
* returned. Doesn't validate `docIdFilter` against MANAGED_DOCS itself —
|
|
101
|
+
* an unrecognized filter here would just silently produce `[]`, the wrong
|
|
102
|
+
* failure mode for a typo'd docId, so that check lives in the caller.
|
|
103
|
+
*/
|
|
104
|
+
export function listReprintableBlocks(projectRoot, docIdFilter) {
|
|
105
|
+
const results = [];
|
|
106
|
+
for (const targetFile of KNOWN_TARGET_FILES) {
|
|
107
|
+
const content = readTextIfExists(path.join(projectRoot, targetFile));
|
|
108
|
+
if (!content) continue;
|
|
109
|
+
for (const block of listManagedBlocks(content)) {
|
|
110
|
+
if (docIdFilter && block.docId !== docIdFilter) continue;
|
|
111
|
+
results.push({ targetFile, ...block });
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return results;
|
|
115
|
+
}
|
|
116
|
+
|
|
95
117
|
/**
|
|
96
118
|
* Reports drift without staging any patches — a read-only diagnostic.
|
|
97
119
|
* "No drift" here answers a different question than "are you on the
|
|
98
120
|
* latest version," which is checked separately below; the two are
|
|
99
121
|
* deliberately not conflated (see design notes).
|
|
100
122
|
*/
|
|
101
|
-
export async function doctorCommand() {
|
|
123
|
+
export async function doctorCommand(options = {}) {
|
|
102
124
|
const projectRoot = process.cwd();
|
|
125
|
+
|
|
126
|
+
// Reprint mode is a different question entirely from everything below —
|
|
127
|
+
// "what's the current managed-block content" rather than "has anything
|
|
128
|
+
// drifted" — so it branches before p.intro/readLock and skips both.
|
|
129
|
+
// Left entirely clack-free (no p.log, no intro/outro): the block content
|
|
130
|
+
// is meant to be re-fed into an agent's context, and clack's per-line
|
|
131
|
+
// `│` decoration would corrupt copy/paste of multi-line Markdown: kept
|
|
132
|
+
// the whole branch undecorated rather than just the payload lines, so
|
|
133
|
+
// there's no orphaned p.log message with no intro/outro frame around it.
|
|
134
|
+
if (options.reprintManagedBlock !== undefined) {
|
|
135
|
+
const docIdFilter = options.reprintManagedBlock === true ? undefined : options.reprintManagedBlock;
|
|
136
|
+
if (docIdFilter !== undefined && !MANAGED_DOCS[docIdFilter]) {
|
|
137
|
+
console.error(`Unknown docId "${docIdFilter}" — expected one of: ${Object.keys(MANAGED_DOCS).join(', ')}`);
|
|
138
|
+
process.exitCode = 1;
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
const blocks = listReprintableBlocks(projectRoot, docIdFilter);
|
|
142
|
+
if (blocks.length === 0) {
|
|
143
|
+
console.warn(
|
|
144
|
+
docIdFilter
|
|
145
|
+
? `No managed block "${docIdFilter}" found in AGENTS.md/CLAUDE.md.`
|
|
146
|
+
: 'No managed blocks found in AGENTS.md/CLAUDE.md — nothing to reprint.'
|
|
147
|
+
);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
for (const block of blocks) {
|
|
151
|
+
console.log(`--- ${block.targetFile}: managed block "${block.docId}" (v${block.version}) ---`);
|
|
152
|
+
console.log(block.content);
|
|
153
|
+
console.log('');
|
|
154
|
+
}
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
|
|
103
158
|
p.intro('toolcrib doctor');
|
|
104
159
|
|
|
105
160
|
const lock = readLock(projectRoot);
|
package/src/commands/init.js
CHANGED
|
@@ -3,8 +3,8 @@ import * as p from '@clack/prompts';
|
|
|
3
3
|
import { fetchRelease } from '../lib/release.js';
|
|
4
4
|
import { PendingChanges, joinPatchPath } from '../lib/patches.js';
|
|
5
5
|
import { resolveDependencyDecisions, buildProposedPackageJson, mergeImportsField } from '../lib/deps.js';
|
|
6
|
-
import { readJsonIfExists, readTextIfExists, proposeGitignore, proposeLockUpdate } from '../lib/project.js';
|
|
7
|
-
import { MANAGED_DOCS, DEFAULT_TARGET_FILE, upsertManagedBlock } from '../lib/managedDocs.js';
|
|
6
|
+
import { readJsonIfExists, readTextIfExists, fileExists, proposeGitignore, proposeLockUpdate } from '../lib/project.js';
|
|
7
|
+
import { MANAGED_DOCS, DEFAULT_TARGET_FILE, KNOWN_TARGET_FILES, upsertManagedBlock } from '../lib/managedDocs.js';
|
|
8
8
|
|
|
9
9
|
const TOOLKIT_DIR = './toolcrib';
|
|
10
10
|
// The subpath-imports entry that gives consumer code a stable, file-location-
|
|
@@ -16,6 +16,23 @@ const TOOLKIT_IMPORTS_ENTRY = { '#toolcrib': './toolcrib/index.ts' };
|
|
|
16
16
|
// docIds always written, plus the situational one --situation selects.
|
|
17
17
|
const SITUATION_TO_DOC_ID = { new: 'new-app', refactor: 'refactor-app' };
|
|
18
18
|
|
|
19
|
+
/**
|
|
20
|
+
* Which instruction file to write the managed block into. Mirrors what
|
|
21
|
+
* doctor/merge already scan (KNOWN_TARGET_FILES) rather than always
|
|
22
|
+
* defaulting to AGENTS.md — a project that already has a CLAUDE.md (e.g.
|
|
23
|
+
* an existing Claude Code setup) and no AGENTS.md would otherwise get a
|
|
24
|
+
* brand-new AGENTS.md sitting unused next to the file its own assistant
|
|
25
|
+
* actually reads, while merge/doctor go on dutifully tracking blocks in
|
|
26
|
+
* both. First existing file wins; DEFAULT_TARGET_FILE only applies when
|
|
27
|
+
* neither is present yet.
|
|
28
|
+
*/
|
|
29
|
+
function resolveTargetFile(projectRoot) {
|
|
30
|
+
for (const file of KNOWN_TARGET_FILES) {
|
|
31
|
+
if (readTextIfExists(path.join(projectRoot, file))) return file;
|
|
32
|
+
}
|
|
33
|
+
return DEFAULT_TARGET_FILE;
|
|
34
|
+
}
|
|
35
|
+
|
|
19
36
|
export async function initCommand(options) {
|
|
20
37
|
const projectRoot = process.cwd();
|
|
21
38
|
|
|
@@ -93,7 +110,11 @@ export async function initCommand(options) {
|
|
|
93
110
|
const situationDocId = SITUATION_TO_DOC_ID[options.situation];
|
|
94
111
|
const docIdsToWrite = situationDocId ? ['core', situationDocId] : ['core'];
|
|
95
112
|
|
|
96
|
-
const
|
|
113
|
+
const agentsFileExisted = fileExists(path.join(projectRoot, 'AGENTS.md'));
|
|
114
|
+
const claudeFileExisted = fileExists(path.join(projectRoot, 'CLAUDE.md'));
|
|
115
|
+
|
|
116
|
+
const targetFile = resolveTargetFile(projectRoot);
|
|
117
|
+
const agentsPath = path.join(projectRoot, targetFile);
|
|
97
118
|
const originalAgentsContent = readTextIfExists(agentsPath);
|
|
98
119
|
let proposedAgentsContent = originalAgentsContent;
|
|
99
120
|
for (const docId of docIdsToWrite) {
|
|
@@ -101,7 +122,23 @@ export async function initCommand(options) {
|
|
|
101
122
|
proposedAgentsContent = upsertManagedBlock(proposedAgentsContent, docId, release.version, docContent);
|
|
102
123
|
}
|
|
103
124
|
if (proposedAgentsContent !== originalAgentsContent) {
|
|
104
|
-
changes.propose(
|
|
125
|
+
changes.propose(targetFile, originalAgentsContent, proposedAgentsContent, targetFile);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// 5b. Claude Code discovery: Claude Code reads CLAUDE.md by default, not
|
|
129
|
+
// AGENTS.md (this repo's own root CLAUDE.md is a one-line `@AGENTS.md`
|
|
130
|
+
// import for exactly that reason). resolveTargetFile() only falls back to
|
|
131
|
+
// AGENTS.md when NEITHER file existed yet — in that specific case, a
|
|
132
|
+
// Claude Code user would otherwise get instructions their own tool never
|
|
133
|
+
// discovers. Scoped strictly to that case: an existing AGENTS.md-only
|
|
134
|
+
// setup (even without a CLAUDE.md) reflects a choice already made and
|
|
135
|
+
// shouldn't be second-guessed uninvited. Staged as its own independent
|
|
136
|
+
// patch (see PendingChanges.propose), so a non-Claude-Code user can just
|
|
137
|
+
// delete that one patch file before `toolcrib apply` and keep everything
|
|
138
|
+
// else.
|
|
139
|
+
const claudeStubProposed = !agentsFileExisted && !claudeFileExisted && targetFile === 'AGENTS.md';
|
|
140
|
+
if (claudeStubProposed) {
|
|
141
|
+
changes.propose('CLAUDE.md', '', '@AGENTS.md\n', 'CLAUDE.md');
|
|
105
142
|
}
|
|
106
143
|
|
|
107
144
|
await release.cleanup();
|
|
@@ -117,15 +154,22 @@ export async function initCommand(options) {
|
|
|
117
154
|
reportConflicts(depDecisions);
|
|
118
155
|
|
|
119
156
|
const missingSituation = !situationDocId
|
|
120
|
-
? `\n\nThis staged a "core" block in ${
|
|
157
|
+
? `\n\nThis staged a "core" block in ${targetFile}, but not a situational one — re-run with ` +
|
|
121
158
|
`--situation new (greenfield project) or --situation refactor (adopting into an existing app) to add it, ` +
|
|
122
159
|
`or add it by hand wrapped in the same <!-- toolcrib:managed:... --> fence so 'toolcrib merge' can still ` +
|
|
123
160
|
`track it. See ./toolcrib/ai-docs/NEW_APP.md / REFACTOR_APP.md.`
|
|
124
161
|
: '';
|
|
125
162
|
|
|
163
|
+
const claudeStubNote = claudeStubProposed
|
|
164
|
+
? `\n\nAlso staged a minimal CLAUDE.md (\`@AGENTS.md\`) since neither file existed yet — Claude Code reads ` +
|
|
165
|
+
`CLAUDE.md by default, not AGENTS.md, so this is what makes the staged instructions visible to it. Not ` +
|
|
166
|
+
`using Claude Code? Delete the CLAUDE.md patch under ./toolcrib-patches/ before running 'toolcrib apply' ` +
|
|
167
|
+
`and everything else still applies cleanly.`
|
|
168
|
+
: '';
|
|
169
|
+
|
|
126
170
|
p.outro(
|
|
127
171
|
`Review the patches in ./toolcrib-patches/, then run:\n` +
|
|
128
|
-
` toolcrib apply${missingSituation}`
|
|
172
|
+
` toolcrib apply${missingSituation}${claudeStubNote}`
|
|
129
173
|
);
|
|
130
174
|
}
|
|
131
175
|
|
package/src/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
2
3
|
import { Command } from 'commander';
|
|
3
4
|
import { initCommand } from './commands/init.js';
|
|
4
5
|
import { mergeCommand } from './commands/merge.js';
|
|
@@ -6,6 +7,14 @@ import { applyCommand } from './commands/apply.js';
|
|
|
6
7
|
import { doctorCommand } from './commands/doctor.js';
|
|
7
8
|
import { versionsCommand } from './commands/versions.js';
|
|
8
9
|
|
|
10
|
+
// Read at runtime instead of a JSON import assertion: `assert { type: 'json' }`
|
|
11
|
+
// vs `with { type: 'json' }` differs across the Node 18-22 range this CLI's
|
|
12
|
+
// `engines.node >= 18` promises to support, so plain fs avoids picking a
|
|
13
|
+
// syntax that breaks on some of those versions.
|
|
14
|
+
const packageJson = JSON.parse(
|
|
15
|
+
readFileSync(new URL('../package.json', import.meta.url), 'utf8')
|
|
16
|
+
);
|
|
17
|
+
|
|
9
18
|
const program = new Command();
|
|
10
19
|
|
|
11
20
|
// Without this, commander resolves `--version` anywhere in argv against the
|
|
@@ -20,7 +29,7 @@ program.enablePositionalOptions();
|
|
|
20
29
|
program
|
|
21
30
|
.name('toolcrib')
|
|
22
31
|
.description('Bootstrap and maintain the toolcrib UI toolkit in your project')
|
|
23
|
-
.version(
|
|
32
|
+
.version(packageJson.version);
|
|
24
33
|
|
|
25
34
|
program
|
|
26
35
|
.command('init')
|
|
@@ -52,8 +61,12 @@ program
|
|
|
52
61
|
program
|
|
53
62
|
.command('doctor')
|
|
54
63
|
.description('Check installed files for local drift and available updates (read-only)')
|
|
55
|
-
.
|
|
56
|
-
|
|
64
|
+
.option(
|
|
65
|
+
'--reprint-managed-block [docId]',
|
|
66
|
+
're-print the current managed block(s) to stdout, for re-injecting into an agent session that lost the primer to context compaction; optionally scope to one docId (core/new-app/refactor-app)'
|
|
67
|
+
)
|
|
68
|
+
.action(async (options) => {
|
|
69
|
+
await doctorCommand(options).catch(fail);
|
|
57
70
|
});
|
|
58
71
|
|
|
59
72
|
program
|
package/src/lib/fences.js
CHANGED
|
@@ -35,6 +35,10 @@ function bannerFor(style) {
|
|
|
35
35
|
return style === 'markdown' ? `<!-- ${text} -->` : style === 'hash' ? `# ${text}` : `// ${text}`;
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
+
function escapeRegExp(text) {
|
|
39
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
40
|
+
}
|
|
41
|
+
|
|
38
42
|
export const FENCE_STYLES = {
|
|
39
43
|
// Markdown / HTML-comment files: AGENTS.md, CLAUDE.md.
|
|
40
44
|
markdown: {
|
|
@@ -50,18 +54,31 @@ export const FENCE_STYLES = {
|
|
|
50
54
|
// content run through normalize() by their callers (doctor.js,
|
|
51
55
|
// merge.js) so a pure line-ending difference is never itself reported
|
|
52
56
|
// as drift — this is about matching the fence at all.
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
+
//
|
|
58
|
+
// `id` is escaped before interpolation into the RegExp source — every
|
|
59
|
+
// `id` this CLI actually passes today is a fixed internal constant
|
|
60
|
+
// ('gitignore', 'core', 'new-app', 'refactor-app'), never attacker- or
|
|
61
|
+
// even user-controlled, so this has never been reachable in practice.
|
|
62
|
+
// Escaping anyway costs nothing and means that stays true by
|
|
63
|
+
// construction rather than by every future caller happening to keep
|
|
64
|
+
// passing safe ids — the same reasoning as escaping the version string,
|
|
65
|
+
// just not yet applied here consistently.
|
|
66
|
+
pattern: (id) => {
|
|
67
|
+
const safeId = escapeRegExp(id);
|
|
68
|
+
return new RegExp(
|
|
69
|
+
`<!-- toolcrib:managed:${safeId}:start version=(\\S+) -->\\r?\\n([\\s\\S]*?)<!-- toolcrib:managed:${safeId}:end -->\\r?\\n?`
|
|
70
|
+
);
|
|
71
|
+
},
|
|
57
72
|
},
|
|
58
73
|
// #-comment files: .gitignore, .env, YAML, shell scripts.
|
|
59
74
|
hash: {
|
|
60
75
|
start: (id, version) => `# toolcrib:managed:${id}:start version=${version}`,
|
|
61
76
|
banner: () => bannerFor('hash'),
|
|
62
77
|
end: (id) => `# toolcrib:managed:${id}:end`,
|
|
63
|
-
pattern: (id) =>
|
|
64
|
-
|
|
78
|
+
pattern: (id) => {
|
|
79
|
+
const safeId = escapeRegExp(id);
|
|
80
|
+
return new RegExp(`# toolcrib:managed:${safeId}:start version=(\\S+)\\r?\\n([\\s\\S]*?)# toolcrib:managed:${safeId}:end\\r?\\n?`);
|
|
81
|
+
},
|
|
65
82
|
},
|
|
66
83
|
// JS/TS/JSX/TSX source files. Not used by any current CLI feature — no
|
|
67
84
|
// command patches user source code yet — but defined here so a future
|
|
@@ -72,8 +89,10 @@ export const FENCE_STYLES = {
|
|
|
72
89
|
start: (id, version) => `// toolcrib:managed:${id}:start version=${version}`,
|
|
73
90
|
banner: () => bannerFor('js'),
|
|
74
91
|
end: (id) => `// toolcrib:managed:${id}:end`,
|
|
75
|
-
pattern: (id) =>
|
|
76
|
-
|
|
92
|
+
pattern: (id) => {
|
|
93
|
+
const safeId = escapeRegExp(id);
|
|
94
|
+
return new RegExp(`// toolcrib:managed:${safeId}:start version=(\\S+)\\r?\\n([\\s\\S]*?)// toolcrib:managed:${safeId}:end\\r?\\n?`);
|
|
95
|
+
},
|
|
77
96
|
},
|
|
78
97
|
};
|
|
79
98
|
|
|
@@ -83,10 +102,6 @@ export const FENCE_STYLES = {
|
|
|
83
102
|
// dependency/imports key names (see lib/deps.js), not by an inline marker.
|
|
84
103
|
export const NO_FENCE_ASSET_TYPES = ['json'];
|
|
85
104
|
|
|
86
|
-
function escapeRegExp(text) {
|
|
87
|
-
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
88
|
-
}
|
|
89
|
-
|
|
90
105
|
/** Build a complete fenced block (start marker, banner, content, end marker) in the given style. */
|
|
91
106
|
export function buildFence(style, id, version, content) {
|
|
92
107
|
const banner = style.banner ? `${style.banner()}\n` : '';
|
package/src/lib/patchFallback.js
CHANGED
|
@@ -16,6 +16,21 @@ export function applyPatchFallback(patchPath, projectRoot) {
|
|
|
16
16
|
const targetRelPath = parsed.newFileName.replace(/^b\//, '');
|
|
17
17
|
const targetPath = path.join(projectRoot, targetRelPath);
|
|
18
18
|
|
|
19
|
+
// Defense in depth: every relPath this CLI itself writes into a patch
|
|
20
|
+
// header comes from its own vendored file list or fixed strings
|
|
21
|
+
// (package.json, .gitignore, ...), never from anything an attacker
|
|
22
|
+
// controls directly — but nothing enforced that at the point a patch is
|
|
23
|
+
// actually applied. Rejecting a resolved target outside projectRoot here
|
|
24
|
+
// means a corrupted, hand-edited, or (in a worse scenario) tampered
|
|
25
|
+
// patch file can't be used to write outside the project regardless of
|
|
26
|
+
// how it got that path, rather than relying solely on every upstream
|
|
27
|
+
// producer of a patch file staying honest.
|
|
28
|
+
const resolvedRoot = path.resolve(projectRoot);
|
|
29
|
+
const resolvedTarget = path.resolve(targetPath);
|
|
30
|
+
if (resolvedTarget !== resolvedRoot && !resolvedTarget.startsWith(resolvedRoot + path.sep)) {
|
|
31
|
+
return { success: false, error: `Refusing to apply patch: target path "${targetRelPath}" resolves outside the project root.` };
|
|
32
|
+
}
|
|
33
|
+
|
|
19
34
|
const isNewFile = parsed.oldFileName === '/dev/null';
|
|
20
35
|
const currentContent = isNewFile ? '' : fs.readFileSync(targetPath, 'utf-8');
|
|
21
36
|
|
package/src/lib/project.js
CHANGED
|
@@ -32,6 +32,17 @@ export function readTextIfExists(filePath) {
|
|
|
32
32
|
return fs.existsSync(filePath) ? stripBOM(fs.readFileSync(filePath, 'utf-8')) : '';
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
+
/**
|
|
36
|
+
* True existence check, distinct from readTextIfExists's '' return value --
|
|
37
|
+
* that '' can't tell "the file doesn't exist" apart from "the file exists
|
|
38
|
+
* and is empty." Callers that specifically need the former (e.g. deciding
|
|
39
|
+
* whether to propose a brand-new file vs. one that just happens to be
|
|
40
|
+
* blank) should use this instead of `readTextIfExists(...) !== ''`.
|
|
41
|
+
*/
|
|
42
|
+
export function fileExists(filePath) {
|
|
43
|
+
return fs.existsSync(filePath);
|
|
44
|
+
}
|
|
45
|
+
|
|
35
46
|
/**
|
|
36
47
|
* The ONLY thing persisted locally between CLI runs is the installed
|
|
37
48
|
* version string — no cached hashes, no file-by-file state. Everything
|
package/src/lib/zip.js
CHANGED
|
@@ -19,6 +19,16 @@ const execFileAsync = promisify(execFile);
|
|
|
19
19
|
* If you'd rather have zero external-binary reliance, swap this for the
|
|
20
20
|
* `unzipper` or `yauzl` npm package — either is fine for CLI-only code.
|
|
21
21
|
*/
|
|
22
|
+
/**
|
|
23
|
+
* Escape a value for embedding inside a PowerShell single-quoted string
|
|
24
|
+
* literal. PowerShell's escape rule for a single quote inside a
|
|
25
|
+
* single-quoted string is to double it (`''`), not backslash-escape it —
|
|
26
|
+
* this is PowerShell's own rule, unrelated to Node/shell escaping.
|
|
27
|
+
*/
|
|
28
|
+
export function powerShellQuote(value) {
|
|
29
|
+
return `'${value.replace(/'/g, "''")}'`;
|
|
30
|
+
}
|
|
31
|
+
|
|
22
32
|
export async function extractZip(zipBuffer, targetDir) {
|
|
23
33
|
await fsp.mkdir(targetDir, { recursive: true });
|
|
24
34
|
|
|
@@ -28,11 +38,24 @@ export async function extractZip(zipBuffer, targetDir) {
|
|
|
28
38
|
try {
|
|
29
39
|
if (process.platform === 'win32') {
|
|
30
40
|
// PowerShell's Expand-Archive ships on all modern Windows installs.
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
41
|
+
//
|
|
42
|
+
// The script text is passed via -EncodedCommand (a base64-encoded
|
|
43
|
+
// UTF-16LE string) rather than as a plain -Command string built by
|
|
44
|
+
// interpolating paths directly into single-quoted PowerShell literals.
|
|
45
|
+
// execFile doesn't invoke a shell, so Node itself never reinterprets
|
|
46
|
+
// these arguments — but powershell.exe's own argument handling for a
|
|
47
|
+
// multi-token -Command re-joins everything after it into one script
|
|
48
|
+
// line, which put the actual escaping burden on this string being
|
|
49
|
+
// built correctly to begin with. -EncodedCommand takes exactly one
|
|
50
|
+
// argument (the encoded blob) with nothing left for powershell.exe's
|
|
51
|
+
// own parser to re-split or reinterpret, and powerShellQuote() above
|
|
52
|
+
// still applies PowerShell's real single-quote escaping rule to each
|
|
53
|
+
// value, so a path containing a literal `'` (however unlikely from
|
|
54
|
+
// os.tmpdir()/mkdtemp() in practice) is handled correctly rather than
|
|
55
|
+
// relying on that never happening.
|
|
56
|
+
const script = `Expand-Archive -Path ${powerShellQuote(tmpZipPath)} -DestinationPath ${powerShellQuote(targetDir)} -Force`;
|
|
57
|
+
const encodedScript = Buffer.from(script, 'utf16le').toString('base64');
|
|
58
|
+
await execFileAsync('powershell', ['-NoProfile', '-EncodedCommand', encodedScript]);
|
|
36
59
|
} else {
|
|
37
60
|
await execFileAsync('unzip', ['-o', '-q', tmpZipPath, '-d', targetDir]);
|
|
38
61
|
}
|