dotfiles
bugabingas dorkfiles
owned by bugabinga
pi: add extension footer fallbacks
4d5ffa9296d4999fa964673f557c706bf628c045
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
Browse filesCompare with HEAD
Changed files (9)
25 25 Prefer `peerDependencies` for Pi packages (`@earendil-works/*`).
26 26 Run `bun install` after any structural change.
30 +- Extensions must be standalone packages.
31 +- Never import from another `@bugabinga/pi-ext-*` package.
32 +- Optional integration must be capability/event based and degrade cleanly.
33 +- If behavior is important, provide a native fallback; decorative integration may no-op.
37 +- Source of truth for release gates: `justfile` → `scripts/extensions.py`.
38 +- Run `just check [{name}]` before `npm publish`.
43 +- READMEs must be terse.
44 +- Do not duplicate source-of-truth docs/config/API details.
45 +- Link to canonical source files, commands, settings, or upstream docs instead.
46 +- Package README should answer: what, install/load, commands/tools, settings link, optional integrations.
30 50 | Package | Provides | Use |
pi/agent/extensions/context-size/index.ts
Modified 6 6 } from
"@earendil-works/pi-coding-agent";
8 +const FOOTER_KEY
= Symbol.
for(
"@bugabinga/pi-ext-footer");
9 +const STATUS_ID
= "context-size";
8 11 const FOOTER_SEGMENT
= {
47 +function hasFooter()
: boolean {
48 + const footer
= (globalThis
as any)[FOOTER_KEY];
49 + return footer?.loaded
=== true && footer.
version >= 1;
44 52 function clamp(value
: number, min
: number, max
: number)
: number {
45 53 return Math.
min(max,
Math.
max(min, value));
98 106 pi.events.
emit(
"footer:segment", { id: FOOTER_SEGMENT.
id, text:
undefined });
109 + function clearPublished(ctx
: ExtensionContext) {
111 + ctx.ui.
setStatus(STATUS_ID,
undefined);
101 114 function updateSegment(ctx
: ExtensionContext) {
103 116 if (
!ctx.hasUI)
return;
105 118 const usage
= ctx.
getContextUsage();
120 + clearPublished(ctx);
111 124 const view
= buildSegment(ctx, usage);
112 - pi.events.
emit(
"footer:segment", {
126 + ctx.ui.
setStatus(STATUS_ID,
undefined);
127 + pi.events.
emit(
"footer:segment", {
136 + ctx.ui.
setStatus(STATUS_ID, view.
text);
123 143 pi.
on(eventName,
async (_event, ctx)
=> updateSegment(ctx));
146 + pi.
on(
"session_shutdown",
async (_event, ctx)
=> {
147 + if (ctx.hasUI) ctx.ui.
setStatus(STATUS_ID,
undefined);
pi/agent/extensions/cost/index.ts
Modified 17 +const FOOTER_KEY
= Symbol.
for(
"@bugabinga/pi-ext-footer");
18 +const STATUS_ID
= "cost";
17 19 const PRICE_UNIT_TOKENS
= 1_000_000;
18 20 const COUNT_DECIMAL_THRESHOLD
= 1_000;
19 21 const COUNT_ROUND_THRESHOLD
= 10_000;
71 73 type SegmentId = "model" | "tokens" | "cost";
77 +function hasFooter()
: boolean {
78 + const footer
= (globalThis
as any)[FOOTER_KEY];
79 + return footer?.loaded
=== true && footer.
version >= 1;
270 -function emitSnapshot(pi
: ExtensionAPI, snapshot
: Snapshot) {
271 - emitSegment(pi,
"model", snapshot.modelLabel);
272 - emitSegment(pi,
"tokens",
tokenLabel(snapshot.usage));
273 - emitSegment(pi,
"cost",
costLabel(snapshot));
279 +function statusLabel(snapshot
: Snapshot)
: string {
280 + return [snapshot.modelLabel,
tokenLabel(snapshot.usage),
costLabel(snapshot)]
281 + .
filter((part)
: part
is string => !!part)
285 +function publishSnapshot(pi
: ExtensionAPI, ctx
: ExtensionContext, snapshot
: Snapshot) {
287 + ctx.ui.
setStatus(STATUS_ID,
undefined);
288 + emitSegment(pi,
"model", snapshot.modelLabel);
289 + emitSegment(pi,
"tokens",
tokenLabel(snapshot.usage));
290 + emitSegment(pi,
"cost",
costLabel(snapshot));
295 + ctx.ui.
setStatus(STATUS_ID,
statusLabel(snapshot));
276 298 function clearSegments(pi
: ExtensionAPI) {
279 301 emitSegment(pi,
"cost",
undefined);
304 +function clearPublished(pi
: ExtensionAPI, ctx
?: ExtensionContext) {
306 + if (ctx?.hasUI) ctx.ui.
setStatus(STATUS_ID,
undefined);
284 311 function buildSnapshot(ctx
: ExtensionContext, previousSessionCost
: number, monthlyCost
: number)
: Snapshot {
325 352 if (nextSignature
=== lastSignature)
return;
326 353 lastSignature
= nextSignature;
328 - emitSnapshot(pi, snapshot);
355 + publishSnapshot(pi, ctx, snapshot);
331 358 async function syncBestEffort(ctx
: ExtensionContext) {
360 - pi.
on(
"session_shutdown",
async ()
=> {
387 + pi.
on(
"session_shutdown",
async (_event, ctx)
=> {
388 + clearPublished(pi, ctx);
pi/agent/extensions/footer/index.ts
Modified 8 8 * line
3 = extension statuses via ctx.ui.
setStatus()
10 10 * Producers use semantic
zones (
"workspace" | "llm"). Footer decides row mapping.
11 + * Publishes a
process-global capability flag so producers can choose footer
12 + * segments over ctx.ui.
setStatus() fallbacks without ping events.
11 13 * Uses
setFooter() — the single footer owner. Producers are decoupled.
13 15 * /footer or ctrl
+alt
+f toggles visibility by swapping between
25 +const FOOTER_KEY
= Symbol.
for(
"@bugabinga/pi-ext-footer");
23 26 const SEPARATOR_COLOR
= "borderMuted" as ThemeColor;
24 27 const DEFAULT_SEGMENT_COLOR
= "muted" as ThemeColor;
25 28 const STATUS_COLOR
= "dim" as ThemeColor;
34 +type FooterGlobal = {
31 39 type FooterZone = "workspace" | "llm";
69 77 export default function footerExtension(pi
: ExtensionAPI) {
78 + const state
: FooterGlobal = { version:
1, loaded:
true };
79 + (globalThis
as any)[FOOTER_KEY]
= state;
70 81 const segments
= new Map<
string,
Segment>();
71 82 let requestRender
: (()
=> void)
| undefined;
72 83 let renderScheduled
= false;
284 - pi.
on(
"session_shutdown",
async ()
=> {
295 + pi.
on(
"session_shutdown",
async (event)
=> {
296 + if (
event.reason
=== "quit" || event.reason
=== "reload") state.loaded
= false;
285 297 segments.
clear();
286 298 requestRender
= undefined;
287 299 currentCtx
= undefined;
pi/agent/extensions/git-status/index.ts
Modified 10 10 import { promisify }
from "node:util";
12 12 const execFileAsync
= promisify(execFile);
13 +const FOOTER_KEY
= Symbol.
for(
"@bugabinga/pi-ext-footer");
14 +const CWD_STATUS_ID
= "cwd";
15 +const GIT_STATUS_ID
= "git";
30 33 modified:
"!",
staged:
"+",
renamed:
"»",
deleted:
"✘",
36 +function hasFooter()
: boolean {
37 + const footer
= (globalThis
as any)[FOOTER_KEY];
38 + return footer?.loaded
=== true && footer.
version >= 1;
33 41 function parsePorcelain(stdout
: string, hasStash
: boolean)
: GitStatus {
34 42 const s
: GitStatus = { branch:
undefined, ahead:
0, behind:
0, conflicted:
0, untracked:
0, stashed:
false, modified:
0, staged:
0, renamed:
0, deleted:
0 };
35 43 s.stashed
= hasStash;
75 83 }
catch {
return empty; }
78 -function emitGit(pi
: ExtensionAPI, cwd
: string, status
: GitStatus) {
86 +function gitLabel(status
: GitStatus)
: string | undefined {
87 + if (
!status.branch)
return undefined;
89 + status.conflicted
> 0 ? ICONS.conflicted
: "",
90 + status.stashed
? ICONS.stashed
: "",
91 + status.deleted
> 0 ? ICONS.deleted
: "",
92 + status.renamed
> 0 ? ICONS.renamed
: "",
93 + status.modified
> 0 ? ICONS.modified
: "",
94 + status.staged
> 0 ? ICONS.staged
: "",
95 + status.untracked
> 0 ? ICONS.untracked
: "",
97 + const ab
= status.ahead
> 0 && status.behind
> 0 ? ICONS.diverged
98 + : status.ahead
> 0 ? ICONS.ahead
99 + : status.behind
> 0 ? ICONS.behind
: "";
100 + const statusBlock
= allStatus
|| ab
? `[${allStatus}${ab}]` : "";
101 + return `${status.branch}${statusBlock ? ` ${statusBlock}` : ""}`;
104 +function clearSegments(pi
: ExtensionAPI) {
105 + pi.events.
emit(
"footer:segment", { id:
"cwd", text:
undefined });
106 + pi.events.
emit(
"footer:segment", { id:
"git-branch", text:
undefined });
109 +function emitGit(pi
: ExtensionAPI, ctx
: ExtensionContext, status
: GitStatus) {
79 110 const home
= process.
env.HOME;
80 - const path
= home
&& cwd.
startsWith(home)
? `~${cwd.slice(home.length)}` : cwd;
111 + const path
= home
&& ctx.cwd.
startsWith(home)
? `~${ctx.cwd.slice(home.length)}` : ctx.cwd;
112 + const branch
= gitLabel(status);
83 - pi.events.
emit(
"footer:segment", { id:
"cwd", text: path, icon:
"", color:
"syntaxOperator", zone:
"workspace", order:
0 });
86 - if (status.branch) {
88 - status.conflicted
> 0 ? ICONS.conflicted
: "",
89 - status.stashed
? ICONS.stashed
: "",
90 - status.deleted
> 0 ? ICONS.deleted
: "",
91 - status.renamed
> 0 ? ICONS.renamed
: "",
92 - status.modified
> 0 ? ICONS.modified
: "",
93 - status.staged
> 0 ? ICONS.staged
: "",
94 - status.untracked
> 0 ? ICONS.untracked
: "",
96 - const ab
= status.ahead
> 0 && status.behind
> 0 ? ICONS.diverged
97 - : status.ahead
> 0 ? ICONS.ahead
98 - : status.behind
> 0 ? ICONS.behind
: "";
99 - const statusBlock
= allStatus
|| ab
? `[${allStatus}${ab}]` : "";
100 - pi.events.
emit(
"footer:segment", {
102 - text:
`${status.branch}${statusBlock ? ` ${statusBlock}` : ""}`,
104 - color:
"syntaxKeyword",
109 - pi.events.
emit(
"footer:segment", { id:
"git-branch", text:
undefined });
115 + ctx.ui.
setStatus(CWD_STATUS_ID,
undefined);
116 + ctx.ui.
setStatus(GIT_STATUS_ID,
undefined);
117 + pi.events.
emit(
"footer:segment", { id:
"cwd", text: path, icon:
"", color:
"syntaxOperator", zone:
"workspace", order:
0 });
119 + pi.events.
emit(
"footer:segment", {
123 + color:
"syntaxKeyword",
128 + pi.events.
emit(
"footer:segment", { id:
"git-branch", text:
undefined });
134 + ctx.ui.
setStatus(CWD_STATUS_ID, path);
135 + ctx.ui.
setStatus(GIT_STATUS_ID, branch);
113 138 export default function gitStatusExtension(pi
: ExtensionAPI) {
114 139 let currentCwd
= "";
140 + let currentCtx
: ExtensionContext | undefined;
115 141 let hasUI
= false;
116 142 let refreshInFlight
= false;
117 143 let refreshPending
= false;
119 145 const refresh = async ()
=> {
120 - if (
!hasUI
|| refreshInFlight) { refreshPending
= true;
return; }
146 + if (
!hasUI
|| !currentCtx
|| refreshInFlight) { refreshPending
= true;
return; }
147 + const ctx
= currentCtx;
121 148 refreshInFlight
= true;
123 150 const status
= await readGitStatus(currentCwd);
124 - emitGit(pi, currentCwd, status);
151 + emitGit(pi, ctx, status);
126 153 refreshInFlight
= false;
127 154 if (refreshPending) { refreshPending
= false;
refresh(); }
131 - pi.
on(
"session_start",
async (_e, ctx)
=> { hasUI
= ctx.hasUI; currentCwd
= ctx.cwd;
refresh(); });
158 + pi.
on(
"session_start",
async (_e, ctx)
=> { hasUI
= ctx.hasUI; currentCwd
= ctx.cwd; currentCtx
= ctx;
refresh(); });
132 159 pi.
on(
"agent_end",
async ()
=> {
if (hasUI)
refresh(); });
133 160 pi.
on(
"tool_execution_end",
async ()
=> {
if (hasUI)
refresh(); });
161 + pi.
on(
"session_shutdown",
async (_e, ctx)
=> {
164 + ctx.ui.
setStatus(CWD_STATUS_ID,
undefined);
165 + ctx.ui.
setStatus(GIT_STATUS_ID,
undefined);
167 + currentCtx
= undefined;
pi/agent/extensions/quota/index.ts
Modified 10 10 import { join }
from "node:path";
11 11 import type { ExtensionAPI, ExtensionContext }
from "@earendil-works/pi-coding-agent";
13 +const FOOTER_KEY
= Symbol.
for(
"@bugabinga/pi-ext-footer");
14 +const STATUS_ID
= "quota";
15 18 interface MinimaxResponse {
246 249 return used
< 50 ? "accent" : used
< 80 ? "warning" : "error";
252 +function hasFooter()
: boolean {
253 + const footer
= (globalThis
as any)[FOOTER_KEY];
254 + return footer?.loaded
=== true && footer.
version >= 1;
251 259 export default function usageExtension(pi
: ExtensionAPI) {
347 355 footerIds.
clear();
358 + function quotaStatusLabel(ctx
: ExtensionContext)
: string | undefined {
359 + const active
= activeProvider(ctx);
360 + const rows
= providers
361 + .
filter(p
=> p.fiveH.total
> 0)
362 + .
filter(p
=> !active
|| p.
name.
startsWith(active))
364 + const used
= Math.
round((p.fiveH.used
/ p.fiveH.total)
* 100);
365 + const label
= p.
name.
split(
" ")[
0];
366 + const reset
= fmtReset(p.fiveH.resetAt);
367 + return `${label} ${used}%${reset ? ` ↻${reset}` : ""}`;
369 + return rows.
length > 0 ? rows.
join(
" · ")
: undefined;
350 372 function updateFooter(ctx
: ExtensionContext) {
351 373 const active
= activeProvider(ctx);
375 + if (
!hasFooter()) {
377 + ctx.ui.
setStatus(STATUS_ID,
quotaStatusLabel(ctx));
381 + ctx.ui.
setStatus(STATUS_ID,
undefined);
352 382 const seen
= new Set<
string>();
354 384 for (
const p
of providers.
filter(p
=> p.fiveH.total
> 0)) {
446 476 pi.
on(
"session_start",
async (_e, ctx)
=> {
447 - fetchedAt
= 0; widgetVisible
= false;
clearFooter();
477 + fetchedAt
= 0; widgetVisible
= false;
clearFooter(); ctx.ui.
setStatus(STATUS_ID,
undefined);
448 478 try {
await getOrFetch(ctx);
updateFooter(ctx); }
449 - catch {
if (
!providers.
length)
clearFooter(); }
479 + catch {
if (
!providers.
length) {
clearFooter(); ctx.ui.
setStatus(STATUS_ID,
undefined); } }
452 482 pi.
on(
"agent_start",
async (_e, ctx)
=> updateFooter(ctx));
460 490 widgetVisible
= false;
492 + ctx.ui.
setStatus(STATUS_ID,
undefined);
462 493 ctx.ui.
setWidget(
"usage",
undefined);
pi/agent/extensions/runtime/index.ts
Modified 5 5 * under $HOME and emits a
footer:segment
with zone
"workspace".
8 -import type { ExtensionAPI }
from "@earendil-works/pi-coding-agent";
8 +import type { ExtensionAPI, ExtensionContext }
from "@earendil-works/pi-coding-agent";
9 9 import { execFile }
from "node:child_process";
10 10 import { readdir, realpath }
from "node:fs/promises";
11 11 import { dirname, isAbsolute, relative, resolve }
from "node:path";
14 14 const execFileAsync
= promisify(execFile);
16 +const FOOTER_KEY
= Symbol.
for(
"@bugabinga/pi-ext-footer");
16 17 const VERSION_TIMEOUT_MS
= 2500;
17 18 const SEGMENT_ID
= "runtime";
19 +const STATUS_ID
= "runtime";
18 20 const SEGMENT_ZONE
= "workspace";
19 21 const SEGMENT_ORDER
= 3;
43 45 version: ()
=> Promise<string
| undefined>;
48 +function hasFooter()
: boolean {
49 + const footer
= (globalThis
as any)[FOOTER_KEY];
50 + return footer?.loaded
=== true && footer.
version >= 1;
46 53 async function commandOutput(cmd
: string, args
: readonly string[]
= [])
: Promise<
string | undefined> {
48 55 const { stdout, stderr }
= await execFileAsync(cmd, [
...args], { timeout: VERSION_TIMEOUT_MS });
168 175 export default function runtimeExtension(pi
: ExtensionAPI) {
169 176 let currentCwd
= "";
177 + let currentCtx
: ExtensionContext | undefined;
170 178 let hasUI
= false;
171 179 let refreshInFlight
= false;
181 + function clearSegment() {
182 + pi.events.
emit(
"footer:segment", { id: SEGMENT_ID, text:
undefined });
173 185 async function refresh() {
174 - if (
!hasUI
|| refreshInFlight)
return;
186 + if (
!hasUI
|| !currentCtx
|| refreshInFlight)
return;
187 + const ctx
= currentCtx;
175 188 refreshInFlight
= true;
178 191 const rt
= await detect(currentCwd);
180 - pi.events.
emit(
"footer:segment", { id: SEGMENT_ID, text:
undefined });
194 + ctx.ui.
setStatus(STATUS_ID,
undefined);
184 - pi.events.
emit(
"footer:segment", {
187 - text: rt.
version ?? rt.
name,
188 - color: RUNTIME_COLORS[rt.
name],
189 - zone: SEGMENT_ZONE,
190 - order: SEGMENT_ORDER,
198 + const text
= rt.
version ?? rt.
name;
200 + ctx.ui.
setStatus(STATUS_ID,
undefined);
201 + pi.events.
emit(
"footer:segment", {
205 + color: RUNTIME_COLORS[rt.
name],
206 + zone: SEGMENT_ZONE,
207 + order: SEGMENT_ORDER,
213 + ctx.ui.
setStatus(STATUS_ID,
`${rt.icon} ${text}`);
193 215 refreshInFlight
= false;
197 219 pi.
on(
"session_start",
async (_e, ctx)
=> {
198 220 hasUI
= ctx.hasUI;
199 221 currentCwd
= ctx.cwd;
203 226 pi.
on(
"agent_end",
async ()
=> refresh());
227 + pi.
on(
"session_shutdown",
async (_e, ctx)
=> {
229 + if (ctx.hasUI) ctx.ui.
setStatus(STATUS_ID,
undefined);
230 + currentCtx
= undefined;
new file mode 100644 2 + python3 scripts/extensions.py list
5 + python3 scripts/extensions.py check
{{ ext }} pi/scripts/extensions.py
Addednew file mode 100755 4 +from __future__
import annotations
13 +from pathlib
import Path
15 +ROOT
= Path(
__file__).resolve().parents[
1]
16 +EXT_ROOT
= ROOT
/ "agent" / "extensions" 18 + "@earendil-works/pi-ai",
19 + "@earendil-works/pi-agent-core",
20 + "@earendil-works/pi-coding-agent",
21 + "@earendil-works/pi-tui",
24 +IMPORT_RE
= re.compile(
r"(?:import|export)\s+(?:[^'\"]+?\s+from\s+)?['\"]([^'\"]+)['\"]|import\(['\"]([^'\"]+)['\"]\)")
25 +SECRET_RE
= re.compile(
r"(api[_-]?key|secret|token|password)\s*[:=]\s*['\"][^'\"]{12,}", re.I)
28 +def pkg_name(spec:
str) ->
str:
29 + if spec.startswith(
"@"):
30 + parts
= spec.split(
"/")
31 + return "/".join(parts[:
2])
32 + return spec.split(
"/")[
0]
35 +def read_pkg(ext: Path) ->
dict:
36 + return json.loads((ext
/ "package.json").read_text())
39 +def ext_dirs(selected:
list[
str]) ->
list[Path]:
40 + dirs
= sorted(p.parent
for p
in EXT_ROOT.glob(
"*/package.json"))
44 + wanted
= set(selected)
48 + if ext.name
in wanted
or pkg.get(
"name")
in wanted:
51 + found
= {ext.name
for ext
in result}
| {read_pkg(ext).get(
"name")
for ext
in result}
52 + missing
= wanted
- found
54 + raise SystemExit(
f"unknown extension(s): {
', '.join(
sorted(missing))}
")
58 +def ts_files(ext: Path) ->
list[Path]:
59 + return sorted(p
for p
in ext.rglob(
"*.ts")
if "node_modules" not in p.parts)
62 +def import_specs(ext: Path) ->
set[
str]:
63 + specs:
set[
str]
= set()
64 + for file
in ts_files(ext):
65 + for match
in IMPORT_RE.finditer(file.read_text(errors
="ignore")):
66 + spec
= match.group(
1)
or match.group(
2)
72 +def err(errors:
list[
str], ext: Path, msg:
str) ->
None:
73 + errors.append(
f"{ext.name}
: {msg}
")
76 +def static_check(ext: Path) ->
list[
str]:
77 + errors:
list[
str]
= []
80 + except Exception as e:
81 + return [
f"{ext.name}
: invalid package.json: {e}
"]
83 + expected
= f"@bugabinga/pi-ext-{ext.name}
" 84 + if pkg.get(
"name")
!= expected:
85 + err(errors, ext,
f"package name must be {expected
!r}
")
86 + if pkg.get(
"type")
!= "module":
87 + err(errors, ext,
"package.json type must be 'module'")
88 + if pkg.get(
"main")
!= "index.ts":
89 + err(errors, ext,
"package.json main must be 'index.ts'")
90 + if not (ext
/ "index.ts").exists():
91 + err(errors, ext,
"missing index.ts")
93 + if pkg.get(
"private")
is True:
94 + err(errors, ext,
"package must not have private:true")
95 + if pkg.get(
"license")
!= "MIT":
96 + err(errors, ext,
"package license must be MIT")
97 + if not (ext
/ "README.md").exists():
98 + err(errors, ext,
"missing README.md")
100 + deps
= pkg.get(
"dependencies", {})
or {}
101 + peers
= pkg.get(
"peerDependencies", {})
or {}
102 + dev
= pkg.get(
"devDependencies", {})
or {}
105 + if dep
in PI_PEERS:
106 + err(errors, ext,
f"Pi package {dep}
belongs in peerDependencies, not dependencies")
107 + if dep.startswith(
"@bugabinga/pi-ext-"):
108 + err(errors, ext,
f"must not depend on sibling extension {dep}
")
110 + if dep.startswith(
"@bugabinga/pi-ext-"):
111 + err(errors, ext,
f"must not peer-depend on sibling extension {dep}
")
113 + specs
= import_specs(ext)
117 + if not (s.startswith(
".")
or s.startswith(
"/")
or s.startswith(
"node:")
or s.startswith(
"bun:"))
121 + if spec.startswith(
"@bugabinga/pi-ext-"):
122 + err(errors, ext,
f"must not import sibling extension {spec}
")
124 + for file
in ts_files(ext):
125 + text
= file.read_text(errors
="ignore")
126 + for match
in IMPORT_RE.finditer(text):
127 + spec
= match.group(
1)
or match.group(
2)
128 + if not spec
or not spec.startswith(
"../"):
130 + resolved
= (file.parent
/ spec).resolve()
132 + resolved.relative_to(ext.resolve())
134 + err(errors, ext,
f"cross-extension relative import {spec}
in {file.relative_to(ext)}
")
135 + if SECRET_RE.search(text):
136 + err(errors, ext,
f"possible secret in {file.relative_to(ext)}
")
138 + for dep
in sorted(packages
& PI_PEERS):
139 + if dep
not in peers:
140 + err(errors, ext,
f"imported {dep}
but missing peerDependency")
141 + for dep
in sorted(packages
- PI_PEERS):
142 + if dep
not in deps
and dep
not in peers
and dep
not in dev:
143 + err(errors, ext,
f"imported external package {dep}
but package.json does not declare it")
148 +def external_deps(pkg:
dict) ->
list[
str]:
150 + for key
in (
"dependencies",
"peerDependencies",
"devDependencies"):
151 + deps.update((pkg.get(key)
or {}).keys())
152 + return sorted(deps)
155 +def build(ext: Path, out_root: Path) ->
None:
156 + pkg
= read_pkg(ext)
157 + cmd
= [
"bun",
"build",
"index.ts",
"--target",
"bun",
"--outdir",
str(out_root
/ ext.name)]
158 + for dep
in external_deps(pkg):
159 + cmd.extend([
"--external", dep])
160 + subprocess.run(cmd, cwd
=ext, check
=True, stdout
=subprocess.PIPE, stderr
=subprocess.PIPE, text
=True)
163 +def pack_dry(ext: Path) ->
None:
164 + proc
= subprocess.run(
165 + [
"npm",
"pack",
"--dry-run",
"--json"],
168 + stdout
=subprocess.PIPE,
169 + stderr
=subprocess.PIPE,
171 + if proc.returncode
!= 0:
172 + raise subprocess.CalledProcessError(proc.returncode, proc.args, proc.stdout, proc.stderr)
173 + info
= json.loads(proc.stdout)[
0]
174 + print(
f"OK pack {ext.name}
({
len(info.get(
'files', []))}
files, {info.get(
'unpackedSize',
0)}
bytes unpacked)")
177 +def cmd_list(selected:
list[
str]) ->
int:
178 + for ext
in ext_dirs(selected):
179 + print(
f"{ext.name}
\t{read_pkg(ext).get(
'name')}
")
183 +def cmd_check(selected:
list[
str]) ->
int:
184 + dirs
= ext_dirs(selected)
185 + errors:
list[
str]
= []
187 + errors.extend(static_check(ext))
190 + print(
f"ERROR {e}
", file
=sys.stderr)
192 + print(
f"OK static {
len(dirs)}
extension package(s)")
194 + if not shutil.which(
"bun"):
195 + print(
"ERROR bun not found", file
=sys.stderr)
197 + if not shutil.which(
"npm"):
198 + print(
"ERROR npm not found", file
=sys.stderr)
201 + with tempfile.TemporaryDirectory(prefix
="pi-ext-build-")
as tmp:
202 + out_root
= Path(tmp)
205 + build(ext, out_root)
206 + print(
f"OK build {ext.name}
")
207 + except subprocess.CalledProcessError
as e:
208 + print(
f"ERROR build {ext.name}
", file
=sys.stderr)
210 + print(e.stdout, file
=sys.stderr)
212 + print(e.stderr, file
=sys.stderr)
213 + return e.returncode
or 1 214 + print(
f"OK build {
len(dirs)}
extension package(s)")
219 + except subprocess.CalledProcessError
as e:
220 + print(
f"ERROR pack {ext.name}
", file
=sys.stderr)
222 + print(e.stdout, file
=sys.stderr)
224 + print(e.stderr, file
=sys.stderr)
225 + return e.returncode
or 1 226 + print(
f"OK pack {
len(dirs)}
extension package(s)")
231 + parser
= argparse.ArgumentParser()
232 + sub
= parser.add_subparsers(dest
="command", required
=True)
233 + list_p
= sub.add_parser(
"list")
234 + list_p.add_argument(
"extensions", nargs
="*")
235 + check_p
= sub.add_parser(
"check")
236 + check_p.add_argument(
"extensions", nargs
="*")
237 + args
= parser.parse_args()
239 + if args.command
== "list":
240 + return cmd_list(args.extensions)
241 + if args.command
== "check":
242 + return cmd_check(args.extensions)
243 + raise AssertionError(args.command)
246 +if __name__ == "__main__":
247 + raise SystemExit(main())