@hop-top/kit 0.5.0-alpha.1 → 0.5.0-alpha.11
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/CHANGELOG.md +275 -0
- package/LICENSE +1 -1
- package/LICENSE-cobra.txt +174 -0
- package/NOTICE +15 -0
- package/README.md +55 -259
- package/dist/aim-DZHwwiIc.d.ts +139 -0
- package/dist/aim.d.ts +1 -116
- package/dist/aim.js +13 -414
- package/dist/alias-D9_qFlyP.d.ts +174 -0
- package/dist/alias.d.ts +2 -73
- package/dist/alias.js +27 -207
- package/dist/api-DAexsu2H.d.ts +77 -0
- package/dist/api.d.ts +1 -62
- package/dist/api.js +10 -164
- package/dist/auth-2-jfgiHn.d.ts +34 -0
- package/dist/auth.d.ts +1 -26
- package/dist/auth.js +6 -40
- package/dist/chunk-3FIKGFKI.js +54 -0
- package/dist/chunk-4FMALWYB.js +669 -0
- package/dist/chunk-4GPCWBBA.js +143 -0
- package/dist/chunk-4UE5TCMQ.js +104 -0
- package/dist/chunk-65VPWMPV.js +1134 -0
- package/dist/chunk-6HFAEZ52.js +29 -0
- package/dist/chunk-6SVOHNIC.js +17 -0
- package/dist/chunk-BDNNPRX6.js +41 -0
- package/dist/chunk-BRNEKPWX.js +37 -0
- package/dist/chunk-BXJ2J27B.js +219 -0
- package/dist/chunk-CSJWB6D3.js +151 -0
- package/dist/chunk-CXBZTONY.js +65 -0
- package/dist/chunk-EE4M2UOF.js +818 -0
- package/dist/chunk-GFRAYYRD.js +817 -0
- package/dist/chunk-IVQHLI56.js +1890 -0
- package/dist/chunk-IZ6Q4SE3.js +178 -0
- package/dist/chunk-JKMQSAJP.js +174 -0
- package/dist/chunk-K7E34Q3A.js +1445 -0
- package/dist/chunk-KVG7YCTS.js +115 -0
- package/dist/chunk-L23O2FFE.js +51 -0
- package/dist/chunk-MFVUENZR.js +1549 -0
- package/dist/chunk-ML7D5DWY.js +263 -0
- package/dist/chunk-MQXYDYRD.js +968 -0
- package/dist/chunk-POR5L2DG.js +247 -0
- package/dist/chunk-QJVSKKRQ.js +369 -0
- package/dist/chunk-QQQYCWSC.js +240 -0
- package/dist/chunk-R5U7XKVJ.js +16 -0
- package/dist/chunk-RYKLVOVK.js +309 -0
- package/dist/chunk-SNVGDYX7.js +187 -0
- package/dist/chunk-T6OZMPPV.js +68 -0
- package/dist/chunk-UKZIAQA7.js +26 -0
- package/dist/chunk-VGOA5Y7S.js +251 -0
- package/dist/chunk-VWGP4NVJ.js +513 -0
- package/dist/chunk-WBVO43HU.js +355 -0
- package/dist/chunk-WUOAQVOA.js +86 -0
- package/dist/chunk-XJTRY453.js +868 -0
- package/dist/chunk-YOBAUCVN.js +583 -0
- package/dist/cli-RSRk1M36.d.ts +707 -0
- package/dist/cli.d.ts +7 -309
- package/dist/cli.js +125 -945
- package/dist/completion-csVun6SP.d.ts +112 -0
- package/dist/completion-values-By-mnjNt.d.ts +142 -0
- package/dist/completion-values.d.ts +1 -0
- package/dist/completion-values.js +29 -0
- package/dist/completion.d.ts +3 -0
- package/dist/completion.js +34 -0
- package/dist/compliance-AxFf-uMy.d.ts +60 -0
- package/dist/compliance.d.ts +1 -0
- package/dist/compliance.js +17 -0
- package/dist/config-CaK60ByQ.d.ts +241 -0
- package/dist/config.d.ts +1 -97
- package/dist/config.js +8 -78
- package/dist/errcorrect-BcX1Ft0K.d.ts +44 -0
- package/dist/errcorrect.d.ts +1 -37
- package/dist/errcorrect.js +8 -68
- package/dist/error-Do8Qji43.d.ts +231 -0
- package/dist/id/index.d.ts +2 -83
- package/dist/id/index.js +14 -65
- package/dist/index-BKJZClJx.d.ts +1486 -0
- package/dist/index-C3Zw4wDJ.d.ts +359 -0
- package/dist/index-CGE5yLBj.d.ts +328 -0
- package/dist/index-VLDcI5NF.d.ts +95 -0
- package/dist/index.d.ts +37 -0
- package/dist/index.js +132 -0
- package/dist/llm-DYuR7_uX.d.ts +1069 -0
- package/dist/llm-anthropic-Cd_I2xXB.d.ts +67 -0
- package/dist/llm-anthropic.d.ts +2 -0
- package/dist/llm-anthropic.js +13 -0
- package/dist/llm-openai-DyFrucmV.d.ts +87 -0
- package/dist/llm-openai.d.ts +2 -0
- package/dist/llm-openai.js +19 -0
- package/dist/llm.d.ts +1 -188
- package/dist/llm.js +101 -356
- package/dist/log-CkaxMX3U.d.ts +115 -0
- package/dist/log.d.ts +2 -0
- package/dist/log.js +14 -0
- package/dist/mcp/index.d.ts +4 -0
- package/dist/mcp/index.js +185 -0
- package/dist/netpolicy-Brx5XZUB.d.ts +151 -0
- package/dist/netpolicy.d.ts +1 -0
- package/dist/netpolicy.js +25 -0
- package/dist/output-CjZWmL8s.d.ts +420 -0
- package/dist/output.d.ts +3 -213
- package/dist/output.js +135 -447
- package/dist/parity-CvMuYcVI.d.ts +61 -0
- package/dist/progress-CAzyxeWl.d.ts +38 -0
- package/dist/progress.d.ts +1 -30
- package/dist/progress.js +6 -55
- package/dist/provenance-SMFHm5gx.d.ts +30 -0
- package/dist/provenance.d.ts +1 -24
- package/dist/provenance.js +6 -31
- package/dist/routellm-B0nv59mH.d.ts +111 -0
- package/dist/routellm.d.ts +2 -64
- package/dist/routellm.js +13 -255
- package/dist/rpc-D31Lg0Kc.d.ts +32 -0
- package/dist/rpc.d.ts +2 -25
- package/dist/rpc.js +4 -98
- package/dist/safety-CUaYEjZc.d.ts +30 -0
- package/dist/safety.d.ts +1 -24
- package/dist/safety.js +6 -43
- package/dist/scope-BrhYB4ij.d.ts +141 -0
- package/dist/scope.d.ts +1 -121
- package/dist/scope.js +20 -377
- package/dist/serve-D8yWMrTc.d.ts +646 -0
- package/dist/serve.d.ts +3 -0
- package/dist/serve.js +75 -0
- package/dist/sqlstore.js +6 -39
- package/dist/stream-CrjeCp0M.d.ts +44 -0
- package/dist/stream.d.ts +1 -35
- package/dist/stream.js +8 -51
- package/dist/telemetry/index.d.ts +1 -315
- package/dist/telemetry/index.js +26 -599
- package/dist/toolspec-DcPwwoAZ.d.ts +368 -0
- package/dist/toolspec.d.ts +2 -0
- package/dist/toolspec.js +37 -0
- package/dist/tui/index.d.ts +6 -298
- package/dist/tui/index.js +17 -381
- package/dist/upgrade-C3RWGwRi.d.ts +125 -0
- package/dist/upgrade.d.ts +1 -95
- package/dist/upgrade.js +6 -114
- package/dist/xdg-DB7Shoib.d.ts +179 -0
- package/dist/xdg.d.ts +1 -169
- package/dist/xdg.js +14 -128
- package/package.json +192 -24
- package/src/README.md +15 -0
- package/src/alias.conformance.test.ts +250 -0
- package/src/alias.test.ts +206 -2
- package/src/alias.ts +196 -21
- package/src/cli.help-command.test.ts +105 -0
- package/src/cli.offline.test.ts +93 -0
- package/src/cli.parity.test.ts +192 -0
- package/src/cli.root.conformance.test.ts +166 -0
- package/src/cli.test.ts +95 -1
- package/src/cli.ts +234 -25
- package/src/completion-scripts.ts +16 -0
- package/src/completion-values.test.ts +76 -16
- package/src/completion-values.ts +170 -66
- package/src/completion.conformance.test.ts +298 -0
- package/src/completion.test.ts +268 -145
- package/src/completion.ts +772 -121
- package/src/compliance.test.ts +196 -2
- package/src/compliance.ts +440 -20
- package/src/config-merge.test.ts +425 -0
- package/src/config.test.ts +228 -1
- package/src/config.ts +429 -16
- package/src/delegation.test.ts +299 -0
- package/src/delegation.ts +807 -0
- package/src/gen/crud_pb.ts +7 -7
- package/src/id/README.md +38 -0
- package/src/id/contract.test.ts +1 -1
- package/src/id/index.test.ts +1 -1
- package/src/id/index.ts +3 -2
- package/src/index.test.ts +71 -0
- package/src/index.ts +46 -0
- package/src/llm-anthropic.conformance.test.ts +1135 -0
- package/src/llm-anthropic.test.ts +152 -0
- package/src/llm-anthropic.ts +940 -0
- package/src/llm-choice-hermetic.test.ts +335 -0
- package/src/llm-config.test.ts +232 -0
- package/src/llm-config.ts +106 -0
- package/src/llm-endpoint.ts +254 -0
- package/src/llm-error.ts +17 -0
- package/src/llm-errors.ts +152 -0
- package/src/llm-file.ts +126 -0
- package/src/llm-http.ts +317 -0
- package/src/llm-keys.ts +167 -0
- package/src/llm-media.conformance.test.ts +87 -0
- package/src/llm-media.test.ts +279 -0
- package/src/llm-media.ts +322 -0
- package/src/llm-openai.conformance.test.ts +407 -0
- package/src/llm-openai.test.ts +510 -0
- package/src/llm-openai.ts +708 -0
- package/src/llm-payload.ts +155 -0
- package/src/llm-quote.ts +46 -0
- package/src/llm-routellm.conformance.test.ts +44 -0
- package/src/llm-toolnames.conformance.test.ts +112 -0
- package/src/llm-toolnames.test.ts +132 -0
- package/src/llm-toolnames.ts +298 -0
- package/src/llm-uri.ts +99 -0
- package/src/llm.test.ts +43 -15
- package/src/llm.toolcall.test.ts +175 -0
- package/src/llm.ts +602 -190
- package/src/log.parity.test.ts +105 -0
- package/src/log.test.ts +270 -1
- package/src/log.ts +228 -49
- package/src/mcp/README.md +63 -0
- package/src/mcp/args-separator.test.ts +164 -0
- package/src/mcp/args.test.ts +223 -0
- package/src/mcp/args.ts +160 -0
- package/src/mcp/audit.test.ts +520 -0
- package/src/mcp/audit.ts +70 -0
- package/src/mcp/bridge.test.ts +250 -0
- package/src/mcp/bridge.ts +286 -0
- package/src/mcp/conformance.test.ts +357 -0
- package/src/mcp/dispatch.ts +359 -0
- package/src/mcp/identity.test.ts +166 -0
- package/src/mcp/identity.ts +72 -0
- package/src/mcp/index.ts +176 -0
- package/src/mcp/legacy-notify.test.ts +59 -0
- package/src/mcp/legacy.ts +367 -0
- package/src/mcp/mcp.test.ts +707 -0
- package/src/mcp/modern-confirm.test.ts +520 -0
- package/src/mcp/modern-confirm.ts +484 -0
- package/src/mcp/modern.ts +788 -0
- package/src/mcp/stdio.test.ts +313 -0
- package/src/mcp/stdio.ts +254 -0
- package/src/mcp/tasks.ts +82 -0
- package/src/mcp/testtree.ts +250 -0
- package/src/mcp/toolname.test.ts +147 -0
- package/src/mcp/types.ts +689 -0
- package/src/netpolicy.test.ts +280 -0
- package/src/netpolicy.ts +256 -0
- package/src/output/README.md +46 -0
- package/src/output/builtins.ts +5 -5
- package/src/output/dispatch.ts +10 -2
- package/src/output/error.ts +459 -0
- package/src/output/formatter.ts +29 -5
- package/src/output/formatters/README.md +50 -0
- package/src/output/formatters/csv.ts +48 -12
- package/src/output/formatters/json.ts +4 -25
- package/src/output/formatters/project.ts +34 -0
- package/src/output/formatters/table.ts +8 -6
- package/src/output/formatters/text.ts +7 -3
- package/src/output/formatters/yaml.ts +5 -22
- package/src/output/projection.test.ts +298 -0
- package/src/output/projection.ts +33 -59
- package/src/output/template.ts +11 -21
- package/src/output.surface.test.ts +41 -0
- package/src/output.ts +64 -3
- package/src/plan.ts +89 -0
- package/src/policy.ts +472 -0
- package/src/published-types.test.ts +133 -0
- package/src/routellm.test.ts +209 -28
- package/src/routellm.toolcall.test.ts +521 -0
- package/src/routellm.ts +213 -177
- package/src/router/README.md +44 -0
- package/src/router/server.test.ts +41 -0
- package/src/router/server.ts +11 -0
- package/src/safety.test.ts +19 -9
- package/src/scope-defaults.json +29 -29
- package/src/serve.test.ts +1257 -0
- package/src/serve.ts +1665 -0
- package/src/sideeffect.ts +105 -0
- package/src/telemetry/README.md +48 -0
- package/src/telemetry/client.test.ts +31 -0
- package/src/telemetry/client.ts +12 -6
- package/src/telemetry/offline.test.ts +64 -0
- package/src/toolspec-internal.ts +279 -0
- package/src/toolspec-manifest.test.ts +167 -0
- package/src/toolspec-manifest.ts +415 -0
- package/src/toolspec-spec-schemas.ts +12 -0
- package/src/toolspec-spec.test.ts +273 -0
- package/src/toolspec-spec.ts +458 -0
- package/src/toolspec.from-command.test.ts +350 -0
- package/src/toolspec.test.ts +2 -2
- package/src/toolspec.ts +222 -0
- package/src/triton/README.md +34 -0
- package/src/tui/README.md +42 -0
- package/src/tui/parity.test.ts +120 -31
- package/src/tui/parity.ts +58 -7
- package/src/upgrade.test.ts +291 -0
- package/src/upgrade.ts +116 -7
- package/src/wizard.test.ts +7 -7
- package/test/llm/conformance-helpers.ts +100 -0
- package/test/output/csv.test.ts +164 -0
- package/test/output/dispatch.test.ts +1 -2
- package/test/output/error.test.ts +277 -0
- package/test/output/smoke-capture.ts +2 -2
- package/test/output/smoke.test.ts +2 -2
- package/test/output/taxonomy-contract.test.ts +148 -0
- package/test/setup-env.ts +16 -0
- package/test/toolspec/fixture.ts +79 -0
- package/tsconfig.json +3 -1
- package/tsconfig.test.json +10 -0
- package/vitest.config.ts +9 -0
- package/src/tui/parity.json +0 -74
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mirrors `go/core/netpolicy/netpolicy_test.go` and `install_test.go`.
|
|
3
|
+
*
|
|
4
|
+
* The semantics under test are the Go contract: block external egress when
|
|
5
|
+
* the marker is set, exempt loopback, treat DNS names as remote, leave an
|
|
6
|
+
* unmarked scope untouched, and fail with a matchable error rather than a
|
|
7
|
+
* silent no-op.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
11
|
+
|
|
12
|
+
import {
|
|
13
|
+
ErrOffline,
|
|
14
|
+
guardFetch,
|
|
15
|
+
install,
|
|
16
|
+
isOffline,
|
|
17
|
+
isOfflineError,
|
|
18
|
+
OfflineError,
|
|
19
|
+
withOffline,
|
|
20
|
+
} from './netpolicy';
|
|
21
|
+
|
|
22
|
+
/** A fetch stand-in recording whether the wrapped implementation was reached. */
|
|
23
|
+
function recorder() {
|
|
24
|
+
const state = { reached: false };
|
|
25
|
+
const fn = vi.fn(async (_input: any, _init?: any) => {
|
|
26
|
+
state.reached = true;
|
|
27
|
+
return new Response(null, { status: 204 });
|
|
28
|
+
});
|
|
29
|
+
return { state, fn: fn as unknown as typeof globalThis.fetch };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
describe('guardFetch', () => {
|
|
33
|
+
// A marked scope must stop the request before it reaches the wire. The
|
|
34
|
+
// destination is external: loopback is exempt by design.
|
|
35
|
+
it('blocks external hosts when offline', async () => {
|
|
36
|
+
const rec = recorder();
|
|
37
|
+
const guarded = guardFetch(rec.fn);
|
|
38
|
+
|
|
39
|
+
const err = await withOffline(true, async () => {
|
|
40
|
+
try {
|
|
41
|
+
await guarded('https://example.invalid/v1/thing');
|
|
42
|
+
return null;
|
|
43
|
+
} catch (e) {
|
|
44
|
+
return e;
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
expect(err, 'expected an offline error, got none').not.toBeNull();
|
|
49
|
+
expect(isOfflineError(err)).toBe(true);
|
|
50
|
+
expect(rec.state.reached, 'request reached the transport despite offline scope').toBe(false);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
// Unmarked scopes must be entirely unaffected.
|
|
54
|
+
it('allows requests when not offline', async () => {
|
|
55
|
+
const rec = recorder();
|
|
56
|
+
const guarded = guardFetch(rec.fn);
|
|
57
|
+
|
|
58
|
+
const res = await guarded('https://example.invalid/v1/thing');
|
|
59
|
+
expect(res.status).toBe(204);
|
|
60
|
+
expect(rec.state.reached).toBe(true);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
// Loopback stays reachable when offline: --offline means "no network",
|
|
64
|
+
// not "cannot talk to myself".
|
|
65
|
+
it('allows loopback when offline', async () => {
|
|
66
|
+
for (const target of [
|
|
67
|
+
'http://127.0.0.1:8080/health',
|
|
68
|
+
'http://localhost:9000/health',
|
|
69
|
+
'http://[::1]:9000/health',
|
|
70
|
+
]) {
|
|
71
|
+
const rec = recorder();
|
|
72
|
+
const guarded = guardFetch(rec.fn);
|
|
73
|
+
|
|
74
|
+
await withOffline(true, async () => {
|
|
75
|
+
const res = await guarded(target);
|
|
76
|
+
expect(res.status, `${target}: unexpected status`).toBe(204);
|
|
77
|
+
});
|
|
78
|
+
expect(rec.state.reached, `${target}: loopback request was blocked`).toBe(true);
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
// A DNS name is remote even if it might resolve to loopback: resolving
|
|
83
|
+
// it is itself network access.
|
|
84
|
+
it('blocks DNS names when offline', async () => {
|
|
85
|
+
const rec = recorder();
|
|
86
|
+
const guarded = guardFetch(rec.fn);
|
|
87
|
+
|
|
88
|
+
const err = await withOffline(true, async () => {
|
|
89
|
+
try {
|
|
90
|
+
await guarded('http://my-host.internal/health');
|
|
91
|
+
return null;
|
|
92
|
+
} catch (e) {
|
|
93
|
+
return e;
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
expect(isOfflineError(err), `expected ErrOffline, got ${err}`).toBe(true);
|
|
98
|
+
expect(rec.state.reached, 'DNS-named host was allowed through').toBe(false);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
// Request objects carry the URL on `.url`, not as a bare string.
|
|
102
|
+
it('reads the target from a Request object', async () => {
|
|
103
|
+
const rec = recorder();
|
|
104
|
+
const guarded = guardFetch(rec.fn);
|
|
105
|
+
|
|
106
|
+
const err = await withOffline(true, async () => {
|
|
107
|
+
try {
|
|
108
|
+
await guarded(new Request('https://example.invalid/x'));
|
|
109
|
+
return null;
|
|
110
|
+
} catch (e) {
|
|
111
|
+
return e;
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
expect(isOfflineError(err)).toBe(true);
|
|
116
|
+
expect(rec.state.reached).toBe(false);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
// The refusal must be matchable and name the target, mirroring Go's
|
|
120
|
+
// "%s %s: %w" wrapping of ErrOffline.
|
|
121
|
+
it('rejects with a matchable, informative error', async () => {
|
|
122
|
+
const guarded = guardFetch(recorder().fn);
|
|
123
|
+
|
|
124
|
+
const err = await withOffline(true, async () => {
|
|
125
|
+
try {
|
|
126
|
+
await guarded('https://example.invalid/x', { method: 'POST' });
|
|
127
|
+
return null;
|
|
128
|
+
} catch (e) {
|
|
129
|
+
return e;
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
expect(err).toBeInstanceOf(Error);
|
|
134
|
+
expect((err as Error).name).toBe(ErrOffline);
|
|
135
|
+
expect((err as Error).message).toContain('POST');
|
|
136
|
+
expect((err as Error).message).toContain('https://example.invalid/x');
|
|
137
|
+
expect((err as Error).message).toContain('--offline');
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
// The refusal names where the request was going, never what it carried:
|
|
141
|
+
// scheme, host and path only. Query, fragment and userinfo may hold
|
|
142
|
+
// credentials (an API key param, basic-auth userinfo) and are dropped.
|
|
143
|
+
// Mirrors Go's TestGuard_RefusalOmitsQueryFragmentUserinfo.
|
|
144
|
+
describe('refusal omits query, fragment and userinfo', () => {
|
|
145
|
+
const raw =
|
|
146
|
+
'https://alice:pw-secret@example.invalid/v1/models/m:generate' +
|
|
147
|
+
'?alt=sse&key=q-secret#frag-secret';
|
|
148
|
+
const leaks = ['alice', 'pw-secret', 'q-secret', 'key=', 'alt=sse', 'frag-secret', '?', '#', '@'];
|
|
149
|
+
|
|
150
|
+
// The fetch spec forbids credentials in a Request URL, so the Request
|
|
151
|
+
// case carries query and fragment only.
|
|
152
|
+
const noUserinfo = raw.replace('alice:pw-secret@', '');
|
|
153
|
+
|
|
154
|
+
for (const [label, call] of [
|
|
155
|
+
['string input', (f: typeof globalThis.fetch) => f(raw, { method: 'POST' })],
|
|
156
|
+
['URL input', (f: typeof globalThis.fetch) => f(new URL(raw), { method: 'POST' })],
|
|
157
|
+
[
|
|
158
|
+
'Request input',
|
|
159
|
+
(f: typeof globalThis.fetch) => f(new Request(noUserinfo, { method: 'POST' })),
|
|
160
|
+
],
|
|
161
|
+
] as const) {
|
|
162
|
+
it(label, async () => {
|
|
163
|
+
const guarded = guardFetch(recorder().fn);
|
|
164
|
+
|
|
165
|
+
const err = await withOffline(true, async () => {
|
|
166
|
+
try {
|
|
167
|
+
await call(guarded);
|
|
168
|
+
return null;
|
|
169
|
+
} catch (e) {
|
|
170
|
+
return e;
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
expect(isOfflineError(err), `expected ErrOffline, got ${err}`).toBe(true);
|
|
175
|
+
const msg = (err as Error).message;
|
|
176
|
+
expect(msg).toBe(
|
|
177
|
+
'POST https://example.invalid/v1/models/m:generate: network disabled by --offline',
|
|
178
|
+
);
|
|
179
|
+
for (const leak of leaks) {
|
|
180
|
+
expect(msg, `refusal carries ${leak}`).not.toContain(leak);
|
|
181
|
+
}
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// An unparseable target is refused (fail closed) and cannot be
|
|
186
|
+
// stripped reliably, so none of it is echoed.
|
|
187
|
+
it('unparseable target', async () => {
|
|
188
|
+
const guarded = guardFetch(recorder().fn);
|
|
189
|
+
|
|
190
|
+
const err = await withOffline(true, async () => {
|
|
191
|
+
try {
|
|
192
|
+
await guarded('not a url?key=q-secret#frag-secret');
|
|
193
|
+
return null;
|
|
194
|
+
} catch (e) {
|
|
195
|
+
return e;
|
|
196
|
+
}
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
expect(isOfflineError(err), `expected ErrOffline, got ${err}`).toBe(true);
|
|
200
|
+
const msg = (err as Error).message;
|
|
201
|
+
expect(msg).toMatch(/^GET .*: network disabled by --offline$/);
|
|
202
|
+
for (const leak of leaks) {
|
|
203
|
+
expect(msg, `refusal carries ${leak}`).not.toContain(leak);
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
// An adopter constructing the error by hand gets the same stripping.
|
|
208
|
+
it('OfflineError constructed directly', () => {
|
|
209
|
+
const err = new OfflineError('GET', raw);
|
|
210
|
+
expect(isOfflineError(err)).toBe(true);
|
|
211
|
+
expect(err.message).toBe(
|
|
212
|
+
'GET https://example.invalid/v1/models/m:generate: network disabled by --offline',
|
|
213
|
+
);
|
|
214
|
+
});
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
// Wrapping must be idempotent, mirroring Go's Guard.
|
|
218
|
+
it('does not double-wrap', () => {
|
|
219
|
+
const once = guardFetch(recorder().fn);
|
|
220
|
+
expect(guardFetch(once)).toBe(once);
|
|
221
|
+
});
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
describe('withOffline / isOffline', () => {
|
|
225
|
+
// withOffline(false) must not mark the scope.
|
|
226
|
+
it('leaves the scope clean when false', async () => {
|
|
227
|
+
expect(isOffline()).toBe(false);
|
|
228
|
+
await withOffline(false, async () => {
|
|
229
|
+
expect(isOffline()).toBe(false);
|
|
230
|
+
});
|
|
231
|
+
expect(isOffline()).toBe(false);
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
it('marks the scope when true, and unmarks it on exit', async () => {
|
|
235
|
+
await withOffline(true, async () => {
|
|
236
|
+
expect(isOffline()).toBe(true);
|
|
237
|
+
});
|
|
238
|
+
expect(isOffline()).toBe(false);
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
// The marker must survive an await boundary — otherwise a guard running
|
|
242
|
+
// inside an async fetch implementation would not see it.
|
|
243
|
+
it('survives await boundaries', async () => {
|
|
244
|
+
await withOffline(true, async () => {
|
|
245
|
+
await new Promise((r) => setTimeout(r, 1));
|
|
246
|
+
expect(isOffline()).toBe(true);
|
|
247
|
+
});
|
|
248
|
+
});
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
describe('install', () => {
|
|
252
|
+
const orig = globalThis.fetch;
|
|
253
|
+
afterEach(() => {
|
|
254
|
+
globalThis.fetch = orig;
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
// install must make a bare `fetch(...)` call — the common case across kit
|
|
258
|
+
// and adopter code — enforce the policy, and must be idempotent.
|
|
259
|
+
it('guards globalThis.fetch and is idempotent', async () => {
|
|
260
|
+
const rec = recorder();
|
|
261
|
+
globalThis.fetch = rec.fn;
|
|
262
|
+
|
|
263
|
+
install();
|
|
264
|
+
const afterFirst = globalThis.fetch;
|
|
265
|
+
install();
|
|
266
|
+
expect(globalThis.fetch, 'install double-wrapped globalThis.fetch').toBe(afterFirst);
|
|
267
|
+
|
|
268
|
+
const err = await withOffline(true, async () => {
|
|
269
|
+
try {
|
|
270
|
+
await globalThis.fetch('https://example.invalid/x');
|
|
271
|
+
return null;
|
|
272
|
+
} catch (e) {
|
|
273
|
+
return e;
|
|
274
|
+
}
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
expect(isOfflineError(err), `global fetch not guarded after install: ${err}`).toBe(true);
|
|
278
|
+
expect(rec.state.reached).toBe(false);
|
|
279
|
+
});
|
|
280
|
+
});
|
package/src/netpolicy.ts
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module netpolicy
|
|
3
|
+
* @package @hop-top/kit
|
|
4
|
+
*
|
|
5
|
+
* Owns the process-wide network policy marker and the `fetch` wrapper that
|
|
6
|
+
* enforces it.
|
|
7
|
+
*
|
|
8
|
+
* The `--offline` global (cli-parity-guide, "Global Flags") promises that
|
|
9
|
+
* network access is disabled. Marking a scope alone cannot keep that
|
|
10
|
+
* promise: it is advisory, so any caller that forgets to consult it still
|
|
11
|
+
* reaches the wire. {@link guardFetch} closes that gap by refusing the
|
|
12
|
+
* request inside the fetch implementation, beneath every caller, where no
|
|
13
|
+
* naive leaf can route around it.
|
|
14
|
+
*
|
|
15
|
+
* The marker lives in its own module rather than in `cli` so library code
|
|
16
|
+
* can enforce the policy without importing the CLI factory back.
|
|
17
|
+
*
|
|
18
|
+
* Loopback is deliberately exempt. `--offline` means "do not talk to the
|
|
19
|
+
* network", not "do not talk to myself": a local `kit serve` peer, a dev
|
|
20
|
+
* backend on 127.0.0.1 and unix sockets stay reachable so offline
|
|
21
|
+
* workflows remain usable.
|
|
22
|
+
*
|
|
23
|
+
* ## Scope
|
|
24
|
+
*
|
|
25
|
+
* {@link install} wraps `globalThis.fetch`, so it covers HTTP and HTTPS
|
|
26
|
+
* through the fetch API — which is every network client in kit today
|
|
27
|
+
* (`api`, `aim`, `upgrade`, `routellm`, `triton`, `telemetry`, and the
|
|
28
|
+
* ConnectRPC transport, which resolves `globalThis.fetch` lazily per
|
|
29
|
+
* call). undici's `setGlobalDispatcher` is not used: undici is not a
|
|
30
|
+
* dependency of this package, so the dispatcher hook is unavailable
|
|
31
|
+
* without adding one, and it would not cover callers that inject their
|
|
32
|
+
* own `fetch` anyway.
|
|
33
|
+
*
|
|
34
|
+
* It does NOT cover code that opens a socket directly: `node:net`,
|
|
35
|
+
* `node:http`/`node:https` (`http.request`), `node:dgram`, database
|
|
36
|
+
* drivers, or raw TLS. Nor does it cover a caller that captured a
|
|
37
|
+
* reference to the unguarded `fetch` before {@link install} ran, or one
|
|
38
|
+
* that injects its own transport (`APIClient({ fetch })`). For those,
|
|
39
|
+
* `--offline` remains advisory and the call site must consult
|
|
40
|
+
* {@link isOffline} itself, or wrap its own transport with
|
|
41
|
+
* {@link guardFetch}. Closing that gap needs a guarded dialer threaded
|
|
42
|
+
* through each such client; it is deliberately not attempted here.
|
|
43
|
+
*/
|
|
44
|
+
|
|
45
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Name carried by the error {@link guardFetch} rejects with when a request
|
|
49
|
+
* is attempted in an offline-marked scope. JavaScript has no `errors.Is`,
|
|
50
|
+
* so the name is the matchable analogue of Go's sentinel `ErrOffline`;
|
|
51
|
+
* prefer {@link isOfflineError} over comparing it by hand.
|
|
52
|
+
*/
|
|
53
|
+
export const ErrOffline = 'OfflineError';
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Error rejected by {@link guardFetch}. Matchable via {@link isOfflineError}.
|
|
57
|
+
*
|
|
58
|
+
* The message names the method and the destination as scheme, host and
|
|
59
|
+
* path only; `url` is reduced by {@link destination} whoever constructs
|
|
60
|
+
* the error.
|
|
61
|
+
*/
|
|
62
|
+
export class OfflineError extends Error {
|
|
63
|
+
override readonly name = ErrOffline;
|
|
64
|
+
|
|
65
|
+
constructor(method: string, url: string) {
|
|
66
|
+
super(`${method} ${destination(url)}: network disabled by --offline`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Render url as scheme, host and path only: enough to say where a refused
|
|
72
|
+
* request was going, nothing it carried. Query, fragment and userinfo are
|
|
73
|
+
* dropped because they may hold credentials (an API key param, basic-auth
|
|
74
|
+
* userinfo). An opaque URL (`data:`, `mailto:`) keeps its scheme alone,
|
|
75
|
+
* and a target that does not parse cannot be stripped reliably, so none
|
|
76
|
+
* of it is echoed. Mirrors Go's `netpolicy` refusal.
|
|
77
|
+
*/
|
|
78
|
+
function destination(url: string): string {
|
|
79
|
+
let u: URL;
|
|
80
|
+
try {
|
|
81
|
+
u = new URL(url);
|
|
82
|
+
} catch {
|
|
83
|
+
return '<unparseable URL>';
|
|
84
|
+
}
|
|
85
|
+
if (u.host === '' && !u.pathname.startsWith('/')) return u.protocol;
|
|
86
|
+
return `${u.protocol}//${u.host}${u.pathname}`;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Report whether err is the refusal raised by the offline guard. Matches on
|
|
91
|
+
* the error name rather than `instanceof` so a copy of this module loaded
|
|
92
|
+
* through a different resolution path (bundled adopter, dual dist/src
|
|
93
|
+
* graph) still matches — the JS analogue of `errors.Is`.
|
|
94
|
+
*/
|
|
95
|
+
export function isOfflineError(err: unknown): boolean {
|
|
96
|
+
return err instanceof Error && err.name === ErrOffline;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// ---------------------------------------------------------------------------
|
|
100
|
+
// Marker
|
|
101
|
+
// ---------------------------------------------------------------------------
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Per-invocation marker. AsyncLocalStorage is the TypeScript analogue of
|
|
105
|
+
* Go's `context.Context` value: it propagates across `await` boundaries
|
|
106
|
+
* into the guarded fetch without threading a parameter through every
|
|
107
|
+
* library call.
|
|
108
|
+
*/
|
|
109
|
+
const store = new AsyncLocalStorage<boolean>();
|
|
110
|
+
|
|
111
|
+
/** Set when the policy applies process-wide rather than to one async scope. */
|
|
112
|
+
let processOffline = false;
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Run fn in a scope marked offline. Passing false runs fn unchanged so an
|
|
116
|
+
* unmarked scope stays clean, mirroring Go's `WithOffline(ctx, false)`.
|
|
117
|
+
*/
|
|
118
|
+
export function withOffline<T>(offline: boolean, fn: () => T): T {
|
|
119
|
+
if (!offline) return fn();
|
|
120
|
+
return store.run(true, fn);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Mark the whole process offline. The CLI uses this rather than
|
|
125
|
+
* {@link withOffline} because commander dispatches an action handler
|
|
126
|
+
* without giving the framework a scope to wrap around it, and because a
|
|
127
|
+
* detached callback (a timer, an unawaited promise) must stay refused.
|
|
128
|
+
* Mirrors the process-global reach of Go's `netpolicy.Install`.
|
|
129
|
+
*/
|
|
130
|
+
export function setProcessOffline(offline: boolean): void {
|
|
131
|
+
processOffline = offline;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Report whether the caller is running under the offline marker — either
|
|
136
|
+
* an enclosing {@link withOffline} scope or a process-wide
|
|
137
|
+
* {@link setProcessOffline}.
|
|
138
|
+
*/
|
|
139
|
+
export function isOffline(): boolean {
|
|
140
|
+
return processOffline || store.getStore() === true;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// ---------------------------------------------------------------------------
|
|
144
|
+
// Enforcement
|
|
145
|
+
// ---------------------------------------------------------------------------
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Report whether host names a loopback address. Hosts that are not literal
|
|
149
|
+
* IPs (DNS names) are treated as remote: resolving them would itself be
|
|
150
|
+
* network access.
|
|
151
|
+
*/
|
|
152
|
+
export function isLoopback(hostname: string): boolean {
|
|
153
|
+
// URL.hostname keeps IPv6 literals bracketed and lower-cases the rest.
|
|
154
|
+
const h = hostname.replace(/^\[|\]$/g, '');
|
|
155
|
+
if (h === 'localhost') return true;
|
|
156
|
+
if (h === '::1') return true;
|
|
157
|
+
// IPv4 loopback is the whole 127.0.0.0/8 block.
|
|
158
|
+
const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(h);
|
|
159
|
+
if (v4) {
|
|
160
|
+
return v4.slice(1).every((o) => Number(o) <= 255) && Number(v4[1]) === 127;
|
|
161
|
+
}
|
|
162
|
+
// IPv4-mapped IPv6 loopback, in either textual form.
|
|
163
|
+
const mapped = /^::ffff:(.+)$/i.exec(h);
|
|
164
|
+
if (mapped) {
|
|
165
|
+
const inner = mapped[1] ?? '';
|
|
166
|
+
if (/^7f00:1$/i.test(inner)) return true;
|
|
167
|
+
return isLoopback(inner);
|
|
168
|
+
}
|
|
169
|
+
return false;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Resolve the method and absolute URL a fetch call targets. */
|
|
173
|
+
function target(input: RequestInfo | URL, init?: RequestInit): { method: string; url: string } {
|
|
174
|
+
if (typeof Request !== 'undefined' && input instanceof Request) {
|
|
175
|
+
return { method: init?.method ?? input.method, url: input.url };
|
|
176
|
+
}
|
|
177
|
+
return { method: init?.method ?? 'GET', url: String(input) };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Marks a fetch implementation as already guarded, so wrapping is idempotent. */
|
|
181
|
+
const guarded = Symbol.for('hop.top/kit/netpolicy.guarded');
|
|
182
|
+
const unguardedBase = Symbol.for('hop.top/kit/netpolicy.unguardedBase');
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Wrap base so requests made in an offline-marked scope reject with an
|
|
186
|
+
* {@link OfflineError} instead of reaching the network. Wrapping is
|
|
187
|
+
* idempotent: guarding an already guarded fetch returns it unchanged.
|
|
188
|
+
*
|
|
189
|
+
* A URL that does not parse is refused when offline: an unparseable target
|
|
190
|
+
* cannot be shown to be loopback, and the policy fails closed.
|
|
191
|
+
*/
|
|
192
|
+
export function guardFetch(base: typeof globalThis.fetch): typeof globalThis.fetch {
|
|
193
|
+
if ((base as { [guarded]?: boolean })[guarded]) return base;
|
|
194
|
+
|
|
195
|
+
const wrapper: typeof globalThis.fetch = async (input, init) => {
|
|
196
|
+
if (isOffline()) {
|
|
197
|
+
const { method, url } = target(input, init);
|
|
198
|
+
let loopback = false;
|
|
199
|
+
try {
|
|
200
|
+
loopback = isLoopback(new URL(url).hostname);
|
|
201
|
+
} catch {
|
|
202
|
+
loopback = false; // fail closed on an unparseable target
|
|
203
|
+
}
|
|
204
|
+
if (!loopback) throw new OfflineError(method, url);
|
|
205
|
+
}
|
|
206
|
+
return base(input, init);
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
(wrapper as { [guarded]?: boolean })[guarded] = true;
|
|
210
|
+
// Remember the unwrapped transport so logging-class sinks can reach
|
|
211
|
+
// past the guard without capturing a reference at module load.
|
|
212
|
+
(wrapper as { [unguardedBase]?: typeof globalThis.fetch })[unguardedBase] = base;
|
|
213
|
+
return wrapper;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Wrap `globalThis.fetch` with {@link guardFetch}, so every caller that
|
|
218
|
+
* does not inject its own transport — the common case across kit and
|
|
219
|
+
* adopter code — enforces the policy without a per-site change.
|
|
220
|
+
*
|
|
221
|
+
* Idempotent and safe to call more than once. Call it once during process
|
|
222
|
+
* start-up (`createCLI` does this) and never concurrently with in-flight
|
|
223
|
+
* requests: it mutates a process-global.
|
|
224
|
+
*
|
|
225
|
+
* Callers that DO inject their own fetch must wrap it themselves with
|
|
226
|
+
* {@link guardFetch}; install cannot reach them.
|
|
227
|
+
*/
|
|
228
|
+
export function install(): void {
|
|
229
|
+
globalThis.fetch = guardFetch(globalThis.fetch);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Fetch for logging-class egress — telemetry, and any future
|
|
234
|
+
* remote-logging or crash-reporting sink.
|
|
235
|
+
*
|
|
236
|
+
* `--offline` means "do not talk to the network on the user's behalf". It
|
|
237
|
+
* does not silence diagnostics, the same way a remote syslog target is
|
|
238
|
+
* not muted by an offline flag. Consent and the telemetry mode already
|
|
239
|
+
* govern whether those sinks emit at all; `--offline` is not a second
|
|
240
|
+
* consent gate.
|
|
241
|
+
*
|
|
242
|
+
* Resolved lazily, per call: it reads the *current* `globalThis.fetch`
|
|
243
|
+
* and unwraps the guard if {@link install} has wrapped it. Capturing a
|
|
244
|
+
* reference at module load instead would freeze out later stubbing —
|
|
245
|
+
* breaking both test fakes and adopters who swap the global transport.
|
|
246
|
+
*
|
|
247
|
+
* Never use this for anything the user asked for — that is exactly the
|
|
248
|
+
* traffic `--offline` exists to stop.
|
|
249
|
+
*/
|
|
250
|
+
export function observabilityFetch(): typeof globalThis.fetch {
|
|
251
|
+
const current = globalThis.fetch as {
|
|
252
|
+
[guarded]?: boolean;
|
|
253
|
+
[unguardedBase]?: typeof globalThis.fetch;
|
|
254
|
+
};
|
|
255
|
+
return current?.[unguardedBase] ?? (globalThis.fetch as typeof globalThis.fetch);
|
|
256
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# output
|
|
2
|
+
|
|
3
|
+
## What it answers
|
|
4
|
+
|
|
5
|
+
How a command turns a structured value into bytes on a stream in the format the caller picked: table, json, yaml, csv, text, or a `--template`. It also owns the structured error envelope and the exit-code table. Wrong module for terminal widgets (`@hop-top/kit/tui`), progress events (`@hop-top/kit/progress`), or any flag outside the output suite (`@hop-top/kit/cli`).
|
|
6
|
+
|
|
7
|
+
## Use it when
|
|
8
|
+
|
|
9
|
+
- one-off render, no flags involved: `render(w, format, data)`
|
|
10
|
+
- Commander program that must honour `--format`, `--format-opt`, `--cols`, `--template`, `--output|-o`, `--format-help`: `registerOutputFlags(program)` then `dispatch(program, data)`
|
|
11
|
+
- fail with a machine-readable error under `--format json|yaml`: `notFoundError`, `usageError`, `wrapError` and friends, rendered by `renderError`
|
|
12
|
+
- add a format: implement `Formatter`, `defaultRegistry.register(f)`; built-ins live in [`formatters/`](formatters/README.md)
|
|
13
|
+
|
|
14
|
+
## Quick start
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import { render, TABLE_FORMAT, JSON_FORMAT } from '@hop-top/kit/output';
|
|
18
|
+
|
|
19
|
+
render(process.stdout, TABLE_FORMAT, [{ id: '1', name: 'Alice' }]);
|
|
20
|
+
render(process.stdout, JSON_FORMAT, { ok: true });
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Contract
|
|
24
|
+
|
|
25
|
+
- `render(w, format, v)` renders every column in payload key order. `ColumnSpec[]` and `--cols` are reachable only through `dispatch`.
|
|
26
|
+
- `--cols` selects and reorders; the user's order wins over the `ColumnSpec` list.
|
|
27
|
+
- `--template` and `--cols` are mutually exclusive; `dispatch` throws.
|
|
28
|
+
- Format resolution: explicit `--format`, else the `--output` extension, else `table`.
|
|
29
|
+
- Error envelope keys are wire snake_case; empty optionals stay off the wire (Go `omitempty`).
|
|
30
|
+
- Exit codes are exported constants (`EXIT_*`); import them, never hardcode, and read the constants rather than a list in prose — the line that used to sit here named four and stopped at 65, so it read as a ceiling once `EXIT_PREREQUISITE` 70 existed.
|
|
31
|
+
- Parity: [`sdk/tests/cross-lang/fixtures/ordering.json`](../../../tests/cross-lang/fixtures/ordering.json), replayed by `sdk/tests/cross-lang/run-order.sh`.
|
|
32
|
+
|
|
33
|
+
## Neighbours
|
|
34
|
+
|
|
35
|
+
- `@hop-top/kit/cli`: program factory, help layout, `Theme`
|
|
36
|
+
- `@hop-top/kit/tui`: styled TTY widgets (status, badge, spinner)
|
|
37
|
+
- `@hop-top/kit/progress`: Factor 9 progress events
|
|
38
|
+
- `@hop-top/kit/provenance`: `_meta` provenance wrapper around payloads
|
|
39
|
+
- `@hop-top/kit/stream`: stdout/stderr discipline
|
|
40
|
+
- Go reference: [`go/console/output`](../../../../go/console/output/README.md); Python port: [`hop_top_kit/output`](../../../py/hop_top_kit/output/README.md)
|
|
41
|
+
|
|
42
|
+
## See also
|
|
43
|
+
|
|
44
|
+
- [`sdk/ts/README.md`](../../README.md), section "Output formatting": flag surface, column-ordering rules, conformance status
|
|
45
|
+
- [`docs/adopters/reference/ts-api-reference.md`](../../../../docs/adopters/reference/ts-api-reference.md)
|
|
46
|
+
- [`sdk/tests/cross-lang/README.md`](../../../tests/cross-lang/README.md): column-ordering harness
|
package/src/output/builtins.ts
CHANGED
|
@@ -7,25 +7,25 @@
|
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
9
|
import { defaultRegistry } from './registry';
|
|
10
|
+
import { csvFormatter } from './formatters/csv';
|
|
10
11
|
import { jsonFormatter } from './formatters/json';
|
|
11
|
-
import { yamlFormatter } from './formatters/yaml';
|
|
12
12
|
import { tableFormatter } from './formatters/table';
|
|
13
|
-
import { csvFormatter } from './formatters/csv';
|
|
14
13
|
import { textFormatter } from './formatters/text';
|
|
14
|
+
import { yamlFormatter } from './formatters/yaml';
|
|
15
15
|
|
|
16
16
|
let registered = false;
|
|
17
17
|
|
|
18
18
|
/**
|
|
19
|
-
* Register the built-in formatters (
|
|
19
|
+
* Register the built-in formatters (csv, json, table, text, yaml) against
|
|
20
20
|
* defaultRegistry. Idempotent — safe to call from multiple entry points.
|
|
21
21
|
*/
|
|
22
22
|
export function registerBuiltins(): void {
|
|
23
23
|
if (registered) return;
|
|
24
|
+
defaultRegistry.register(csvFormatter);
|
|
24
25
|
defaultRegistry.register(jsonFormatter);
|
|
25
|
-
defaultRegistry.register(yamlFormatter);
|
|
26
26
|
defaultRegistry.register(tableFormatter);
|
|
27
|
-
defaultRegistry.register(csvFormatter);
|
|
28
27
|
defaultRegistry.register(textFormatter);
|
|
28
|
+
defaultRegistry.register(yamlFormatter);
|
|
29
29
|
registered = true;
|
|
30
30
|
}
|
|
31
31
|
|
package/src/output/dispatch.ts
CHANGED
|
@@ -15,7 +15,7 @@ import type { ColumnSpec, Formatter } from './formatter';
|
|
|
15
15
|
import { parseOptions } from './formatter';
|
|
16
16
|
import { registryFor, resolveCols } from './flags';
|
|
17
17
|
import { renderFormatHelp } from './format_help';
|
|
18
|
-
import { validateCols } from './projection';
|
|
18
|
+
import { resolveEffectiveCols, validateCols } from './projection';
|
|
19
19
|
import { renderTemplate } from './template';
|
|
20
20
|
|
|
21
21
|
/** Sentinel value of --output meaning "write to stdout". */
|
|
@@ -101,8 +101,16 @@ export async function dispatch<T>(
|
|
|
101
101
|
const rows = Array.isArray(data) ? (data as readonly unknown[]) : [data];
|
|
102
102
|
validateCols(rows, options.columns, cols);
|
|
103
103
|
}
|
|
104
|
+
// Resolve column precedence once, here, rather than in each formatter:
|
|
105
|
+
// user --cols wins, else the ColumnSpec list's order, else payload keys.
|
|
106
|
+
const effectiveCols = resolveEffectiveCols(cols, options.columns);
|
|
104
107
|
await Promise.resolve(
|
|
105
|
-
(formatter as Formatter).render(
|
|
108
|
+
(formatter as Formatter).render(
|
|
109
|
+
writer,
|
|
110
|
+
data as never,
|
|
111
|
+
parsedOpts,
|
|
112
|
+
effectiveCols,
|
|
113
|
+
),
|
|
106
114
|
);
|
|
107
115
|
} finally {
|
|
108
116
|
if (close) await close();
|