@cnrai/pave 0.11.108 → 0.11.110

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.
Files changed (98) hide show
  1. package/lib/polyfill-invocation.js +115 -0
  2. package/package.json +5 -2
  3. package/pave.js +14 -2
  4. package/sandbox/SandboxRunner.js +1 -1
  5. package/sandbox/auth/auth.js +1 -0
  6. package/sandbox/auth/broker.js +1 -0
  7. package/sandbox/auth/membership.js +1 -0
  8. package/sandbox/auth/refresh-backoff.js +1 -0
  9. package/sandbox/auth/skill-identity.js +1 -0
  10. package/sandbox/pave-run.js +1 -1
  11. package/sandbox/permission.js +1 -1
  12. package/sandbox/session/claim-ownerless.js +1 -0
  13. package/sandbox/session/owner-repair.js +1 -0
  14. package/sandbox/tools/agent-http.js +1 -0
  15. package/sandbox/tools/cross-session.js +1 -0
  16. package/sandbox/tools/lib/shell-parse.js +1 -0
  17. package/sandbox/tools/self-call-token.js +1 -0
  18. package/sandbox/tools/session-rename.js +1 -0
  19. package/sandbox/tools/session-tools.js +1 -0
  20. package/sandbox/utils/fetch-retry.js +1 -0
  21. package/sandbox/utils/identity.js +1 -0
  22. package/sandbox/utils/internal-token.js +1 -0
  23. package/sandbox/utils/request-source.js +1 -0
  24. package/sandbox/utils/secure-fs.js +1 -0
  25. package/sandbox/utils/sidecar-identity.js +1 -0
  26. package/sandbox/utils/yaml.js +1 -1
  27. package/token-api-polyfill.js +636 -0
  28. package/web/assets/{abnfDiagram-VCTEODGH-C7FOL3-u.js → abnfDiagram-VCTEODGH-Dt5g4zhh.js} +1 -1
  29. package/web/assets/{arc-BRc5A1yw.js → arc-BE9wRRQg.js} +1 -1
  30. package/web/assets/{architectureDiagram-5GKGNRK7-D3BcYg2r.js → architectureDiagram-5GKGNRK7-CWvHq3O3.js} +1 -1
  31. package/web/assets/{blockDiagram-I7D4REHJ-CF_-iaun.js → blockDiagram-I7D4REHJ-uPEvyXY2.js} +1 -1
  32. package/web/assets/{c4Diagram-7LVT6UL2-zhW2gHSL.js → c4Diagram-7LVT6UL2-CQNTOOS_.js} +1 -1
  33. package/web/assets/channel-10VjAYxT.js +1 -0
  34. package/web/assets/{chunk-2Q5K7J3B-DY7QZMMo.js → chunk-2Q5K7J3B-DADJXaGG.js} +1 -1
  35. package/web/assets/{chunk-5VM5RSS4-3I_pofP_.js → chunk-5VM5RSS4-CVR-xFkP.js} +1 -1
  36. package/web/assets/{chunk-F27PBJKO-D5u5N7KW.js → chunk-F27PBJKO-BXi8Uu9v.js} +1 -1
  37. package/web/assets/{chunk-IMKFNOWR-BfbbGVlB.js → chunk-IMKFNOWR-DGQay7wR.js} +1 -1
  38. package/web/assets/{chunk-JWPE2WC7-io3vEm5B.js → chunk-JWPE2WC7-Ci9Rz3ir.js} +1 -1
  39. package/web/assets/{chunk-POPQ4Y6H-Bf6OrRZ9.js → chunk-POPQ4Y6H-B0g_ugRb.js} +1 -1
  40. package/web/assets/{chunk-SVP7TREG-BOXaKiCJ.js → chunk-SVP7TREG-BMiilnNh.js} +1 -1
  41. package/web/assets/{chunk-TICWLB2K-B60vk_SL.js → chunk-TICWLB2K-CvEQ638N.js} +1 -1
  42. package/web/assets/{chunk-XXDRQBXY-DQB-D5Kw.js → chunk-XXDRQBXY-Co7wcMli.js} +1 -1
  43. package/web/assets/classDiagram-ZZMXUADV-Ba-PtJpI.js +1 -0
  44. package/web/assets/classDiagram-v2-VYDZK3BY-Ba-PtJpI.js +1 -0
  45. package/web/assets/{cose-bilkent-JH36ORCC-bfMKYaaU.js → cose-bilkent-JH36ORCC-BYjlBTMd.js} +1 -1
  46. package/web/assets/{cynefin-OW5HDTMX-CzRtRY7-.js → cynefin-OW5HDTMX-DTvHKGJR.js} +1 -1
  47. package/web/assets/{cynefinDiagram-5FMLGOSQ-CUMCB_Zy.js → cynefinDiagram-5FMLGOSQ-BPwjn83q.js} +1 -1
  48. package/web/assets/{dagre-GXQ25YYZ-BvEOwwtY.js → dagre-GXQ25YYZ-BD6vL3FI.js} +1 -1
  49. package/web/assets/{diagram-S7CK7UJ4-DQemhM43.js → diagram-S7CK7UJ4-PcNd7BDe.js} +1 -1
  50. package/web/assets/{diagram-UQ7AKVKN-sc4h0Qsv.js → diagram-UQ7AKVKN-C94KD-RQ.js} +1 -1
  51. package/web/assets/{diagram-VSXAHHWV-BBwa4wEL.js → diagram-VSXAHHWV-xs71MJFo.js} +1 -1
  52. package/web/assets/{diagram-VX7I27RA-UuCdZHOf.js → diagram-VX7I27RA-zmIfQH8n.js} +1 -1
  53. package/web/assets/{diagram-Z3DM3KII-BktpqFre.js → diagram-Z3DM3KII-DcJR_P_I.js} +1 -1
  54. package/web/assets/{ebnfDiagram-PWID7BFC-CacOYoaf.js → ebnfDiagram-PWID7BFC-C_9S0027.js} +1 -1
  55. package/web/assets/{erDiagram-RLTQ6QDP-CmmKnMIP.js → erDiagram-RLTQ6QDP-1aJGBmSr.js} +1 -1
  56. package/web/assets/{flowDiagram-HODETNUW-evvyUXb_.js → flowDiagram-HODETNUW-DpmCinaL.js} +1 -1
  57. package/web/assets/{ganttDiagram-EL5Y4UJY-dWUFeIWw.js → ganttDiagram-EL5Y4UJY-Dl80tYXz.js} +1 -1
  58. package/web/assets/{gitGraphDiagram-WWUBYQGX-By-K_SPc.js → gitGraphDiagram-WWUBYQGX-BNpOlH6C.js} +1 -1
  59. package/web/assets/index-77AXC_0m.js +129 -0
  60. package/web/assets/index-BZHQaMW2.css +10 -0
  61. package/web/assets/{infoDiagram-27XIBGKW-BP3Wh-VS.js → infoDiagram-27XIBGKW-DMcZRgQu.js} +1 -1
  62. package/web/assets/{ishikawaDiagram-5VMMS53U-DGuSWCyR.js → ishikawaDiagram-5VMMS53U-B90yo0EN.js} +1 -1
  63. package/web/assets/{journeyDiagram-3NMN7TZE-DNp0ft2I.js → journeyDiagram-3NMN7TZE-DIHTjBOP.js} +1 -1
  64. package/web/assets/{kanban-definition-UXKFOSKX-CzCZvBfP.js → kanban-definition-UXKFOSKX-COobxa5A.js} +1 -1
  65. package/web/assets/{layout-9WDlxMrA.js → layout-BnbZ4TrL.js} +1 -1
  66. package/web/assets/{linear-CZP__jeZ.js → linear-DtzIt5Oi.js} +1 -1
  67. package/web/assets/{mermaid.core-Cx9gMKa8.js → mermaid.core-8M-OPiHq.js} +5 -5
  68. package/web/assets/{mindmap-definition-YA3MSWOX-BtEk9JE9.js → mindmap-definition-YA3MSWOX-C1sEali1.js} +1 -1
  69. package/web/assets/{pegDiagram-XKGWAZYB-BJP2ukXu.js → pegDiagram-XKGWAZYB-m0-4TMt6.js} +1 -1
  70. package/web/assets/{pieDiagram-E7YTZNPT-Dn4m8Ddk.js → pieDiagram-E7YTZNPT-BKXdbK7S.js} +1 -1
  71. package/web/assets/{quadrantDiagram-AXDQQJYC-DT1B_hW-.js → quadrantDiagram-AXDQQJYC-CDb2_5gt.js} +1 -1
  72. package/web/assets/{railroadDiagram-O6MQD6OU-_onKS9cV.js → railroadDiagram-O6MQD6OU-Cxm7gmfN.js} +1 -1
  73. package/web/assets/{requirementDiagram-BXWQKSXE-nm1t_F4E.js → requirementDiagram-BXWQKSXE-4sjPhIvh.js} +1 -1
  74. package/web/assets/{sankeyDiagram-P5KCCOFB-CVEAGkS-.js → sankeyDiagram-P5KCCOFB-Cw4HGD2A.js} +1 -1
  75. package/web/assets/{sequenceDiagram-WJ2MYXX4-ZfkSEG_C.js → sequenceDiagram-WJ2MYXX4-DP0FDxdo.js} +1 -1
  76. package/web/assets/{sizeCapture-INFHLROL-BHhMi6Lx.js → sizeCapture-INFHLROL-DP9Bxc8A.js} +1 -1
  77. package/web/assets/{stateDiagram-D77RDMKH-BmkZMrir.js → stateDiagram-D77RDMKH-C7QFSmy6.js} +1 -1
  78. package/web/assets/stateDiagram-v2-MP3YSRHH-CIsV3XvU.js +1 -0
  79. package/web/assets/{swimlanes-42K2YHIH-Dl_7Ltat.js → swimlanes-42K2YHIH-DRZ7FdPl.js} +1 -1
  80. package/web/assets/swimlanesDiagram-VR7AAH4N-7-EEFHDh.js +8 -0
  81. package/web/assets/{timeline-definition-24CTP7MA-C7dD_6nn.js → timeline-definition-24CTP7MA-DAvUT8r9.js} +1 -1
  82. package/web/assets/{vennDiagram-4TSXK5OY-D0DPqLIf.js → vennDiagram-4TSXK5OY-CuwdoIA5.js} +1 -1
  83. package/web/assets/{wardleyDiagram-VM6X3IG4-Bq7v6XT1.js → wardleyDiagram-VM6X3IG4-F2h34SNS.js} +1 -1
  84. package/web/assets/{xychartDiagram-S5SC5T6Z-By7o4pD7.js → xychartDiagram-S5SC5T6Z-CjwMWNdN.js} +1 -1
  85. package/web/assets/zh-TW-CQ2QK_nU.js +1 -0
  86. package/web/fonts/OFL.txt +92 -0
  87. package/web/fonts/inter-var-latin.woff2 +0 -0
  88. package/web/index.html +2 -2
  89. package/web/manifest.json +5 -5
  90. package/web/sw.js +13 -4
  91. package/web/assets/channel-B9jLDYtV.js +0 -1
  92. package/web/assets/classDiagram-ZZMXUADV-DEWInF6E.js +0 -1
  93. package/web/assets/classDiagram-v2-VYDZK3BY-DEWInF6E.js +0 -1
  94. package/web/assets/index-B87hi2au.js +0 -130
  95. package/web/assets/index-X3umQNqs.css +0 -10
  96. package/web/assets/stateDiagram-v2-MP3YSRHH-BgI6gtUp.js +0 -1
  97. package/web/assets/swimlanesDiagram-VR7AAH4N-CCIza_Fw.js +0 -8
  98. package/web/assets/zh-TW-CoR3jQfM.js +0 -1
