pal-code 0.0.10 → 0.0.12
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 +5 -0
- package/package.json +3 -2
- package/packages/cli/src/commands/config-export.ts +99 -0
- package/packages/cli/src/commands/config-io.ts +264 -0
- package/packages/cli/src/commands/ext.ts +122 -6
- package/packages/cli/src/commands/portable.ts +295 -0
- package/packages/cli/src/commands.ts +20 -15
- package/packages/cli/src/config.ts +28 -2
- package/packages/cli/src/index.ts +128 -35
- package/packages/cli/src/turn.ts +29 -21
- package/packages/cli/src/utils/format.ts +19 -1
package/README.md
CHANGED
|
@@ -102,6 +102,11 @@ API keys are resolved from (in order):
|
|
|
102
102
|
|
|
103
103
|
Keyless providers are opted into by setting `"keyless": "<provider-id>"`.
|
|
104
104
|
|
|
105
|
+
Non-key settings can also live in `~/.pal/config.json` — for example
|
|
106
|
+
`"model"`, `"systemPrompt"`, `"extensions"`, and `"contextLimit"`. A
|
|
107
|
+
`contextLimit` set here is overridden by the `CONTEXT_LIMIT` env var, and
|
|
108
|
+
invalid values are ignored in favour of the defaults.
|
|
109
|
+
|
|
105
110
|
### Data storage
|
|
106
111
|
|
|
107
112
|
All user data lives in `~/.pal/`:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pal-code",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.12",
|
|
4
4
|
"description": "A terminal coding agent with BYOK, tool use, and extensions",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"engines": {
|
|
@@ -30,6 +30,7 @@
|
|
|
30
30
|
"start": "cd packages/cli && bun src/index.ts",
|
|
31
31
|
"dev": "cd packages/cli && bun src/index.ts",
|
|
32
32
|
"test": "bun test",
|
|
33
|
+
"eval": "bun run evals/run.ts",
|
|
33
34
|
"typecheck": "bunx tsc --noEmit",
|
|
34
35
|
"lint": "biome check .",
|
|
35
36
|
"lint:fix": "biome check --write .",
|
|
@@ -61,7 +62,7 @@
|
|
|
61
62
|
"gemini"
|
|
62
63
|
],
|
|
63
64
|
"dependencies": {
|
|
64
|
-
"@pal-code/core": "0.0.
|
|
65
|
+
"@pal-code/core": "0.0.12",
|
|
65
66
|
"@earendil-works/pi-tui": "^0.85.1"
|
|
66
67
|
},
|
|
67
68
|
"devDependencies": {
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Config as code — the export side of `pal export [file]` / `/export`.
|
|
3
|
+
*
|
|
4
|
+
* Writes one versionable JSON file built from ~/.pal/config.json (minus key
|
|
5
|
+
* material), ~/.pal/providers.json (sanitized), optional hooks/agents/skills
|
|
6
|
+
* references, and the project .pal.json pattern fields. Corrupt local files
|
|
7
|
+
* abort the export instead of producing a partial document.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import {resolve} from 'node:path';
|
|
11
|
+
|
|
12
|
+
import {readPalConfig} from '@pal-code/core';
|
|
13
|
+
|
|
14
|
+
import {
|
|
15
|
+
EXPORT_VERSION,
|
|
16
|
+
HOOKS_LIKE_FIELDS,
|
|
17
|
+
PROJECT_FIELDS,
|
|
18
|
+
collectSecretStrings,
|
|
19
|
+
isHooksLike,
|
|
20
|
+
isRecord,
|
|
21
|
+
isSecretField,
|
|
22
|
+
sanitizeProvider,
|
|
23
|
+
scrubSecrets,
|
|
24
|
+
} from './portable.js';
|
|
25
|
+
import type {PortableConfig, PortableProject} from './portable.js';
|
|
26
|
+
|
|
27
|
+
import {
|
|
28
|
+
loadLocalProviders,
|
|
29
|
+
projectFilePath,
|
|
30
|
+
providersJsonPath,
|
|
31
|
+
readLocalJson,
|
|
32
|
+
writeJson,
|
|
33
|
+
} from './config-io.js';
|
|
34
|
+
import type {ConfigCommandResult} from './config-io.js';
|
|
35
|
+
|
|
36
|
+
const DEFAULT_EXPORT_FILE = 'pal-export.json';
|
|
37
|
+
|
|
38
|
+
/** Build the versionable export document from local state; refuses on corrupt local files. */
|
|
39
|
+
export function buildPortableConfig():
|
|
40
|
+
| {ok: true; doc: PortableConfig}
|
|
41
|
+
| {ok: false; message: string} {
|
|
42
|
+
const cfg = readPalConfig();
|
|
43
|
+
const secrets = collectSecretStrings(cfg, false);
|
|
44
|
+
|
|
45
|
+
const providers = loadLocalProviders(providersJsonPath());
|
|
46
|
+
if (!providers.ok) return {ok: false, message: `Export failed: ${providers.message}`};
|
|
47
|
+
secrets.push(...collectSecretStrings(providers.raw, false));
|
|
48
|
+
|
|
49
|
+
const settings: Record<string, unknown> = {};
|
|
50
|
+
for (const [k, v] of Object.entries(cfg)) {
|
|
51
|
+
if (isSecretField(k) || isHooksLike(k)) continue;
|
|
52
|
+
settings[k] = scrubSecrets(v, secrets);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const doc: PortableConfig = {version: EXPORT_VERSION, settings};
|
|
56
|
+
for (const field of HOOKS_LIKE_FIELDS) {
|
|
57
|
+
if (cfg[field] !== undefined) doc[field] = scrubSecrets(cfg[field], secrets);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
if (Array.isArray(providers.raw)) {
|
|
61
|
+
const entries = providers.raw
|
|
62
|
+
.filter(
|
|
63
|
+
(entry): entry is Record<string, unknown> =>
|
|
64
|
+
isRecord(entry) && typeof entry.id === 'string' && typeof entry.baseUrl === 'string',
|
|
65
|
+
)
|
|
66
|
+
.map((entry) => scrubSecrets(sanitizeProvider(entry), secrets));
|
|
67
|
+
if (entries.length > 0) doc.providers = entries;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const projectPath = projectFilePath();
|
|
71
|
+
if (projectPath) {
|
|
72
|
+
const project = readLocalJson(projectPath);
|
|
73
|
+
if (project.state === 'invalid') {
|
|
74
|
+
return {ok: false, message: `Export failed: ${projectPath} is not valid JSON`};
|
|
75
|
+
}
|
|
76
|
+
if (project.state === 'ok') {
|
|
77
|
+
if (!isRecord(project.value)) {
|
|
78
|
+
return {ok: false, message: `Export failed: ${projectPath} must contain a JSON object`};
|
|
79
|
+
}
|
|
80
|
+
const patterns: PortableProject = {};
|
|
81
|
+
for (const field of PROJECT_FIELDS) {
|
|
82
|
+
const v = project.value[field];
|
|
83
|
+
if (v !== undefined) Object.assign(patterns, {[field]: v});
|
|
84
|
+
}
|
|
85
|
+
if (Object.keys(patterns).length > 0) doc.project = patterns;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return {ok: true, doc};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function exportConfig(file?: string): ConfigCommandResult {
|
|
93
|
+
const built = buildPortableConfig();
|
|
94
|
+
if (!built.ok) return built;
|
|
95
|
+
|
|
96
|
+
const target = resolve(file ?? DEFAULT_EXPORT_FILE);
|
|
97
|
+
writeJson(target, built.doc, true);
|
|
98
|
+
return {ok: true, message: `Exported pal config to ${target} (secrets excluded).`};
|
|
99
|
+
}
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Config as code — the import side of `pal import <file>` / `/import`, plus
|
|
3
|
+
* the local-state helpers shared with the export side (config-export.ts).
|
|
4
|
+
*
|
|
5
|
+
* Import merges an export file back into local config: local API keys are
|
|
6
|
+
* never overwritten or removed, every change is reported as a diff, and a
|
|
7
|
+
* malformed file is rejected before any write. The file is fully parsed and
|
|
8
|
+
* every write is planned before the first byte hits disk.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import {existsSync, mkdirSync, readFileSync, writeFileSync} from 'node:fs';
|
|
12
|
+
import {dirname, join, resolve} from 'node:path';
|
|
13
|
+
|
|
14
|
+
import {readPalConfig, resolveProjectRoot, saveSetting} from '@pal-code/core';
|
|
15
|
+
|
|
16
|
+
import {
|
|
17
|
+
HOOKS_LIKE_FIELDS,
|
|
18
|
+
PROJECT_FIELDS,
|
|
19
|
+
fmtValue,
|
|
20
|
+
isRecord,
|
|
21
|
+
isSecretField,
|
|
22
|
+
jsonEqual,
|
|
23
|
+
parsePortableConfig,
|
|
24
|
+
} from './portable.js';
|
|
25
|
+
import type {PortableConfig} from './portable.js';
|
|
26
|
+
|
|
27
|
+
export interface ConfigCommandResult {
|
|
28
|
+
ok: boolean;
|
|
29
|
+
message: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const home = () => process.env.USERPROFILE ?? process.env.HOME ?? '';
|
|
33
|
+
export const providersJsonPath = () => join(home(), '.pal', 'providers.json');
|
|
34
|
+
|
|
35
|
+
type LocalJson =
|
|
36
|
+
| {state: 'absent'}
|
|
37
|
+
| {state: 'ok'; value: unknown}
|
|
38
|
+
| {state: 'invalid'; error: string};
|
|
39
|
+
|
|
40
|
+
export function readLocalJson(path: string): LocalJson {
|
|
41
|
+
if (!existsSync(path)) return {state: 'absent'};
|
|
42
|
+
try {
|
|
43
|
+
return {state: 'ok', value: JSON.parse(readFileSync(path, 'utf-8'))};
|
|
44
|
+
} catch (err) {
|
|
45
|
+
return {state: 'invalid', error: errMsg(err)};
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function errMsg(err: unknown): string {
|
|
50
|
+
return err instanceof Error ? err.message : String(err);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function writeJson(path: string, value: unknown, trailingNewline: boolean): void {
|
|
54
|
+
mkdirSync(dirname(path), {recursive: true});
|
|
55
|
+
const json = JSON.stringify(value, null, 2);
|
|
56
|
+
writeFileSync(path, trailingNewline ? `${json}\n` : json, 'utf-8');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Nearest project config file path, or null when the project has none yet. */
|
|
60
|
+
export function projectFilePath(): string | null {
|
|
61
|
+
const root = resolveProjectRoot();
|
|
62
|
+
if (!root) return null;
|
|
63
|
+
for (const name of ['.pal.json', '.pal.config.json']) {
|
|
64
|
+
const path = join(root, name);
|
|
65
|
+
if (existsSync(path)) return path;
|
|
66
|
+
}
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function loadLocalProviders(
|
|
71
|
+
path: string,
|
|
72
|
+
): {ok: true; list: Record<string, unknown>[]; raw: unknown} | {ok: false; message: string} {
|
|
73
|
+
const local = readLocalJson(path);
|
|
74
|
+
if (local.state === 'invalid') {
|
|
75
|
+
return {ok: false, message: `${path} is not valid JSON (${local.error})`};
|
|
76
|
+
}
|
|
77
|
+
if (local.state === 'absent') return {ok: true, list: [], raw: undefined};
|
|
78
|
+
if (!Array.isArray(local.value)) {
|
|
79
|
+
return {ok: false, message: `${path} must contain a JSON array`};
|
|
80
|
+
}
|
|
81
|
+
const list: Record<string, unknown>[] = [];
|
|
82
|
+
for (const entry of local.value) {
|
|
83
|
+
if (!isRecord(entry)) return {ok: false, message: `${path} contains a non-object entry`};
|
|
84
|
+
list.push(entry);
|
|
85
|
+
}
|
|
86
|
+
return {ok: true, list, raw: local.value};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
interface ImportPlan {
|
|
90
|
+
settings: Array<[string, unknown]>;
|
|
91
|
+
skippedSecretFields: string[];
|
|
92
|
+
providers: Record<string, unknown>[];
|
|
93
|
+
providersPath: string;
|
|
94
|
+
providersChanged: boolean;
|
|
95
|
+
projectPath: string;
|
|
96
|
+
project: Record<string, unknown>;
|
|
97
|
+
projectChanged: boolean;
|
|
98
|
+
diff: string[];
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function planSettings(
|
|
102
|
+
doc: PortableConfig,
|
|
103
|
+
): Pick<ImportPlan, 'settings' | 'skippedSecretFields' | 'diff'> {
|
|
104
|
+
const incoming: Record<string, unknown> = {...doc.settings};
|
|
105
|
+
for (const field of HOOKS_LIKE_FIELDS) {
|
|
106
|
+
if (doc[field] !== undefined) incoming[field] = doc[field];
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const localCfg = readPalConfig();
|
|
110
|
+
const settings: Array<[string, unknown]> = [];
|
|
111
|
+
const skippedSecretFields: string[] = [];
|
|
112
|
+
const diff: string[] = [];
|
|
113
|
+
|
|
114
|
+
for (const [k, v] of Object.entries(incoming)) {
|
|
115
|
+
if (isSecretField(k)) {
|
|
116
|
+
skippedSecretFields.push(k);
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (!jsonEqual(localCfg[k], v)) {
|
|
120
|
+
diff.push(`${k}: ${fmtValue(localCfg[k])} → ${fmtValue(v)}`);
|
|
121
|
+
settings.push([k, v]);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return {settings, skippedSecretFields, diff};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function planProviders(
|
|
128
|
+
doc: PortableConfig,
|
|
129
|
+
diff: string[],
|
|
130
|
+
):
|
|
131
|
+
| {
|
|
132
|
+
ok: true;
|
|
133
|
+
providers: Record<string, unknown>[];
|
|
134
|
+
providersPath: string;
|
|
135
|
+
providersChanged: boolean;
|
|
136
|
+
}
|
|
137
|
+
| {ok: false; message: string} {
|
|
138
|
+
const providersPath = providersJsonPath();
|
|
139
|
+
const local = loadLocalProviders(providersPath);
|
|
140
|
+
if (!local.ok) return {ok: false, message: `Import failed: ${local.message}`};
|
|
141
|
+
|
|
142
|
+
const merged = [...local.list];
|
|
143
|
+
const localIds = new Set(local.list.map((entry) => String(entry.id)));
|
|
144
|
+
let changed = false;
|
|
145
|
+
|
|
146
|
+
for (const incoming of doc.providers ?? []) {
|
|
147
|
+
const incomingId = String(incoming.id);
|
|
148
|
+
if (localIds.has(incomingId)) {
|
|
149
|
+
if (
|
|
150
|
+
!jsonEqual(
|
|
151
|
+
local.list.find((entry) => entry.id === incoming.id),
|
|
152
|
+
incoming,
|
|
153
|
+
)
|
|
154
|
+
) {
|
|
155
|
+
diff.push(`provider ${incomingId}: kept local definition (imported copy ignored)`);
|
|
156
|
+
}
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
merged.push(incoming);
|
|
160
|
+
localIds.add(incomingId);
|
|
161
|
+
changed = true;
|
|
162
|
+
diff.push(`+ provider ${incomingId} (${fmtValue(incoming.name ?? incoming.baseUrl)})`);
|
|
163
|
+
}
|
|
164
|
+
return {ok: true, providers: merged, providersPath, providersChanged: changed};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function planProject(
|
|
168
|
+
doc: PortableConfig,
|
|
169
|
+
diff: string[],
|
|
170
|
+
):
|
|
171
|
+
| {ok: true; projectPath: string; project: Record<string, unknown>; projectChanged: boolean}
|
|
172
|
+
| {ok: false; message: string} {
|
|
173
|
+
let projectPath = projectFilePath();
|
|
174
|
+
let local: Record<string, unknown> = {};
|
|
175
|
+
if (projectPath) {
|
|
176
|
+
const existing = readLocalJson(projectPath);
|
|
177
|
+
if (existing.state === 'invalid') {
|
|
178
|
+
return {
|
|
179
|
+
ok: false,
|
|
180
|
+
message: `Import failed: ${projectPath} is not valid JSON (${existing.error})`,
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
if (existing.state === 'ok') {
|
|
184
|
+
if (!isRecord(existing.value)) {
|
|
185
|
+
return {ok: false, message: `Import failed: ${projectPath} must contain a JSON object`};
|
|
186
|
+
}
|
|
187
|
+
local = existing.value;
|
|
188
|
+
}
|
|
189
|
+
} else {
|
|
190
|
+
projectPath = join(process.cwd(), '.pal.json');
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const next = {...local};
|
|
194
|
+
let changed = false;
|
|
195
|
+
if (doc.project) {
|
|
196
|
+
for (const field of PROJECT_FIELDS) {
|
|
197
|
+
if (field === 'ignore') {
|
|
198
|
+
const incoming = doc.project.ignore;
|
|
199
|
+
if (incoming === undefined) continue;
|
|
200
|
+
const existing = Array.isArray(local.ignore)
|
|
201
|
+
? local.ignore.filter((p): p is string => typeof p === 'string')
|
|
202
|
+
: [];
|
|
203
|
+
const added = incoming.filter((p) => !existing.includes(p));
|
|
204
|
+
if (added.length > 0) {
|
|
205
|
+
next.ignore = [...existing, ...added];
|
|
206
|
+
changed = true;
|
|
207
|
+
diff.push(`project.ignore: +${added.join(' +')}`);
|
|
208
|
+
}
|
|
209
|
+
} else {
|
|
210
|
+
const incoming = doc.project[field];
|
|
211
|
+
if (incoming === undefined) continue;
|
|
212
|
+
if (!jsonEqual(local[field], incoming)) {
|
|
213
|
+
diff.push(`project.${field}: ${fmtValue(local[field])} → ${fmtValue(incoming)}`);
|
|
214
|
+
next[field] = incoming;
|
|
215
|
+
changed = true;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return {ok: true, projectPath, project: next, projectChanged: changed};
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Merge an export file into local config; a malformed file leaves local config untouched. */
|
|
224
|
+
export function importConfig(file: string): ConfigCommandResult {
|
|
225
|
+
const source = resolve(file);
|
|
226
|
+
if (!existsSync(source)) {
|
|
227
|
+
return {ok: false, message: `Import failed: file not found: ${source}`};
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
let parsed: unknown;
|
|
231
|
+
try {
|
|
232
|
+
parsed = JSON.parse(readFileSync(source, 'utf-8'));
|
|
233
|
+
} catch (err) {
|
|
234
|
+
return {ok: false, message: `Import failed: ${source} is not valid JSON: ${errMsg(err)}`};
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const result = parsePortableConfig(parsed);
|
|
238
|
+
if (!result.ok) {
|
|
239
|
+
return {ok: false, message: `Import failed: ${result.message}`};
|
|
240
|
+
}
|
|
241
|
+
const doc = result.doc;
|
|
242
|
+
|
|
243
|
+
const settingsPlan = planSettings(doc);
|
|
244
|
+
const providersPlan = planProviders(doc, settingsPlan.diff);
|
|
245
|
+
if (!providersPlan.ok) return providersPlan;
|
|
246
|
+
const projectPlan = planProject(doc, settingsPlan.diff);
|
|
247
|
+
if (!projectPlan.ok) return projectPlan;
|
|
248
|
+
|
|
249
|
+
for (const [key, value] of settingsPlan.settings) saveSetting(key, value);
|
|
250
|
+
if (providersPlan.providersChanged) {
|
|
251
|
+
writeJson(providersPlan.providersPath, providersPlan.providers, false);
|
|
252
|
+
}
|
|
253
|
+
if (projectPlan.projectChanged) {
|
|
254
|
+
writeJson(projectPlan.projectPath, projectPlan.project, false);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const lines = settingsPlan.diff.length
|
|
258
|
+
? settingsPlan.diff.map((line) => ` ${line}`)
|
|
259
|
+
: [' (no changes)'];
|
|
260
|
+
const skipped = settingsPlan.skippedSecretFields.length
|
|
261
|
+
? `\n skipped secret fields (never imported): ${settingsPlan.skippedSecretFields.join(', ')}`
|
|
262
|
+
: '';
|
|
263
|
+
return {ok: true, message: `Imported ${source}:\n${lines.join('\n')}${skipped}`};
|
|
264
|
+
}
|
|
@@ -1,19 +1,29 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Extension install/uninstall commands.
|
|
2
|
+
* Extension install/uninstall commands + npm-native discovery.
|
|
3
3
|
*
|
|
4
|
-
* `pal add <pkg>`
|
|
5
|
-
* registers the package in
|
|
6
|
-
* `pal remove <pkg>` does the reverse.
|
|
4
|
+
* `pal add <pkg>` validates the name against the public npm registry, runs
|
|
5
|
+
* `bun add <pkg>` inside ~/.pal/extensions/, and registers the package in
|
|
6
|
+
* ~/.pal/config.json. `pal remove <pkg>` does the reverse.
|
|
7
|
+
*
|
|
8
|
+
* Discovery queries the npm registry search API directly from the client —
|
|
9
|
+
* no backend and no hand-maintained manifest: install/search work for any
|
|
10
|
+
* package on npm, not just `@pal-code/*`.
|
|
7
11
|
*/
|
|
8
12
|
|
|
9
13
|
import {homedir} from 'node:os';
|
|
10
14
|
import {join} from 'node:path';
|
|
11
|
-
import {existsSync, mkdirSync,
|
|
15
|
+
import {existsSync, mkdirSync, writeFileSync} from 'node:fs';
|
|
12
16
|
import {execSync} from 'node:child_process';
|
|
13
17
|
import {readPalConfig, saveSetting} from '@pal-code/core';
|
|
14
18
|
|
|
15
19
|
const EXTENSIONS_DIR = join(homedir(), '.pal', 'extensions');
|
|
16
20
|
|
|
21
|
+
const NPM_SEARCH_URL = 'https://registry.npmjs.org/-/v1/search';
|
|
22
|
+
const NPM_REGISTRY_URL = 'https://registry.npmjs.org';
|
|
23
|
+
|
|
24
|
+
/** Conservative npm-name pattern (also blocks shell metacharacters in execSync). */
|
|
25
|
+
const NPM_NAME_RE = /^(?:@[A-Za-z0-9][A-Za-z0-9._~-]*\/)?[A-Za-z0-9][A-Za-z0-9._~-]*$/;
|
|
26
|
+
|
|
17
27
|
function ensureExtensionsDir(): void {
|
|
18
28
|
if (!existsSync(EXTENSIONS_DIR)) {
|
|
19
29
|
mkdirSync(EXTENSIONS_DIR, {recursive: true});
|
|
@@ -35,7 +45,113 @@ export interface ExtCommandResult {
|
|
|
35
45
|
message: string;
|
|
36
46
|
}
|
|
37
47
|
|
|
38
|
-
export
|
|
48
|
+
export interface NpmSearchHit {
|
|
49
|
+
name: string;
|
|
50
|
+
description: string;
|
|
51
|
+
version: string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface ExtSearchResult extends ExtCommandResult {
|
|
55
|
+
results: NpmSearchHit[];
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
59
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Shape-tolerant parse of an npm search API response body. */
|
|
63
|
+
export function parseNpmSearch(data: unknown): NpmSearchHit[] {
|
|
64
|
+
if (!isRecord(data) || !Array.isArray(data.objects)) return [];
|
|
65
|
+
const hits: NpmSearchHit[] = [];
|
|
66
|
+
for (const entry of data.objects) {
|
|
67
|
+
if (!isRecord(entry) || !isRecord(entry.package)) continue;
|
|
68
|
+
const pkg = entry.package;
|
|
69
|
+
if (typeof pkg.name !== 'string') continue;
|
|
70
|
+
hits.push({
|
|
71
|
+
name: pkg.name,
|
|
72
|
+
description: typeof pkg.description === 'string' ? pkg.description : '',
|
|
73
|
+
version: typeof pkg.version === 'string' ? pkg.version : '',
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
return hits;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function truncate(text: string, max: number): string {
|
|
80
|
+
return text.length <= max ? text : `${text.slice(0, max - 1)}…`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Query the public npm registry search API (client-side, zero backend).
|
|
85
|
+
* Hits whose name contains the query (e.g. `@pal-code/*` for "pal") are
|
|
86
|
+
* ranked ahead of npm's popularity ordering.
|
|
87
|
+
*/
|
|
88
|
+
export async function extSearch(query: string): Promise<ExtSearchResult> {
|
|
89
|
+
const text = query.trim();
|
|
90
|
+
if (!text) {
|
|
91
|
+
return {ok: false, message: 'Usage: /ext search <query>', results: []};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
let data: unknown;
|
|
95
|
+
try {
|
|
96
|
+
const res = await fetch(`${NPM_SEARCH_URL}?text=${encodeURIComponent(text)}&size=30`);
|
|
97
|
+
if (!res.ok) {
|
|
98
|
+
return {
|
|
99
|
+
ok: false,
|
|
100
|
+
message: `npm search failed with HTTP ${res.status}.`,
|
|
101
|
+
results: [],
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
data = await res.json();
|
|
105
|
+
} catch (err) {
|
|
106
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
107
|
+
return {ok: false, message: `npm search failed: ${msg}`, results: []};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const needle = text.toLowerCase();
|
|
111
|
+
const results = parseNpmSearch(data).sort((a, b) => {
|
|
112
|
+
const aMatch = a.name.toLowerCase().includes(needle) ? 0 : 1;
|
|
113
|
+
const bMatch = b.name.toLowerCase().includes(needle) ? 0 : 1;
|
|
114
|
+
return aMatch - bMatch;
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
if (results.length === 0) {
|
|
118
|
+
return {ok: false, message: `No npm packages matched "${text}".`, results};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const lines = results.map(
|
|
122
|
+
(hit) => ` ${hit.name.padEnd(28)} ${hit.version.padEnd(10)} ${truncate(hit.description, 64)}`,
|
|
123
|
+
);
|
|
124
|
+
return {
|
|
125
|
+
ok: true,
|
|
126
|
+
message: `npm results for "${text}" (${results.length}):\n${lines.join('\n')}`,
|
|
127
|
+
results,
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** 404 → package is absent from npm; other failures → unknown (offline-tolerant). */
|
|
132
|
+
async function lookupNpmPackage(pkg: string): Promise<'found' | 'missing' | 'unknown'> {
|
|
133
|
+
const url = `${NPM_REGISTRY_URL}/${pkg.replaceAll('/', '%2F')}`;
|
|
134
|
+
try {
|
|
135
|
+
const res = await fetch(url);
|
|
136
|
+
if (res.status === 404) return 'missing';
|
|
137
|
+
return res.ok ? 'found' : 'unknown';
|
|
138
|
+
} catch {
|
|
139
|
+
return 'unknown';
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export async function extAdd(pkg: string): Promise<ExtCommandResult> {
|
|
144
|
+
if (!NPM_NAME_RE.test(pkg)) {
|
|
145
|
+
return {ok: false, message: `Invalid package name: ${pkg}`};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// Validate against npm before installing; on registry/network failure fall
|
|
149
|
+
// through to `bun add` so offline installs still work (bun will 404 itself).
|
|
150
|
+
const lookup = await lookupNpmPackage(pkg);
|
|
151
|
+
if (lookup === 'missing') {
|
|
152
|
+
return {ok: false, message: `"${pkg}" was not found on the npm registry.`};
|
|
153
|
+
}
|
|
154
|
+
|
|
39
155
|
try {
|
|
40
156
|
ensureExtensionsDir();
|
|
41
157
|
|