@@ -0,0 +1,636 @@
1
+ /**
2
+ * Token API Polyfill for Non-Sandboxed Skills
3
+ *
4
+ * When skills run without the SpiderMonkey sandbox (PAVE_SANDBOX != 1) this
5
+ * module provides the authenticatedFetch/hasToken/listTokens globals by talking
6
+ * to the PAVE auth proxy — mounted at /proxy/:tokenName/*path on the server,
7
+ * which injects tokens and headers before forwarding to the upstream API.
8
+ *
9
+ * Usage (via node -r preload):
10
+ * node -r token-api-polyfill.js ~/.pave/skills/wrike/index.js query --summary
11
+ *
12
+ * Or programmatically:
13
+ * require('./token-api-polyfill').install();
14
+ * const response = authenticatedFetch('wrike', 'https://www.wrike.com/api/v4/tasks', {});
15
+ *
16
+ * Environment variables:
17
+ * PAVE_PROXY_URL - Base URL of the auth proxy (e.g. http://127.0.0.1:4096/proxy); set by the PAVE server on startup.
18
+ * PAVE_TOKEN_PROXY - Legacy: URL of the separate token-proxy server (fallback if PAVE_PROXY_URL is not set)
19
+ * PAVE_SKILL_IDENTITY - #2641 per-spawn skill identity (see auth/skill-identity.js)
20
+ */
21
+
22
+ const _http = require('http'); // kept for future HTTP proxy support
23
+ const { execFileSync } = require('child_process'); // #1886 hoist (inert builtin)
24
+ const _https = require('https'); // kept for future HTTPS proxy support
25
+ const _urlModule = require('url'); // kept for future URL parsing
26
+ const fs = require('fs'); // #2623 temp-file handoff for oversized bodies
27
+ const os = require('os'); // #2623 temp path
28
+ const path = require('path'); // #2623 temp path
29
+
30
+ // #2623: makes each temp body path unique within a process (two requests in the
31
+ // same millisecond must not collide).
32
+ let _bodyFileCounter = 0;
33
+
34
+ // Resolve the proxy URL from environment
35
+ const PROXY_URL = process.env.PAVE_PROXY_URL || process.env.PAVE_TOKEN_PROXY || '';
36
+
37
+ // Cached token list (fetched once, refreshed on explicit call)
38
+ let _cachedTokens = null;
39
+
40
+ // ─── #2641: per-skill proxy identity ──────────────────────────────────────
41
+ // PAVE_SKILL_IDENTITY is minted per skill spawn (auth/skill-identity.js) as
42
+ // "<base64url({skill,tokens,exp})>.<hmac-sha256-hex>". It is presented as a
43
+ // credential PAIR on every proxy-targeting call at TWO seams: this file's own
44
+ // curl/node invocation (seam 1, in syncHttpRequest) and the child_process wrap
45
+ // (seam 2, below) — the 13 skill sources build their own curl argv and bypass
46
+ // seam 1 entirely. Loopback-proxy targets ONLY: the pair must never travel to a
47
+ // peer that could replay it. With the env var unset nothing here changes.
48
+ const SKILL_IDENTITY = process.env.PAVE_SKILL_IDENTITY || '';
49
+ const PROXY_BASE = PROXY_URL.replace(/\/$/, '');
50
+ // Bracket-strip + dotted-quad match, not a bare startsWith('127.') — that would also admit "127.example.com".
51
+ const LOOPBACK_PROXY = /^https?:\/\/(?:\[::?1\]|localhost(?:\.localdomain)?|127\.\d{1,3}\.\d{1,3}\.\d{1,3})(?::\d{1,5})?(?:\/|$)/i
52
+ .test(PROXY_URL);
53
+
54
+ /** The minted credential pair, or null when there is nothing to present. */
55
+ const IDENTITY_HEADERS = (() => {
56
+ const dot = SKILL_IDENTITY.lastIndexOf('.');
57
+ if (dot <= 0 || !LOOPBACK_PROXY || !PROXY_BASE) return null;
58
+ try {
59
+ const p = JSON.parse(Buffer.from(SKILL_IDENTITY.slice(0, dot), 'base64url').toString('utf8'));
60
+ if (!p.skill || !Array.isArray(p.tokens) || p.tokens.length === 0) return null;
61
+ return {
62
+ 'x-pave-internal-user': 'skill@' + p.skill,
63
+ 'x-pave-internal-token': SKILL_IDENTITY,
64
+ };
65
+ } catch (_) {
66
+ return null; // a malformed identity presents nothing rather than a partial pair
67
+ }
68
+ })();
69
+
70
+ /**
71
+ * The credential pair for one URL, or null when it is not a loopback-proxy call.
72
+ * @param {string} urlStr
73
+ * @returns {object|null}
74
+ */
75
+ function _identityHeaders(urlStr) {
76
+ return IDENTITY_HEADERS && urlStr.indexOf(PROXY_BASE) === 0 ? IDENTITY_HEADERS : null;
77
+ }
78
+
79
+ /**
80
+ * Synchronous HTTP request using child_process.execFileSync with curl, falling
81
+ * back to an inline Node script when curl is absent. Synchronous because skills
82
+ * expect authenticatedFetch to return a result synchronously (sandbox API parity).
83
+ *
84
+ * @param {string} urlStr - Full URL to request
85
+ * @param {object} options - { method, headers, body, timeout }
86
+ * @returns {string} Response body as string
87
+ */
88
+ function syncHttpRequest(urlStr, options) {
89
+ options = options || {};
90
+ const method = options.method || 'GET';
91
+ const headers = { ...options.headers, ..._identityHeaders(urlStr) };
92
+ const body = options.body || null;
93
+ const timeout = options.timeout || 30000;
94
+
95
+ // Execute synchronously WITHOUT a shell (#1628). The old form composed one
96
+ // command string for execSync and quoted arguments with POSIX single quotes;
97
+ // on Windows the shell is cmd.exe, which does not treat ' as quoting at all,
98
+ // so curl received a literal 'http://host:port/path', read 'http as the
99
+ // hostname and failed with "curl: (3) URL rejected". CI never saw it because
100
+ // CI runs Linux, where the quoting was correct. execFileSync takes an argv
101
+ // array and spawns the binary directly — no shell to quote for on any
102
+ // platform, and one less shell-injection surface.
103
+
104
+ // #2623: a body above _BODY_ARGV_LIMIT cannot ride on argv — a single argv
105
+ // entry over Linux MAX_ARG_STRLEN (131,072 B) fails with E2BIG before curl or
106
+ // node ever starts (the same class the issue reports for skill spawns). Write
107
+ // it to a temp file and hand the PATH to the builder instead, so the bytes
108
+ // never reach argv. At/below the limit nothing changes: no temp file, argv
109
+ // byte-identical to before.
110
+ let bodyFile = null;
111
+ if (typeof body === 'string' && body.length > _BODY_ARGV_LIMIT) {
112
+ bodyFile = path.join(os.tmpdir(),
113
+ 'pave-polyfill-body-' + process.pid + '-' + Date.now() + '-' + (++_bodyFileCounter) + '.json');
114
+ fs.writeFileSync(bodyFile, body, { encoding: 'utf8', mode: 0o600 });
115
+ }
116
+
117
+ // Build the invocation for synchronous execution.
118
+ // Fall back to an inline Node script if curl is not available (e.g. iSH).
119
+ const spec = _hasCurl
120
+ ? _buildCurlInvocation(urlStr, method, headers, body, timeout, bodyFile)
121
+ : _buildNodeSyncInvocation(urlStr, method, headers, body, timeout, bodyFile);
122
+
123
+ try {
124
+ const result = execFileSync(spec.file, spec.args, {
125
+ encoding: 'utf8',
126
+ timeout: timeout + 5000, // Add buffer to exec timeout
127
+ maxBuffer: 2 * 1024 * 1024, // 2MB buffer
128
+ stdio: ['pipe', 'pipe', 'pipe'],
129
+ });
130
+ return result;
131
+ } catch (err) {
132
+ // If the HTTP response is an error status (4xx/5xx), curl exits non-zero
133
+ // but may still have useful output in stderr. Try to extract it.
134
+ const stderr = err.stderr ? err.stderr.toString() : '';
135
+ const stdout = err.stdout ? err.stdout.toString() : '';
136
+ if (stdout) {
137
+ return stdout; // curl sometimes puts response body on stdout even on error
138
+ }
139
+ if (stderr) {
140
+ throw new Error('Proxy request failed: ' + stderr.trim());
141
+ }
142
+ throw new Error('Proxy request failed: ' + (err.message || 'unknown error'));
143
+ } finally {
144
+ // #2623: the temp body is ours alone and must not outlive the request —
145
+ // unlink on success AND on throw (the catch above rethrows). Best-effort:
146
+ // a cleanup failure must never mask the request's own result or error.
147
+ if (bodyFile) {
148
+ try {
149
+ fs.unlinkSync(bodyFile);
150
+ } catch (_) { /* best-effort cleanup */ }
151
+ }
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Check if curl is available on this system (cached on first call)
157
+ */
158
+ let _hasCurl = null; // lazy-init
159
+ (function _checkCurl() {
160
+ try {
161
+ // execFileSync, not execSync: no shell involved, same reason as #1628 above.
162
+ execFileSync('curl', ['--version'], { stdio: 'pipe', timeout: 3000 });
163
+ _hasCurl = true;
164
+ } catch (e) {
165
+ _hasCurl = false;
166
+ }
167
+ }());
168
+
169
+ // ─── Seam 2: child_process wrap ───────────────────────────────────────────
170
+ // The 13 skill sources call child_process directly, so the pair has to reach THEIR
171
+ // curl too. The polyfill's own calls use the execFileSync binding destructured at
172
+ // load (still the ORIGINAL — no double splice); #2667 R1b POSIX-escapes header values.
173
+ const _childProcess = require('child_process');
174
+
175
+ // #2623: the two argv builders moved to a pure module — the request path (the
176
+ // execFileSync call and the temp-file handoff) stays in this file. The relative
177
+ // require sits after the builtin ones (import/order); nothing calls a builder
178
+ // during module load, so the late destructure is safe.
179
+ const {
180
+ _BODY_ARGV_LIMIT,
181
+ _buildCurlInvocation,
182
+ _buildNodeSyncInvocation,
183
+ } = require('./lib/polyfill-invocation.js');
184
+
185
+ const _IDENTITY_ARGS = IDENTITY_HEADERS
186
+ ? Object.entries(IDENTITY_HEADERS).flatMap(([k, v]) => ['-H', `${k}: ${v}`])
187
+ : null;
188
+ // #2672 seam-2 platform split: cmd.exe treats ' as a literal, so a POSIX-quoted
189
+ // header reaches the skill's own curl mangled (proxy 401). The charset gate
190
+ // DECLINES an identity that would need more than bare-shell-word escaping.
191
+ // PAVE_POLYFILL_PLATFORM_SIM overrides the splice decision in tests ONLY.
192
+ const _SPLICE_PLATFORM = process.env.PAVE_POLYFILL_PLATFORM_SIM || process.platform;
193
+ const _SPLICE_CHARSET_OK = /^[-A-Za-z0-9_.:@]+$/;
194
+
195
+ /** Splice for one shell. null DECLINES: the caller's command passes through byte-identical. */
196
+ function _buildIdentitySplice(platform, headers) {
197
+ const entries = Object.entries(headers);
198
+ for (const [k, v] of entries) if (!_SPLICE_CHARSET_OK.test(k) || !_SPLICE_CHARSET_OK.test(v)) return null;
199
+ if (platform !== 'win32') {
200
+ return entries.flatMap(([k, v]) => ['-H', `${k}: ${v}`])
201
+ .map((a) => (a === '-H' ? a : `'${a.replace(/'/g, "'\\''")}'`)).join(' ');
202
+ }
203
+ return entries.map(([k, v]) => `-H "${k}: ${v}"`).join(' ');
204
+ }
205
+
206
+ const _IDENTITY_STRING = IDENTITY_HEADERS ? _buildIdentitySplice(_SPLICE_PLATFORM, IDENTITY_HEADERS) : null;
207
+ if (IDENTITY_HEADERS && !_IDENTITY_STRING) {
208
+ console.error('[TOKEN-POLYFILL] identity value not shell-safe; splice declined (see #2672)');
209
+ }
210
+
211
+ const _origExecSync = _childProcess.execSync;
212
+ const _origExecFileSync = _childProcess.execFileSync;
213
+
214
+ function _isProxyCall(text) {
215
+ return !!_IDENTITY_ARGS && !!PROXY_BASE && text.indexOf(PROXY_BASE) !== -1;
216
+ }
217
+
218
+ _childProcess.execSync = function (command, options) {
219
+ // Function replacer, not a string: a literal '$' in the token would be read
220
+ // as a replacement pattern. Each header stays one shell word either way.
221
+ // #2672 B1b: the replacer re-emits the captured delimiter — without it the
222
+ // match consumes the separator before `curl` ("echo curl X" -> "echocurl X").
223
+ // D5: the splice is gated on _IDENTITY_STRING, so a DECLINED identity leaves
224
+ // the command byte-identical (never "curl null"); argv form stays unaffected.
225
+ const cmd = typeof command === 'string' && _IDENTITY_STRING && _isProxyCall(command)
226
+ ? command.replace(/(^|[;&|(\s])curl(?=\s)/, (m, d) => `${d}curl ${_IDENTITY_STRING}`)
227
+ : command;
228
+ try { return _origExecSync.call(this, cmd, options); }
229
+ catch (err) { // #2667 R2: scrub the token from "Command failed: <cmd>" before rethrow
230
+ if (SKILL_IDENTITY) err.message = err.message.split(SKILL_IDENTITY).join('[identity]');
231
+ throw err;
232
+ }
233
+ };
234
+
235
+ _childProcess.execFileSync = function (file, args, options) {
236
+ const argv = file === 'curl' && Array.isArray(args) && _isProxyCall(args.join(' '))
237
+ ? _IDENTITY_ARGS.concat(args)
238
+ : args;
239
+ return _origExecFileSync.call(this, file, argv, options);
240
+ };
241
+
242
+ /**
243
+ * List available token names.
244
+ * Calls the auth proxy's GET /proxy/_tokens endpoint.
245
+ *
246
+ * @returns {string[]} Array of token names
247
+ */
248
+ function listTokens() {
249
+ if (_cachedTokens !== null) {
250
+ return _cachedTokens;
251
+ }
252
+
253
+ if (!PROXY_URL) {
254
+ return [];
255
+ }
256
+
257
+ try {
258
+ const tokensUrl = PROXY_URL.replace(/\/$/, '') + '/_tokens';
259
+ const body = syncHttpRequest(tokensUrl, {
260
+ method: 'GET',
261
+ timeout: 5000,
262
+ });
263
+
264
+ const data = JSON.parse(body);
265
+ _cachedTokens = data.tokens || [];
266
+ return _cachedTokens;
267
+ } catch (err) {
268
+ console.error('[TOKEN-POLYFILL] Failed to fetch tokens:', err.message);
269
+ return [];
270
+ }
271
+ }
272
+
273
+ /**
274
+ * Check if a token is available.
275
+ *
276
+ * @param {string} tokenName - Name of the token to check
277
+ * @returns {boolean} True if token exists
278
+ */
279
+ function hasToken(tokenName) {
280
+ const tokens = listTokens();
281
+ return tokens.indexOf(tokenName) !== -1;
282
+ }
283
+
284
+ /**
285
+ * Make an authenticated fetch request using a named token. Token injection is
286
+ * handled by the auth proxy — tokens are never visible to this code or the
287
+ * skill scripts.
288
+ *
289
+ * Auth proxy path convention: authenticatedFetch('wrike', 'https://www.wrike.com
290
+ * /api/v4/tasks', opts) → GET /proxy/wrike/api/v4/tasks?_mode=json. The proxy
291
+ * reconstructs the upstream URL from the token's baseUrl, injects the auth
292
+ * headers, and returns { ok, status, headers, body } — _mode=json is what makes
293
+ * the HTTP status readable by synchronous parsing.
294
+ *
295
+ * @param {string} tokenName - Name of the token (e.g., 'wrike', 'gmail')
296
+ * @param {string} url - Upstream URL to fetch (must match token's allowed domains)
297
+ * @param {object} [options] - { method, headers, body, timeout, saveTo }.
298
+ * saveTo writes the response to that file (binary-safe, avoids UTF-8
299
+ * corruption) and returns { savedTo, size } instead of a body.
300
+ * @returns {object} Response-like object with ok, status, headers, text(), json()
301
+ */
302
+ function authenticatedFetch(tokenName, url, options) {
303
+ if (!tokenName || typeof tokenName !== 'string') {
304
+ throw new Error('authenticatedFetch: tokenName is required');
305
+ }
306
+ if (!url || typeof url !== 'string') {
307
+ throw new Error('authenticatedFetch: url is required');
308
+ }
309
+
310
+ if (!PROXY_URL) {
311
+ throw new Error(
312
+ 'authenticatedFetch: No proxy configured. ' +
313
+ 'Ensure the PAVE server is running (sets PAVE_PROXY_URL) or enable sandbox (PAVE_SANDBOX=1).',
314
+ );
315
+ }
316
+
317
+ options = options || {};
318
+
319
+ // Build the proxy URL from the upstream URL
320
+ const isAuthProxy = PROXY_URL.indexOf('/proxy') !== -1;
321
+ let proxyUrl;
322
+
323
+ if (isAuthProxy) {
324
+ // New auth-proxy mode: rewrite upstream URL to proxy path
325
+ // Extract the path+query from the upstream URL
326
+ let upstreamPath;
327
+ try {
328
+ const parsed = new URL(url);
329
+ upstreamPath = parsed.pathname + parsed.search;
330
+ } catch (e) {
331
+ throw new Error('authenticatedFetch: Invalid URL: ' + url);
332
+ }
333
+
334
+ const proxyBase = PROXY_URL.replace(/\/$/, '');
335
+ // Build: /proxy/:tokenName/path?_mode=json&_saveTo=<path>
336
+ proxyUrl = proxyBase + '/' + encodeURIComponent(tokenName) + upstreamPath;
337
+
338
+ // Add query parameters for the auth proxy
339
+ const queryParts = [];
340
+
341
+ // saveTo: binary-safe file download — proxy writes response to file
342
+ // instead of returning body as text (prevents UTF-8 corruption)
343
+ if (options.saveTo) {
344
+ queryParts.push('_saveTo=' + encodeURIComponent(options.saveTo));
345
+ }
346
+
347
+ // Always use _mode=json so the proxy returns { ok, status, headers, body }
348
+ // This is essential for synchronous parsing — we need the HTTP status code
349
+ // in the response body (not just as an HTTP status that curl treats as exit code).
350
+ // When saveTo is used, the proxy returns { ok, status, savedTo, size } instead.
351
+ queryParts.push('_mode=json');
352
+
353
+ const sep = proxyUrl.indexOf('?') !== -1 ? '&' : '?';
354
+ proxyUrl += sep + queryParts.join('&');
355
+ } else {
356
+ // Legacy token-proxy mode: POST to /fetch with JSON body
357
+ proxyUrl = PROXY_URL.replace(/\/$/, '') + '/fetch';
358
+ }
359
+
360
+ // Build request headers
361
+ const reqHeaders = {};
362
+ if (options.headers) {
363
+ const headerKeys = Object.keys(options.headers);
364
+ for (let i = 0; i < headerKeys.length; i++) {
365
+ reqHeaders[headerKeys[i]] = options.headers[headerKeys[i]];
366
+ }
367
+ }
368
+
369
+ // Prepare request body
370
+ let reqBody = null;
371
+ if (options.body) {
372
+ reqBody = typeof options.body === 'string' ? options.body : JSON.stringify(options.body);
373
+ if (!reqHeaders['Content-Type']) {
374
+ reqHeaders['Content-Type'] = 'application/json';
375
+ }
376
+ }
377
+
378
+ // For legacy token-proxy mode, send token metadata in the body
379
+ if (!isAuthProxy) {
380
+ reqBody = JSON.stringify({
381
+ tokenName,
382
+ url,
383
+ method: options.method || 'GET',
384
+ headers: options.headers || {},
385
+ body: options.body || null,
386
+ timeout: options.timeout || 30000,
387
+ });
388
+ reqHeaders['Content-Type'] = 'application/json';
389
+ }
390
+
391
+ // Execute the request
392
+ const responseBody = syncHttpRequest(proxyUrl, {
393
+ method: isAuthProxy ? (options.method || 'GET') : 'POST',
394
+ headers: reqHeaders,
395
+ body: reqBody,
396
+ timeout: (options.timeout || 30000) + 5000, // Add buffer
397
+ });
398
+
399
+ // Parse the response
400
+ if (isAuthProxy) {
401
+ // Auth-proxy with _mode=json returns: { ok, status, headers, body }
402
+ try {
403
+ const result = JSON.parse(responseBody);
404
+ if (result.error) {
405
+ throw new Error(result.error);
406
+ }
407
+ // Handle saveTo response: proxy returns { ok, status, savedTo, size }
408
+ if (result.savedTo) {
409
+ return {
410
+ ok: result.ok || false,
411
+ status: result.status || 200,
412
+ statusText: (result.status || 200) >= 200 && (result.status || 200) < 300 ? 'OK' : 'Error',
413
+ savedTo: result.savedTo,
414
+ headers: { get() { return null; } },
415
+ text() { return ''; }, // Body was saved to file, not returned
416
+ json() { return {}; },
417
+ };
418
+ }
419
+ // #1316: binary bodies arrive base64-encoded with bodyBase64 set (the
420
+ // proxy can't return non-UTF-8 bytes in a JSON string). Decode once so
421
+ // text()/json()/arrayBuffer() stay lossless. TextDecoder (global since
422
+ // Node 11) matches fetch .text() semantics: it strips a leading UTF-8
423
+ // BOM, unlike Buffer.toString('utf8').
424
+ const bodyBuffer = result.bodyBase64
425
+ ? Buffer.from(result.body || '', 'base64')
426
+ : null;
427
+ const bodyAsText = bodyBuffer
428
+ ? () => new TextDecoder('utf-8').decode(bodyBuffer)
429
+ : null;
430
+ return {
431
+ ok: result.ok || false,
432
+ status: result.status || 200,
433
+ statusText: (result.status || 200) >= 200 && (result.status || 200) < 300 ? 'OK' : 'Error',
434
+ headers: {
435
+ get(name) {
436
+ const headers = result.headers || {};
437
+ const lowerName = name.toLowerCase();
438
+ const keys = Object.keys(headers);
439
+ for (let i = 0; i < keys.length; i++) {
440
+ if (keys[i].toLowerCase() === lowerName) {
441
+ return Array.isArray(headers[keys[i]]) ? headers[keys[i]][0] : headers[keys[i]];
442
+ }
443
+ }
444
+ return null;
445
+ },
446
+ },
447
+ text() { return bodyAsText ? bodyAsText() : (result.body || ''); },
448
+ json() { return JSON.parse(bodyAsText ? bodyAsText() : (result.body || '{}')); },
449
+ // Binary access (#1316, fetch-like but synchronous to match text/json):
450
+ // returns the exact upstream bytes as an ArrayBuffer.
451
+ arrayBuffer() {
452
+ const buf = bodyBuffer || Buffer.from(result.body || '', 'utf8');
453
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
454
+ },
455
+ };
456
+ } catch (parseErr) {
457
+ if (parseErr.message && parseErr.message.indexOf('authenticatedFetch') !== -1) {
458
+ throw parseErr; // Re-throw our own errors
459
+ }
460
+ // If JSON parsing fails, return raw body with assumed-OK status
461
+ return {
462
+ ok: true,
463
+ status: 200,
464
+ statusText: 'OK',
465
+ headers: { get() { return null; } },
466
+ text() { return responseBody; },
467
+ json() { return JSON.parse(responseBody || '{}'); },
468
+ // #1316: same binary accessor as the main response object.
469
+ arrayBuffer() {
470
+ const buf = Buffer.from(responseBody || '', 'utf8');
471
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
472
+ },
473
+ };
474
+ }
475
+ } else {
476
+ // Legacy token-proxy mode: response is JSON with status/body
477
+ try {
478
+ const legacyResult = JSON.parse(responseBody);
479
+ if (legacyResult.error) {
480
+ throw new Error(legacyResult.error);
481
+ }
482
+ return {
483
+ ok: legacyResult.ok || false,
484
+ status: legacyResult.status || 200,
485
+ statusText: (legacyResult.status || 200) >= 200 && (legacyResult.status || 200) < 300 ? 'OK' : 'Error',
486
+ headers: {
487
+ get(name) {
488
+ const headers = legacyResult.headers || {};
489
+ const lowerName = name.toLowerCase();
490
+ const keys = Object.keys(headers);
491
+ for (let i = 0; i < keys.length; i++) {
492
+ if (keys[i].toLowerCase() === lowerName) {
493
+ return Array.isArray(headers[keys[i]]) ? headers[keys[i]][0] : headers[keys[i]];
494
+ }
495
+ }
496
+ return null;
497
+ },
498
+ },
499
+ text() { return legacyResult.body || ''; },
500
+ json() { return JSON.parse(legacyResult.body || '{}'); },
501
+ };
502
+ } catch (legacyParseErr) {
503
+ return {
504
+ ok: true,
505
+ status: 200,
506
+ statusText: 'OK',
507
+ headers: { get() { return null; } },
508
+ text() { return responseBody; },
509
+ json() { return JSON.parse(responseBody || '{}'); },
510
+ };
511
+ }
512
+ }
513
+ }
514
+
515
+ // ── btoa / atob polyfill (Node 16 / iSH compatibility) ──────────
516
+ // Node <18 does not provide global btoa/atob. The SpiderMonkey
517
+ // sandbox exposes them, so the polyfill must too.
518
+
519
+ /**
520
+ * btoa: binary string → base64 (browser-compatible).
521
+ * @param {string} str - Latin1 binary string
522
+ * @returns {string} Base64-encoded string
523
+ */
524
+ function btoa(str) {
525
+ if (typeof global.btoa === 'function' && global.btoa !== btoa) {
526
+ return global.btoa(str); // use native if available
527
+ }
528
+ str = String(str);
529
+ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
530
+ let result = '';
531
+ for (let i = 0; i < str.length; i += 3) {
532
+ const a = str.charCodeAt(i);
533
+ if (a > 255) throw new Error('The string to be encoded contains characters outside of the Latin1 range.');
534
+ const b = i + 1 < str.length ? str.charCodeAt(i + 1) : 0;
535
+ if (b > 255) throw new Error('The string to be encoded contains characters outside of the Latin1 range.');
536
+ const c = i + 2 < str.length ? str.charCodeAt(i + 2) : 0;
537
+ if (c > 255) throw new Error('The string to be encoded contains characters outside of the Latin1 range.');
538
+ result += chars[a >> 2];
539
+ result += chars[((a & 3) << 4) | (b >> 4)];
540
+ result += i + 1 < str.length ? chars[((b & 15) << 2) | (c >> 6)] : '=';
541
+ result += i + 2 < str.length ? chars[c & 63] : '=';
542
+ }
543
+ return result;
544
+ }
545
+
546
+ /**
547
+ * atob: base64 → binary string (browser-compatible).
548
+ * @param {string} str - Base64-encoded string
549
+ * @returns {string} Decoded binary string
550
+ */
551
+ function atob(str) {
552
+ if (typeof global.atob === 'function' && global.atob !== atob) {
553
+ return global.atob(str); // use native if available
554
+ }
555
+ str = String(str);
556
+ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
557
+ str = str.replace(/[ \t\r\n\f\v]/g, '');
558
+ for (let v = 0; v < str.length; v++) {
559
+ if (chars.indexOf(str[v]) === -1) throw new Error('The string to be decoded is not correctly encoded.');
560
+ }
561
+ let padding = 0;
562
+ if (str.endsWith('==')) {
563
+ padding = 2;
564
+ } else if (str.endsWith('=')) {
565
+ padding = 1;
566
+ }
567
+ if (padding > 0 && str.length % 4 !== 0) {
568
+ throw new Error('The string to be decoded is not correctly encoded.');
569
+ }
570
+ if (padding > 0 && str.slice(0, -padding).indexOf('=') !== -1) {
571
+ throw new Error('The string to be decoded is not correctly encoded.');
572
+ }
573
+ if (padding === 0 && str.indexOf('=') !== -1) {
574
+ throw new Error('The string to be decoded is not correctly encoded.');
575
+ }
576
+ const remainder = str.length % 4;
577
+ if (remainder === 1) throw new Error('The string to be decoded is not correctly encoded.');
578
+ if (padding === 0 && remainder > 0) {
579
+ str += remainder === 2 ? '==' : '=';
580
+ padding = remainder === 2 ? 2 : 1;
581
+ }
582
+ const clean = padding > 0 ? str.slice(0, -padding) : str;
583
+ let result = '';
584
+ for (let i = 0; i < clean.length; i += 4) {
585
+ const a = chars.indexOf(clean[i]);
586
+ const b = i + 1 < clean.length ? chars.indexOf(clean[i + 1]) : 0;
587
+ const c = i + 2 < clean.length ? chars.indexOf(clean[i + 2]) : 0;
588
+ const d = i + 3 < clean.length ? chars.indexOf(clean[i + 3]) : 0;
589
+ result += String.fromCharCode((a << 2) | (b >> 4));
590
+ if (i + 2 < clean.length) result += String.fromCharCode(((b & 15) << 4) | (c >> 2));
591
+ if (i + 3 < clean.length) result += String.fromCharCode(((c & 3) << 6) | d);
592
+ }
593
+ return result;
594
+ }
595
+
596
+ /**
597
+ * Install the polyfill globally.
598
+ * Makes authenticatedFetch, hasToken, listTokens, btoa, atob available as globals.
599
+ */
600
+ function install() {
601
+ global.authenticatedFetch = authenticatedFetch;
602
+ global.hasToken = hasToken;
603
+ global.listTokens = listTokens;
604
+ // btoa/atob: only install our polyfill version if native is absent
605
+ if (typeof global.btoa !== 'function') global.btoa = btoa;
606
+ if (typeof global.atob !== 'function') global.atob = atob;
607
+ }
608
+
609
+ /**
610
+ * Check if polyfill should be used.
611
+ * Returns true when sandbox is disabled (PAVE_SANDBOX != 1/true).
612
+ */
613
+ function shouldUsePolyfill() {
614
+ const sandbox = process.env.PAVE_SANDBOX;
615
+ return sandbox !== '1' && sandbox !== 'true';
616
+ }
617
+
618
+ // Auto-install when loaded via node -r (preload)
619
+ // This makes authenticatedFetch/hasToken/listTokens available globally for skills
620
+ if (shouldUsePolyfill()) {
621
+ install();
622
+ }
623
+
624
+ module.exports = {
625
+ install,
626
+ shouldUsePolyfill,
627
+ authenticatedFetch,
628
+ hasToken,
629
+ listTokens,
630
+ btoa,
631
+ atob,
632
+ // #2623: re-exported for tests — the builders moved to lib/polyfill-invocation.js.
633
+ _BODY_ARGV_LIMIT,
634
+ _buildCurlInvocation,
635
+ _buildNodeSyncInvocation,
636
+ };
@@ -1 +1 @@
1
- import{g as p,r as u,d as a}from"./chunk-SVP7TREG-BOXaKiCJ.js";import{p as f}from"./chunk-JWPE2WC7-io3vEm5B.js";import{_ as n,l as o}from"./mermaid.core-Cx9gMKa8.js";import{M as c,b as d}from"./cynefin-OW5HDTMX-CzRtRY7-.js";import"./index-B87hi2au.js";var v=d().RailroadAbnf.parser.LangiumParser,i=n(e=>{const r=e.alternatives.map(g);return r.length===1?r[0]:{type:"choice",alternatives:r}},"transformAlternation"),g=n(e=>{const r=e.elements.map(y);return r.length===1?r[0]:{type:"sequence",elements:r}},"transformConcatenation"),b=n(e=>{if(e.includes("*")){const[t,s]=e.split("*"),l=t?parseInt(t,10):0,m=s?parseInt(s,10):1/0;return{min:l,max:m}}const r=parseInt(e,10);return{min:r,max:r}},"parseRepeat"),y=n(e=>{const r=A(e.primary);if(!e.repeat)return r;const{min:t,max:s}=b(e.repeat);return t===0&&s===1?{type:"optional",element:r}:{type:"repetition",element:r,min:t,max:s}},"transformElement"),A=n(e=>{switch(e.$type){case"AbnfStringLiteral":return{type:"terminal",value:e.value};case"AbnfNumVal":return{type:"terminal",value:e.value};case"AbnfRuleName":return{type:"nonterminal",name:e.name};case"AbnfGroup":return i(e.element);case"AbnfOptionalGroup":return{type:"optional",element:i(e.element)};default:throw new Error(`Unsupported ABNF primary node: ${e.$type}`)}},"transformPrimary"),P=n(e=>({name:e.name,definition:i(e.definition)}),"transformRule"),h=n(e=>{f(e,a),e.title&&a.setTitle(e.title),e.rules.map(r=>a.addRule(P(r)))},"populateDb"),R={parse:n(e=>{a.clear(),o.debug("[ABNF Parser] Starting Langium parse");const r=v.parse(e);if(r.lexerErrors.length>0||r.parserErrors.length>0)throw new c(r);const t=r.value;o.debug("[ABNF Parser] Parsed rules:",t.rules.length),h(t),o.debug("[ABNF Parser] Parse complete")},"parse"),parser:{yy:a}},B={parser:R,db:a,renderer:u,styles:p};export{B as diagram};
1
+ import{g as p,r as u,d as a}from"./chunk-SVP7TREG-BMiilnNh.js";import{p as f}from"./chunk-JWPE2WC7-Ci9Rz3ir.js";import{_ as n,l as o}from"./mermaid.core-8M-OPiHq.js";import{M as c,b as d}from"./cynefin-OW5HDTMX-DTvHKGJR.js";import"./index-77AXC_0m.js";var v=d().RailroadAbnf.parser.LangiumParser,i=n(e=>{const r=e.alternatives.map(g);return r.length===1?r[0]:{type:"choice",alternatives:r}},"transformAlternation"),g=n(e=>{const r=e.elements.map(y);return r.length===1?r[0]:{type:"sequence",elements:r}},"transformConcatenation"),b=n(e=>{if(e.includes("*")){const[t,s]=e.split("*"),l=t?parseInt(t,10):0,m=s?parseInt(s,10):1/0;return{min:l,max:m}}const r=parseInt(e,10);return{min:r,max:r}},"parseRepeat"),y=n(e=>{const r=A(e.primary);if(!e.repeat)return r;const{min:t,max:s}=b(e.repeat);return t===0&&s===1?{type:"optional",element:r}:{type:"repetition",element:r,min:t,max:s}},"transformElement"),A=n(e=>{switch(e.$type){case"AbnfStringLiteral":return{type:"terminal",value:e.value};case"AbnfNumVal":return{type:"terminal",value:e.value};case"AbnfRuleName":return{type:"nonterminal",name:e.name};case"AbnfGroup":return i(e.element);case"AbnfOptionalGroup":return{type:"optional",element:i(e.element)};default:throw new Error(`Unsupported ABNF primary node: ${e.$type}`)}},"transformPrimary"),P=n(e=>({name:e.name,definition:i(e.definition)}),"transformRule"),h=n(e=>{f(e,a),e.title&&a.setTitle(e.title),e.rules.map(r=>a.addRule(P(r)))},"populateDb"),R={parse:n(e=>{a.clear(),o.debug("[ABNF Parser] Starting Langium parse");const r=v.parse(e);if(r.lexerErrors.length>0||r.parserErrors.length>0)throw new c(r);const t=r.value;o.debug("[ABNF Parser] Parsed rules:",t.rules.length),h(t),o.debug("[ABNF Parser] Parse complete")},"parse"),parser:{yy:a}},B={parser:R,db:a,renderer:u,styles:p};export{B as diagram};
@@ -1 +1 @@
1
- import{$ as ln,a0 as an,a1 as y,a2 as tn,a3 as G,a4 as q,a5 as _,a6 as un,a7 as rn,a8 as K,a9 as o,aa as z,ab as sn,ac as on,ad as fn}from"./mermaid.core-Cx9gMKa8.js";function cn(l){return l.innerRadius}function yn(l){return l.outerRadius}function gn(l){return l.startAngle}function dn(l){return l.endAngle}function mn(l){return l&&l.padAngle}function pn(l,h,I,D,v,A,B,a){var O=I-l,i=D-h,n=B-v,d=a-A,u=d*O-n*i;if(!(u*u<y))return u=(n*(h-A)-d*(l-v))/u,[l+u*O,h+u*i]}function V(l,h,I,D,v,A,B){var a=l-I,O=h-D,i=(B?A:-A)/K(a*a+O*O),n=i*O,d=-i*a,u=l+n,s=h+d,f=I+n,c=D+d,C=(u+f)/2,t=(s+c)/2,m=f-u,g=c-s,R=m*m+g*g,T=v-A,P=u*c-f*s,S=(g<0?-1:1)*K(fn(0,T*T*R-P*P)),$=(P*g-m*S)/R,j=(-P*m-g*S)/R,w=(P*g+m*S)/R,p=(-P*m+g*S)/R,x=$-C,e=j-t,r=w-C,F=p-t;return x*x+e*e>r*r+F*F&&($=w,j=p),{cx:$,cy:j,x01:-n,y01:-d,x11:$*(v/T-1),y11:j*(v/T-1)}}function hn(){var l=cn,h=yn,I=z(0),D=null,v=gn,A=dn,B=mn,a=null,O=ln(i);function i(){var n,d,u=+l.apply(this,arguments),s=+h.apply(this,arguments),f=v.apply(this,arguments)-an,c=A.apply(this,arguments)-an,C=un(c-f),t=c>f;if(a||(a=n=O()),s<u&&(d=s,s=u,u=d),!(s>y))a.moveTo(0,0);else if(C>tn-y)a.moveTo(s*G(f),s*q(f)),a.arc(0,0,s,f,c,!t),u>y&&(a.moveTo(u*G(c),u*q(c)),a.arc(0,0,u,c,f,t));else{var m=f,g=c,R=f,T=c,P=C,S=C,$=B.apply(this,arguments)/2,j=$>y&&(D?+D.apply(this,arguments):K(u*u+s*s)),w=_(un(s-u)/2,+I.apply(this,arguments)),p=w,x=w,e,r;if(j>y){var F=sn(j/u*q($)),L=sn(j/s*q($));(P-=F*2)>y?(F*=t?1:-1,R+=F,T-=F):(P=0,R=T=(f+c)/2),(S-=L*2)>y?(L*=t?1:-1,m+=L,g-=L):(S=0,m=g=(f+c)/2)}var H=s*G(m),J=s*q(m),M=u*G(T),N=u*q(T);if(w>y){var Q=s*G(g),U=s*q(g),W=u*G(R),X=u*q(R),E;if(C<rn)if(E=pn(H,J,W,X,Q,U,M,N)){var Y=H-E[0],Z=J-E[1],b=Q-E[0],k=U-E[1],nn=1/q(on((Y*b+Z*k)/(K(Y*Y+Z*Z)*K(b*b+k*k)))/2),en=K(E[0]*E[0]+E[1]*E[1]);p=_(w,(u-en)/(nn-1)),x=_(w,(s-en)/(nn+1))}else p=x=0}S>y?x>y?(e=V(W,X,H,J,s,x,t),r=V(Q,U,M,N,s,x,t),a.moveTo(e.cx+e.x01,e.cy+e.y01),x<w?a.arc(e.cx,e.cy,x,o(e.y01,e.x01),o(r.y01,r.x01),!t):(a.arc(e.cx,e.cy,x,o(e.y01,e.x01),o(e.y11,e.x11),!t),a.arc(0,0,s,o(e.cy+e.y11,e.cx+e.x11),o(r.cy+r.y11,r.cx+r.x11),!t),a.arc(r.cx,r.cy,x,o(r.y11,r.x11),o(r.y01,r.x01),!t))):(a.moveTo(H,J),a.arc(0,0,s,m,g,!t)):a.moveTo(H,J),!(u>y)||!(P>y)?a.lineTo(M,N):p>y?(e=V(M,N,Q,U,u,-p,t),r=V(H,J,W,X,u,-p,t),a.lineTo(e.cx+e.x01,e.cy+e.y01),p<w?a.arc(e.cx,e.cy,p,o(e.y01,e.x01),o(r.y01,r.x01),!t):(a.arc(e.cx,e.cy,p,o(e.y01,e.x01),o(e.y11,e.x11),!t),a.arc(0,0,u,o(e.cy+e.y11,e.cx+e.x11),o(r.cy+r.y11,r.cx+r.x11),t),a.arc(r.cx,r.cy,p,o(r.y11,r.x11),o(r.y01,r.x01),!t))):a.arc(0,0,u,T,R,t)}if(a.closePath(),n)return a=null,n+""||null}return i.centroid=function(){var n=(+l.apply(this,arguments)+ +h.apply(this,arguments))/2,d=(+v.apply(this,arguments)+ +A.apply(this,arguments))/2-rn/2;return[G(d)*n,q(d)*n]},i.innerRadius=function(n){return arguments.length?(l=typeof n=="function"?n:z(+n),i):l},i.outerRadius=function(n){return arguments.length?(h=typeof n=="function"?n:z(+n),i):h},i.cornerRadius=function(n){return arguments.length?(I=typeof n=="function"?n:z(+n),i):I},i.padRadius=function(n){return arguments.length?(D=n==null?null:typeof n=="function"?n:z(+n),i):D},i.startAngle=function(n){return arguments.length?(v=typeof n=="function"?n:z(+n),i):v},i.endAngle=function(n){return arguments.length?(A=typeof n=="function"?n:z(+n),i):A},i.padAngle=function(n){return arguments.length?(B=typeof n=="function"?n:z(+n),i):B},i.context=function(n){return arguments.length?(a=n??null,i):a},i}export{hn as d};
1
+ import{$ as ln,a0 as an,a1 as y,a2 as tn,a3 as G,a4 as q,a5 as _,a6 as un,a7 as rn,a8 as K,a9 as o,aa as z,ab as sn,ac as on,ad as fn}from"./mermaid.core-8M-OPiHq.js";function cn(l){return l.innerRadius}function yn(l){return l.outerRadius}function gn(l){return l.startAngle}function dn(l){return l.endAngle}function mn(l){return l&&l.padAngle}function pn(l,h,I,D,v,A,B,a){var O=I-l,i=D-h,n=B-v,d=a-A,u=d*O-n*i;if(!(u*u<y))return u=(n*(h-A)-d*(l-v))/u,[l+u*O,h+u*i]}function V(l,h,I,D,v,A,B){var a=l-I,O=h-D,i=(B?A:-A)/K(a*a+O*O),n=i*O,d=-i*a,u=l+n,s=h+d,f=I+n,c=D+d,C=(u+f)/2,t=(s+c)/2,m=f-u,g=c-s,R=m*m+g*g,T=v-A,P=u*c-f*s,S=(g<0?-1:1)*K(fn(0,T*T*R-P*P)),$=(P*g-m*S)/R,j=(-P*m-g*S)/R,w=(P*g+m*S)/R,p=(-P*m+g*S)/R,x=$-C,e=j-t,r=w-C,F=p-t;return x*x+e*e>r*r+F*F&&($=w,j=p),{cx:$,cy:j,x01:-n,y01:-d,x11:$*(v/T-1),y11:j*(v/T-1)}}function hn(){var l=cn,h=yn,I=z(0),D=null,v=gn,A=dn,B=mn,a=null,O=ln(i);function i(){var n,d,u=+l.apply(this,arguments),s=+h.apply(this,arguments),f=v.apply(this,arguments)-an,c=A.apply(this,arguments)-an,C=un(c-f),t=c>f;if(a||(a=n=O()),s<u&&(d=s,s=u,u=d),!(s>y))a.moveTo(0,0);else if(C>tn-y)a.moveTo(s*G(f),s*q(f)),a.arc(0,0,s,f,c,!t),u>y&&(a.moveTo(u*G(c),u*q(c)),a.arc(0,0,u,c,f,t));else{var m=f,g=c,R=f,T=c,P=C,S=C,$=B.apply(this,arguments)/2,j=$>y&&(D?+D.apply(this,arguments):K(u*u+s*s)),w=_(un(s-u)/2,+I.apply(this,arguments)),p=w,x=w,e,r;if(j>y){var F=sn(j/u*q($)),L=sn(j/s*q($));(P-=F*2)>y?(F*=t?1:-1,R+=F,T-=F):(P=0,R=T=(f+c)/2),(S-=L*2)>y?(L*=t?1:-1,m+=L,g-=L):(S=0,m=g=(f+c)/2)}var H=s*G(m),J=s*q(m),M=u*G(T),N=u*q(T);if(w>y){var Q=s*G(g),U=s*q(g),W=u*G(R),X=u*q(R),E;if(C<rn)if(E=pn(H,J,W,X,Q,U,M,N)){var Y=H-E[0],Z=J-E[1],b=Q-E[0],k=U-E[1],nn=1/q(on((Y*b+Z*k)/(K(Y*Y+Z*Z)*K(b*b+k*k)))/2),en=K(E[0]*E[0]+E[1]*E[1]);p=_(w,(u-en)/(nn-1)),x=_(w,(s-en)/(nn+1))}else p=x=0}S>y?x>y?(e=V(W,X,H,J,s,x,t),r=V(Q,U,M,N,s,x,t),a.moveTo(e.cx+e.x01,e.cy+e.y01),x<w?a.arc(e.cx,e.cy,x,o(e.y01,e.x01),o(r.y01,r.x01),!t):(a.arc(e.cx,e.cy,x,o(e.y01,e.x01),o(e.y11,e.x11),!t),a.arc(0,0,s,o(e.cy+e.y11,e.cx+e.x11),o(r.cy+r.y11,r.cx+r.x11),!t),a.arc(r.cx,r.cy,x,o(r.y11,r.x11),o(r.y01,r.x01),!t))):(a.moveTo(H,J),a.arc(0,0,s,m,g,!t)):a.moveTo(H,J),!(u>y)||!(P>y)?a.lineTo(M,N):p>y?(e=V(M,N,Q,U,u,-p,t),r=V(H,J,W,X,u,-p,t),a.lineTo(e.cx+e.x01,e.cy+e.y01),p<w?a.arc(e.cx,e.cy,p,o(e.y01,e.x01),o(r.y01,r.x01),!t):(a.arc(e.cx,e.cy,p,o(e.y01,e.x01),o(e.y11,e.x11),!t),a.arc(0,0,u,o(e.cy+e.y11,e.cx+e.x11),o(r.cy+r.y11,r.cx+r.x11),t),a.arc(r.cx,r.cy,p,o(r.y11,r.x11),o(r.y01,r.x01),!t))):a.arc(0,0,u,T,R,t)}if(a.closePath(),n)return a=null,n+""||null}return i.centroid=function(){var n=(+l.apply(this,arguments)+ +h.apply(this,arguments))/2,d=(+v.apply(this,arguments)+ +A.apply(this,arguments))/2-rn/2;return[G(d)*n,q(d)*n]},i.innerRadius=function(n){return arguments.length?(l=typeof n=="function"?n:z(+n),i):l},i.outerRadius=function(n){return arguments.length?(h=typeof n=="function"?n:z(+n),i):h},i.cornerRadius=function(n){return arguments.length?(I=typeof n=="function"?n:z(+n),i):I},i.padRadius=function(n){return arguments.length?(D=n==null?null:typeof n=="function"?n:z(+n),i):D},i.startAngle=function(n){return arguments.length?(v=typeof n=="function"?n:z(+n),i):v},i.endAngle=function(n){return arguments.length?(A=typeof n=="function"?n:z(+n),i):A},i.padAngle=function(n){return arguments.length?(B=typeof n=="function"?n:z(+n),i):B},i.context=function(n){return arguments.length?(a=n??null,i):a},i}export{hn as d};