@ggui-ai/ui-gen 0.28.0 → 0.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-h4_V69LI.d.ts → adapter-DLQ-5COm.d.ts} +1 -1
- package/dist/adapters/base.js +2 -27
- package/dist/adapters/base.js.map +1 -1
- package/dist/adapters/generation-dispatch.d.ts +14 -6
- package/dist/adapters/generation-dispatch.js +40 -19260
- package/dist/adapters/generation-dispatch.js.map +1 -1
- package/dist/adapters/index.d.ts +1 -1
- package/dist/adapters/index.js +25 -3561
- package/dist/adapters/index.js.map +1 -1
- package/dist/adapters/types.js +2 -9
- package/dist/adapters/types.js.map +1 -1
- package/dist/advanced/index.d.ts +13 -12
- package/dist/advanced/index.js +63 -21954
- package/dist/advanced/index.js.map +1 -1
- package/dist/{bank-Ctdp3FUA.d.ts → bank-LWaiAtaA.d.ts} +1 -1
- package/dist/blueprint-validator.js +6 -2301
- package/dist/blueprint-validator.js.map +1 -1
- package/dist/boilerplate.d.ts +3 -2
- package/dist/boilerplate.js +6 -1867
- package/dist/boilerplate.js.map +1 -1
- package/dist/check/index.d.ts +3 -2
- package/dist/check/index.js +6 -1923
- package/dist/check/index.js.map +1 -1
- package/dist/chunk-33B3BAWS.js +24 -0
- package/dist/chunk-33B3BAWS.js.map +1 -0
- package/dist/chunk-3HSGA6NI.js +591 -0
- package/dist/chunk-3HSGA6NI.js.map +1 -0
- package/dist/chunk-3NNNGNTO.js +1707 -0
- package/dist/chunk-3NNNGNTO.js.map +1 -0
- package/dist/chunk-3T2HMTON.js +79 -0
- package/dist/chunk-3T2HMTON.js.map +1 -0
- package/dist/chunk-3ZSSDV3L.js +123 -0
- package/dist/chunk-3ZSSDV3L.js.map +1 -0
- package/dist/chunk-4MBR5GA3.js +99 -0
- package/dist/chunk-4MBR5GA3.js.map +1 -0
- package/dist/chunk-56NJFD55.js +337 -0
- package/dist/chunk-56NJFD55.js.map +1 -0
- package/dist/chunk-5AGTY555.js +26 -0
- package/dist/chunk-5AGTY555.js.map +1 -0
- package/dist/chunk-5EJM7EGY.js +115 -0
- package/dist/chunk-5EJM7EGY.js.map +1 -0
- package/dist/chunk-5KXCQLLR.js +529 -0
- package/dist/chunk-5KXCQLLR.js.map +1 -0
- package/dist/chunk-5VBXHVEH.js +171 -0
- package/dist/chunk-5VBXHVEH.js.map +1 -0
- package/dist/chunk-6KDDEING.js +515 -0
- package/dist/chunk-6KDDEING.js.map +1 -0
- package/dist/chunk-6VDRWAP6.js +123 -0
- package/dist/chunk-6VDRWAP6.js.map +1 -0
- package/dist/chunk-732IBFEJ.js +2400 -0
- package/dist/chunk-732IBFEJ.js.map +1 -0
- package/dist/chunk-73AURS3I.js +46 -0
- package/dist/chunk-73AURS3I.js.map +1 -0
- package/dist/chunk-77H5SKLX.js +8 -0
- package/dist/chunk-77H5SKLX.js.map +1 -0
- package/dist/chunk-7QE3AHLE.js +35 -0
- package/dist/chunk-7QE3AHLE.js.map +1 -0
- package/dist/chunk-A375NNWN.js +11 -0
- package/dist/chunk-A375NNWN.js.map +1 -0
- package/dist/chunk-AOU33EFS.js +140 -0
- package/dist/chunk-AOU33EFS.js.map +1 -0
- package/dist/chunk-BA4QYA6E.js +461 -0
- package/dist/chunk-BA4QYA6E.js.map +1 -0
- package/dist/chunk-DBP764GL.js +3 -0
- package/dist/chunk-DBP764GL.js.map +1 -0
- package/dist/chunk-DUU3ZJDQ.js +41 -0
- package/dist/chunk-DUU3ZJDQ.js.map +1 -0
- package/dist/chunk-DXKRBXNU.js +30 -0
- package/dist/chunk-DXKRBXNU.js.map +1 -0
- package/dist/chunk-FB7OEEAH.js +1467 -0
- package/dist/chunk-FB7OEEAH.js.map +1 -0
- package/dist/chunk-FLRNMZV2.js +18 -0
- package/dist/chunk-FLRNMZV2.js.map +1 -0
- package/dist/chunk-FWJIMKFZ.js +2032 -0
- package/dist/chunk-FWJIMKFZ.js.map +1 -0
- package/dist/chunk-FXRHWYIQ.js +163 -0
- package/dist/chunk-FXRHWYIQ.js.map +1 -0
- package/dist/chunk-G3PMV62Z.js +33 -0
- package/dist/chunk-G3PMV62Z.js.map +1 -0
- package/dist/chunk-GAJI7Y3P.js +13 -0
- package/dist/chunk-GAJI7Y3P.js.map +1 -0
- package/dist/chunk-GYINWMPR.js +2052 -0
- package/dist/chunk-GYINWMPR.js.map +1 -0
- package/dist/chunk-HD6ABIK7.js +484 -0
- package/dist/chunk-HD6ABIK7.js.map +1 -0
- package/dist/chunk-HDQVHYO6.js +100 -0
- package/dist/chunk-HDQVHYO6.js.map +1 -0
- package/dist/chunk-IHUT3SIW.js +7 -0
- package/dist/chunk-IHUT3SIW.js.map +1 -0
- package/dist/chunk-JDH5EGNZ.js +126 -0
- package/dist/chunk-JDH5EGNZ.js.map +1 -0
- package/dist/chunk-JMD4RGSV.js +37 -0
- package/dist/chunk-JMD4RGSV.js.map +1 -0
- package/dist/chunk-KJWGZL5B.js +33 -0
- package/dist/chunk-KJWGZL5B.js.map +1 -0
- package/dist/chunk-MKMDQFZ7.js +86 -0
- package/dist/chunk-MKMDQFZ7.js.map +1 -0
- package/dist/chunk-NF6JUZWF.js +85 -0
- package/dist/chunk-NF6JUZWF.js.map +1 -0
- package/dist/chunk-O2YC6XDC.js +1933 -0
- package/dist/chunk-O2YC6XDC.js.map +1 -0
- package/dist/chunk-OVLH5ICV.js +29 -0
- package/dist/chunk-OVLH5ICV.js.map +1 -0
- package/dist/chunk-PBOYHGSD.js +106 -0
- package/dist/chunk-PBOYHGSD.js.map +1 -0
- package/dist/chunk-PJFH7QWA.js +81 -0
- package/dist/chunk-PJFH7QWA.js.map +1 -0
- package/dist/chunk-PUH4CXGZ.js +284 -0
- package/dist/chunk-PUH4CXGZ.js.map +1 -0
- package/dist/chunk-QLXXPGTV.js +18 -0
- package/dist/chunk-QLXXPGTV.js.map +1 -0
- package/dist/chunk-R5GIGPW2.js +2845 -0
- package/dist/chunk-R5GIGPW2.js.map +1 -0
- package/dist/chunk-RH4IUSTO.js +83 -0
- package/dist/chunk-RH4IUSTO.js.map +1 -0
- package/dist/chunk-S2GVXKKY.js +153 -0
- package/dist/chunk-S2GVXKKY.js.map +1 -0
- package/dist/chunk-TVHGKFJS.js +58 -0
- package/dist/chunk-TVHGKFJS.js.map +1 -0
- package/dist/chunk-U7GALWLG.js +66 -0
- package/dist/chunk-U7GALWLG.js.map +1 -0
- package/dist/chunk-VTC263LT.js +256 -0
- package/dist/chunk-VTC263LT.js.map +1 -0
- package/dist/chunk-WEOXFEVE.js +739 -0
- package/dist/chunk-WEOXFEVE.js.map +1 -0
- package/dist/chunk-WYHP46LT.js +28 -0
- package/dist/chunk-WYHP46LT.js.map +1 -0
- package/dist/chunk-XGLO5LGG.js +274 -0
- package/dist/chunk-XGLO5LGG.js.map +1 -0
- package/dist/chunk-XRBCRKA2.js +29 -0
- package/dist/chunk-XRBCRKA2.js.map +1 -0
- package/dist/chunk-XW7ADFFV.js +340 -0
- package/dist/chunk-XW7ADFFV.js.map +1 -0
- package/dist/chunk-YIQ42IUX.js +34 -0
- package/dist/chunk-YIQ42IUX.js.map +1 -0
- package/dist/chunk-YJZTUY7B.js +101 -0
- package/dist/chunk-YJZTUY7B.js.map +1 -0
- package/dist/chunk-Z3CXME3K.js +107 -0
- package/dist/chunk-Z3CXME3K.js.map +1 -0
- package/dist/classifier/index.js +2 -527
- package/dist/classifier/index.js.map +1 -1
- package/dist/client-JBPCXU7W.js +4 -0
- package/dist/client-JBPCXU7W.js.map +1 -0
- package/dist/compose.js +3 -367
- package/dist/compose.js.map +1 -1
- package/dist/cost-tracker-HHGQ4FTW.js +67 -0
- package/dist/cost-tracker-HHGQ4FTW.js.map +1 -0
- package/dist/{create-ui-generator-BrZHF0cf.d.ts → create-ui-generator-BY-WeaPi.d.ts} +3 -3
- package/dist/{design-mode-DGWN_Gkm.d.ts → design-mode-XyOQmzE0.d.ts} +4 -3
- package/dist/{dispatch-B07TI30d.d.ts → dispatch-8LzTddKw.d.ts} +3 -2
- package/dist/dist-UALN6ZVB.js +543 -0
- package/dist/dist-UALN6ZVB.js.map +1 -0
- package/dist/dupe-break-X6K7QFIS.js +4 -0
- package/dist/dupe-break-X6K7QFIS.js.map +1 -0
- package/dist/evaluation/axis-checks/index.d.ts +5 -4
- package/dist/evaluation/axis-checks/index.js +6 -1914
- package/dist/evaluation/axis-checks/index.js.map +1 -1
- package/dist/evaluation/axis-checks/registry.d.ts +3 -2
- package/dist/evaluation/axis-checks/registry.js +3 -1844
- package/dist/evaluation/axis-checks/registry.js.map +1 -1
- package/dist/evaluation/index.d.ts +49 -132
- package/dist/evaluation/index.js +302 -6466
- package/dist/evaluation/index.js.map +1 -1
- package/dist/evaluation/types.d.ts +3 -2
- package/dist/evaluation/types.js +2 -5
- package/dist/evaluation/types.js.map +1 -1
- package/dist/fragments/index.js +2 -338
- package/dist/fragments/index.js.map +1 -1
- package/dist/{generate-tSO_shQ0.d.ts → generate-DQ4ci90s.d.ts} +1 -1
- package/dist/harness/check/runtime-render/index.d.ts +35 -15
- package/dist/harness/check/runtime-render/index.js +6 -2390
- package/dist/harness/check/runtime-render/index.js.map +1 -1
- package/dist/harness/check/runtime-render/render-check-worker.js +4 -1739
- package/dist/harness/check/runtime-render/render-check-worker.js.map +1 -1
- package/dist/harness/index.d.ts +3 -2
- package/dist/harness/index.js +23 -5126
- package/dist/harness/index.js.map +1 -1
- package/dist/harness/llm-trace-sink.js +2 -24
- package/dist/harness/llm-trace-sink.js.map +1 -1
- package/dist/harness/prompts.d.ts +2 -2
- package/dist/harness/prompts.js +8 -324
- package/dist/harness/prompts.js.map +1 -1
- package/dist/harness/result-types.d.ts +6 -5
- package/dist/harness/result-types.js +2 -0
- package/dist/harness/result-types.js.map +1 -1
- package/dist/harness/runtime.d.ts +22 -5
- package/dist/harness/runtime.js +10 -2313
- package/dist/harness/runtime.js.map +1 -1
- package/dist/harness/types-public.d.ts +3 -2
- package/dist/harness/types-public.js +16 -2954
- package/dist/harness/types-public.js.map +1 -1
- package/dist/harness/validator-trace-sink.d.ts +3 -2
- package/dist/harness/validator-trace-sink.js +2 -26
- package/dist/harness/validator-trace-sink.js.map +1 -1
- package/dist/hash.js +2 -39
- package/dist/hash.js.map +1 -1
- package/dist/hashline-5OKREIRM.js +4 -0
- package/dist/hashline-5OKREIRM.js.map +1 -0
- package/dist/index.d.ts +50 -11
- package/dist/index.js +57 -22015
- package/dist/index.js.map +1 -1
- package/dist/llm-evaluator-PN3WFCS4.js +653 -0
- package/dist/llm-evaluator-PN3WFCS4.js.map +1 -0
- package/dist/magic-string.es-2NZTC4GZ.js +1307 -0
- package/dist/magic-string.es-2NZTC4GZ.js.map +1 -0
- package/dist/patch.d.ts +3 -2
- package/dist/patch.js +2 -56
- package/dist/patch.js.map +1 -1
- package/dist/policy-VCYKGSAC.js +5 -0
- package/dist/policy-VCYKGSAC.js.map +1 -0
- package/dist/policy.js +2 -35
- package/dist/policy.js.map +1 -1
- package/dist/primitive-index-2OF6F4TZ.js +131 -0
- package/dist/primitive-index-2OF6F4TZ.js.map +1 -0
- package/dist/primitive-slice-WTMBLYFJ.js +235 -0
- package/dist/primitive-slice-WTMBLYFJ.js.map +1 -0
- package/dist/{prompts-BhNUuRoZ.d.ts → prompts-CLZGywMP.d.ts} +1 -1
- package/dist/provider-adapter-contract.js +10407 -14204
- package/dist/provider-adapter-contract.js.map +1 -1
- package/dist/provider-adapter.js +2 -44
- package/dist/provider-adapter.js.map +1 -1
- package/dist/providers/index.d.ts +89 -1
- package/dist/providers/index.js +115 -44
- package/dist/providers/index.js.map +1 -1
- package/dist/raw-C6KBH5I3.js +141 -0
- package/dist/raw-C6KBH5I3.js.map +1 -0
- package/dist/raw-FXSBXQTZ.js +7 -0
- package/dist/raw-FXSBXQTZ.js.map +1 -0
- package/dist/raw-MURDUPGK.js +8 -0
- package/dist/raw-MURDUPGK.js.map +1 -0
- package/dist/raw-T3GW3UVX.js +8 -0
- package/dist/raw-T3GW3UVX.js.map +1 -0
- package/dist/render-check-host-ZNIS6BJ5.js +5 -0
- package/dist/render-check-host-ZNIS6BJ5.js.map +1 -0
- package/dist/sdk-4JNSDNSR.js +6 -0
- package/dist/sdk-4JNSDNSR.js.map +1 -0
- package/dist/sdk-DIVJMHCX.js +7 -0
- package/dist/sdk-DIVJMHCX.js.map +1 -0
- package/dist/sdk-QRJOCRTS.js +7 -0
- package/dist/sdk-QRJOCRTS.js.map +1 -0
- package/dist/tag-balance-CTHCTRJ7.js +123 -0
- package/dist/tag-balance-CTHCTRJ7.js.map +1 -0
- package/dist/tools/get-primitives-ts.d.ts +1 -1
- package/dist/tools/get-primitives-ts.js +3 -1
- package/dist/tools/get-primitives-ts.js.map +1 -1
- package/dist/tools/render-check-worker.js +3 -40
- package/dist/tools/render-check-worker.js.map +1 -1
- package/dist/{types-public-h8IMnYuh.d.ts → types-public-hYlrerZh.d.ts} +35 -2
- package/dist/validation/index.d.ts +2 -2
- package/dist/validation/index.js +3 -498
- package/dist/validation/index.js.map +1 -1
- package/dist/{visual-evaluator-C2strxqD.d.ts → visual-evaluator-KskajxD5.d.ts} +14 -4
- package/dist/visual-evaluator-TGEXYQTP.js +12 -0
- package/dist/visual-evaluator-TGEXYQTP.js.map +1 -0
- package/dist/workflows.d.ts +3 -2
- package/dist/workflows.js +2 -151
- package/dist/workflows.js.map +1 -1
- package/package.json +20 -16
- package/src/adapters/claude/sdk.ts +4 -2
- package/src/adapters/claude/tool-bridge.ts +2 -1
- package/src/adapters/generation-dispatch.ts +9 -0
- package/src/adapters/openai/raw.ts +4 -0
- package/src/adapters/openai/sdk.ts +6 -1
- package/src/adapters/openai/tokens.ts +21 -7
- package/src/adapters/tool-bridge.ts +1 -1
- package/src/adapters/tools.ts +1 -1
- package/src/advanced/feedback.ts +1 -2
- package/src/advanced/generator.ts +4 -3
- package/src/boilerplate/free-design-prompt.ts +7 -0
- package/src/boilerplate/generate.ts +18 -5
- package/src/boilerplate/hard-sections.ts +8 -3
- package/src/boilerplate/react-hooks.ts +56 -0
- package/src/boilerplate/system-prompt.ts +12 -3
- package/src/check/run-tier0.ts +233 -8
- package/src/check/type-checker.ts +128 -16
- package/src/coding-agent/tools.ts +26 -3
- package/src/design-mode.ts +4 -9
- package/src/evaluation/axis-checks/checks/state-merge.ts +2 -4
- package/src/evaluation/axis-checks/checks/state-payload.ts +1 -28
- package/src/evaluation/axis-checks/checks/tint.ts +197 -0
- package/src/evaluation/axis-checks/helpers.ts +121 -0
- package/src/evaluation/axis-checks/registry.ts +2 -0
- package/src/evaluation/criteria/__fixtures__/edge-v2-draw2.json +4629 -0
- package/src/evaluation/criteria/bank.ts +1 -1
- package/src/evaluation/criteria/edge-instruments.ts +14 -0
- package/src/evaluation/criteria/edge-probe-v2.ts +352 -0
- package/src/evaluation/criteria/edge-v2.ts +242 -0
- package/src/evaluation/criteria/resolve.ts +24 -5
- package/src/evaluation/index.ts +3 -5
- package/src/evaluation/mcp-server.ts +0 -50
- package/src/evaluation/types-public.ts +6 -1
- package/src/evaluation/visual-evaluator.ts +161 -30
- package/src/harness/check/runtime-render/index.ts +28 -4
- package/src/harness/check/runtime-render/render-check.ts +20 -21
- package/src/harness/claude-agent-sdk-loader.ts +93 -0
- package/src/harness/claude-code-login-query.ts +1 -1
- package/src/harness/coding/generate-task-runner.ts +1 -0
- package/src/harness/coding/run-coding-turn.ts +3 -0
- package/src/harness/coding/run-eval-round.ts +9 -0
- package/src/harness/llm-router.ts +50 -2
- package/src/harness/runtime.ts +17 -0
- package/src/index.ts +9 -0
- package/src/providers/anthropic-tool-call.ts +263 -0
- package/src/providers/index.ts +13 -0
- package/src/tools/get-primitives-ts.ts +1 -1
- package/src/tools/render-check.ts +4 -4
- package/src/validation/primitives.ts +2 -1
- package/src/evaluation/loop.ts +0 -218
package/dist/adapters/index.js
CHANGED
|
@@ -1,3563 +1,27 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
import
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
import
|
|
13
|
-
import
|
|
14
|
-
import
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
};
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
// src/adapters/base.ts
|
|
27
|
-
function stripModelPrefix(modelId) {
|
|
28
|
-
const slashIndex = modelId.indexOf("/");
|
|
29
|
-
return slashIndex >= 0 ? modelId.slice(slashIndex + 1) : modelId;
|
|
30
|
-
}
|
|
31
|
-
function hasCredentials(config, ...envVarNames) {
|
|
32
|
-
if (config.apiKey) return true;
|
|
33
|
-
if (config.useBedrock) return true;
|
|
34
|
-
if (config.claudeCodeLogin) return true;
|
|
35
|
-
return envVarNames.some((name) => !!process.env[name]);
|
|
36
|
-
}
|
|
37
|
-
var GeneratorAdapter;
|
|
38
|
-
var init_base = __esm({
|
|
39
|
-
"src/adapters/base.ts"() {
|
|
40
|
-
GeneratorAdapter = class {
|
|
41
|
-
constructor(config) {
|
|
42
|
-
this.config = config;
|
|
43
|
-
}
|
|
44
|
-
config;
|
|
45
|
-
/**
|
|
46
|
-
* Map a LiteLLM-format model ID to this SDK's native format.
|
|
47
|
-
* Default: strips the provider prefix (e.g., 'anthropic/claude-sonnet-4-6' -> 'claude-sonnet-4-6').
|
|
48
|
-
* Override only if the prefix convention differs.
|
|
49
|
-
*/
|
|
50
|
-
resolveModelId(litellmModelId) {
|
|
51
|
-
return stripModelPrefix(litellmModelId);
|
|
52
|
-
}
|
|
53
|
-
};
|
|
54
|
-
}
|
|
55
|
-
});
|
|
56
|
-
function zodToJsonSchema(schema) {
|
|
57
|
-
return z.toJSONSchema(schema);
|
|
58
|
-
}
|
|
59
|
-
function toolArgsToJsonObject(args) {
|
|
60
|
-
const out = {};
|
|
61
|
-
for (const [key, value] of Object.entries(args)) {
|
|
62
|
-
out[key] = value === void 0 ? void 0 : toJsonValue(value, key);
|
|
63
|
-
}
|
|
64
|
-
return out;
|
|
65
|
-
}
|
|
66
|
-
function toJsonValue(value, path2) {
|
|
67
|
-
if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
|
68
|
-
return value;
|
|
69
|
-
}
|
|
70
|
-
if (Array.isArray(value)) {
|
|
71
|
-
return value.map((item, i) => toJsonValue(item, `${path2}[${i}]`));
|
|
72
|
-
}
|
|
73
|
-
if (typeof value === "object") {
|
|
74
|
-
const out = {};
|
|
75
|
-
for (const [key, entry] of Object.entries(value)) {
|
|
76
|
-
out[key] = entry === void 0 ? void 0 : toJsonValue(entry, `${path2}.${key}`);
|
|
77
|
-
}
|
|
78
|
-
return out;
|
|
79
|
-
}
|
|
80
|
-
throw new Error(
|
|
81
|
-
`Tool-call arguments contain a non-JSON value at '${path2}' (${typeof value})`
|
|
82
|
-
);
|
|
83
|
-
}
|
|
84
|
-
var init_tool_bridge = __esm({
|
|
85
|
-
"src/adapters/tool-bridge.ts"() {
|
|
86
|
-
}
|
|
87
|
-
});
|
|
88
|
-
function createCapture() {
|
|
89
|
-
return { compiledCode: "", sourceCode: void 0, stream: void 0, generatorMeta: void 0 };
|
|
90
|
-
}
|
|
91
|
-
function captureSourceCode(capture, toolName, args) {
|
|
92
|
-
if (toolName === "compile_component" && typeof args.code === "string") {
|
|
93
|
-
capture.sourceCode = args.code;
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
function captureCompiledCode(capture, toolName, result) {
|
|
97
|
-
if (toolName !== "compile_component" || result.isError) return;
|
|
98
|
-
try {
|
|
99
|
-
const parsed = JSON.parse(result.content[0].text);
|
|
100
|
-
if (parsed.success && parsed.compiledCode) {
|
|
101
|
-
capture.compiledCode = parsed.compiledCode;
|
|
102
|
-
}
|
|
103
|
-
} catch {
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
function captureMarkers(capture, text) {
|
|
107
|
-
if (!capture.stream && text.includes("__GGUI_STREAM_SPEC__")) {
|
|
108
|
-
const match = text.match(/__GGUI_STREAM_SPEC__\s*([\s\S]*?)\s*__GGUI_STREAM_SPEC_END__/);
|
|
109
|
-
if (match) {
|
|
110
|
-
try {
|
|
111
|
-
capture.stream = JSON.parse(
|
|
112
|
-
match[1].replace(/\\n/g, "\n").replace(/\\"/g, '"').replace(/\\\\/g, "\\")
|
|
113
|
-
);
|
|
114
|
-
} catch {
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
if (!capture.generatorMeta && text.includes("__GGUI_META__")) {
|
|
119
|
-
const match = text.match(/__GGUI_META__\s*([\s\S]*?)\s*__GGUI_META_END__/);
|
|
120
|
-
if (match) {
|
|
121
|
-
try {
|
|
122
|
-
const stripped = match[1].replace(/```(?:json)?\s*/g, "").trim();
|
|
123
|
-
const raw = stripped.replace(/\\n/g, "\n").replace(/\\"/g, '"').replace(/\\\\/g, "\\");
|
|
124
|
-
const parsed = JSON.parse(raw);
|
|
125
|
-
if (parsed.category) {
|
|
126
|
-
capture.generatorMeta = { category: parsed.category, description: parsed.description ?? "" };
|
|
127
|
-
}
|
|
128
|
-
} catch {
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
async function extractCodeFromText(finalOutput, tools, capture) {
|
|
134
|
-
if (finalOutput.length <= 100) return;
|
|
135
|
-
const codeMatch = finalOutput.match(/```(?:tsx?|jsx?|typescript|javascript)?\s*\n([\s\S]*?)```/) ?? finalOutput.match(/```\s*\n([\s\S]*?)```/);
|
|
136
|
-
let code = codeMatch ? codeMatch[1].trim() : "";
|
|
137
|
-
if (!code && (finalOutput.includes("export default") || finalOutput.includes("export function"))) {
|
|
138
|
-
code = finalOutput;
|
|
139
|
-
}
|
|
140
|
-
if (!code || !(code.includes("export default") || code.includes("export function"))) {
|
|
141
|
-
return;
|
|
142
|
-
}
|
|
143
|
-
capture.sourceCode = code;
|
|
144
|
-
const compileTool = tools.find((t) => t.name === "compile_component");
|
|
145
|
-
if (!compileTool) return;
|
|
146
|
-
const compileResult = await compileTool.handler({ code, filename: "Component.tsx" });
|
|
147
|
-
if (compileResult.isError) {
|
|
148
|
-
console.warn("[extractCodeFromText] compile_component failed:", compileResult.content[0]?.text?.slice(0, 300));
|
|
149
|
-
}
|
|
150
|
-
captureCompiledCode(capture, "compile_component", compileResult);
|
|
151
|
-
}
|
|
152
|
-
async function compileLastResort(capture, allTextOutput) {
|
|
153
|
-
if (capture.compiledCode) return;
|
|
154
|
-
let code = capture.sourceCode;
|
|
155
|
-
if (!code && allTextOutput && allTextOutput.length > 100) {
|
|
156
|
-
const codeMatch = allTextOutput.match(/```(?:tsx?|jsx?|typescript|javascript)?\s*\n([\s\S]*?)```/) ?? allTextOutput.match(/```\s*\n([\s\S]*?)```/);
|
|
157
|
-
code = codeMatch ? codeMatch[1].trim() : void 0;
|
|
158
|
-
if (!code && (allTextOutput.includes("export default") || allTextOutput.includes("export function"))) {
|
|
159
|
-
code = allTextOutput;
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
if (!code || !(code.includes("export default") || code.includes("export function"))) {
|
|
163
|
-
return;
|
|
164
|
-
}
|
|
165
|
-
try {
|
|
166
|
-
const result = await esbuild.transform(code, {
|
|
167
|
-
loader: "tsx",
|
|
168
|
-
target: "es2020",
|
|
169
|
-
format: "esm",
|
|
170
|
-
jsx: "automatic",
|
|
171
|
-
jsxImportSource: "react",
|
|
172
|
-
minify: true,
|
|
173
|
-
sourcefile: "Component.tsx"
|
|
174
|
-
});
|
|
175
|
-
capture.compiledCode = result.code;
|
|
176
|
-
capture.sourceCode = code;
|
|
177
|
-
console.warn("[compileLastResort] Compiled code bypassing self-checks \u2014 may have quality issues");
|
|
178
|
-
} catch (err) {
|
|
179
|
-
console.warn("[compileLastResort] esbuild failed:", err instanceof Error ? err.message : String(err));
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
var init_extract_code = __esm({
|
|
183
|
-
"src/adapters/extract-code.ts"() {
|
|
184
|
-
}
|
|
185
|
-
});
|
|
186
|
-
function createAnthropicClient(rawKey) {
|
|
187
|
-
if (rawKey === void 0) {
|
|
188
|
-
return new Anthropic({
|
|
189
|
-
baseURL: "https://api.anthropic.com"
|
|
190
|
-
});
|
|
191
|
-
}
|
|
192
|
-
return new Anthropic({
|
|
193
|
-
apiKey: rawKey,
|
|
194
|
-
baseURL: "https://api.anthropic.com"
|
|
195
|
-
});
|
|
196
|
-
}
|
|
197
|
-
var init_client = __esm({
|
|
198
|
-
"src/adapters/claude/client.ts"() {
|
|
199
|
-
}
|
|
200
|
-
});
|
|
201
|
-
|
|
202
|
-
// src/adapters/claude/raw.ts
|
|
203
|
-
var raw_exports = {};
|
|
204
|
-
__export(raw_exports, {
|
|
205
|
-
ClaudeRawAdapter: () => ClaudeRawAdapter
|
|
206
|
-
});
|
|
207
|
-
function toAnthropicTool(def) {
|
|
208
|
-
return {
|
|
209
|
-
name: def.name,
|
|
210
|
-
description: def.description,
|
|
211
|
-
input_schema: zodToJsonSchema(def.inputSchema)
|
|
212
|
-
};
|
|
213
|
-
}
|
|
214
|
-
var ClaudeRawAdapter;
|
|
215
|
-
var init_raw = __esm({
|
|
216
|
-
"src/adapters/claude/raw.ts"() {
|
|
217
|
-
init_base();
|
|
218
|
-
init_tool_bridge();
|
|
219
|
-
init_extract_code();
|
|
220
|
-
init_client();
|
|
221
|
-
ClaudeRawAdapter = class extends GeneratorAdapter {
|
|
222
|
-
provider = "claude";
|
|
223
|
-
mode = "raw";
|
|
224
|
-
displayName = "Claude (Raw API)";
|
|
225
|
-
client = null;
|
|
226
|
-
constructor(config = {}) {
|
|
227
|
-
super(config);
|
|
228
|
-
}
|
|
229
|
-
isAvailable() {
|
|
230
|
-
return hasCredentials(this.config, "ANTHROPIC_API_KEY");
|
|
231
|
-
}
|
|
232
|
-
async generate(params) {
|
|
233
|
-
const startTime = Date.now();
|
|
234
|
-
if (!this.client) {
|
|
235
|
-
if (this.config.useBedrock) {
|
|
236
|
-
this.client = createAnthropicClient(void 0);
|
|
237
|
-
} else {
|
|
238
|
-
const rawKey = this.config.apiKey || process.env.ANTHROPIC_API_KEY;
|
|
239
|
-
this.client = createAnthropicClient(rawKey);
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
const anthropicTools = params.tools.map(toAnthropicTool);
|
|
243
|
-
const capture = createCapture();
|
|
244
|
-
let totalInputTokens = 0;
|
|
245
|
-
let totalOutputTokens = 0;
|
|
246
|
-
let turnsUsed = 0;
|
|
247
|
-
const messages = [
|
|
248
|
-
{ role: "user", content: params.userPrompt }
|
|
249
|
-
];
|
|
250
|
-
for (let turn = 0; turn < params.maxTurns; turn++) {
|
|
251
|
-
turnsUsed = turn + 1;
|
|
252
|
-
const response = await this.client.messages.create({
|
|
253
|
-
model: params.model,
|
|
254
|
-
max_tokens: 16384,
|
|
255
|
-
system: params.systemPrompt,
|
|
256
|
-
messages,
|
|
257
|
-
tools: anthropicTools
|
|
258
|
-
});
|
|
259
|
-
totalInputTokens += response.usage.input_tokens;
|
|
260
|
-
totalOutputTokens += response.usage.output_tokens;
|
|
261
|
-
const toolUseBlocks = response.content.filter(
|
|
262
|
-
(block) => block.type === "tool_use"
|
|
263
|
-
);
|
|
264
|
-
for (const block of response.content) {
|
|
265
|
-
if (block.type === "text") captureMarkers(capture, block.text);
|
|
266
|
-
}
|
|
267
|
-
if (toolUseBlocks.length === 0 || response.stop_reason === "end_turn") {
|
|
268
|
-
break;
|
|
269
|
-
}
|
|
270
|
-
messages.push({
|
|
271
|
-
role: "assistant",
|
|
272
|
-
content: response.content.map((block) => {
|
|
273
|
-
if (block.type === "text") {
|
|
274
|
-
return { type: "text", text: block.text };
|
|
275
|
-
}
|
|
276
|
-
return {
|
|
277
|
-
type: "tool_use",
|
|
278
|
-
id: block.id,
|
|
279
|
-
name: block.name,
|
|
280
|
-
input: block.input
|
|
281
|
-
};
|
|
282
|
-
})
|
|
283
|
-
});
|
|
284
|
-
const toolResults = [];
|
|
285
|
-
for (const toolBlock of toolUseBlocks) {
|
|
286
|
-
const toolDef = params.tools.find((t) => t.name === toolBlock.name);
|
|
287
|
-
if (!toolDef) {
|
|
288
|
-
toolResults.push({
|
|
289
|
-
type: "tool_result",
|
|
290
|
-
tool_use_id: toolBlock.id,
|
|
291
|
-
content: `Tool '${toolBlock.name}' not found`,
|
|
292
|
-
is_error: true
|
|
293
|
-
});
|
|
294
|
-
continue;
|
|
295
|
-
}
|
|
296
|
-
const args = toolBlock.input ?? {};
|
|
297
|
-
captureSourceCode(capture, toolBlock.name, args);
|
|
298
|
-
const result = await toolDef.handler(args);
|
|
299
|
-
captureCompiledCode(capture, toolBlock.name, result);
|
|
300
|
-
toolResults.push({
|
|
301
|
-
type: "tool_result",
|
|
302
|
-
tool_use_id: toolBlock.id,
|
|
303
|
-
content: result.content.map((c) => ({ type: "text", text: c.text })),
|
|
304
|
-
is_error: result.isError
|
|
305
|
-
});
|
|
306
|
-
}
|
|
307
|
-
messages.push({ role: "user", content: toolResults });
|
|
308
|
-
}
|
|
309
|
-
if (!capture.compiledCode) {
|
|
310
|
-
throw new Error("Claude raw adapter: no compiled code produced after all turns");
|
|
311
|
-
}
|
|
312
|
-
return {
|
|
313
|
-
compiledCode: capture.compiledCode,
|
|
314
|
-
sourceCode: capture.sourceCode,
|
|
315
|
-
stream: capture.stream,
|
|
316
|
-
generatorMeta: capture.generatorMeta,
|
|
317
|
-
tokens: {
|
|
318
|
-
input: totalInputTokens,
|
|
319
|
-
output: totalOutputTokens,
|
|
320
|
-
total: totalInputTokens + totalOutputTokens
|
|
321
|
-
},
|
|
322
|
-
generationTimeMs: Date.now() - startTime,
|
|
323
|
-
turnsUsed
|
|
324
|
-
};
|
|
325
|
-
}
|
|
326
|
-
};
|
|
327
|
-
}
|
|
328
|
-
});
|
|
329
|
-
|
|
330
|
-
// src/adapters/claude/source-capture.ts
|
|
331
|
-
function sourceCodeFromToolUse(name, input) {
|
|
332
|
-
if (typeof name !== "string") return void 0;
|
|
333
|
-
const field = name === "Write" ? "content" : name.endsWith(COMPILE_TOOL_SUFFIX) ? "code" : void 0;
|
|
334
|
-
if (field === void 0 || typeof input !== "object" || input === null) return void 0;
|
|
335
|
-
const value = Reflect.get(input, field);
|
|
336
|
-
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
337
|
-
}
|
|
338
|
-
var COMPILE_TOOL_SUFFIX;
|
|
339
|
-
var init_source_capture = __esm({
|
|
340
|
-
"src/adapters/claude/source-capture.ts"() {
|
|
341
|
-
COMPILE_TOOL_SUFFIX = "__compile_component";
|
|
342
|
-
}
|
|
343
|
-
});
|
|
344
|
-
|
|
345
|
-
// src/adapters/claude/message-parser.ts
|
|
346
|
-
function createArtifacts() {
|
|
347
|
-
return {
|
|
348
|
-
compiledCode: "",
|
|
349
|
-
sourceCode: void 0,
|
|
350
|
-
stream: void 0,
|
|
351
|
-
generatorMeta: void 0,
|
|
352
|
-
sdkSessionId: void 0,
|
|
353
|
-
turnCount: 0,
|
|
354
|
-
inputTokens: 0,
|
|
355
|
-
outputTokens: 0,
|
|
356
|
-
cacheCreationTokens: 0,
|
|
357
|
-
cacheReadTokens: 0,
|
|
358
|
-
estimatedCostUsd: void 0,
|
|
359
|
-
subagentsUsed: []
|
|
360
|
-
};
|
|
361
|
-
}
|
|
362
|
-
function processMessage(message, artifacts, onProgress, maxTurns) {
|
|
363
|
-
extractSessionId(message, artifacts);
|
|
364
|
-
trackTurns(message, artifacts, onProgress, maxTurns);
|
|
365
|
-
trackTokenUsage(message, artifacts);
|
|
366
|
-
extractCompiledCode(message, artifacts, onProgress);
|
|
367
|
-
extractSourceCode(message, artifacts);
|
|
368
|
-
extractStreamSpec(message, artifacts);
|
|
369
|
-
extractGeneratorMeta(message, artifacts);
|
|
370
|
-
}
|
|
371
|
-
function extractSessionId(message, artifacts) {
|
|
372
|
-
if (message.type !== "system") return;
|
|
373
|
-
const systemMsg = message;
|
|
374
|
-
if (systemMsg.subtype === "init") {
|
|
375
|
-
artifacts.sdkSessionId = systemMsg.session_id;
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
|
-
function trackTurns(message, artifacts, onProgress, maxTurns) {
|
|
379
|
-
if (message.type !== "assistant") return;
|
|
380
|
-
const assistantMsg = message;
|
|
381
|
-
artifacts.turnCount++;
|
|
382
|
-
const contentBlocks = assistantMsg.message?.content;
|
|
383
|
-
if (Array.isArray(contentBlocks)) {
|
|
384
|
-
for (const block of contentBlocks) {
|
|
385
|
-
if (block.type === "tool_use") {
|
|
386
|
-
onProgress?.({ type: "tool_call", tool: block.name || "unknown" });
|
|
387
|
-
}
|
|
388
|
-
}
|
|
389
|
-
}
|
|
390
|
-
onProgress?.({ type: "turn", turn: artifacts.turnCount, maxTurns: maxTurns ?? 0 });
|
|
391
|
-
}
|
|
392
|
-
function trackTokenUsage(message, artifacts) {
|
|
393
|
-
if (message.type !== "result") return;
|
|
394
|
-
const resultMsg = message;
|
|
395
|
-
if (resultMsg.subtype === "success") {
|
|
396
|
-
const usage = resultMsg.usage;
|
|
397
|
-
artifacts.inputTokens = usage.input_tokens || 0;
|
|
398
|
-
artifacts.cacheCreationTokens = usage.cache_creation_input_tokens || 0;
|
|
399
|
-
artifacts.cacheReadTokens = usage.cache_read_input_tokens || 0;
|
|
400
|
-
artifacts.outputTokens = usage.output_tokens || 0;
|
|
401
|
-
artifacts.estimatedCostUsd = resultMsg.total_cost_usd;
|
|
402
|
-
}
|
|
403
|
-
}
|
|
404
|
-
function extractCompiledCode(message, artifacts, onProgress) {
|
|
405
|
-
if (artifacts.compiledCode) return;
|
|
406
|
-
const msgStr = JSON.stringify(message);
|
|
407
|
-
if (!msgStr.includes("compiledCode")) return;
|
|
408
|
-
const match = msgStr.match(/"compiledCode"\s*:\s*"([^"\\]*(\\.[^"\\]*)*)"/);
|
|
409
|
-
if (match) {
|
|
410
|
-
try {
|
|
411
|
-
artifacts.compiledCode = JSON.parse(`"${match[1]}"`);
|
|
412
|
-
onProgress?.({ type: "compiled", bytes: artifacts.compiledCode.length });
|
|
413
|
-
return;
|
|
414
|
-
} catch {
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
if (message.type === "user") {
|
|
418
|
-
const userMsg = message;
|
|
419
|
-
const code = extractFromToolResults(userMsg);
|
|
420
|
-
if (code) artifacts.compiledCode = code;
|
|
421
|
-
}
|
|
422
|
-
}
|
|
423
|
-
function extractFromToolResults(message) {
|
|
424
|
-
const content = message.message?.content;
|
|
425
|
-
if (!Array.isArray(content)) return void 0;
|
|
426
|
-
for (const item of content) {
|
|
427
|
-
if (typeof item === "object" && item !== null && "type" in item && item.type === "tool_result") {
|
|
428
|
-
const toolResultItem = item;
|
|
429
|
-
const code = parseCompiledCodeFromContent(toolResultItem.content);
|
|
430
|
-
if (code) return code;
|
|
431
|
-
}
|
|
432
|
-
}
|
|
433
|
-
return void 0;
|
|
434
|
-
}
|
|
435
|
-
function parseCompiledCodeFromContent(content) {
|
|
436
|
-
if (Array.isArray(content)) {
|
|
437
|
-
for (const item of content) {
|
|
438
|
-
const textItem = item;
|
|
439
|
-
if (textItem.type === "text" && textItem.text?.includes("compiledCode")) {
|
|
440
|
-
const code = tryParseCompiledCode(textItem.text);
|
|
441
|
-
if (code) return code;
|
|
442
|
-
}
|
|
443
|
-
}
|
|
444
|
-
}
|
|
445
|
-
if (typeof content === "string" && content.includes("compiledCode")) {
|
|
446
|
-
return tryParseCompiledCode(content);
|
|
447
|
-
}
|
|
448
|
-
return void 0;
|
|
449
|
-
}
|
|
450
|
-
function tryParseCompiledCode(text) {
|
|
451
|
-
try {
|
|
452
|
-
const parsed = JSON.parse(text);
|
|
453
|
-
if (parsed.success && parsed.compiledCode) return parsed.compiledCode;
|
|
454
|
-
} catch {
|
|
455
|
-
}
|
|
456
|
-
return void 0;
|
|
457
|
-
}
|
|
458
|
-
function extractSourceCode(message, artifacts) {
|
|
459
|
-
if (message.type !== "assistant") return;
|
|
460
|
-
const assistantMsg = message;
|
|
461
|
-
const content = assistantMsg.message?.content;
|
|
462
|
-
if (!Array.isArray(content)) return;
|
|
463
|
-
for (const block of content) {
|
|
464
|
-
if (block.type !== "tool_use") continue;
|
|
465
|
-
const value = sourceCodeFromToolUse(block.name, block.input);
|
|
466
|
-
if (value !== void 0) artifacts.sourceCode = value;
|
|
467
|
-
}
|
|
468
|
-
}
|
|
469
|
-
function unescapeJsonString(s) {
|
|
470
|
-
return s.replace(/\\n/g, "\n").replace(/\\"/g, '"').replace(/\\\\/g, "\\");
|
|
471
|
-
}
|
|
472
|
-
function extractMarker(msgStr, startMarker, endMarker) {
|
|
473
|
-
if (!msgStr.includes(startMarker)) return void 0;
|
|
474
|
-
const match = msgStr.match(new RegExp(`${startMarker}\\s*([\\s\\S]*?)\\s*${endMarker}`));
|
|
475
|
-
return match?.[1];
|
|
476
|
-
}
|
|
477
|
-
function extractStreamSpec(message, artifacts) {
|
|
478
|
-
if (artifacts.stream) return;
|
|
479
|
-
const raw = extractMarker(JSON.stringify(message), "__GGUI_STREAM_SPEC__", "__GGUI_STREAM_SPEC_END__");
|
|
480
|
-
if (!raw) return;
|
|
481
|
-
try {
|
|
482
|
-
artifacts.stream = JSON.parse(unescapeJsonString(raw));
|
|
483
|
-
} catch {
|
|
484
|
-
}
|
|
485
|
-
}
|
|
486
|
-
function extractGeneratorMeta(message, artifacts) {
|
|
487
|
-
if (artifacts.generatorMeta) return;
|
|
488
|
-
const raw = extractMarker(JSON.stringify(message), "__GGUI_META__", "__GGUI_META_END__");
|
|
489
|
-
if (!raw) return;
|
|
490
|
-
try {
|
|
491
|
-
const stripped = raw.replace(/```(?:json)?\s*/g, "").trim();
|
|
492
|
-
const parsed = JSON.parse(unescapeJsonString(stripped));
|
|
493
|
-
if (parsed.category) {
|
|
494
|
-
artifacts.generatorMeta = {
|
|
495
|
-
category: parsed.category,
|
|
496
|
-
description: parsed.description ?? ""
|
|
497
|
-
};
|
|
498
|
-
}
|
|
499
|
-
} catch {
|
|
500
|
-
}
|
|
501
|
-
}
|
|
502
|
-
var init_message_parser = __esm({
|
|
503
|
-
"src/adapters/claude/message-parser.ts"() {
|
|
504
|
-
init_source_capture();
|
|
505
|
-
}
|
|
506
|
-
});
|
|
507
|
-
|
|
508
|
-
// src/adapters/claude/tool-bridge.ts
|
|
509
|
-
async function createToolMcpServer(tools) {
|
|
510
|
-
const { tool, createSdkMcpServer } = await import('@anthropic-ai/claude-agent-sdk');
|
|
511
|
-
const mcpTools = tools.map((def) => {
|
|
512
|
-
const shape = def.inputSchema.shape ?? {};
|
|
513
|
-
return tool(
|
|
514
|
-
def.name,
|
|
515
|
-
def.description,
|
|
516
|
-
shape,
|
|
517
|
-
async (args) => {
|
|
518
|
-
const result = await def.handler(args);
|
|
519
|
-
return {
|
|
520
|
-
content: result.content.map((c) => ({
|
|
521
|
-
type: "text",
|
|
522
|
-
text: c.text
|
|
523
|
-
})),
|
|
524
|
-
...result.isError && { isError: true }
|
|
525
|
-
};
|
|
526
|
-
}
|
|
527
|
-
);
|
|
528
|
-
});
|
|
529
|
-
const server = createSdkMcpServer({
|
|
530
|
-
name: MCP_SERVER_NAME,
|
|
531
|
-
version: "1.0.0",
|
|
532
|
-
tools: mcpTools
|
|
533
|
-
});
|
|
534
|
-
const allowedToolNames = tools.map((t) => `mcp__${MCP_SERVER_NAME}__${t.name}`);
|
|
535
|
-
return { server, allowedToolNames };
|
|
536
|
-
}
|
|
537
|
-
var MCP_SERVER_NAME;
|
|
538
|
-
var init_tool_bridge2 = __esm({
|
|
539
|
-
"src/adapters/claude/tool-bridge.ts"() {
|
|
540
|
-
MCP_SERVER_NAME = "ggui";
|
|
541
|
-
}
|
|
542
|
-
});
|
|
543
|
-
|
|
544
|
-
// src/adapters/claude/claude-code-login.ts
|
|
545
|
-
function loginChildEnv(env) {
|
|
546
|
-
const out = {};
|
|
547
|
-
for (const [k, v] of Object.entries(env)) {
|
|
548
|
-
if (v !== void 0 && (LOGIN_CHILD_ENV.has(k) || k.startsWith("LC_"))) out[k] = v;
|
|
549
|
-
}
|
|
550
|
-
return out;
|
|
551
|
-
}
|
|
552
|
-
function claudeCodeLoginQueryOptions() {
|
|
553
|
-
return { tools: [], settingSources: [] };
|
|
554
|
-
}
|
|
555
|
-
var LOGIN_CHILD_ENV_NAMES, LOGIN_CHILD_ENV;
|
|
556
|
-
var init_claude_code_login = __esm({
|
|
557
|
-
"src/adapters/claude/claude-code-login.ts"() {
|
|
558
|
-
LOGIN_CHILD_ENV_NAMES = [
|
|
559
|
-
"PATH",
|
|
560
|
-
"HOME",
|
|
561
|
-
"USER",
|
|
562
|
-
"LOGNAME",
|
|
563
|
-
"SHELL",
|
|
564
|
-
"TMPDIR",
|
|
565
|
-
"TMP",
|
|
566
|
-
"TEMP",
|
|
567
|
-
"TERM",
|
|
568
|
-
"TZ",
|
|
569
|
-
"LANG",
|
|
570
|
-
"CLAUDE_CONFIG_DIR",
|
|
571
|
-
"CLAUDE_CODE_OAUTH_TOKEN",
|
|
572
|
-
"XDG_CONFIG_HOME",
|
|
573
|
-
"XDG_DATA_HOME",
|
|
574
|
-
"XDG_CACHE_HOME",
|
|
575
|
-
"XDG_STATE_HOME",
|
|
576
|
-
"XDG_RUNTIME_DIR",
|
|
577
|
-
"HTTPS_PROXY",
|
|
578
|
-
"https_proxy",
|
|
579
|
-
"HTTP_PROXY",
|
|
580
|
-
"http_proxy",
|
|
581
|
-
"NO_PROXY",
|
|
582
|
-
"no_proxy",
|
|
583
|
-
"ALL_PROXY",
|
|
584
|
-
"all_proxy",
|
|
585
|
-
"NODE_EXTRA_CA_CERTS",
|
|
586
|
-
"SSL_CERT_FILE",
|
|
587
|
-
"SSL_CERT_DIR"
|
|
588
|
-
];
|
|
589
|
-
LOGIN_CHILD_ENV = new Set(LOGIN_CHILD_ENV_NAMES);
|
|
590
|
-
}
|
|
591
|
-
});
|
|
592
|
-
|
|
593
|
-
// src/adapters/claude/sdk-tool-pins.ts
|
|
594
|
-
function sdkToolPins(input) {
|
|
595
|
-
const builtins = [...input.builtinTools ?? []];
|
|
596
|
-
const approved = input.allowedTools !== void 0 ? [...input.allowedTools] : Object.keys(input.mcpServers ?? {}).map((name) => `mcp__${name}`);
|
|
597
|
-
return { tools: builtins, settingSources: [], allowedTools: [...approved, ...builtins] };
|
|
598
|
-
}
|
|
599
|
-
var init_sdk_tool_pins = __esm({
|
|
600
|
-
"src/adapters/claude/sdk-tool-pins.ts"() {
|
|
601
|
-
}
|
|
602
|
-
});
|
|
603
|
-
|
|
604
|
-
// src/adapters/claude/sdk.ts
|
|
605
|
-
var sdk_exports = {};
|
|
606
|
-
__export(sdk_exports, {
|
|
607
|
-
ClaudeSdkAdapter: () => ClaudeSdkAdapter
|
|
608
|
-
});
|
|
609
|
-
function buildEnv(configEnv) {
|
|
610
|
-
if (configEnv) return sanitizeEnv({ ...configEnv });
|
|
611
|
-
const env = {};
|
|
612
|
-
for (const [key, value] of Object.entries(process.env)) {
|
|
613
|
-
if (value !== void 0) env[key] = value;
|
|
614
|
-
}
|
|
615
|
-
return sanitizeEnv(env);
|
|
616
|
-
}
|
|
617
|
-
function sanitizeEnv(env) {
|
|
618
|
-
if (env.ANTHROPIC_BASE_URL?.includes("localhost")) {
|
|
619
|
-
delete env.ANTHROPIC_BASE_URL;
|
|
620
|
-
}
|
|
621
|
-
return env;
|
|
622
|
-
}
|
|
623
|
-
var ClaudeSdkAdapter;
|
|
624
|
-
var init_sdk = __esm({
|
|
625
|
-
"src/adapters/claude/sdk.ts"() {
|
|
626
|
-
init_base();
|
|
627
|
-
init_message_parser();
|
|
628
|
-
init_tool_bridge2();
|
|
629
|
-
init_claude_code_login();
|
|
630
|
-
init_sdk_tool_pins();
|
|
631
|
-
ClaudeSdkAdapter = class extends GeneratorAdapter {
|
|
632
|
-
provider = "claude";
|
|
633
|
-
mode = "sdk";
|
|
634
|
-
displayName = "Claude (Agent SDK)";
|
|
635
|
-
constructor(config = {}) {
|
|
636
|
-
super(config);
|
|
637
|
-
}
|
|
638
|
-
/** Narrowed config access for Claude SDK-specific fields. */
|
|
639
|
-
get sdkConfig() {
|
|
640
|
-
return this.config;
|
|
641
|
-
}
|
|
642
|
-
isAvailable() {
|
|
643
|
-
return hasCredentials(this.config, "ANTHROPIC_API_KEY");
|
|
644
|
-
}
|
|
645
|
-
async generate(params) {
|
|
646
|
-
const startTime = Date.now();
|
|
647
|
-
const cfg = this.sdkConfig;
|
|
648
|
-
const { query } = await import('@anthropic-ai/claude-agent-sdk');
|
|
649
|
-
const login = cfg.claudeCodeLogin === true;
|
|
650
|
-
const env = login ? loginChildEnv(buildEnv(cfg.env)) : buildEnv(cfg.env);
|
|
651
|
-
const artifacts = createArtifacts();
|
|
652
|
-
const onProgress = cfg.onProgress;
|
|
653
|
-
let mcpServers = cfg.mcpServers;
|
|
654
|
-
let allowedTools = cfg.allowedTools;
|
|
655
|
-
if (!mcpServers && params.tools.length > 0) {
|
|
656
|
-
const bridge = await createToolMcpServer(params.tools);
|
|
657
|
-
mcpServers = { ggui: bridge.server };
|
|
658
|
-
allowedTools = bridge.allowedToolNames;
|
|
659
|
-
}
|
|
660
|
-
for await (const message of query({
|
|
661
|
-
prompt: params.userPrompt,
|
|
662
|
-
options: {
|
|
663
|
-
cwd: cfg.cwd,
|
|
664
|
-
env,
|
|
665
|
-
model: params.model,
|
|
666
|
-
maxTurns: params.maxTurns,
|
|
667
|
-
systemPrompt: params.systemPrompt,
|
|
668
|
-
...mcpServers && { mcpServers },
|
|
669
|
-
...cfg.agents && { agents: cfg.agents },
|
|
670
|
-
// ggui#1714 — no CLI built-ins unless asked for, no host settings, no permission bypass.
|
|
671
|
-
...sdkToolPins({ mcpServers, allowedTools, builtinTools: cfg.builtinTools }),
|
|
672
|
-
...cfg.cliPath && { pathToClaudeCodeExecutable: cfg.cliPath },
|
|
673
|
-
...cfg.stderr && { stderr: cfg.stderr },
|
|
674
|
-
// ggui#1185 — tool-less, config-less, non-bare; the model is pinned above.
|
|
675
|
-
...login ? claudeCodeLoginQueryOptions() : {}
|
|
676
|
-
}
|
|
677
|
-
})) {
|
|
678
|
-
processMessage(
|
|
679
|
-
message,
|
|
680
|
-
artifacts,
|
|
681
|
-
onProgress,
|
|
682
|
-
params.maxTurns
|
|
683
|
-
);
|
|
684
|
-
}
|
|
685
|
-
const generationTimeMs = Date.now() - startTime;
|
|
686
|
-
const totalCacheIn = artifacts.inputTokens + artifacts.cacheCreationTokens + artifacts.cacheReadTokens;
|
|
687
|
-
const cacheReadPct = totalCacheIn > 0 ? Math.round(artifacts.cacheReadTokens / totalCacheIn * 100) : 0;
|
|
688
|
-
console.log(
|
|
689
|
-
`[claude-sdk] cache: created=${artifacts.cacheCreationTokens} read=${artifacts.cacheReadTokens} input=${artifacts.inputTokens} output=${artifacts.outputTokens} turns=${artifacts.turnCount} cache-read-pct=${cacheReadPct}%`
|
|
690
|
-
);
|
|
691
|
-
if (!artifacts.compiledCode) {
|
|
692
|
-
const wasExhausted = artifacts.turnCount >= params.maxTurns;
|
|
693
|
-
throw new Error(
|
|
694
|
-
wasExhausted ? `Generation used all ${params.maxTurns} turns without producing compiled code.` : "Generation completed without compiled code"
|
|
695
|
-
);
|
|
696
|
-
}
|
|
697
|
-
return {
|
|
698
|
-
compiledCode: artifacts.compiledCode,
|
|
699
|
-
sourceCode: artifacts.sourceCode,
|
|
700
|
-
tokens: {
|
|
701
|
-
input: artifacts.inputTokens,
|
|
702
|
-
output: artifacts.outputTokens,
|
|
703
|
-
total: artifacts.inputTokens + artifacts.cacheCreationTokens + artifacts.cacheReadTokens + artifacts.outputTokens
|
|
704
|
-
},
|
|
705
|
-
generationTimeMs,
|
|
706
|
-
turnsUsed: artifacts.turnCount,
|
|
707
|
-
rawCostUsd: artifacts.estimatedCostUsd,
|
|
708
|
-
stream: artifacts.stream,
|
|
709
|
-
generatorMeta: artifacts.generatorMeta,
|
|
710
|
-
subagentsUsed: artifacts.subagentsUsed,
|
|
711
|
-
cacheCreationTokens: artifacts.cacheCreationTokens,
|
|
712
|
-
cacheReadTokens: artifacts.cacheReadTokens,
|
|
713
|
-
sdkSessionId: artifacts.sdkSessionId
|
|
714
|
-
};
|
|
715
|
-
}
|
|
716
|
-
};
|
|
717
|
-
}
|
|
718
|
-
});
|
|
719
|
-
|
|
720
|
-
// src/adapters/openai/tokens.ts
|
|
721
|
-
function splitOpenAiUsage(inputTokensInclCached, outputTokens, cachedTokens) {
|
|
722
|
-
return splitCacheInclusiveUsage(inputTokensInclCached, outputTokens, cachedTokens);
|
|
723
|
-
}
|
|
724
|
-
function splitCacheInclusiveUsage(inputTokensInclCached, outputTokens, cachedTokens) {
|
|
725
|
-
const cacheRead = Math.min(
|
|
726
|
-
Math.max(cachedTokens, 0),
|
|
727
|
-
Math.max(inputTokensInclCached, 0)
|
|
728
|
-
);
|
|
729
|
-
const nonCachedInput = Math.max(inputTokensInclCached, 0) - cacheRead;
|
|
730
|
-
return {
|
|
731
|
-
tokens: {
|
|
732
|
-
input: nonCachedInput,
|
|
733
|
-
output: outputTokens,
|
|
734
|
-
total: nonCachedInput + cacheRead + outputTokens
|
|
735
|
-
},
|
|
736
|
-
cacheReadTokens: cacheRead
|
|
737
|
-
};
|
|
738
|
-
}
|
|
739
|
-
var init_tokens = __esm({
|
|
740
|
-
"src/adapters/openai/tokens.ts"() {
|
|
741
|
-
}
|
|
742
|
-
});
|
|
743
|
-
|
|
744
|
-
// src/adapters/openai/raw.ts
|
|
745
|
-
var raw_exports2 = {};
|
|
746
|
-
__export(raw_exports2, {
|
|
747
|
-
OpenAiRawAdapter: () => OpenAiRawAdapter
|
|
748
|
-
});
|
|
749
|
-
async function loadOpenAI() {
|
|
750
|
-
return import('openai');
|
|
751
|
-
}
|
|
752
|
-
function toResponsesTool(def) {
|
|
753
|
-
return {
|
|
754
|
-
type: "function",
|
|
755
|
-
name: def.name,
|
|
756
|
-
description: def.description,
|
|
757
|
-
parameters: zodToJsonSchema(def.inputSchema),
|
|
758
|
-
strict: false
|
|
759
|
-
};
|
|
760
|
-
}
|
|
761
|
-
var OpenAiRawAdapter;
|
|
762
|
-
var init_raw2 = __esm({
|
|
763
|
-
"src/adapters/openai/raw.ts"() {
|
|
764
|
-
init_base();
|
|
765
|
-
init_tool_bridge();
|
|
766
|
-
init_tokens();
|
|
767
|
-
init_extract_code();
|
|
768
|
-
OpenAiRawAdapter = class extends GeneratorAdapter {
|
|
769
|
-
provider = "openai";
|
|
770
|
-
mode = "raw";
|
|
771
|
-
displayName = "OpenAI (Raw API)";
|
|
772
|
-
client = null;
|
|
773
|
-
constructor(config = {}) {
|
|
774
|
-
super(config);
|
|
775
|
-
}
|
|
776
|
-
isAvailable() {
|
|
777
|
-
return hasCredentials(this.config, "OPENAI_API_KEY");
|
|
778
|
-
}
|
|
779
|
-
async generate(params) {
|
|
780
|
-
const startTime = Date.now();
|
|
781
|
-
if (!this.client) {
|
|
782
|
-
const { default: OpenAIClient } = await loadOpenAI();
|
|
783
|
-
this.client = new OpenAIClient({
|
|
784
|
-
apiKey: this.config.apiKey || process.env.OPENAI_API_KEY
|
|
785
|
-
});
|
|
786
|
-
}
|
|
787
|
-
const tools = params.tools.map(toResponsesTool);
|
|
788
|
-
const capture = createCapture();
|
|
789
|
-
let totalInputTokens = 0;
|
|
790
|
-
let totalOutputTokens = 0;
|
|
791
|
-
let totalCachedInputTokens = 0;
|
|
792
|
-
let turnsUsed = 0;
|
|
793
|
-
let allTextOutput = "";
|
|
794
|
-
let response = await this.client.responses.create({
|
|
795
|
-
model: params.model,
|
|
796
|
-
instructions: params.systemPrompt,
|
|
797
|
-
input: [{ role: "user", content: params.userPrompt }],
|
|
798
|
-
tools,
|
|
799
|
-
store: true
|
|
800
|
-
// Required for previous_response_id to work on subsequent turns
|
|
801
|
-
});
|
|
802
|
-
for (let turn = 0; turn < params.maxTurns; turn++) {
|
|
803
|
-
turnsUsed = turn + 1;
|
|
804
|
-
if (response.usage) {
|
|
805
|
-
totalInputTokens += response.usage.input_tokens ?? 0;
|
|
806
|
-
totalOutputTokens += response.usage.output_tokens ?? 0;
|
|
807
|
-
totalCachedInputTokens += response.usage.input_tokens_details?.cached_tokens ?? 0;
|
|
808
|
-
}
|
|
809
|
-
const output = response.output ?? [];
|
|
810
|
-
const functionCalls = output.filter(
|
|
811
|
-
(item) => item.type === "function_call"
|
|
812
|
-
);
|
|
813
|
-
for (const item of output) {
|
|
814
|
-
if (item.type === "message" && "content" in item && item.content) {
|
|
815
|
-
for (const part of item.content) {
|
|
816
|
-
if (part.type === "output_text" && part.text) {
|
|
817
|
-
allTextOutput += part.text + "\n";
|
|
818
|
-
captureMarkers(capture, part.text);
|
|
819
|
-
}
|
|
820
|
-
}
|
|
821
|
-
}
|
|
822
|
-
}
|
|
823
|
-
if (functionCalls.length === 0) break;
|
|
824
|
-
const nextInput = [];
|
|
825
|
-
for (const fc of functionCalls) {
|
|
826
|
-
const toolDef = params.tools.find((t) => t.name === fc.name);
|
|
827
|
-
if (!toolDef) {
|
|
828
|
-
nextInput.push({
|
|
829
|
-
type: "function_call_output",
|
|
830
|
-
call_id: fc.call_id,
|
|
831
|
-
output: JSON.stringify({ error: `Tool '${fc.name}' not found` })
|
|
832
|
-
});
|
|
833
|
-
continue;
|
|
834
|
-
}
|
|
835
|
-
let args = {};
|
|
836
|
-
try {
|
|
837
|
-
args = JSON.parse(fc.arguments || "{}");
|
|
838
|
-
} catch {
|
|
839
|
-
}
|
|
840
|
-
captureSourceCode(capture, fc.name, args);
|
|
841
|
-
const result = await toolDef.handler(args);
|
|
842
|
-
captureCompiledCode(capture, fc.name, result);
|
|
843
|
-
nextInput.push({
|
|
844
|
-
type: "function_call_output",
|
|
845
|
-
call_id: fc.call_id,
|
|
846
|
-
output: result.content[0]?.text ?? ""
|
|
847
|
-
});
|
|
848
|
-
}
|
|
849
|
-
response = await this.client.responses.create({
|
|
850
|
-
model: params.model,
|
|
851
|
-
instructions: params.systemPrompt,
|
|
852
|
-
input: nextInput,
|
|
853
|
-
tools,
|
|
854
|
-
previous_response_id: response.id,
|
|
855
|
-
store: true
|
|
856
|
-
});
|
|
857
|
-
}
|
|
858
|
-
if (!capture.compiledCode && allTextOutput) {
|
|
859
|
-
captureMarkers(capture, allTextOutput);
|
|
860
|
-
await extractCodeFromText(allTextOutput, params.tools, capture);
|
|
861
|
-
}
|
|
862
|
-
if (!capture.compiledCode) {
|
|
863
|
-
await compileLastResort(capture, allTextOutput);
|
|
864
|
-
}
|
|
865
|
-
if (!capture.compiledCode) {
|
|
866
|
-
throw new Error("OpenAI raw adapter: no compiled code produced after all turns");
|
|
867
|
-
}
|
|
868
|
-
return {
|
|
869
|
-
compiledCode: capture.compiledCode,
|
|
870
|
-
sourceCode: capture.sourceCode,
|
|
871
|
-
stream: capture.stream,
|
|
872
|
-
generatorMeta: capture.generatorMeta,
|
|
873
|
-
...splitOpenAiUsage(
|
|
874
|
-
totalInputTokens,
|
|
875
|
-
totalOutputTokens,
|
|
876
|
-
totalCachedInputTokens
|
|
877
|
-
),
|
|
878
|
-
generationTimeMs: Date.now() - startTime,
|
|
879
|
-
turnsUsed
|
|
880
|
-
};
|
|
881
|
-
}
|
|
882
|
-
};
|
|
883
|
-
}
|
|
884
|
-
});
|
|
885
|
-
|
|
886
|
-
// src/adapters/openai/sdk.ts
|
|
887
|
-
var sdk_exports2 = {};
|
|
888
|
-
__export(sdk_exports2, {
|
|
889
|
-
OpenAiSdkAdapter: () => OpenAiSdkAdapter
|
|
890
|
-
});
|
|
891
|
-
async function loadOpenAIAgents() {
|
|
892
|
-
return import('@openai/agents');
|
|
893
|
-
}
|
|
894
|
-
var OpenAiSdkAdapter;
|
|
895
|
-
var init_sdk2 = __esm({
|
|
896
|
-
"src/adapters/openai/sdk.ts"() {
|
|
897
|
-
init_base();
|
|
898
|
-
init_tokens();
|
|
899
|
-
init_extract_code();
|
|
900
|
-
OpenAiSdkAdapter = class extends GeneratorAdapter {
|
|
901
|
-
provider = "openai";
|
|
902
|
-
mode = "sdk";
|
|
903
|
-
displayName = "OpenAI (Agents SDK)";
|
|
904
|
-
constructor(config = {}) {
|
|
905
|
-
super(config);
|
|
906
|
-
}
|
|
907
|
-
isAvailable() {
|
|
908
|
-
return hasCredentials(this.config, "OPENAI_API_KEY");
|
|
909
|
-
}
|
|
910
|
-
async generate(params) {
|
|
911
|
-
const startTime = Date.now();
|
|
912
|
-
const apiKey = this.config.apiKey || process.env.OPENAI_API_KEY;
|
|
913
|
-
if (apiKey) process.env.OPENAI_API_KEY = apiKey;
|
|
914
|
-
const capture = createCapture();
|
|
915
|
-
const { Agent, run, tool } = await loadOpenAIAgents();
|
|
916
|
-
const wiredTools = params.tools.map(
|
|
917
|
-
(def) => tool({
|
|
918
|
-
name: def.name,
|
|
919
|
-
description: def.description,
|
|
920
|
-
parameters: def.inputSchema,
|
|
921
|
-
execute: async (args) => {
|
|
922
|
-
const typedArgs = args ?? {};
|
|
923
|
-
captureSourceCode(capture, def.name, typedArgs);
|
|
924
|
-
const result2 = await def.handler(typedArgs);
|
|
925
|
-
captureCompiledCode(capture, def.name, result2);
|
|
926
|
-
return result2.content[0]?.text ?? "";
|
|
927
|
-
}
|
|
928
|
-
})
|
|
929
|
-
);
|
|
930
|
-
const agent = new Agent({
|
|
931
|
-
name: "ui-generator",
|
|
932
|
-
instructions: params.systemPrompt,
|
|
933
|
-
model: params.model,
|
|
934
|
-
tools: wiredTools
|
|
935
|
-
});
|
|
936
|
-
const result = await run(agent, params.userPrompt, {
|
|
937
|
-
maxTurns: params.maxTurns
|
|
938
|
-
});
|
|
939
|
-
const finalOutput = String(result.finalOutput ?? "");
|
|
940
|
-
if (finalOutput) captureMarkers(capture, finalOutput);
|
|
941
|
-
if (!capture.compiledCode) {
|
|
942
|
-
await extractCodeFromText(finalOutput, params.tools, capture);
|
|
943
|
-
if (!capture.compiledCode) {
|
|
944
|
-
throw new Error("OpenAI SDK adapter: no compiled code produced after all turns");
|
|
945
|
-
}
|
|
946
|
-
}
|
|
947
|
-
const usage = result.state.usage;
|
|
948
|
-
const inputTokens = usage.inputTokens;
|
|
949
|
-
const outputTokens = usage.outputTokens;
|
|
950
|
-
const cachedInputTokens = (usage.inputTokensDetails ?? []).reduce(
|
|
951
|
-
(sum, details) => sum + (details.cached_tokens ?? 0),
|
|
952
|
-
0
|
|
953
|
-
);
|
|
954
|
-
return {
|
|
955
|
-
compiledCode: capture.compiledCode,
|
|
956
|
-
sourceCode: capture.sourceCode,
|
|
957
|
-
stream: capture.stream,
|
|
958
|
-
generatorMeta: capture.generatorMeta,
|
|
959
|
-
...splitOpenAiUsage(inputTokens, outputTokens, cachedInputTokens),
|
|
960
|
-
generationTimeMs: Date.now() - startTime,
|
|
961
|
-
turnsUsed: result.rawResponses?.length ?? 0
|
|
962
|
-
};
|
|
963
|
-
}
|
|
964
|
-
};
|
|
965
|
-
}
|
|
966
|
-
});
|
|
967
|
-
|
|
968
|
-
// src/adapters/google/raw.ts
|
|
969
|
-
var raw_exports3 = {};
|
|
970
|
-
__export(raw_exports3, {
|
|
971
|
-
GoogleRawAdapter: () => GoogleRawAdapter
|
|
972
|
-
});
|
|
973
|
-
async function loadGoogleGenAI() {
|
|
974
|
-
return import('@google/genai');
|
|
975
|
-
}
|
|
976
|
-
function toInteractionTool(def) {
|
|
977
|
-
return {
|
|
978
|
-
type: "function",
|
|
979
|
-
name: def.name,
|
|
980
|
-
description: def.description,
|
|
981
|
-
parameters: zodToJsonSchema(def.inputSchema)
|
|
982
|
-
};
|
|
983
|
-
}
|
|
984
|
-
var GoogleRawAdapter;
|
|
985
|
-
var init_raw3 = __esm({
|
|
986
|
-
"src/adapters/google/raw.ts"() {
|
|
987
|
-
init_base();
|
|
988
|
-
init_tool_bridge();
|
|
989
|
-
init_extract_code();
|
|
990
|
-
GoogleRawAdapter = class extends GeneratorAdapter {
|
|
991
|
-
provider = "google";
|
|
992
|
-
mode = "raw";
|
|
993
|
-
displayName = "Google Gemini (Interactions API)";
|
|
994
|
-
client = null;
|
|
995
|
-
constructor(config = {}) {
|
|
996
|
-
super(config);
|
|
997
|
-
}
|
|
998
|
-
isAvailable() {
|
|
999
|
-
return hasCredentials(this.config, "GEMINI_API_KEY", "GOOGLE_API_KEY");
|
|
1000
|
-
}
|
|
1001
|
-
async generate(params) {
|
|
1002
|
-
const startTime = Date.now();
|
|
1003
|
-
if (!this.client) {
|
|
1004
|
-
const { GoogleGenAI } = await loadGoogleGenAI();
|
|
1005
|
-
this.client = new GoogleGenAI({
|
|
1006
|
-
apiKey: this.config.apiKey || process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY,
|
|
1007
|
-
httpOptions: { timeout: 3e5 }
|
|
1008
|
-
// 5 min — Pro models can be slow
|
|
1009
|
-
});
|
|
1010
|
-
}
|
|
1011
|
-
const tools = params.tools.map(toInteractionTool);
|
|
1012
|
-
const capture = createCapture();
|
|
1013
|
-
let totalInputTokens = 0;
|
|
1014
|
-
let totalOutputTokens = 0;
|
|
1015
|
-
let turnsUsed = 0;
|
|
1016
|
-
const thinkingLevel = this.config.thinkingLevel;
|
|
1017
|
-
const generationConfig = thinkingLevel ? { thinking_level: thinkingLevel } : void 0;
|
|
1018
|
-
let interaction = await this.client.interactions.create({
|
|
1019
|
-
model: params.model,
|
|
1020
|
-
system_instruction: params.systemPrompt,
|
|
1021
|
-
tools,
|
|
1022
|
-
input: params.userPrompt,
|
|
1023
|
-
...generationConfig ? { generation_config: generationConfig } : {}
|
|
1024
|
-
});
|
|
1025
|
-
for (let turn = 0; turn < params.maxTurns; turn++) {
|
|
1026
|
-
turnsUsed = turn + 1;
|
|
1027
|
-
if (interaction.usage) {
|
|
1028
|
-
totalInputTokens += interaction.usage.total_input_tokens ?? 0;
|
|
1029
|
-
totalOutputTokens += interaction.usage.total_output_tokens ?? 0;
|
|
1030
|
-
}
|
|
1031
|
-
for (const step of interaction.steps) {
|
|
1032
|
-
if (step.type === "model_output") {
|
|
1033
|
-
for (const content of step.content ?? []) {
|
|
1034
|
-
if (content.type === "text") {
|
|
1035
|
-
captureMarkers(capture, content.text);
|
|
1036
|
-
}
|
|
1037
|
-
}
|
|
1038
|
-
}
|
|
1039
|
-
}
|
|
1040
|
-
const functionCalls = interaction.steps.filter(
|
|
1041
|
-
(s) => s.type === "function_call"
|
|
1042
|
-
);
|
|
1043
|
-
if (functionCalls.length === 0) break;
|
|
1044
|
-
const results = [];
|
|
1045
|
-
for (const fc of functionCalls) {
|
|
1046
|
-
const toolDef = params.tools.find((t) => t.name === fc.name);
|
|
1047
|
-
if (!toolDef) {
|
|
1048
|
-
results.push({
|
|
1049
|
-
type: "function_result",
|
|
1050
|
-
call_id: fc.id,
|
|
1051
|
-
name: fc.name,
|
|
1052
|
-
result: JSON.stringify({ error: `Tool '${fc.name}' not found` }),
|
|
1053
|
-
is_error: true
|
|
1054
|
-
});
|
|
1055
|
-
continue;
|
|
1056
|
-
}
|
|
1057
|
-
const args = toolArgsToJsonObject(fc.arguments);
|
|
1058
|
-
captureSourceCode(capture, fc.name, args);
|
|
1059
|
-
const result = await toolDef.handler(args);
|
|
1060
|
-
captureCompiledCode(capture, fc.name, result);
|
|
1061
|
-
results.push({
|
|
1062
|
-
type: "function_result",
|
|
1063
|
-
call_id: fc.id,
|
|
1064
|
-
name: fc.name,
|
|
1065
|
-
result: result.content[0]?.text ?? ""
|
|
1066
|
-
});
|
|
1067
|
-
}
|
|
1068
|
-
interaction = await this.client.interactions.create({
|
|
1069
|
-
model: params.model,
|
|
1070
|
-
previous_interaction_id: interaction.id,
|
|
1071
|
-
input: results,
|
|
1072
|
-
...generationConfig ? { generation_config: generationConfig } : {}
|
|
1073
|
-
});
|
|
1074
|
-
}
|
|
1075
|
-
if (!capture.compiledCode) {
|
|
1076
|
-
throw new Error("Google raw adapter: no compiled code produced after all turns");
|
|
1077
|
-
}
|
|
1078
|
-
return {
|
|
1079
|
-
compiledCode: capture.compiledCode,
|
|
1080
|
-
sourceCode: capture.sourceCode,
|
|
1081
|
-
stream: capture.stream,
|
|
1082
|
-
generatorMeta: capture.generatorMeta,
|
|
1083
|
-
tokens: {
|
|
1084
|
-
input: totalInputTokens,
|
|
1085
|
-
output: totalOutputTokens,
|
|
1086
|
-
total: totalInputTokens + totalOutputTokens
|
|
1087
|
-
},
|
|
1088
|
-
generationTimeMs: Date.now() - startTime,
|
|
1089
|
-
turnsUsed
|
|
1090
|
-
};
|
|
1091
|
-
}
|
|
1092
|
-
};
|
|
1093
|
-
}
|
|
1094
|
-
});
|
|
1095
|
-
|
|
1096
|
-
// src/adapters/google/sdk.ts
|
|
1097
|
-
var sdk_exports3 = {};
|
|
1098
|
-
__export(sdk_exports3, {
|
|
1099
|
-
GoogleSdkAdapter: () => GoogleSdkAdapter,
|
|
1100
|
-
runAdkLoop: () => runAdkLoop
|
|
1101
|
-
});
|
|
1102
|
-
async function runAdkLoop(params) {
|
|
1103
|
-
const startTime = Date.now();
|
|
1104
|
-
const { FunctionTool, Gemini, LlmAgent, InMemoryRunner, isFinalResponse } = await import('@google/adk');
|
|
1105
|
-
const capture = createCapture();
|
|
1106
|
-
const adkTools = params.tools.map(
|
|
1107
|
-
(def) => new FunctionTool({
|
|
1108
|
-
name: def.name,
|
|
1109
|
-
description: def.description,
|
|
1110
|
-
// Pass Zod schema directly — ADK accepts ZodObject natively
|
|
1111
|
-
parameters: def.inputSchema,
|
|
1112
|
-
execute: async (args) => {
|
|
1113
|
-
const typedArgs = args ?? {};
|
|
1114
|
-
captureSourceCode(capture, def.name, typedArgs);
|
|
1115
|
-
const result = await def.handler(typedArgs);
|
|
1116
|
-
captureCompiledCode(capture, def.name, result);
|
|
1117
|
-
return result.content[0]?.text ?? "";
|
|
1118
|
-
}
|
|
1119
|
-
})
|
|
1120
|
-
);
|
|
1121
|
-
const model = params.apiKey ? new Gemini({ model: params.model, apiKey: params.apiKey }) : params.model;
|
|
1122
|
-
const agent = new LlmAgent({
|
|
1123
|
-
name: "ui_generator",
|
|
1124
|
-
model,
|
|
1125
|
-
instruction: params.systemPrompt,
|
|
1126
|
-
tools: adkTools
|
|
1127
|
-
});
|
|
1128
|
-
const runner = new InMemoryRunner({ agent, appName: "ggui_generator" });
|
|
1129
|
-
const session = await runner.sessionService.createSession({
|
|
1130
|
-
appName: "ggui_generator",
|
|
1131
|
-
userId: "benchmark"
|
|
1132
|
-
});
|
|
1133
|
-
const userMessage = {
|
|
1134
|
-
role: "user",
|
|
1135
|
-
parts: [{ text: params.userPrompt }]
|
|
1136
|
-
};
|
|
1137
|
-
let finalText = "";
|
|
1138
|
-
let turnCount = 0;
|
|
1139
|
-
let totalInputTokens = 0;
|
|
1140
|
-
let totalOutputTokens = 0;
|
|
1141
|
-
for await (const event of runner.runAsync({
|
|
1142
|
-
userId: "benchmark",
|
|
1143
|
-
sessionId: session.id,
|
|
1144
|
-
newMessage: userMessage
|
|
1145
|
-
})) {
|
|
1146
|
-
turnCount++;
|
|
1147
|
-
const usage = event.usageMetadata;
|
|
1148
|
-
if (usage) {
|
|
1149
|
-
totalInputTokens += usage.promptTokenCount ?? 0;
|
|
1150
|
-
totalOutputTokens += usage.candidatesTokenCount ?? 0;
|
|
1151
|
-
}
|
|
1152
|
-
if (event.content?.parts) {
|
|
1153
|
-
const text = event.content.parts.map((p) => p.text ?? "").join("");
|
|
1154
|
-
if (text) captureMarkers(capture, text);
|
|
1155
|
-
}
|
|
1156
|
-
if (isFinalResponse(event)) {
|
|
1157
|
-
const parts = event.content?.parts;
|
|
1158
|
-
finalText = parts?.map((p) => p.text ?? "").join("") ?? "";
|
|
1159
|
-
}
|
|
1160
|
-
}
|
|
1161
|
-
if (finalText) captureMarkers(capture, finalText);
|
|
1162
|
-
if (!capture.compiledCode) {
|
|
1163
|
-
throw new Error("Google ADK adapter: no compiled code produced after all turns");
|
|
1164
|
-
}
|
|
1165
|
-
return {
|
|
1166
|
-
compiledCode: capture.compiledCode,
|
|
1167
|
-
sourceCode: capture.sourceCode,
|
|
1168
|
-
stream: capture.stream,
|
|
1169
|
-
generatorMeta: capture.generatorMeta,
|
|
1170
|
-
tokens: {
|
|
1171
|
-
input: totalInputTokens,
|
|
1172
|
-
output: totalOutputTokens,
|
|
1173
|
-
total: totalInputTokens + totalOutputTokens
|
|
1174
|
-
},
|
|
1175
|
-
generationTimeMs: Date.now() - startTime,
|
|
1176
|
-
turnsUsed: turnCount
|
|
1177
|
-
};
|
|
1178
|
-
}
|
|
1179
|
-
var GoogleSdkAdapter;
|
|
1180
|
-
var init_sdk3 = __esm({
|
|
1181
|
-
"src/adapters/google/sdk.ts"() {
|
|
1182
|
-
init_base();
|
|
1183
|
-
init_extract_code();
|
|
1184
|
-
GoogleSdkAdapter = class extends GeneratorAdapter {
|
|
1185
|
-
provider = "google";
|
|
1186
|
-
mode = "sdk";
|
|
1187
|
-
displayName = "Google Gemini (ADK)";
|
|
1188
|
-
constructor(config = {}) {
|
|
1189
|
-
super(config);
|
|
1190
|
-
}
|
|
1191
|
-
isAvailable() {
|
|
1192
|
-
return hasCredentials(this.config, "GEMINI_API_KEY", "GOOGLE_API_KEY");
|
|
1193
|
-
}
|
|
1194
|
-
async generate(params) {
|
|
1195
|
-
const apiKey = this.config.apiKey || process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY;
|
|
1196
|
-
return runAdkLoop({
|
|
1197
|
-
systemPrompt: params.systemPrompt,
|
|
1198
|
-
userPrompt: params.userPrompt,
|
|
1199
|
-
model: params.model,
|
|
1200
|
-
tools: params.tools,
|
|
1201
|
-
apiKey
|
|
1202
|
-
});
|
|
1203
|
-
}
|
|
1204
|
-
};
|
|
1205
|
-
}
|
|
1206
|
-
});
|
|
1207
|
-
|
|
1208
|
-
// src/adapters/openrouter/types.ts
|
|
1209
|
-
var OpenRouterError;
|
|
1210
|
-
var init_types = __esm({
|
|
1211
|
-
"src/adapters/openrouter/types.ts"() {
|
|
1212
|
-
OpenRouterError = class extends Error {
|
|
1213
|
-
constructor(message, status, code, headers) {
|
|
1214
|
-
super(message);
|
|
1215
|
-
this.status = status;
|
|
1216
|
-
this.code = code;
|
|
1217
|
-
this.headers = headers;
|
|
1218
|
-
this.name = "OpenRouterError";
|
|
1219
|
-
}
|
|
1220
|
-
status;
|
|
1221
|
-
code;
|
|
1222
|
-
headers;
|
|
1223
|
-
get isTransient() {
|
|
1224
|
-
return this.status === 408 || this.status === 429 || this.status === 502 || this.status === 503;
|
|
1225
|
-
}
|
|
1226
|
-
};
|
|
1227
|
-
}
|
|
1228
|
-
});
|
|
1229
|
-
|
|
1230
|
-
// src/adapters/openrouter/client.ts
|
|
1231
|
-
var DEFAULT_BASE_URL, OpenRouterClient;
|
|
1232
|
-
var init_client2 = __esm({
|
|
1233
|
-
"src/adapters/openrouter/client.ts"() {
|
|
1234
|
-
init_types();
|
|
1235
|
-
DEFAULT_BASE_URL = "https://openrouter.ai/api/v1";
|
|
1236
|
-
OpenRouterClient = class {
|
|
1237
|
-
constructor(config) {
|
|
1238
|
-
this.config = config;
|
|
1239
|
-
this.baseUrl = config.baseUrl ?? process.env.OPENROUTER_BASE_URL ?? DEFAULT_BASE_URL;
|
|
1240
|
-
this.headers = {
|
|
1241
|
-
"Authorization": `Bearer ${config.apiKey}`,
|
|
1242
|
-
"Content-Type": "application/json",
|
|
1243
|
-
"HTTP-Referer": config.siteUrl ?? process.env.OPENROUTER_SITE_URL ?? "https://ggui.ai",
|
|
1244
|
-
"X-Title": config.siteName ?? process.env.OPENROUTER_SITE_NAME ?? "ggui"
|
|
1245
|
-
};
|
|
1246
|
-
}
|
|
1247
|
-
config;
|
|
1248
|
-
baseUrl;
|
|
1249
|
-
headers;
|
|
1250
|
-
/**
|
|
1251
|
-
* Non-streaming chat completion.
|
|
1252
|
-
*/
|
|
1253
|
-
async chatCompletion(params) {
|
|
1254
|
-
const body = { ...params, stream: false };
|
|
1255
|
-
const response = await fetch(`${this.baseUrl}/chat/completions`, {
|
|
1256
|
-
method: "POST",
|
|
1257
|
-
headers: this.headers,
|
|
1258
|
-
body: JSON.stringify(body)
|
|
1259
|
-
});
|
|
1260
|
-
if (!response.ok) {
|
|
1261
|
-
const errorBody = await response.json().catch(() => ({ error: { message: response.statusText } }));
|
|
1262
|
-
const message = errorBody.error?.message ?? response.statusText;
|
|
1263
|
-
throw new OpenRouterError(message, response.status, void 0, response.headers);
|
|
1264
|
-
}
|
|
1265
|
-
return response.json();
|
|
1266
|
-
}
|
|
1267
|
-
/**
|
|
1268
|
-
* Streaming chat completion via SSE.
|
|
1269
|
-
* Yields delta chunks, accumulates the final usage from the last chunk.
|
|
1270
|
-
*/
|
|
1271
|
-
async *chatCompletionStream(params) {
|
|
1272
|
-
const body = { ...params, stream: true };
|
|
1273
|
-
const response = await fetch(`${this.baseUrl}/chat/completions`, {
|
|
1274
|
-
method: "POST",
|
|
1275
|
-
headers: this.headers,
|
|
1276
|
-
body: JSON.stringify(body)
|
|
1277
|
-
});
|
|
1278
|
-
if (!response.ok) {
|
|
1279
|
-
const errorBody = await response.json().catch(() => ({ error: { message: response.statusText } }));
|
|
1280
|
-
const message = errorBody.error?.message ?? response.statusText;
|
|
1281
|
-
throw new OpenRouterError(message, response.status, void 0, response.headers);
|
|
1282
|
-
}
|
|
1283
|
-
if (!response.body) {
|
|
1284
|
-
throw new OpenRouterError("No response body for streaming request", 500);
|
|
1285
|
-
}
|
|
1286
|
-
const reader = response.body.getReader();
|
|
1287
|
-
const decoder = new TextDecoder();
|
|
1288
|
-
let buffer = "";
|
|
1289
|
-
try {
|
|
1290
|
-
while (true) {
|
|
1291
|
-
const { done, value } = await reader.read();
|
|
1292
|
-
if (done) break;
|
|
1293
|
-
buffer += decoder.decode(value, { stream: true });
|
|
1294
|
-
const lines = buffer.split("\n");
|
|
1295
|
-
buffer = lines.pop() ?? "";
|
|
1296
|
-
for (const line of lines) {
|
|
1297
|
-
const trimmed = line.trim();
|
|
1298
|
-
if (!trimmed || trimmed.startsWith(":")) continue;
|
|
1299
|
-
if (trimmed === "data: [DONE]") return;
|
|
1300
|
-
if (!trimmed.startsWith("data: ")) continue;
|
|
1301
|
-
const json = trimmed.slice("data: ".length);
|
|
1302
|
-
try {
|
|
1303
|
-
yield JSON.parse(json);
|
|
1304
|
-
} catch {
|
|
1305
|
-
}
|
|
1306
|
-
}
|
|
1307
|
-
}
|
|
1308
|
-
} finally {
|
|
1309
|
-
reader.releaseLock();
|
|
1310
|
-
}
|
|
1311
|
-
}
|
|
1312
|
-
};
|
|
1313
|
-
}
|
|
1314
|
-
});
|
|
1315
|
-
|
|
1316
|
-
// src/adapters/openrouter/raw.ts
|
|
1317
|
-
var raw_exports4 = {};
|
|
1318
|
-
__export(raw_exports4, {
|
|
1319
|
-
OpenRouterRawAdapter: () => OpenRouterRawAdapter
|
|
1320
|
-
});
|
|
1321
|
-
function toOpenRouterTool(def) {
|
|
1322
|
-
return {
|
|
1323
|
-
type: "function",
|
|
1324
|
-
function: {
|
|
1325
|
-
name: def.name,
|
|
1326
|
-
description: def.description,
|
|
1327
|
-
parameters: zodToJsonSchema(def.inputSchema)
|
|
1328
|
-
}
|
|
1329
|
-
};
|
|
1330
|
-
}
|
|
1331
|
-
var OpenRouterRawAdapter;
|
|
1332
|
-
var init_raw4 = __esm({
|
|
1333
|
-
"src/adapters/openrouter/raw.ts"() {
|
|
1334
|
-
init_base();
|
|
1335
|
-
init_tool_bridge();
|
|
1336
|
-
init_extract_code();
|
|
1337
|
-
init_client2();
|
|
1338
|
-
OpenRouterRawAdapter = class extends GeneratorAdapter {
|
|
1339
|
-
provider = "openrouter";
|
|
1340
|
-
mode = "raw";
|
|
1341
|
-
displayName = "OpenRouter (Raw API)";
|
|
1342
|
-
client = null;
|
|
1343
|
-
constructor(config = {}) {
|
|
1344
|
-
super(config);
|
|
1345
|
-
}
|
|
1346
|
-
isAvailable() {
|
|
1347
|
-
return hasCredentials(this.config, "OPENROUTER_API_KEY");
|
|
1348
|
-
}
|
|
1349
|
-
async generate(params) {
|
|
1350
|
-
const startTime = Date.now();
|
|
1351
|
-
if (!this.client) {
|
|
1352
|
-
this.client = new OpenRouterClient({
|
|
1353
|
-
apiKey: this.config.apiKey || process.env.OPENROUTER_API_KEY
|
|
1354
|
-
});
|
|
1355
|
-
}
|
|
1356
|
-
const tools = params.tools.map(toOpenRouterTool);
|
|
1357
|
-
const capture = createCapture();
|
|
1358
|
-
let totalInputTokens = 0;
|
|
1359
|
-
let totalOutputTokens = 0;
|
|
1360
|
-
let cacheCreationTokens;
|
|
1361
|
-
let cacheReadTokens;
|
|
1362
|
-
let turnsUsed = 0;
|
|
1363
|
-
let allTextOutput = "";
|
|
1364
|
-
const modelId = params.model;
|
|
1365
|
-
const isAnthropicModel = modelId.includes("anthropic/") || modelId.includes("claude");
|
|
1366
|
-
const systemMessage = isAnthropicModel ? {
|
|
1367
|
-
role: "system",
|
|
1368
|
-
content: [{ type: "text", text: params.systemPrompt, cache_control: { type: "ephemeral" } }]
|
|
1369
|
-
} : { role: "system", content: params.systemPrompt };
|
|
1370
|
-
const messages = [
|
|
1371
|
-
systemMessage,
|
|
1372
|
-
{ role: "user", content: params.userPrompt }
|
|
1373
|
-
];
|
|
1374
|
-
for (let turn = 0; turn < params.maxTurns; turn++) {
|
|
1375
|
-
turnsUsed = turn + 1;
|
|
1376
|
-
const response = await this.client.chatCompletion({
|
|
1377
|
-
model: modelId,
|
|
1378
|
-
messages,
|
|
1379
|
-
tools: tools.length > 0 ? tools : void 0,
|
|
1380
|
-
tool_choice: tools.length > 0 ? "auto" : void 0,
|
|
1381
|
-
max_tokens: 16384
|
|
1382
|
-
});
|
|
1383
|
-
if (response.usage) {
|
|
1384
|
-
totalInputTokens += response.usage.prompt_tokens;
|
|
1385
|
-
totalOutputTokens += response.usage.completion_tokens;
|
|
1386
|
-
if (response.usage.cache_creation_input_tokens) {
|
|
1387
|
-
cacheCreationTokens = (cacheCreationTokens ?? 0) + response.usage.cache_creation_input_tokens;
|
|
1388
|
-
}
|
|
1389
|
-
if (response.usage.cache_read_input_tokens) {
|
|
1390
|
-
cacheReadTokens = (cacheReadTokens ?? 0) + response.usage.cache_read_input_tokens;
|
|
1391
|
-
}
|
|
1392
|
-
}
|
|
1393
|
-
const choice = response.choices[0];
|
|
1394
|
-
if (!choice) break;
|
|
1395
|
-
if (choice.message.content) {
|
|
1396
|
-
allTextOutput += choice.message.content + "\n";
|
|
1397
|
-
captureMarkers(capture, choice.message.content);
|
|
1398
|
-
}
|
|
1399
|
-
const toolCalls = choice.message.tool_calls;
|
|
1400
|
-
if (!toolCalls || toolCalls.length === 0) break;
|
|
1401
|
-
messages.push({
|
|
1402
|
-
role: "assistant",
|
|
1403
|
-
content: choice.message.content,
|
|
1404
|
-
tool_calls: toolCalls
|
|
1405
|
-
});
|
|
1406
|
-
for (const tc of toolCalls) {
|
|
1407
|
-
const toolDef = params.tools.find((t) => t.name === tc.function.name);
|
|
1408
|
-
if (!toolDef) {
|
|
1409
|
-
messages.push({
|
|
1410
|
-
role: "tool",
|
|
1411
|
-
tool_call_id: tc.id,
|
|
1412
|
-
content: JSON.stringify({ error: `Tool '${tc.function.name}' not found` })
|
|
1413
|
-
});
|
|
1414
|
-
continue;
|
|
1415
|
-
}
|
|
1416
|
-
let args = {};
|
|
1417
|
-
try {
|
|
1418
|
-
args = JSON.parse(tc.function.arguments || "{}");
|
|
1419
|
-
} catch {
|
|
1420
|
-
}
|
|
1421
|
-
captureSourceCode(capture, tc.function.name, args);
|
|
1422
|
-
const result = await toolDef.handler(args);
|
|
1423
|
-
captureCompiledCode(capture, tc.function.name, result);
|
|
1424
|
-
messages.push({
|
|
1425
|
-
role: "tool",
|
|
1426
|
-
tool_call_id: tc.id,
|
|
1427
|
-
content: result.content[0]?.text ?? ""
|
|
1428
|
-
});
|
|
1429
|
-
}
|
|
1430
|
-
}
|
|
1431
|
-
if (!capture.compiledCode && allTextOutput) {
|
|
1432
|
-
captureMarkers(capture, allTextOutput);
|
|
1433
|
-
await extractCodeFromText(allTextOutput, params.tools, capture);
|
|
1434
|
-
}
|
|
1435
|
-
if (!capture.compiledCode) {
|
|
1436
|
-
await compileLastResort(capture, allTextOutput);
|
|
1437
|
-
}
|
|
1438
|
-
if (!capture.compiledCode) {
|
|
1439
|
-
throw new Error("OpenRouter raw adapter: no compiled code produced after all turns");
|
|
1440
|
-
}
|
|
1441
|
-
return {
|
|
1442
|
-
compiledCode: capture.compiledCode,
|
|
1443
|
-
sourceCode: capture.sourceCode,
|
|
1444
|
-
stream: capture.stream,
|
|
1445
|
-
generatorMeta: capture.generatorMeta,
|
|
1446
|
-
tokens: {
|
|
1447
|
-
input: totalInputTokens,
|
|
1448
|
-
output: totalOutputTokens,
|
|
1449
|
-
total: totalInputTokens + totalOutputTokens
|
|
1450
|
-
},
|
|
1451
|
-
generationTimeMs: Date.now() - startTime,
|
|
1452
|
-
turnsUsed,
|
|
1453
|
-
cacheCreationTokens,
|
|
1454
|
-
cacheReadTokens
|
|
1455
|
-
};
|
|
1456
|
-
}
|
|
1457
|
-
};
|
|
1458
|
-
}
|
|
1459
|
-
});
|
|
1460
|
-
|
|
1461
|
-
// src/adapters/types.ts
|
|
1462
|
-
var PROVIDER_DISPLAY_NAMES = {
|
|
1463
|
-
claude: "Anthropic Claude",
|
|
1464
|
-
openai: "OpenAI",
|
|
1465
|
-
google: "Google Gemini",
|
|
1466
|
-
openrouter: "OpenRouter"
|
|
1467
|
-
};
|
|
1468
|
-
|
|
1469
|
-
// src/adapters/index.ts
|
|
1470
|
-
init_base();
|
|
1471
|
-
|
|
1472
|
-
// src/adapters/registry.ts
|
|
1473
|
-
var ADAPTER_FACTORIES = {};
|
|
1474
|
-
function registerProvider(provider, factories) {
|
|
1475
|
-
ADAPTER_FACTORIES[provider] = factories;
|
|
1476
|
-
}
|
|
1477
|
-
registerProvider("claude", {
|
|
1478
|
-
raw: async (config) => {
|
|
1479
|
-
const { ClaudeRawAdapter: ClaudeRawAdapter2 } = await Promise.resolve().then(() => (init_raw(), raw_exports));
|
|
1480
|
-
return new ClaudeRawAdapter2(config);
|
|
1481
|
-
},
|
|
1482
|
-
sdk: async (config) => {
|
|
1483
|
-
const { ClaudeSdkAdapter: ClaudeSdkAdapter2 } = await Promise.resolve().then(() => (init_sdk(), sdk_exports));
|
|
1484
|
-
return new ClaudeSdkAdapter2(config);
|
|
1485
|
-
}
|
|
1486
|
-
});
|
|
1487
|
-
registerProvider("openai", {
|
|
1488
|
-
raw: async (config) => {
|
|
1489
|
-
const { OpenAiRawAdapter: OpenAiRawAdapter2 } = await Promise.resolve().then(() => (init_raw2(), raw_exports2));
|
|
1490
|
-
return new OpenAiRawAdapter2(config);
|
|
1491
|
-
},
|
|
1492
|
-
sdk: async (config) => {
|
|
1493
|
-
const { OpenAiSdkAdapter: OpenAiSdkAdapter2 } = await Promise.resolve().then(() => (init_sdk2(), sdk_exports2));
|
|
1494
|
-
return new OpenAiSdkAdapter2(config);
|
|
1495
|
-
}
|
|
1496
|
-
});
|
|
1497
|
-
registerProvider("google", {
|
|
1498
|
-
raw: async (config) => {
|
|
1499
|
-
const { GoogleRawAdapter: GoogleRawAdapter2 } = await Promise.resolve().then(() => (init_raw3(), raw_exports3));
|
|
1500
|
-
return new GoogleRawAdapter2(config);
|
|
1501
|
-
},
|
|
1502
|
-
sdk: async (config) => {
|
|
1503
|
-
const { GoogleSdkAdapter: GoogleSdkAdapter2 } = await Promise.resolve().then(() => (init_sdk3(), sdk_exports3));
|
|
1504
|
-
return new GoogleSdkAdapter2(config);
|
|
1505
|
-
}
|
|
1506
|
-
});
|
|
1507
|
-
registerProvider("openrouter", {
|
|
1508
|
-
raw: async (config) => {
|
|
1509
|
-
const { OpenRouterRawAdapter: OpenRouterRawAdapter2 } = await Promise.resolve().then(() => (init_raw4(), raw_exports4));
|
|
1510
|
-
return new OpenRouterRawAdapter2(config);
|
|
1511
|
-
}
|
|
1512
|
-
});
|
|
1513
|
-
async function getAdapter(provider, mode, config = {}) {
|
|
1514
|
-
const providerFactories = ADAPTER_FACTORIES[provider];
|
|
1515
|
-
if (!providerFactories) {
|
|
1516
|
-
throw new Error(
|
|
1517
|
-
`Unknown provider: ${provider}. Available: ${Object.keys(ADAPTER_FACTORIES).join(", ")}`
|
|
1518
|
-
);
|
|
1519
|
-
}
|
|
1520
|
-
const factory = providerFactories[mode];
|
|
1521
|
-
if (!factory) {
|
|
1522
|
-
throw new Error(
|
|
1523
|
-
`Unknown mode '${mode}' for provider '${provider}'. Available: ${Object.keys(providerFactories).join(", ")}`
|
|
1524
|
-
);
|
|
1525
|
-
}
|
|
1526
|
-
return factory(config);
|
|
1527
|
-
}
|
|
1528
|
-
async function listAdapters(config = {}) {
|
|
1529
|
-
const result = [];
|
|
1530
|
-
for (const [provider, modes] of Object.entries(ADAPTER_FACTORIES)) {
|
|
1531
|
-
for (const mode of Object.keys(modes)) {
|
|
1532
|
-
try {
|
|
1533
|
-
const factory = ADAPTER_FACTORIES[provider]?.[mode];
|
|
1534
|
-
if (!factory) continue;
|
|
1535
|
-
const adapter = await factory(config);
|
|
1536
|
-
result.push({
|
|
1537
|
-
provider,
|
|
1538
|
-
mode,
|
|
1539
|
-
available: adapter.isAvailable(),
|
|
1540
|
-
displayName: adapter.displayName
|
|
1541
|
-
});
|
|
1542
|
-
} catch {
|
|
1543
|
-
result.push({
|
|
1544
|
-
provider,
|
|
1545
|
-
mode,
|
|
1546
|
-
available: false,
|
|
1547
|
-
displayName: `${provider}/${mode} (not installed)`
|
|
1548
|
-
});
|
|
1549
|
-
}
|
|
1550
|
-
}
|
|
1551
|
-
}
|
|
1552
|
-
return result;
|
|
1553
|
-
}
|
|
1554
|
-
|
|
1555
|
-
// src/validation/primitives.ts
|
|
1556
|
-
var PRIMITIVES_DOCUMENTATION = "# ggui Primitives & Design System Reference\n\n> You are a world-class UI engineer working with ggui's component library for the first time.\n> This reference documents every available component, prop, and convention.\n> Components handle theming automatically via built-in variants \u2014 pick the right variant and the theme does the rest.\n> For custom styling beyond variants, use CSS variables: var(--ggui-*, fallback).\n\n## Primitives\n\nImport: `import { Component } from '@ggui-ai/design'`\n\n### Container\n\nContainer -- Width-constrained wrapper that centers content horizontally.\n\nRenders a `<div>` with `width: 100%` and a `maxWidth` constraint.\nWhen `center` is true (the default), applies `margin: 0 auto`.\nNo background, border, or shadow -- use Card for visual containment.\n\nCSS variables used: none (pure layout primitive).\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| children | `ReactNode` | - | children |\n| maxWidth | `'xs' \\| 'sm' \\| 'md' \\| 'lg' \\| 'xl' \\| '2xl' \\| '3xl' \\| 'full' \\| string` | `'lg'` | Maximum width constraint. Accepts a preset token or any CSS width string. - `'xs'` -- 320px - `'sm'` -- 480px - `'md'` -- 640px - `'lg'` -- 768px - `'xl'` -- 1024px - `'2xl'` -- 1280px - `'3xl'` -- 1536px - `'full'` -- 100% Custom strings (e.g., `'900px'`, `'60ch'`) are passed through as-is. |\n| center | `boolean` | `true` | Whether to center the container horizontally via `margin: 0 auto`. |\n| padding | `'none' \\| 'xs' \\| 'sm' \\| 'md' \\| 'lg' \\| 'xl' \\| '2xl' \\| number \\| string` | `undefined (no padding)` | Padding applied to all sides. Prefer a spacing-scale name (`'xs' \\| 'sm' \\| 'md' \\| 'lg' \\| 'xl' \\| '2xl'`) \u2014 each resolves to the matching `--ggui-spacing-*` token. A number is treated as pixels; any other string is passed through as a raw CSS value. |\n\n**Example:**\n```tsx\n<Container maxWidth=\"xl\" padding=\"var(--ggui-spacing-6)\">\n <Stack gap=\"var(--ggui-spacing-4)\">\n <Heading level={1}>Dashboard</Heading>\n <Card shadow=\"md\" padding=\"var(--ggui-spacing-5)\">\n <Text>Welcome back!</Text>\n </Card>\n </Stack>\n</Container>\n```\n\n### Card\n\nCard -- Container with background, shadow, and optional border.\n\nRenders a `<div>` with:\n- Background: `var(--ggui-color-container)`\n- Border (when enabled): `1px solid var(--ggui-color-outlineVariant)`\n- Shadow and radius controlled by design tokens via CSS variables.\n- No built-in transitions.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| children | `ReactNode` | - | children |\n| padding | `'none' \\| 'xs' \\| 'sm' \\| 'md' \\| 'lg' \\| 'xl' \\| '2xl' \\| number \\| string` | `'lg'` | Padding applied to all sides. Prefer a spacing-scale name (`'xs' \\| 'sm' \\| 'md' \\| 'lg' \\| 'xl' \\| '2xl'`) \u2014 each resolves to the matching `--ggui-spacing-*` token. A number is treated as pixels; any other string is passed through as a raw CSS value. |\n| shadow | `'none' \\| 'sm' \\| 'md' \\| 'lg' \\| 'xl'` | `'sm'` | Shadow elevation level. Maps to design tokens: - `'none'` -- no shadow - `'sm'` -- var(--ggui-shape-shadow-sm) -- subtle, default - `'md'` -- var(--ggui-shape-shadow-md) -- dialogs, emphasized sections - `'lg'` -- var(--ggui-shape-shadow-lg) -- floating panels - `'xl'` -- var(--ggui-shape-shadow-xl) -- popovers, modals |\n| border | `boolean` | `true` | Whether to render a 1px border using `var(--ggui-color-outlineVariant)`. |\n| radius | `'none' \\| 'sm' \\| 'md' \\| 'lg' \\| 'xl' \\| number \\| string` | `'lg'` | Corner radius. Prefer a radius-scale name (`'none' \\| 'sm' \\| 'md' \\| 'lg' \\| 'xl'`) \u2014 each resolves to the matching `--ggui-shape-radius-*` token. A number is treated as pixels; any other string is passed through as a raw CSS value. |\n| surface | `'default' \\| 'elevated' \\| 'sunken' \\| 'accent' \\| 'inverted' \\| 'hero' \\| 'transparent'` | `'default'` | Semantic surface slot. Same vocabulary as ; see that prop's docs for the full slot table. Default Card surface is `'default'` (the active theme's `--ggui-color-container`); pair with `shadow=\"md\"\\|\"lg\"` for elevated cards, `'hero'` for a greeting or hero card (the theme's hero ground, right on a light or a dark host), or `'inverted'` for a dark testimonial-style card on a light theme. |\n| bleed | `boolean` | `false` | Span the expanded frame's inset edge to edge (ggui#1083). In a host's fullscreen canvas the frame gives the root a 16 px content inset; a `bleed` element (a full-width row the design means to touch the panel's edges) takes that inset back and meets the panel edge. A `surface=\"hero\"` band that opens the card already does, without it. Ignored everywhere else, so it is safe on any card. |\n\n**Example:**\n```tsx\n<Card shadow=\"md\" padding=\"lg\" radius=\"lg\">\n <Stack gap=\"md\">\n <Text size=\"sm\" weight=\"medium\">Settings</Text>\n <Input label=\"Name\" value={name} onChange={setName} />\n <Button variant=\"primary\">Save</Button>\n </Stack>\n</Card>\n```\n\n### Stack\n\nStack -- Flexbox layout primitive for arranging children along a single axis.\n\nRenders a `<div>` with `display: flex`. Default layout is vertical (column).\nAll flex shorthand values (`align`, `justify`, `wrap`) are abstracted into\nsemantic prop names.\n\nCSS variables used: none (pure layout primitive).\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| children | `ReactNode` | - | children |\n| direction | `'vertical' \\| 'horizontal'` | `'vertical'` | Main axis direction. - `'vertical'` -- `flex-direction: column` - `'horizontal'` -- `flex-direction: row` |\n| gap | `'none' \\| 'xs' \\| 'sm' \\| 'md' \\| 'lg' \\| 'xl' \\| '2xl' \\| number \\| string` | `'sm'` | Gap between children. Prefer a spacing-scale name (`'xs' \\| 'sm' \\| 'md' \\| 'lg' \\| 'xl' \\| '2xl'`) \u2014 each resolves to the matching `--ggui-spacing-*` token. A number is treated as pixels; any other string is passed through as a raw CSS value. |\n| align | `'start' \\| 'center' \\| 'end' \\| 'stretch'` | `'stretch'` | Cross-axis alignment (maps to `align-items`). - `'start'` -- flex-start - `'center'` -- center - `'end'` -- flex-end - `'stretch'` -- stretch (children fill cross-axis) |\n| justify | `'start' \\| 'center' \\| 'end' \\| 'between' \\| 'around' \\| 'evenly'` | `'start'` | Main-axis content distribution (maps to `justify-content`). - `'start'` -- flex-start - `'center'` -- center - `'end'` -- flex-end - `'between'` -- space-between - `'around'` -- space-around - `'evenly'` -- space-evenly |\n| wrap | `boolean` | `false` | Whether children wrap to the next line when they overflow. Maps to `flex-wrap: wrap` when true. |\n\n**Example:**\n```tsx\n<Stack gap=\"lg\" align=\"center\">\n <Heading level={2}>Profile</Heading>\n <Text>Edit your account details below.</Text>\n <Stack direction=\"horizontal\" gap=\"sm\" justify=\"end\">\n <Button variant=\"ghost\">Cancel</Button>\n <Button variant=\"primary\">Save</Button>\n </Stack>\n</Stack>\n```\n\n### Grid\n\nGrid -- 2-D layout primitive. Arranges children into rows AND\ncolumns; reach for it when Stack/Row's single-axis flow isn't\nenough (card galleries, dashboards, stat grids).\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| children | `ReactNode` | - | children |\n| columns | `number \\| ResponsiveColumns` | `2` | Column count. Three forms: - a number \u2014 that many equal columns at every width (`columns={3}`); - a map \u2014 explicit counts per breakpoint (`columns={{ base: 1, md: 3 }}` = 1 column on mobile, 3 from `md`). Use this when the request names exact per-breakpoint counts (\"3 per row on desktop, 1 on mobile\"). Ignored entirely when `minColumnWidth` is set. |\n| gap | `'none' \\| 'xs' \\| 'sm' \\| 'md' \\| 'lg' \\| 'xl' \\| '2xl' \\| number \\| string` | `'md'` | Gap between cells. Prefer a spacing-scale name (`'xs' \\| 'sm' \\| 'md' \\| 'lg' \\| 'xl' \\| '2xl'`); a number is pixels. |\n| minColumnWidth | `number \\| string` | `undefined (use `columns`)` | When set, the grid becomes responsive \u2014 it fits as many equal columns as possible, each at least this wide, and `columns` is ignored. A number is treated as pixels. |\n\n**Example:**\n```tsx\n<Grid columns={3} gap=\"md\">\n {items.map((it) => <Card key={it.id}>{it.name}</Card>)}\n</Grid>\n```\n\n### Skeleton\n\nSkeleton -- a pulsing placeholder for content that has not loaded\nyet. ggui UIs are agent-driven (props arrive late, streams start\nempty), so a loading frame is the rule \u2014 render `Skeleton` instead\nof a blank screen or a hand-rolled pulsing `<div>`.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| variant | `'rect' \\| 'text' \\| 'circle'` | `'rect'` | Shape preset. - `'rect'` -- a block (default); pair with `width` / `height`. - `'text'` -- a single text line (height ~1em). - `'circle'` -- equal width/height, fully rounded (avatar slot). |\n| width | `number \\| string` | - | Width. A number is pixels. Defaults to `100%` (`2.5rem` for circle). |\n| height | `number \\| string` | - | Height. A number is pixels. Defaults by variant when unset. |\n| radius | `'none' \\| 'sm' \\| 'md' \\| 'lg' \\| 'xl' \\| number \\| string` | `'sm'` | Corner radius. Prefer a radius-scale name. Ignored for `variant=\"circle\"` (always fully round). |\n\n**Example:**\n```tsx\n{user === undefined\n ? <Skeleton variant=\"text\" width=\"40%\" />\n : <Text>{user.name}</Text>}\n```\n\n### Box\n\nBox -- Generic container with padding, margin, background, and border-radius.\n\nRenders a plain `<div>`. Unlike Card, Box has no default background, shadow,\nor border -- it is a blank canvas for custom styling. Use it for layout\nspacing, colored sections, or wrapping arbitrary content.\n\nWhen both `paddingX`/`paddingY` and `padding` are provided, the axis-specific\nprops take precedence and `padding` is ignored.\n\nCSS variables used: none (all values are passed through directly).\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| children | `ReactNode` | - | children |\n| padding | `'none' \\| 'xs' \\| 'sm' \\| 'md' \\| 'lg' \\| 'xl' \\| '2xl' \\| number \\| string` | `undefined (no padding)` | Padding applied to all four sides. Prefer a spacing-scale name (`'xs' \\| 'sm' \\| 'md' \\| 'lg' \\| 'xl' \\| '2xl'`) \u2014 each resolves to the matching `--ggui-spacing-*` token. A number is treated as pixels; any other string is passed through as a raw CSS value. Ignored when `paddingX` or `paddingY` is set. |\n| paddingX | `'none' \\| 'xs' \\| 'sm' \\| 'md' \\| 'lg' \\| 'xl' \\| '2xl' \\| number \\| string` | `undefined` | Horizontal (left + right) padding. Accepts a spacing-scale name, a pixel number, or a raw CSS string \u2014 see . When set alongside `paddingY`, they combine into a shorthand `padding: {Y} {X}`. When set without `paddingY`, vertical padding defaults to 0. |\n| paddingY | `'none' \\| 'xs' \\| 'sm' \\| 'md' \\| 'lg' \\| 'xl' \\| '2xl' \\| number \\| string` | `undefined` | Vertical (top + bottom) padding. Accepts a spacing-scale name, a pixel number, or a raw CSS string \u2014 see . When set alongside `paddingX`, they combine into a shorthand `padding: {Y} {X}`. When set without `paddingX`, horizontal padding defaults to 0. |\n| margin | `'none' \\| 'xs' \\| 'sm' \\| 'md' \\| 'lg' \\| 'xl' \\| '2xl' \\| number \\| string` | `undefined (no margin)` | Margin applied to all four sides. Accepts a spacing-scale name, a pixel number, or a raw CSS string \u2014 see . |\n| surface | `'default' \\| 'elevated' \\| 'sunken' \\| 'accent' \\| 'inverted' \\| 'hero' \\| 'transparent'` | `undefined (transparent)` | Semantic surface slot. Picks the right `var(--ggui-color-*)` background token from the active theme. The ONLY way to set a theme-tracking background fill on Box. Available slots: - `'default'` \u2014 base container surface (most common) - `'elevated'` \u2014 same fill, intended to be paired with shadow (use Card.shadow for actual elevation) - `'sunken'` \u2014 recessed / inset region (the `sunken` role; `surfaceVariant` was retired by ggui#987) - `'accent'` \u2014 highlighted / branded fill (`primary-50` token) - `'inverted'` \u2014 dark surface in light mode, light in dark (testimonials, code-snippet cards, hero panels). The surface owns ALL its inks: body text, `muted` / `subtle` labels, chips and outlines inside it re-map to inverse-derived values by cascade \u2014 no `tone=\"inverse\"` needed, and no hand-picked greys. - `'hero'` \u2014 the hero panel's ground: brand-tinted on a light host, the ink pair on a dark one (`heroGround` / `onHeroGround`, derived per mode) \u2014 reach for it for a greeting or hero card instead of guessing the host's darkness with `'inverted'`; it owns its subtree's inks likewise. - `'transparent'` \u2014 explicit \"no fill\" For non-theme-mapped brand colors (e.g. a partner's exact brand hex like Stripe purple) use the escape \u2014 every other hex / rgba on Box is rejected by tier-0 self-check. |\n| bleed | `boolean` | `false` | Span the expanded frame's inset edge to edge (ggui#1083). In a host's fullscreen canvas the frame gives the root a 16 px content inset; a `bleed` element (a full-width row the design means to touch the panel's edges) takes that inset back and meets the panel edge. A `surface=\"hero\"` band that opens the card already does, without it. Ignored everywhere else, so it is safe on any card. |\n| assetColor | `string` | `undefined` | Asset color escape \u2014 the typed valve for legitimate non-theme color values (a partner's exact brand hex, a fixed product surface, etc.). Renders as the Box background. **MUST be paired with .** The semantic name is human-readable documentation of why this color bypasses the theme \u2014 e.g. `\"stripe-brand-purple\"`, `\"slack-aubergine\"`. Tier-0 self-check allows hex / rgba inside `assetColor` ONLY when `assetSemantic` is a non-empty string; one without the other fails the check. Reach for `surface` first. This escape exists for the small set of cases where the operator's theme MUST NOT override the value (brand identity rendering). |\n| assetSemantic | `string` | `undefined` | Human-readable semantic label that documents why bypasses the theme. Required when `assetColor` is set; tier-0 self-check rejects empty strings or a missing `assetSemantic` next to a hex `assetColor`. Examples: `\"stripe-brand-purple\"`, `\"slack-aubergine\"`, `\"partner-logo-orange\"`. Pure documentation \u2014 no rendering effect. |\n| radius | `'none' \\| 'sm' \\| 'md' \\| 'lg' \\| 'xl' \\| number \\| string` | `undefined (no rounding)` | Corner radius. Prefer a radius-scale name (`'none' \\| 'sm' \\| 'md' \\| 'lg' \\| 'xl'`) \u2014 each resolves to the matching `--ggui-shape-radius-*` token. A number is treated as pixels; any other string is passed through as a raw CSS value. |\n\n**Example:**\n```tsx\n<Box paddingX=\"xl\" paddingY=\"lg\" surface=\"accent\" radius=\"lg\">\n <Text size=\"sm\" tone=\"emphasized\">\n Tip: You can customize your theme in Settings.\n </Text>\n</Box>\n```\n\n### Divider\n\nDivider -- A 1px line to visually separate content sections.\n\nRenders an `<hr>` (horizontal) or `<div>` (vertical) with `role=\"separator\"`.\n- Horizontal: 1px tall, full width, with vertical margin.\n- Vertical: 1px wide, stretches to parent height via `align-self: stretch`,\n with horizontal margin. Works best inside a horizontal Stack or Row.\n\nDefault color: `var(--ggui-color-outlineVariant)`.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| orientation | `'horizontal' \\| 'vertical'` | `'horizontal'` | Line direction. - `'horizontal'` -- renders `<hr>`, full width, 1px height, margin top/bottom - `'vertical'` -- renders `<div>`, 1px width, `align-self: stretch`, margin left/right |\n| margin | `number \\| string` | `16` | Spacing around the divider. Numbers are treated as pixels. Applied as vertical margin for horizontal dividers, horizontal margin for vertical. |\n| tone | `\\| 'default' \\| 'muted' \\| 'subtle' \\| 'emphasized' \\| 'loud' \\| 'success' \\| 'warning' \\| 'error' \\| 'info' \\| 'inverse' \\| 'inherit'` | `undefined (uses `var(--ggui-color-outlineVariant)`)` | Semantic color slot. Same vocabulary as ; the theme decides what each tone LOOKS like. Defaults to a quiet outline-variant tint when unset (independent of the tone slots). |\n\n**Example:**\n```tsx\n<Stack gap={0}>\n <Text>Section A</Text>\n <Divider margin=\"var(--ggui-spacing-3)\" />\n <Text>Section B</Text>\n</Stack>\n```\n\n### Spacer\n\nSpacer -- Invisible spacing element, either fixed-size or flexible.\n\nRenders an empty `<div>`.\n- Fixed mode (number): sets both `width` and `height` to the given pixel\n value with `flex-shrink: 0`, creating rigid spacing in any direction.\n- Flex mode (`'flex'`): sets `flex: 1`, expanding to fill remaining space\n in a flex container. Useful for pushing siblings apart.\n\nCSS variables used: none.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| size | `number \\| 'flex'` | `16` | Spacing amount. - Number: fixed square spacer (width and height in pixels, `flex-shrink: 0`). - `'flex'`: expands to fill available space (`flex: 1`). |\n\n**Example:**\n```tsx\n<Stack direction=\"horizontal\" align=\"center\">\n <Heading level={3}>Logo</Heading>\n <Spacer size=\"flex\" />\n <Button variant=\"ghost\">Login</Button>\n</Stack>\n```\n\n### Text\n\nText -- Versatile typography primitive for body copy, captions, and labels.\n\nRenders as `<p>` by default (configurable via `is`). Typography is\ncomposed from three orthogonal axes: `size` (font size, with a\nmatching line-height built in), `weight`, and `tone` (semantic\ncolor). `caps` adds the uppercase, letter-spaced treatment for tiny\nsection labels (the classic overline/eyebrow look) \u2014 the label's text\ncomes from a prop, never from the component: an invented eyebrow is copy\nnothing can change.\n\nDefault text color: `var(--ggui-color-onContainer)`.\nAll text renders with `margin: 0` (no default paragraph spacing).\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| children | `ReactNode` | - | children |\n| size | `'xs' \\| 'sm' \\| 'base' \\| 'lg' \\| 'xl' \\| '2xl' \\| '3xl' \\| '4xl'` | `'base'` | Font size. Maps to CSS variables with pixel fallbacks; each size carries a matching line-height (1.5 for `xs`--`base`, 1.625 for `lg`, then tightening on display sizes: 1.375 at `xl`, 1.25 from `2xl` up): - `'xs'` -- var(--ggui-font-size-xs) (12px) - `'sm'` -- var(--ggui-font-size-sm) (14px) - `'base'` -- var(--ggui-font-size-base) (16px) - `'lg'` -- var(--ggui-font-size-lg) (18px) - `'xl'` -- var(--ggui-font-size-xl) (20px) - `'2xl'` -- var(--ggui-font-size-2xl) (24px) - `'3xl'` -- var(--ggui-font-size-3xl) (30px) - `'4xl'` -- var(--ggui-font-size-4xl) (36px) |\n| weight | `'normal' \\| 'medium' \\| 'semibold' \\| 'bold'` | `'normal'` | Font weight. Maps to CSS variables with numeric fallbacks: - `'normal'` -- var(--ggui-font-weight-normal) - `'medium'` -- var(--ggui-font-weight-medium) - `'semibold'` -- var(--ggui-font-weight-semibold) - `'bold'` -- var(--ggui-font-weight-bold) |\n| caps | `boolean` | `false` | When true, uppercases the text and adds 0.05em letter-spacing -- the eyebrow/overline treatment for tiny section labels. Pair with `size=\"xs\" weight=\"semibold\" tone=\"muted\"`. |\n| tone | `\\| 'default' \\| 'muted' \\| 'subtle' \\| 'emphasized' \\| 'loud' \\| 'success' \\| 'warning' \\| 'error' \\| 'info' \\| 'inverse' \\| 'inherit'` | `'default' (var(--ggui-color-onContainer))` | Semantic color slot. Picks the right `var(--ggui-color-*)` token from the active theme. The theme decides what each tone LOOKS like \u2014 `'muted'` is a quiet warm grey on Claudic, a cool slate on Indigo, dim cyan on Neon-Noir. Components that use `tone` track the operator's theme switch automatically. Available slots: `'default'` (primary body text), `'muted'` (secondary / metadata), `'subtle'` (very-low-emphasis hint), `'emphasized'` (branded accent), `'loud'` (strongest accent \u2014 the theme's readable accent ink), `'success'` / `'warning'` / `'error'` / `'info'` (status text), `'inverse'` (text on dark surface), `'inherit'` (parent's color). `tone` is the ONLY way to set a Text color. The legacy `color?: string` escape was retired \u2014 raw color strings bypass theming and silently override the operator's preset. |\n| align | `'left' \\| 'center' \\| 'right'` | `undefined (inherits from parent)` | Horizontal text alignment. Maps directly to `text-align`. |\n| truncate | `boolean` | `false` | When true, clips overflowing text with an ellipsis. Applies `overflow: hidden`, `text-overflow: ellipsis`, and `white-space: nowrap`. |\n| is | `'p' \\| 'span' \\| 'div' \\| 'label'` | `'p'` | HTML element to render. Choose based on semantic context: - `'p'` -- paragraph (default, block-level) - `'span'` -- inline text within a sentence - `'div'` -- generic block container - `'label'` -- form label (pair with `htmlFor`) |\n| id | `string` | - | `id` for the rendered element \u2014 anchor an in-page link, or pair with a form control's `aria-labelledby`. |\n| htmlFor | `string` | - | Associates an `is=\"label\"` element with a form control by the control's `id`. Only meaningful when `is=\"label\"`. |\n\n**Example:**\n```tsx\n<Stack gap=\"var(--ggui-spacing-1)\">\n <Text size=\"xs\" weight=\"semibold\" caps tone=\"muted\">{props.section}</Text>\n <Text size=\"lg\">Welcome back, Jane.</Text>\n <Text size=\"xs\" tone=\"muted\">\n Last login: 2 hours ago\n </Text>\n</Stack>\n```\n\n### Heading\n\nHeading -- Semantic heading element (h1-h6) with preset typography styles.\n\nRenders the corresponding `<h1>`-`<h6>` HTML element based on `level`.\nEach level has a preset font size, weight, line height, and letter spacing\nfrom the heading typography tokens:\n- Level 1: 36px / bold / 1.25 line-height / -0.025em tracking\n- Level 2: 30px / bold / 1.25 line-height / -0.025em tracking\n- Level 3: 24px / semibold / 1.375 line-height / 0em tracking\n- Level 4: 20px / semibold / 1.375 line-height / 0em tracking\n- Level 5: 18px / semibold / 1.5 line-height / 0em tracking\n- Level 6: 16px / semibold / 1.5 line-height / 0em tracking\n\nDefault text color: `var(--ggui-color-onContainer)`.\nAll headings render with `margin: 0` (no default heading spacing).\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| children | `ReactNode` | - | children |\n| level | `1 \\| 2 \\| 3 \\| 4 \\| 5 \\| 6` | `2` | Semantic heading level. Determines both the HTML element (`<h1>`-`<h6>`) and the preset typography style. |\n| tone | `\\| 'default' \\| 'muted' \\| 'subtle' \\| 'emphasized' \\| 'loud' \\| 'success' \\| 'warning' \\| 'error' \\| 'info' \\| 'inverse' \\| 'inherit'` | `'default' (var(--ggui-color-onContainer))` | Semantic color slot. Same vocabulary as ; see that prop's docs for the full slot table. `tone` is the ONLY way to set a Heading color \u2014 the legacy `color?: string` escape was retired so the operator's theme always wins. |\n| align | `'left' \\| 'center' \\| 'right'` | `undefined (inherits from parent)` | Horizontal text alignment. Maps directly to `text-align`. |\n\n**Example:**\n```tsx\n<Stack gap=\"var(--ggui-spacing-2)\">\n <Heading level={1}>Page Title</Heading>\n <Heading level={3} tone=\"emphasized\">\n Subsection\n </Heading>\n <Text>Body content goes here.</Text>\n</Stack>\n```\n\n### Button\n\nButton -- A clickable button primitive with multiple visual variants and sizes.\n\nRenders a native `<button>` element styled with inline CSS derived from design-token\nCSS variables. Supports a loading spinner, left/right icon slots, and a cross-platform\n`onPress` alias for `onClick`.\n\nBase styles applied to every variant:\n- `border-radius: var(--ggui-shape-radius-control)` \u2014 the control ROLE (the host's button/field radius; falls to `var(--ggui-shape-radius-md)`)\n- `font-weight: var(--ggui-font-weight-medium)`\n- `box-shadow: var(--ggui-shape-shadow-sm)`\n- `gap: var(--ggui-spacing-2)` between icon and text\n- Transitions: background-color, box-shadow, opacity at 200ms ease-in-out\n\nDisabled or loading: `opacity: 0.5`, `cursor: not-allowed`, click handler suppressed.\n\nAlso extends native `ButtonHTMLAttributes` (except `style`/`className`), so props\nlike `type`, `form`, `aria-*`, and `data-*` are forwarded to the `<button>` element.\nThe `type` prop defaults to `'button'` (not `'submit'`), preventing accidental form\nsubmissions.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| children | `ReactNode` | - | children |\n| variant | `'primary' \\| 'secondary' \\| 'outline' \\| 'ghost' \\| 'danger'` | `'primary'` | Visual style. Maps to CSS variables: - `'primary'` -- `var(--ggui-color-primary-600)` background, white text, no border - `'secondary'` -- `var(--ggui-color-sunken)` background, `var(--ggui-color-onContainer)` text, no border - `'outline'` -- transparent background, `1px solid var(--ggui-color-primary-600)` border, label in the surface's on-colour (`onContainer`) so it reads on any ground \u2014 the brand shows on the border, never as label ink on a dark theme - `'ghost'` -- transparent background, `var(--ggui-color-onContainer)` text, no border (its rank is the missing chrome, not a dimmer label, which would read as disabled) - `'danger'` -- `var(--ggui-color-error-600)` background, white text, no border |\n| size | `'xs' \\| 'sm' \\| 'md' \\| 'lg'` | `'md'` | Controls padding, font size, and minimum height: - `'xs'` -- padding `4px 8px`, font `var(--ggui-font-size-xs)`, min-height 24px - `'sm'` -- padding `6px 12px`, font `var(--ggui-font-size-sm)`, min-height 32px - `'md'` -- padding `10px 16px`, font `var(--ggui-font-size-sm)`, min-height 40px - `'lg'` -- padding `12px 24px`, font `var(--ggui-font-size-base)`, min-height 48px |\n| fullWidth | `boolean` | `false` | When true, sets `width: 100%` so the button fills its container. |\n| loading | `boolean` | `false` | When true, replaces children with a 16px `Spinner` (color: `currentColor`) and disables interaction (same effect as `disabled`). |\n| type | `'button' \\| 'submit' \\| 'reset'` | `'button'` | The HTML button type. Defaults to `'button'`, so a Button inside a `<form>` never submits it on click: the ONE control that submits the form sets `type=\"submit\"`; secondary controls keep the default. |\n| leftIcon | `ReactNode` | - | ReactNode rendered before children, inside the flex layout with `var(--ggui-spacing-2)` gap. |\n| rightIcon | `ReactNode` | - | ReactNode rendered after children, inside the flex layout with `var(--ggui-spacing-2)` gap. |\n| onPress | `() => void` | - | Alias for `onClick` for cross-platform compatibility (React Native convention). If both `onClick` and `onPress` are provided, `onClick` takes precedence. |\n\n**Example:**\n```tsx\n<Button variant=\"primary\" size=\"md\" leftIcon={<Icon name=\"save\" />} onClick={handleSave}>\n Save Changes\n</Button>\n```\n\n### Input\n\nInput -- A single-line text input with label, validation, and helper text.\n\nRenders a `<div>` wrapper containing an optional `<label>`, a native `<input>`,\nand an optional message `<span>` for error or helper text.\n\nStyling:\n- Border: `1px solid var(--ggui-color-outline)` (normal),\n `var(--ggui-color-error-500)` (error)\n- Background: `var(--ggui-color-container)` (normal),\n `var(--ggui-color-container)` (disabled)\n- Text: `var(--ggui-color-onContainer)`\n- Border radius: `var(--ggui-shape-radius-control)` \u2014 the control ROLE (the host's button/field radius; falls to `var(--ggui-shape-radius-md)`)\n- Label: `var(--ggui-font-size-sm)`, `var(--ggui-font-weight-medium)`,\n `var(--ggui-color-onSunken)`\n- Transitions: border-color, box-shadow at 200ms ease-in-out\n\nAccessibility: auto-generated `id` links `<label>` to `<input>` via `htmlFor`.\nWhen `error` is set, `aria-invalid` is true and the message has `role=\"alert\"`.\nWhen `required` is true, a red asterisk is appended to the label.\n\nAlso extends native `InputHTMLAttributes` (except `style`, `className`, `onChange`,\n`size`), so props like `autoFocus`, `name`, `pattern`, `aria-*` are forwarded.\n\n**IMPORTANT:** `onChange` receives the string value directly, NOT a React\n`ChangeEvent`. This differs from native `<input>` behavior.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| label | `string` | - | Label rendered above the input. Linked to the input via auto-generated `htmlFor`/`id`. Styled with `var(--ggui-font-size-sm)` and `var(--ggui-color-onSunken)`. |\n| placeholder | `string` | - | Placeholder text shown when the input is empty. |\n| value | `string` | - | Controlled value of the input. |\n| onChange | `(value: string) => void` | - | Change handler. Receives the new string value directly, NOT a React event. |\n| type | `'text' \\| 'email' \\| 'password' \\| 'number' \\| 'tel' \\| 'url' \\| 'search' \\| 'date' \\| 'time' \\| 'datetime-local'` | `'text'` | HTML input type. Determines browser behavior (keyboard on mobile, validation, masking). The date/time types render the browser's native, localized, keyboard-accessible picker; their `value` stays an ISO string (`'2026-07-29'`, `'14:30'`, `'2026-07-29T14:30'`) delivered through the usual value-first `onChange`. |\n| error | `string` | - | Error message displayed below the input in `var(--ggui-color-error-500)`. When set, the border turns red and the message element gets `role=\"alert\"`. Takes precedence over `helperText`. |\n| helperText | `string` | - | Helper text displayed below the input in `var(--ggui-color-onSunken)`. Only shown when `error` is not set. |\n| required | `boolean` | `false` | When true, appends a red asterisk (`*`) to the label and sets the native `required` attribute on the `<input>`. |\n| disabled | `boolean` | `false` | When true, sets the native `disabled` attribute. Background changes to `var(--ggui-color-container)`. |\n| size | `'sm' \\| 'md' \\| 'lg'` | `'md'` | Controls padding and font size: - `'sm'` -- padding `6px 10px`, font `var(--ggui-font-size-sm)` - `'md'` -- padding `10px 12px`, font `var(--ggui-font-size-sm)` - `'lg'` -- padding `12px 14px`, font `var(--ggui-font-size-base)` |\n\n**Example:**\n```tsx\n<Input label=\"Email\" type=\"email\" value={email} onChange={setEmail} error={emailError} />\n```\n\n### TextArea\n\nTextArea -- A multiline text input with label, validation, character count, and auto-resize.\n\nRenders a `<div>` wrapper containing an optional `<label>`, a native `<textarea>`,\nand a footer row with error/helper text on the left and character count on the right.\n\nStyling:\n- Padding: `10px 12px`, font: `var(--ggui-font-size-sm)`, `font-family: inherit`\n- Border: `1px solid var(--ggui-color-outline)` (normal),\n `var(--ggui-color-error-500)` (error)\n- Background: `var(--ggui-color-container)` (normal),\n `var(--ggui-color-container)` (disabled)\n- Border radius: `var(--ggui-shape-radius-control)` \u2014 the control ROLE (the host's button/field radius; falls to `var(--ggui-shape-radius-md)`)\n- Resize: `vertical` by default, `none` when `autoResize` is true\n- Transitions: border-color, box-shadow at 200ms ease-in-out\n\nAccessibility: same label/error linking pattern as Input (auto-generated ids,\n`aria-invalid`, `role=\"alert\"` on error message).\n\nAlso extends native `TextareaHTMLAttributes` (except `style`, `className`, `onChange`).\n\n**IMPORTANT:** `onChange` receives the string value directly, NOT a React\n`ChangeEvent`. This differs from native `<textarea>` behavior.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| label | `string` | - | Label rendered above the textarea. Linked via auto-generated `htmlFor`/`id`. Styled with `var(--ggui-font-size-sm)` and `var(--ggui-color-onSunken)`. |\n| placeholder | `string` | - | Placeholder text shown when the textarea is empty. |\n| value | `string` | - | Controlled value of the textarea. |\n| onChange | `(value: string) => void` | - | Change handler. Receives the new string value directly, NOT a React event. |\n| rows | `number` | `4` | Number of visible text rows (native `rows` attribute on `<textarea>`). |\n| error | `string` | - | Error message displayed below the textarea in `var(--ggui-color-error-500)`. When set, the border turns red and the message element gets `role=\"alert\"`. Takes precedence over `helperText`. |\n| helperText | `string` | - | Helper text displayed below the textarea in `var(--ggui-color-onSunken)`. Only shown when `error` is not set. |\n| required | `boolean` | `false` | When true, appends a red asterisk (`*`) to the label and sets the native `required` attribute on the `<textarea>`. |\n| disabled | `boolean` | `false` | When true, sets the native `disabled` attribute. Background changes to `var(--ggui-color-container)`. |\n| maxLength | `number` | - | Maximum character length (native `maxLength` attribute). Also used as the denominator in the character count display when `showCount` is true. |\n| showCount | `boolean` | `false` | When true AND `maxLength` is set, displays a `{current}/{max}` character counter in the footer row (right-aligned, `var(--ggui-font-size-xs)`). Has no effect without `maxLength`. |\n| autoResize | `boolean` | `false` | When true, sets CSS `resize: none` on the textarea. The flag disables manual resizing to signal that external logic handles sizing. The component does NOT auto-adjust height based on content in the current implementation. |\n\n**Example:**\n```tsx\n<TextArea label=\"Bio\" value={bio} onChange={setBio} rows={6} maxLength={500} showCount />\n```\n\n### Select\n\nSelect -- A native dropdown selection primitive with label and validation.\n\nRenders a `<div>` wrapper containing an optional `<label>`, a native `<select>`\nwith custom styling, and an optional message `<span>`.\n\nThe native `<select>` has `appearance: none` with a custom chevron SVG rendered\nas a `background-image` (right-aligned, 12px, onSurfaceVariant color). Extra right\npadding (36px) accommodates the chevron.\n\nStyling:\n- Border: `1px solid var(--ggui-color-outline)` (normal),\n `var(--ggui-color-error-500)` (error)\n- Background: `var(--ggui-color-container)` (normal),\n `var(--ggui-color-container)` (disabled)\n- Text: `var(--ggui-color-onContainer)` for the displayed option,\n `var(--ggui-color-onSunken)` only while the placeholder shows (a\n `placeholder` with no `value` or `defaultValue`, until the user picks;\n or with `value=\"\"` / `defaultValue=\"\"`)\n- Border radius: `var(--ggui-shape-radius-control)` \u2014 the control ROLE (the host's button/field radius; falls to `var(--ggui-shape-radius-md)`)\n- Cursor: `pointer` (normal), `not-allowed` (disabled)\n- Transitions: border-color, box-shadow at 200ms ease-in-out\n\nAccessibility: auto-generated `id` links `<label>` to `<select>`.\nWhen `error` is set, `aria-invalid` is true and the message has `role=\"alert\"`.\n\nAlso extends native `SelectHTMLAttributes` (except `style`, `className`,\n`onChange`, `size`).\n\n**IMPORTANT:** `onChange` receives the selected value string directly, NOT a\nReact `ChangeEvent`. This differs from native `<select>` behavior.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| label | `string` | - | Label rendered above the select. Linked via auto-generated `htmlFor`/`id`. Styled with `var(--ggui-font-size-sm)` and `var(--ggui-color-onSunken)`. |\n| value | `string` | - | Controlled value. Should match one of the `options[].value` strings. |\n| onChange | `(value: string) => void` | - | Change handler. Receives the selected option's value string directly, NOT a React event. |\n| options | `SelectOption[]` | - | Array of selectable options. Rendered as native `<option>` elements. Must contain at least one option (or use `placeholder` for an empty-state prompt). |\n| placeholder | `string` | - | Placeholder text rendered as a disabled `<option value=\"\">` at the top of the list. With no `value` and no `defaultValue` the select starts on it, so it shows until the user picks; it cannot be picked again after that. |\n| error | `string` | - | Error message displayed below the select in `var(--ggui-color-error-500)`. When set, the border turns red and the message has `role=\"alert\"`. Takes precedence over `helperText`. |\n| helperText | `string` | - | Helper text displayed below the select in `var(--ggui-color-onSunken)`. Only shown when `error` is not set. |\n| required | `boolean` | `false` | When true, appends a red asterisk (`*`) to the label and sets the native `required` attribute. |\n| disabled | `boolean` | `false` | When true, sets the native `disabled` attribute. Background changes to `var(--ggui-color-container)` and cursor becomes `not-allowed`. |\n| size | `'sm' \\| 'md' \\| 'lg'` | `'md'` | Controls padding and font size: - `'sm'` -- padding `6px 10px`, font `var(--ggui-font-size-sm)` - `'md'` -- padding `10px 12px`, font `var(--ggui-font-size-sm)` - `'lg'` -- padding `12px 14px`, font `var(--ggui-font-size-base)` |\n\n**Example:**\n```tsx\n<Select\n label=\"Country\"\n value={country}\n onChange={setCountry}\n options={[\n { value: 'us', label: 'United States' },\n { value: 'uk', label: 'United Kingdom' },\n ]}\n placeholder=\"Select a country\"\n/>\n```\n\n### Checkbox\n\nCheckbox -- A custom-styled checkbox with label and description.\n\nRenders a `<label>` wrapper containing a visually-hidden native `<input type=\"checkbox\">`\noverlaid by a custom 18x18px visual box. Supports checked, unchecked, and indeterminate\nstates, each with a distinct SVG icon (checkmark or horizontal dash).\n\nStyling:\n- Box border: `2px solid var(--ggui-color-primary-600)` (checked/indeterminate),\n `var(--ggui-color-outline)` (unchecked)\n- Box fill: `var(--ggui-color-primary-600)` (checked/indeterminate),\n `var(--ggui-color-container)` (unchecked)\n- Check/dash icon: white SVG, 12x12px\n- Box radius: `var(--ggui-shape-radius-sm)`\n- Transition: all 0.2s\n- Label: `var(--ggui-font-size-sm)`, `var(--ggui-font-weight-medium)`, `var(--ggui-color-onContainer)`\n- Description: `var(--ggui-font-size-xs)`, `var(--ggui-color-onSunken)`\n- Disabled: `opacity: 0.5`, `cursor: not-allowed`\n- Gap between box and text: `var(--ggui-spacing-2)`\n\n**IMPORTANT:** `onChange` receives the boolean checked state directly, NOT a\nReact `ChangeEvent`.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| label | `string` | - | Primary label text rendered beside the checkbox box. Styled with `var(--ggui-font-size-sm)` and `var(--ggui-color-onContainer)`. |\n| checked | `boolean` | - | Controlled checked state. |\n| onChange | `(checked: boolean) => void` | - | Change handler. Receives the new boolean checked state directly, NOT a React event. |\n| disabled | `boolean` | `false` | When true, sets `opacity: 0.5` and `cursor: not-allowed`. The native input is also disabled, preventing keyboard and click interaction. |\n| description | `string` | - | Secondary description text rendered below the label in smaller, muted type (`var(--ggui-font-size-xs)`, `var(--ggui-color-onSunken)`). |\n| indeterminate | `boolean` | `false` | When true, displays a horizontal dash instead of a checkmark. Used for \"select all\" states where some (but not all) children are checked. The `indeterminate` property is set via a ref on the native `<input>`. Visually identical to `checked` in terms of border and fill color. |\n\n**Example:**\n```tsx\n<Checkbox\n label=\"Accept terms\"\n description=\"You agree to the Terms of Service and Privacy Policy\"\n checked={accepted}\n onChange={setAccepted}\n/>\n```\n\n### Toggle\n\nToggle -- A switch/toggle input rendered as a pill-shaped track with a sliding knob.\n\nRenders a `<label>` wrapper with a `<div role=\"switch\">` track and an animated\ncircular knob. Does NOT use a native `<input>` -- keyboard interaction is handled\nmanually (Space and Enter keys toggle the state). The element is focusable via\n`tabIndex={0}` and shows a focus ring on focus.\n\nStyling:\n- Track (on): `var(--ggui-color-primary-600)`\n- Track (off): `var(--ggui-color-outline)`\n- Knob: white circle with `var(--ggui-shape-shadow-sm)`\n- Focus ring: `0 0 0 3px var(--ggui-color-primary-200)`\n- Transitions: background-color, box-shadow, knob position at 200ms ease-in-out\n- Disabled: `opacity: 0.5`, `cursor: not-allowed`, `tabIndex: -1`\n- Gap between toggle and label: `var(--ggui-spacing-2)`\n\n**IMPORTANT:** `onChange` receives the new boolean state directly (inverted from\ncurrent), NOT a React event.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| label | `string` | - | Label text rendered to the right of the toggle track. Also used as `aria-label` on the switch element. Styled with `var(--ggui-font-size-sm)` and `var(--ggui-color-onContainer)`. |\n| checked | `boolean` | - | Controlled checked (on/off) state. |\n| onChange | `(checked: boolean) => void` | - | Change handler. Receives the new boolean state directly (i.e., `!checked`), NOT a React event. |\n| disabled | `boolean` | `false` | When true, sets `opacity: 0.5`, `cursor: not-allowed`, and removes the element from tab order (`tabIndex: -1`). Click and keyboard handlers are suppressed. |\n| size | `'sm' \\| 'md' \\| 'lg'` | `'md'` | Controls track and knob dimensions: - `'sm'` -- track 36x20px, knob 16px diameter - `'md'` -- track 44x24px, knob 20px diameter - `'lg'` -- track 52x28px, knob 24px diameter |\n\n**Example:**\n```tsx\n<Toggle label=\"Enable notifications\" checked={enabled} onChange={setEnabled} size=\"md\" />\n```\n\n### RadioGroup\n\nRadioGroup -- A group of mutually exclusive radio options with optional label and error.\n\nRenders a `<div role=\"radiogroup\">` containing a label span, a flex container of\nradio options, and an optional error message. Each option is a `<label>` with a\nvisually-hidden native `<input type=\"radio\">` and a custom 18px circle indicator.\n\nStyling:\n- Selected circle: `2px solid var(--ggui-color-primary-600)` border with\n an 8px `var(--ggui-color-primary-600)` filled inner dot\n- Unselected circle: `2px solid var(--ggui-color-outline)` border,\n `var(--ggui-color-container)` fill\n- Circle radius: `var(--ggui-shape-radius-full)`\n- Transition: all 0.2s\n- Vertical gap: `var(--ggui-spacing-2)`, horizontal gap: `var(--ggui-spacing-4)`\n- Error: `var(--ggui-font-size-xs)`, `var(--ggui-color-error-500)`,\n `role=\"alert\"`\n- Disabled options: `opacity: 0.5`, `cursor: not-allowed`\n\nAccessibility: the group has `role=\"radiogroup\"` with `aria-labelledby` pointing\nto the label and `aria-describedby` pointing to the error message (when present).\nAll radio inputs share a common auto-generated `name` attribute.\n\n**IMPORTANT:** `onChange` receives the selected option's value string directly,\nNOT a React `ChangeEvent`.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| label | `string` | - | Group label rendered above the options. Used as `aria-labelledby` target on the `role=\"radiogroup\"` container. Styled with `var(--ggui-font-size-sm)` and `var(--ggui-color-onSunken)`. |\n| value | `string` | - | Controlled value. Should match one of `options[].value`. |\n| onChange | `(value: string) => void` | - | Change handler. Receives the newly selected option's value string directly, NOT a React event. |\n| options | `RadioOption[]` | - | Array of radio options. Must contain at least two options for meaningful selection. |\n| direction | `'vertical' \\| 'horizontal'` | `'vertical'` | Layout direction for the options container: - `'vertical'` -- column layout, `var(--ggui-spacing-2)` gap - `'horizontal'` -- row layout with `flex-wrap: wrap`, `var(--ggui-spacing-4)` gap |\n| disabled | `boolean` | `false` | When true, disables ALL options (individual `RadioOption.disabled` is additive). Each option gets `opacity: 0.5` and `cursor: not-allowed`. |\n| error | `string` | - | Error message displayed below all options in `var(--ggui-color-error-500)` with `role=\"alert\"`. Linked to the radiogroup via `aria-describedby`. |\n\n**Example:**\n```tsx\n<RadioGroup\n label=\"Plan\"\n value={plan}\n onChange={setPlan}\n options={[\n { value: 'free', label: 'Free', description: 'Up to 5 projects' },\n { value: 'pro', label: 'Pro', description: 'Unlimited projects' },\n ]}\n/>\n```\n\n### Slider\n\nSlider -- A range input with a custom-styled track, fill, and thumb.\n\nRenders a `<div>` wrapper containing an optional label/value header, and a\ntrack area with three layers: background track, colored fill, and a circular\nthumb. A native `<input type=\"range\">` is overlaid with `opacity: 0` to\nprovide accessible keyboard and pointer interaction.\n\nStyling:\n- Track: 6px tall, `var(--ggui-color-outlineVariant)` background, `border-radius: 3px`\n- Fill: `var(--ggui-color-primary-600)` (normal),\n `var(--ggui-color-outline)` (disabled)\n- Thumb: 20px white circle with `2px solid var(--ggui-color-primary-600)`,\n `var(--ggui-shape-shadow-sm)`; disabled border uses outline\n- Value display (when `showValue`): `var(--ggui-color-primary-600)`,\n `var(--ggui-font-size-sm)`, right-aligned in the header row\n- Fill and thumb transitions: 0.1s for smooth dragging\n\nAccessibility: the native `<input type=\"range\">` carries `aria-valuenow`,\n`aria-valuemin`, `aria-valuemax`, and is linked to the label via `aria-labelledby`.\nFalls back to `aria-label=\"Slider\"` when no label is provided.\n\n**IMPORTANT:** `onChange` receives the numeric value directly, NOT a React\n`ChangeEvent`. The value is coerced via `Number(e.target.value)`.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| label | `string` | - | Label rendered above the slider track (left-aligned). Used as `aria-labelledby` target on the native range input. Styled with `var(--ggui-font-size-sm)` and `var(--ggui-color-onSunken)`. |\n| value | `number` | `0` | Controlled numeric value. Must be between `min` and `max`. |\n| onChange | `(value: number) => void` | - | Change handler. Receives the new numeric value directly, NOT a React event. |\n| min | `number` | `0` | Minimum allowed value. |\n| max | `number` | `100` | Maximum allowed value. |\n| step | `number` | `1` | Step increment for the slider. Determines the granularity of selectable values. |\n| disabled | `boolean` | `false` | When true, sets `cursor: not-allowed` on the native input. The fill color changes to `var(--ggui-color-outline)` and the thumb border also uses outline. |\n| showValue | `boolean` | `false` | When true, displays the current numeric value right-aligned in the header row (beside the label) in `var(--ggui-color-primary-600)`. |\n\n**Example:**\n```tsx\n<Slider label=\"Volume\" value={volume} onChange={setVolume} min={0} max={100} step={5} showValue />\n```\n\n### Badge\n\nBadge -- Inline label for status indicators, counts, or categories.\n\nRenders a `<span>` with `display: inline-flex`, centered content, and\n`white-space: nowrap`. Semantic variant colors use background/text pairings\nfrom the 100/700 color scale. Pill shape uses `border-radius: 9999px`;\nnon-pill uses `var(--ggui-shape-radius-sm)`.\n\nFont weight: `var(--ggui-font-weight-medium)` across all variants.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| children | `ReactNode` | - | children |\n| variant | `'default' \\| 'primary' \\| 'secondary' \\| 'success' \\| 'warning' \\| 'error' \\| 'info' \\| 'tertiary'` | `'default'` | Visual style. Maps to background/text color pairings: - `'default'` -- bg `var(--ggui-color-sunken)`, text `var(--ggui-color-onSunken)` - `'primary'` -- bg `var(--ggui-color-primary-100)`, text `var(--ggui-color-primary-700)` - `'secondary'` -- bg `var(--ggui-color-outlineVariant)`, text `var(--ggui-color-onContainer)` - `'success'` -- bg `var(--ggui-color-success-100)`, text `var(--ggui-color-success-700)` - `'warning'` -- bg `var(--ggui-color-warning-100)`, text `var(--ggui-color-warning-700)` - `'error'` -- bg `var(--ggui-color-error-100)`, text `var(--ggui-color-error-700)` - `'info'` -- bg `var(--ggui-color-info-100)`, text `var(--ggui-color-info-700)` |\n| size | `'sm' \\| 'md' \\| 'lg'` | `'md'` | Controls padding and font size: - `'sm'` -- padding `2px 6px`, font `var(--ggui-font-size-xs)` - `'md'` -- padding `2px 8px`, font `var(--ggui-font-size-xs)` - `'lg'` -- padding `4px 10px`, font `var(--ggui-font-size-sm)` |\n| pill | `boolean` | `true` | When true, uses fully rounded corners (`border-radius: 9999px`). When false, uses `var(--ggui-shape-radius-sm)`. |\n\n**Example:**\n```tsx\n<Badge variant=\"success\" size=\"sm\">Active</Badge>\n```\n\n### Spinner\n\nSpinner -- Animated SVG loading indicator.\n\nRenders an `<svg>` with `role=\"status\"` and `aria-label=\"Loading\"`.\nThe SVG contains a full outlineVariant background circle and a quarter-arc\nforeground stroke in the spinner color.\n\nAnimation: `ggui-spin 1s linear infinite` (360-degree rotation).\nThe `@keyframes ggui-spin` definition is injected inline via a `<style>` tag.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| size | `number` | `24` | Width and height of the SVG element in pixels. The internal viewBox is always `0 0 24 24`, so this controls rendered size only. |\n| tone | `\\| 'default' \\| 'muted' \\| 'subtle' \\| 'emphasized' \\| 'loud' \\| 'success' \\| 'warning' \\| 'error' \\| 'info' \\| 'inverse' \\| 'inherit'` | `undefined (uses `var(--ggui-color-primary-600)`)` | Semantic color slot for the animated foreground arc. Same vocabulary as ; the theme decides the resolved value. The background circle always uses `var(--ggui-color-outlineVariant)`. Use `'inherit'` when the spinner sits inside a colored container (e.g. inside a Button) \u2014 the stroke picks up `currentColor` from the parent so it tracks the container's foreground. |\n\n**Example:**\n```tsx\n<Spinner size={32} tone=\"success\" />\n```\n\n### Avatar\n\nAvatar -- User or entity representation with image or auto-generated initials.\n\nRenders a `<div role=\"img\">` with `overflow: hidden` and `flex-shrink: 0`.\nWhen `src` is provided and loads successfully, renders an `<img>` with\n`object-fit: cover`. On image error (or when no `src`), falls back to\ninitials derived from `name` (up to 2 characters, uppercase).\n\nInitials background: deterministic color from a 5-color palette based on\nname hash (primary-500, success-500, warning-500, error-500, info-500).\nFalls back to `var(--ggui-color-outline)` when no name is given.\nInitials text: white, `font-weight: var(--ggui-font-weight-semibold)`,\n`font-size: resolvedSize * 0.4`.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| src | `string` | - | Image URL. When provided and the image loads, it is rendered with `object-fit: cover`. On load error, falls back to initials. |\n| name | `string` | - | Name used for two purposes: 1. Generating initials (splits on spaces, takes first letter of each word, max 2). 2. Deterministic background color selection via character code hash. Also used as `aria-label` on the container. Falls back to `'Avatar'` if omitted. |\n| size | `number \\| 'xs' \\| 'sm' \\| 'md' \\| 'lg' \\| 'xl'` | `'md'` | Avatar dimensions. Named sizes map to pixel values: - `'xs'` -- 24px - `'sm'` -- 32px - `'md'` -- 40px - `'lg'` -- 48px - `'xl'` -- 64px Numeric values are used directly as pixel dimensions. |\n| shape | `'circle' \\| 'square'` | `'circle'` | Container shape. - `'circle'` -- `border-radius: 50%` - `'square'` -- `border-radius: var(--ggui-shape-radius-md)` |\n\n**Example:**\n```tsx\n<Avatar src=\"/photos/jane.jpg\" name=\"Jane Doe\" size=\"lg\" shape=\"circle\" />\n```\n\n### Alert\n\nAlert -- Contextual message box for important information with icon and optional dismiss.\n\nRenders a `<div role=\"alert\">` with flex layout (12px gap), variant-specific\nbackground, border, text color, and a leading icon. Each variant provides a\ndefault SVG icon (info circle, checkmark, warning triangle, or X circle) that\ncan be overridden via the `icon` prop.\n\nLayout: icon (flex-shrink: 0) | content column (title + body) | close button.\nBorder radius: `var(--ggui-shape-radius-lg)`.\nPadding: `12px 16px`.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| children | `ReactNode` | - | children |\n| variant | `'info' \\| 'success' \\| 'warning' \\| 'error'` | `'info'` | Visual style. Maps to background/border/text/icon color sets: - `'info'` -- bg `var(--ggui-color-info-50)`, border `var(--ggui-color-info-200)`, text `var(--ggui-color-info-800)`, icon `var(--ggui-color-info-500)` - `'success'` -- bg `var(--ggui-color-success-50)`, border `var(--ggui-color-success-200)`, text `var(--ggui-color-success-800)`, icon `var(--ggui-color-success-500)` - `'warning'` -- bg `var(--ggui-color-warning-50)`, border `var(--ggui-color-warning-200)`, text `var(--ggui-color-warning-800)`, icon `var(--ggui-color-warning-500)` - `'error'` -- bg `var(--ggui-color-error-50)`, border `var(--ggui-color-error-200)`, text `var(--ggui-color-error-800)`, icon `var(--ggui-color-error-500)` |\n| title | `string` | - | Optional title rendered above the body in semibold (`var(--ggui-font-weight-semibold)`), `var(--ggui-font-size-sm)`. Title and body are separated by `var(--ggui-spacing-1)` gap. |\n| closable | `boolean` | `false` | When true, renders a close button (X icon) in the top-right area. The button has `min-width: 28px`, `min-height: 28px`, and `opacity: 0.7`. Requires `onClose` to be functional. |\n| onClose | `() => void` | - | Callback fired when the close button is clicked. Only relevant when `closable` is true. |\n| icon | `ReactNode` | - | Custom icon ReactNode to replace the default variant icon. Rendered at the leading position with the variant's icon color applied via `color` CSS property. |\n\n**Example:**\n```tsx\n<Alert variant=\"warning\" title=\"Rate limit\" closable onClose={() => setShow(false)}>\n You have 3 requests remaining this minute.\n</Alert>\n```\n\n### Progress\n\nProgress -- Horizontal progress bar with determinate and indeterminate modes.\n\nRenders a track `<div role=\"progressbar\">` with a colored fill child.\nThe track background is `var(--ggui-color-outlineVariant)` with\npill-shaped corners (border-radius = height / 2).\n\nDeterminate mode: fill width transitions smoothly (`width 0.3s ease`).\nIndeterminate mode: fill is 30% width, animated with\n`ggui-progress-indeterminate 1.5s ease-in-out infinite`\n(translateX from -100% to 400%). The `@keyframes` are injected inline.\n\nAccessibility: `aria-valuenow` is set in determinate mode, omitted in\nindeterminate. `aria-valuemin` is always 0, `aria-valuemax` matches `max`.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| value | `number` | - | Current progress value. Clamped to `[0, max]` and converted to a percentage for the fill width: `Math.min(100, Math.max(0, (value / max) * 100))`. |\n| max | `number` | `100` | Maximum value representing 100% progress. |\n| variant | `'default' \\| 'success' \\| 'warning' \\| 'error'` | `'default'` | Fill bar color. Maps to CSS variables: - `'default'` -- `var(--ggui-color-primary-600)` - `'success'` -- `var(--ggui-color-success-500)` - `'warning'` -- `var(--ggui-color-warning-500)` - `'error'` -- `var(--ggui-color-error-500)` |\n| size | `'sm' \\| 'md' \\| 'lg'` | `'md'` | Controls track height in pixels: - `'sm'` -- 4px - `'md'` -- 8px - `'lg'` -- 12px |\n| label | `string` | - | Accessible name describing what this bar measures, e.g. `\"Survey progress\"` or `\"Upload\"`. Becomes the progressbar's `aria-label` and \u2014 when `showLabel` is set \u2014 the visible header text in place of the generic word \"Progress\". Always pass this when the surrounding context does not already make the meaning obvious. |\n| showLabel | `boolean` | `false` | When true, displays a header row above the track with the `label` text (or \"Progress\" if `label` is unset) on the left, and the rounded percentage value on the right. |\n| indeterminate | `boolean` | `false` | When true, ignores `value` for visual width and plays a looping animation instead. The fill bar is 30% width and slides across the track. Animation: `ggui-progress-indeterminate 1.5s ease-in-out infinite`. `aria-valuenow` is omitted from the progressbar element. |\n\n**Example:**\n```tsx\n<Progress value={65} variant=\"success\" size=\"md\" showLabel />\n```\n\n### Image\n\nImage -- An `<img>` element with built-in error handling and fallback support.\n\nRenders a native `<img>` with `display: block`. On load error, either renders\nthe `fallback` ReactNode (if provided) or a default placeholder `<div>` with a\nsurfaceVariant background and a centered image SVG icon in outline.\n\nSize values: numbers are treated as pixels, strings are passed through as-is.\nWhen no `width` is set, defaults to `100%`. When no `height` is set, defaults\nto `auto`.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| src | `string` | - | Image source URL. Load failure triggers the fallback state. |\n| alt | `string` | - | Alt text for the image. Used as `aria-label` in the error placeholder too. |\n| width | `number \\| string` | `'100%' (applied at render time, not on the type)` | Image width. Numbers are pixels, strings are CSS values (e.g., `'100%'`, `'50vw'`). |\n| height | `number \\| string` | `'auto' (applied at render time, not on the type)` | Image height. Numbers are pixels, strings are CSS values. |\n| objectFit | `'cover' \\| 'contain' \\| 'fill' \\| 'none' \\| 'scale-down'` | `'cover'` | CSS `object-fit` value controlling how the image fills its box. |\n| radius | `'none' \\| 'sm' \\| 'md' \\| 'lg' \\| 'xl' \\| number \\| string` | - | Corner radius applied to both the image and the error placeholder. Prefer a radius-scale name (`'none' \\| 'sm' \\| 'md' \\| 'lg' \\| 'xl'`) \u2014 each resolves to the matching `--ggui-shape-radius-*` token. A number is treated as pixels; any other string is passed through. |\n| fallback | `ReactNode` | - | Custom ReactNode rendered when the image fails to load. When provided, completely replaces the default error placeholder (no wrapper div). When omitted, a surfaceVariant background div with an image icon is shown. |\n\n**Example:**\n```tsx\n<Image src=\"/hero.jpg\" alt=\"Hero banner\" width=\"100%\" height={400} objectFit=\"cover\" radius=\"md\" />\n```\n\n### Icon\n\nIcon -- a curated Lucide subset (~200 names) + emoji passthrough.\n\nThree resolution layers:\n1. **Lucide icon:** pass a name from the curated subset (e.g. `sun`, `cloud-rain`, `heart`, `shopping-cart`, `sparkles`, `arrow-up-right`).\n Accepts kebab-case, camelCase, or PascalCase. Renders as stroke SVG. ONLY the subset renders: an\n unknown name renders an empty box (never a placeholder glyph) \u2014 the `get_available_icons` tool lists the exact names.\n2. **Emoji:** pass emoji/unicode directly (e.g. `\u2600\uFE0F`, `\u{1F327}\uFE0F`). Rendered as text.\n3. **Custom SVG:** pass children (`<svg>` element) for full control.\n\nContainer: `<span>` with `display: inline-flex`, centered content.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| name | `string` | - | Lucide icon name from the curated subset (kebab-case, camelCase, or PascalCase all work); a name outside the subset renders an empty box. Also accepts emoji/unicode characters directly. |\n| size | `number` | `24` | Icon dimensions in pixels (applied to both width and height of the wrapper and the inner SVG element). |\n| tone | `\\| 'default' \\| 'muted' \\| 'subtle' \\| 'emphasized' \\| 'loud' \\| 'success' \\| 'warning' \\| 'error' \\| 'info' \\| 'inverse' \\| 'inherit'` | `undefined (icon uses `currentColor`)` | Semantic color slot. Same vocabulary as ; the theme decides what each tone LOOKS like. Resolves to a CSS `color` on the wrapper which the inner SVG inherits via `currentColor`. Use `'inherit'` (the default behavior when unset) for icons that should pick up the parent's foreground color. |\n| children | `ReactNode` | - | Custom SVG children. When provided, `name` is ignored and children are rendered inside a sized `<span>` wrapper. |\n| 'aria-label' | `string` | - | Accessible name for a standalone, meaning-bearing icon. When set, the icon exposes `role=\"img\"` + this label. When omitted (the default) the icon is decorative and hidden from screen readers (`aria-hidden`) \u2014 the right choice for an icon next to a text label. |\n\n**Example:**\n```tsx\n<Icon name=\"search\" size={20} tone=\"muted\" />\n<Icon name=\"cloud-rain\" size={32} />\n<Icon name=\"\u2600\uFE0F\" size={24} />\n```\n\n### Link\n\nLink -- Styled anchor element with external link support.\n\nRenders a native `<a>` element. When `external` is true, sets\n`target=\"_blank\"` and `rel=\"noopener noreferrer\"`, and appends a small\n(12px) external-link SVG icon after the children.\n\nTransition: `color 0.2s`.\nUnderline behavior is controlled via mouseEnter/mouseLeave event handlers\n(for the `'hover'` mode).\n\nAlso extends native `AnchorHTMLAttributes` (except `style`/`className`),\nso props like `aria-*`, `data-*`, `title`, etc. are forwarded to the `<a>`.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| children | `ReactNode` | - | children |\n| href | `string` | - | Destination URL. Passed directly to the `<a href>` attribute. |\n| external | `boolean` | `false` | When true, opens link in a new tab (`target=\"_blank\"`, `rel=\"noopener noreferrer\"`) and appends a 12px external-link icon after children. |\n| tone | `\\| 'default' \\| 'muted' \\| 'subtle' \\| 'emphasized' \\| 'loud' \\| 'success' \\| 'warning' \\| 'error' \\| 'info' \\| 'inverse' \\| 'inherit'` | `undefined (uses `var(--ggui-color-primary-600)`)` | Semantic color slot for the link text. Same vocabulary as ; the theme decides what each tone LOOKS like. Defaults to a primary-tinted accent (`'loud'`-ish) when unset. |\n| underline | `'always' \\| 'hover' \\| 'none'` | `'hover'` | Underline behavior: - `'always'` -- `text-decoration: underline` at all times - `'hover'` -- underline appears on mouse enter, removed on mouse leave - `'none'` -- no underline ever |\n\n**Example:**\n```tsx\n<Link href=\"https://docs.ggui.ai\" external>Documentation</Link>\n```\n\n### Tooltip\n\nTooltip -- Hoverable information popup positioned relative to a trigger element.\n\nWraps `children` in a `<div>` trigger (display: inline-block) and renders\na fixed-position tooltip `<div role=\"tooltip\">` when visible.\n\nTooltip appearance:\n- Background: `var(--ggui-color-onContainer)`\n- Text: white, `var(--ggui-font-size-xs)`\n- Padding: `6px 10px`, border-radius: `var(--ggui-shape-radius-md)`\n- Max width: 200px, `white-space: nowrap`, `pointer-events: none`\n- Z-index: `zIndex.tooltip` (1800)\n\nShow/hide: triggered by mouseEnter/mouseLeave AND focus/blur on the\ntrigger element. Uses `position: fixed` with coordinates calculated from\n`getBoundingClientRect()` and an 8px offset from the trigger edge.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| children | `ReactNode` | - | Trigger element. Wrapped in a `<div>` with mouseEnter/mouseLeave and focus/blur handlers. |\n| content | `ReactNode` | - | Tooltip content. Can be text or any ReactNode. |\n| position | `'top' \\| 'bottom' \\| 'left' \\| 'right'` | `'top'` | Tooltip placement relative to the trigger element: - `'top'` -- above, centered horizontally, transformed `translateX(-50%) translateY(-100%)` - `'bottom'` -- below, centered horizontally, transformed `translateX(-50%)` - `'left'` -- to the left, centered vertically, transformed `translateX(-100%) translateY(-50%)` - `'right'` -- to the right, centered vertically, transformed `translateY(-50%)` |\n| delay | `number` | `200` | Delay in milliseconds before the tooltip becomes visible after hover/focus. Hiding is immediate (no delay). |\n\n**Example:**\n```tsx\n<Tooltip content=\"Copy to clipboard\" position=\"top\">\n <Button variant=\"ghost\"><Icon name=\"copy\" /></Button>\n</Tooltip>\n```\n\n### Table\n\nTable -- Data table with sortable columns, striped rows, and hover highlights.\n\nRenders a scrollable wrapper `<div>` containing a native `<table>` with\n`border-collapse: collapse` and `width: 100%`. The wrapper has\n`overflow-x: auto` for horizontal scrolling on narrow viewports.\n\nHeader row: 2px bottom border (`var(--ggui-color-outlineVariant)`).\nData rows: 1px bottom border (`var(--ggui-color-sunken)`).\nHover: `var(--ggui-color-container)` background with 150ms ease transition.\nStriped: alternating rows (odd index) get `var(--ggui-color-container)`.\n\nSort behavior: clicking a sortable column header calls `onSort(key, direction)`.\nIf the same column is clicked again while ascending, it toggles to descending.\nThe component does NOT sort data internally -- the parent must sort `data` and\npass updated `sortKey`/`sortDirection`.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| columns | `TableColumn<T>[]` | - | Array of column definitions controlling header labels, data keys, and rendering. |\n| data | `T[]` | - | Array of row data objects. Each object's keys should match the column `key` values. |\n| sortKey | `string` | - | The `key` of the currently sorted column. Used to highlight the active sort indicator and determine toggle direction on next click. |\n| sortDirection | `SortDirection` | `'asc'` | Current sort direction for the column identified by `sortKey`. Controls which triangle indicator is highlighted in the header. |\n| onSort | `(key: string, direction: SortDirection) => void` | - | Sort change handler. Called when a sortable column header is clicked. Receives the column `key` and the new `SortDirection`. The component does NOT sort data internally -- you must sort `data` in your state and pass updated `sortKey`/`sortDirection`. |\n| striped | `boolean` | `false` | When true, alternating rows (odd index) get a `var(--ggui-color-container)` background. |\n| hoverable | `boolean` | `true` | When true, rows highlight with `var(--ggui-color-container)` on mouse enter, with a 150ms ease background-color transition. |\n| compact | `boolean` | `false` | When true, reduces cell padding: - Compact: `var(--ggui-spacing-1) var(--ggui-spacing-2)` - Normal: `var(--ggui-spacing-2) var(--ggui-spacing-4)` |\n| bordered | `boolean` | `false` | When true, adds a 1px border around the table wrapper and between cells. Wrapper border: `1px solid var(--ggui-color-outlineVariant)`. Cell borders: `1px solid var(--ggui-color-sunken)`. Wrapper border-radius: `var(--ggui-shape-radius-lg)`. |\n| caption | `string` | - | Accessible table caption. Rendered as a `<caption>` element with `caption-side: top`, `var(--ggui-font-size-sm)`, `var(--ggui-color-onSunken)`. |\n\n**Example:**\n```tsx\n<Table\n columns={[\n { key: 'name', header: 'Name', sortable: true },\n { key: 'role', header: 'Role' },\n { key: 'status', header: 'Status', render: (v) => <Badge variant={v as string}>{v as string}</Badge> },\n ]}\n data={users}\n sortKey={sortKey}\n sortDirection={sortDir}\n onSort={(key, dir) => { setSortKey(key); setSortDir(dir); }}\n striped\n/>\n```\n\n### Tabs\n\nTabs -- Accessible tab navigation with panels and keyboard support.\n\nRenders a `<div role=\"tablist\">` with `<button role=\"tab\">` elements and a\n`<div role=\"tabpanel\">` for the active tab's content. Supports controlled\n(`activeKey` + `onChange`) and uncontrolled (internal state) modes.\n\nKeyboard navigation: ArrowLeft/ArrowRight (and ArrowUp/ArrowDown) cycle\nthrough enabled tabs. Home/End jump to first/last. Focus follows selection.\nDisabled tabs are skipped during keyboard navigation.\n\n**IMPORTANT:** `onChange` receives the tab's `key` string directly, NOT a\nReact event.\n\nTab panel padding: `var(--ggui-spacing-4) 0` (top/bottom only).\nTransitions: color, background-color, border-color at 200ms ease-in-out.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| items | `TabItem[]` | - | Array of tab definitions. Must contain at least one item. |\n| activeKey | `string` | - | Controlled active tab key. When provided, the component is controlled and will not manage its own state. Must match one of `items[].key`. When omitted, defaults to the first item's key (uncontrolled mode). |\n| onChange | `(key: string) => void` | - | Tab change handler. Receives the selected tab's `key` string directly, NOT a React event. In controlled mode, you must update `activeKey` in response to this callback. |\n| variant | `'line' \\| 'pills' \\| 'enclosed'` | `'line'` | Visual style of the tab bar: - `'line'` -- underline indicator (2px solid primary-600 on active), border-bottom on tab list - `'pills'` -- filled pill buttons (primary-600 bg, white text on active), surfaceVariant container with radius-lg - `'enclosed'` -- bordered tab buttons with open bottom (card-style), border-bottom on tab list |\n| size | `'sm' \\| 'md' \\| 'lg'` | `'md'` | Controls tab button padding and font size: - `'sm'` -- padding `var(--ggui-spacing-1) var(--ggui-spacing-2)`, font `var(--ggui-font-size-xs)` - `'md'` -- padding `var(--ggui-spacing-2) var(--ggui-spacing-4)`, font `var(--ggui-font-size-sm)` - `'lg'` -- padding `var(--ggui-spacing-4) var(--ggui-spacing-6)`, font `var(--ggui-font-size-base)` |\n| fullWidth | `boolean` | `false` | When true, tab buttons expand equally to fill the container width (`flex: 1`, `justify-content: center` on each button). |\n\n**Example:**\n```tsx\n<Tabs\n variant=\"pills\"\n items={[\n { key: 'overview', label: 'Overview', content: <Overview /> },\n { key: 'settings', label: 'Settings', content: <Settings /> },\n ]}\n activeKey={tab}\n onChange={setTab}\n/>\n```\n\n### Toast\n\nToast -- Notification banner with auto-dismiss and slide-in animation.\n\nRenders a `<div role=\"alert\" aria-live=\"assertive\">` with a variant-specific\nicon, optional title, message body, and optional close button.\n\nAnimation: `ggui-slideInUp 200ms ease-out both` on mount (from the motion\ntoken system). The keyframes are provided by the MotionKeyframes provider.\n\nAuto-dismiss: when `onClose` is provided and `duration > 0`, a timer calls\n`onClose` after `duration` ms. Setting `duration` to `0` disables auto-dismiss.\nThe timer resets if `visible`, `duration`, or `onClose` changes.\n\nDimensions: `min-width: 280px`, `max-width: 420px`.\nShadow: `var(--ggui-shape-shadow-lg)`.\nBorder radius: `var(--ggui-shape-radius-lg)`.\n\nWhen `visible` is false, renders nothing (returns `null`).\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| message | `ReactNode` | - | Message body content. Can be text or any ReactNode. |\n| variant | `'info' \\| 'success' \\| 'warning' \\| 'error'` | `'info'` | Visual style. Maps to background/border/text/icon color sets (same palette as Alert): - `'info'` -- bg `var(--ggui-color-info-50)`, border `var(--ggui-color-info-200)`, text `var(--ggui-color-info-800)` - `'success'` -- bg `var(--ggui-color-success-50)`, border `var(--ggui-color-success-200)`, text `var(--ggui-color-success-800)` - `'warning'` -- bg `var(--ggui-color-warning-50)`, border `var(--ggui-color-warning-200)`, text `var(--ggui-color-warning-800)` - `'error'` -- bg `var(--ggui-color-error-50)`, border `var(--ggui-color-error-200)`, text `var(--ggui-color-error-800)` |\n| title | `string` | - | Optional title rendered above the message in semibold (`var(--ggui-font-weight-semibold)`, `var(--ggui-font-size-sm)`). |\n| duration | `number` | `5000` | Auto-dismiss delay in milliseconds. After this duration, `onClose` is called automatically. Set to `0` to disable auto-dismiss (toast stays until manually closed). The timer is only active when both `visible` is true and `onClose` is provided. |\n| onClose | `() => void` | - | Callback fired on auto-dismiss timeout or when the close button is clicked. When provided, a close button (X icon, 16px) is rendered in the top-right area. When omitted, no close button is shown and auto-dismiss is disabled. |\n| visible | `boolean` | `true` | Controls rendering. When false, the component returns `null`. Toggling from false to true triggers the slide-in animation. |\n| position | `'top-right' \\| 'top-left' \\| 'bottom-right' \\| 'bottom-left' \\| 'top-center' \\| 'bottom-center'` | - | Intended screen position. This prop is defined on the interface but is NOT implemented by the Toast component itself -- positioning must be handled by a parent container or toast manager. |\n\n**Example:**\n```tsx\n<Toast variant=\"success\" title=\"Saved\" message=\"Your changes have been saved.\" onClose={() => setShow(false)} />\n```\n\n### Accordion\n\nAccordion -- Collapsible content sections with chevron rotation animation.\n\nRenders a vertical list of items, each with a `<button>` header (inside `<h3>`)\nand a `<div role=\"region\">` panel. Supports controlled (`expandedKeys` + `onChange`)\nand uncontrolled (internal state) modes.\n\nChevron animation: the trailing chevron icon rotates from 0deg (collapsed) to\n180deg (expanded) with `transition: transform var(--ggui-motion-duration-base) var(--ggui-motion-easing-standard)` (ggui#1106).\n\nHeader button: full-width flex layout (`justify-content: space-between`),\n`var(--ggui-font-size-sm)`, `var(--ggui-font-weight-medium)`,\n`var(--ggui-color-onContainer)`.\nHeader padding: `var(--ggui-spacing-2) var(--ggui-spacing-4)`.\nBackground transition: `background-color var(--ggui-motion-duration-fast) var(--ggui-motion-easing-standard)`.\n\n**IMPORTANT:** `onChange` receives the full array of currently expanded keys,\nNOT a single key or a React event. In single mode (`multiple: false`), this\narray will have at most one element.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| items | `AccordionItem[]` | - | Array of collapsible section definitions. |\n| expandedKeys | `string[]` | - | Controlled expanded state. Array of item `key` values that should be open. When provided, the component is controlled and will not manage its own expansion state. When omitted, defaults to `[]` (all collapsed, uncontrolled mode). |\n| onChange | `(expandedKeys: string[]) => void` | - | Expand/collapse handler. Receives the complete array of expanded keys after a toggle. In controlled mode, you must update `expandedKeys` in response to this callback. |\n| multiple | `boolean` | `false` | When true, multiple items can be open simultaneously. When false, opening one item closes any other open item (single-expand mode). |\n| variant | `'default' \\| 'bordered' \\| 'separated'` | `'default'` | Visual style controlling borders and spacing: - `'default'` -- top border on first item, bottom border on all items (`var(--ggui-color-outlineVariant)`), no gap between items - `'bordered'` -- connected card style with left/right/bottom borders on all items, top border on first, shared rounded corners (radius-lg on first/last) - `'separated'` -- each item is an independent card with full border (`1px solid var(--ggui-color-outlineVariant)`), `var(--ggui-shape-radius-lg)` radius, `var(--ggui-spacing-2)` gap between items |\n\n**Example:**\n```tsx\n<Accordion\n variant=\"separated\"\n items={[\n { key: 'faq1', title: 'How do I get started?', content: 'Sign up and...' },\n { key: 'faq2', title: 'What is the pricing?', content: 'We offer...' },\n ]}\n expandedKeys={expanded}\n onChange={setExpanded}\n multiple\n/>\n```\n\n### Support Types\n\n**ResponsiveColumns:**\n\nExplicit column count per viewport breakpoint, mobile-first. `base`\napplies from 0 up; each named key overrides at and above its\nbreakpoint width (`sm` 640px, `md` 768px, `lg` 1024px, `xl` 1280px).\nOmit `base` to default to a single column on the narrowest screens.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| base | `number` | Columns below the `sm` breakpoint. |\n| sm | `number` | Columns from 640px up. |\n| md | `number` | Columns from 768px up. |\n| lg | `number` | Columns from 1024px up. |\n| xl | `number` | Columns from 1280px up. |\n\n**SelectOption:**\n\nAn individual option within a `Select` dropdown.\n\nRendered as a native `<option>` element. When `disabled` is true, the option\nis visible but not selectable.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| value | `string` | The value submitted when this option is selected. Must be unique within the options array. |\n| label | `string` | The display text shown in the dropdown. |\n| disabled | `boolean` | When true, the option is visible but cannot be selected (grayed out by the browser). |\n\n**RadioOption:**\n\nAn individual option within a `RadioGroup`.\n\nRendered as a `<label>` containing a visually-hidden `<input type=\"radio\">`\nand a custom 18px circle indicator. Supports an optional description line\nbelow the label text.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| value | `string` | The value emitted via `RadioGroupProps.onChange` when this option is selected. Must be unique. |\n| label | `string` | Display text for this option. Styled with `var(--ggui-font-size-sm)` and `var(--ggui-color-onContainer)`. |\n| description | `string` | Optional secondary description rendered below the label in smaller, muted type (`var(--ggui-font-size-xs)`, `var(--ggui-color-onSunken)`). |\n| disabled | `boolean` | When true, this individual option is grayed out (`opacity: 0.5`) and cannot be selected, regardless of the group-level `disabled` prop. |\n\n**TableColumn:**\n\nColumn definition for the Table component.\n\nEach column maps a `key` in the row data object to a table column with\na header label, optional sorting, alignment, width, and custom rendering.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| key | `string` | Property key in the row data object. Used to extract cell values via `row[key]`. Must be unique across all columns in a Table. |\n| header | `string` | Column header text. Rendered in uppercase, `var(--ggui-font-size-xs)`, `var(--ggui-font-weight-semibold)`, `var(--ggui-color-onSunken)`, with `letter-spacing: 0.05em`. |\n| width | `number \\| string` | Fixed column width. Numbers are pixels, strings are CSS values (e.g., `'200px'`, `'30%'`). When omitted, the column auto-sizes based on content. |\n| align | `'left' \\| 'center' \\| 'right'` | Horizontal text alignment for both the header and data cells. |\n| sortable | `boolean` | When true, the header cell becomes clickable and shows sort direction indicators (ascending/descending triangles). Clicking toggles between `'asc'` and `'desc'`. The header gets `cursor: pointer`, `tabIndex: 0`, and keyboard support (Enter/Space to toggle). |\n| render | `(value: unknown, row: T, index: number) => ReactNode` | Custom cell renderer. When provided, called instead of rendering `row[key]` directly. Receives the cell value, the full row object, and the row index. |\n\n**TabItem:**\n\nDefinition of a single tab within a Tabs component.\n\nEach item provides a unique `key` for identification, a `label` for the\ntab button, and `content` for the associated panel.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| key | `string` | Unique identifier for this tab. Used to match `activeKey` and as the value passed to `onChange`. |\n| label | `ReactNode` | Tab button label. Can be text or any ReactNode. |\n| content | `ReactNode` | Panel content rendered below the tab bar when this tab is active. |\n| disabled | `boolean` | When true, the tab button shows `opacity: 0.5`, `cursor: not-allowed`, and cannot be selected via click or keyboard navigation. |\n| icon | `ReactNode` | Optional icon rendered before the label inside the tab button, with `var(--ggui-spacing-1)` gap between icon and label. |\n\n**AccordionItem:**\n\nDefinition of a single collapsible section within an Accordion.\n\nEach item provides a unique `key`, a clickable `title` for the header button,\nand `content` revealed when expanded.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| key | `string` | Unique identifier for this item. Used in `expandedKeys` and passed to `onChange`. |\n| title | `ReactNode` | Header label rendered inside the toggle button. Can be text or any ReactNode. |\n| content | `ReactNode` | Panel content rendered below the header when expanded. Styled with `var(--ggui-font-size-sm)`, `var(--ggui-color-onContainer)`, `line-height: var(--ggui-font-lineHeight-normal)`. Padding: `0 var(--ggui-spacing-4) var(--ggui-spacing-4)`. |\n| disabled | `boolean` | When true, the header button shows `opacity: 0.5`, `cursor: not-allowed`, and cannot be toggled. |\n\n\n## Components\n\nImport: `import { Component } from '@ggui-ai/design'`\n\n### SearchField\n\nA text input with a leading search icon and optional submit button.\n\nComposes: `Input` (native `<input type=\"search\">`), `Button`, `Spinner`, `Icon`.\n\nSupports controlled and uncontrolled usage. When `value` is `undefined` the\ncomponent tracks its own state internally. Pressing **Enter** triggers\n`onSearch` with the current value. When `loading` is `true` the search icon\nis replaced by a `Spinner` and the input is disabled.\n\nTokens used: `colors.gray[300]` border, `colors.gray[50]` disabled bg,\n`colors.gray[400]` icon color, `colors.gray[900]` text color.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| value | `string` | - | Current search value. When provided, the component is **controlled** and the caller must update this via `onChange`. When omitted, the component manages its own internal state. |\n| onChange | `(value: string) => void` | - | Called on every keystroke with the new input string (value directly, not a React `ChangeEvent`). |\n| onSearch | `(value: string) => void` | - | Called when the user presses **Enter** or clicks the search button (if `showButton` is `true`). Receives the current value directly. |\n| placeholder | `string` | `'Search...'` | Placeholder text shown when the input is empty. |\n| showButton | `boolean` | `false` | When `true`, renders a `Button` primitive to the right of the input. The button's label is set by `buttonText`. |\n| buttonText | `string` | `'Search'` | Label rendered inside the submit button. Only visible when `showButton` is `true`. |\n| loading | `boolean` | - | When `true`, replaces the search icon with a `Spinner`, disables the input, and disables the submit button. |\n| disabled | `boolean` | - | When `true`, the input and button are visually disabled and do not respond to interaction. The input background changes to `colors.gray[50]`. |\n| size | `'sm' \\| 'md' \\| 'lg'` | `'md'` | Controls input height and font size. - `'sm'` -- 6px vertical padding, 14px font - `'md'` -- 10px vertical padding, 14px font - `'lg'` -- 12px vertical padding, 16px font The Button size maps `sm`->`sm`, `md`->`md`, `lg`->`md`. |\n\n**Example:**\n```tsx\n```tsx\n<SearchField\n value={query}\n onChange={setQuery}\n onSearch={(q) => fetchResults(q)}\n placeholder=\"Search products...\"\n showButton\n buttonText=\"Go\"\n size=\"md\"\n/>\n```\n```\n\n### FormField\n\nA wrapper that adds a label, optional description, error message,\nand helper text around any form input passed as `children`.\n\nComposes: no other primitives -- pure layout with semantic `<label>` and\n`<span>` elements.\n\nVisual hierarchy (top to bottom):\n1. **Label** (required) -- `fontSize.sm`, `fontWeight.medium`, `colors.gray[700]`\n2. **Required indicator** -- red asterisk (`colors.error[500]`) appended to label\n3. **Description** -- `fontSize.xs`, `colors.gray[500]`, 4px bottom margin\n4. **Children** -- the form control itself\n5. **Error / Helper text** -- `fontSize.xs`; error in `colors.error[500]`,\n helper in `colors.gray[500]`. Error takes priority when both are provided.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| label | `string` | - | Text rendered inside the `<label>` element above the input. |\n| children | `ReactNode` | - | The form control (typically an `Input`, `Select`, or `Textarea` primitive) rendered between the label/description and the error/helper row. |\n| error | `string` | - | Error message displayed below `children` in `colors.error[500]`. When present, it takes precedence over `helperText`. |\n| helperText | `string` | - | Neutral guidance text displayed below `children` in `colors.gray[500]`. Hidden when `error` is present. |\n| required | `boolean` | - | When `true`, appends a red asterisk (`*`) after the label text. Does **not** add any HTML validation attributes -- handle that on the child input. |\n| description | `string` | - | Secondary description rendered between the label and the child control in `fontSize.xs` / `colors.gray[500]`. Use for longer guidance that does not belong in `helperText`. |\n\n**Example:**\n```tsx\n```tsx\n<FormField\n label=\"Email address\"\n required\n description=\"We will never share your email.\"\n error={errors.email}\n>\n <Input value={email} onChange={setEmail} placeholder=\"you@example.com\" />\n</FormField>\n```\n```\n\n### MenuItem\n\nA full-width clickable row for menus, sidebars, and action lists.\n\nComposes: none -- renders a native `<button>` element.\n\nBuilt-in transition: `background-color` over `var(--ggui-motion-duration-fast)` / `var(--ggui-motion-easing-standard)` on hover (ggui#1106).\n\nColor logic:\n- **Normal**: text `colors.gray[700]`, hover bg `colors.gray[100]`\n- **Active**: bg `colors.primary[50]`, text `colors.gray[700]`, `fontWeight.medium`\n- **Danger**: text `colors.error[600]`, hover bg `colors.error[50]`, active bg `colors.error[100]`\n- **Disabled**: text `colors.gray[400]`, `cursor: not-allowed`\n\nLayout: flexbox row with `8px` gap, `8px 12px` padding, `radius.md` border-radius.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| label | `string` | - | Primary text content of the menu item. |\n| icon | `ReactNode` | - | Icon or element rendered to the left of the label. Flex-shrink 0. |\n| rightElement | `ReactNode` | - | Element rendered to the right of the label (e.g., a keyboard shortcut badge or a count). Colored `colors.gray[400]`, flex-shrink 0. |\n| onClick | `() => void` | - | Called when the item is clicked. Suppressed when `disabled` is `true`. |\n| disabled | `boolean` | - | When `true`, the item is non-interactive: `colors.gray[400]` text, `cursor: not-allowed`, click handler suppressed. |\n| active | `boolean` | - | Marks this item as the current selection. Applies a tinted background (`colors.primary[50]`, or `colors.error[100]` when `danger` is also set) and `fontWeight.medium`. |\n| danger | `boolean` | - | Switches the item to destructive styling: `colors.error[600]` text, `colors.error[50]` hover background. |\n\n**Example:**\n```tsx\n```tsx\n<MenuItem\n label=\"Delete project\"\n icon={<Icon name=\"trash\" size={16} />}\n danger\n onClick={() => confirmDelete(projectId)}\n/>\n```\n```\n\n### Tag\n\nAn inline label for categories, filters, statuses, or selections.\nOptionally dismissable via a close button.\n\nComposes: none -- pure `<span>` with an optional close `<button>`.\n\nEach `variant` maps to a background / text / border color triple from the\ndesign tokens:\n- `'default'` -- `gray[100]` / `gray[700]` / `gray[200]`\n- `'primary'` -- `primary[50]` / `primary[700]` / `primary[200]`\n- `'success'` -- `success[50]` / `success[700]` / `success[200]`\n- `'warning'` -- `warning[50]` / `warning[700]` / `warning[200]`\n- `'error'` -- `error[50]` / `error[700]` / `error[200]`\n- `'info'` -- `info[50]` / `info[700]` / `info[200]`\n\nThe close button renders an inline SVG \"x\" icon (12x12) with `opacity: 0.7`\nand an `aria-label=\"Remove\"`.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| children | `ReactNode` | - | Tag content -- typically a short text string. |\n| variant | `'default' \\| 'primary' \\| 'success' \\| 'warning' \\| 'error' \\| 'info'` | `'default'` | Semantic color variant applied to background, text, and border. |\n| size | `'sm' \\| 'md' \\| 'lg'` | `'md'` | Controls padding, font size, and internal gap. - `'sm'` -- 2px/6px padding, `fontSize.xs`, 4px gap - `'md'` -- 4px/8px padding, `fontSize.xs`, 6px gap - `'lg'` -- 6px/10px padding, `fontSize.sm`, 6px gap |\n| closable | `boolean` | - | When `true`, renders a small close (\"x\") button after the content. Clicking it fires `onClose`. |\n| onClose | `() => void` | - | Called when the close button is clicked. Only relevant when `closable` is `true`. |\n| icon | `ReactNode` | - | Icon or element rendered before the text content. |\n\n**Example:**\n```tsx\n```tsx\n<Tag variant=\"success\" size=\"md\" closable onClose={() => removeFilter(id)}>\n Active\n</Tag>\n```\n```\n\n### Dropdown\n\nA click-triggered menu anchored to a trigger element. Manages its own\nopen/close state internally.\n\nComposes: `MenuItem` for each option.\n\nBehavior:\n- Clicking the trigger toggles the menu open/closed.\n- Selecting an option calls `onChange(option.value)` and closes the menu.\n- Clicking outside the container or pressing **Escape** closes the menu.\n- The currently selected option (matching `value`) is rendered with\n `MenuItem`'s `active` state.\n\nMenu panel: `colors.white` bg, `colors.gray[200]` border, `radius.lg`\nborder-radius, `shadow.lg`, `zIndex.dropdown`, 160px min-width, 4px padding.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| trigger | `ReactNode` | - | The element the user clicks to open the menu. Receives a wrapping `<div>` with `cursor: pointer` (or `not-allowed` when disabled). |\n| options | `DropdownOption[]` | - | Array of selectable options rendered as `MenuItem` rows. |\n| value | `string` | - | The `value` of the currently selected option. The matching `MenuItem` is rendered with `active` styling. |\n| onChange | `(value: string) => void` | - | Called with the `value` string of the selected option (not the full `DropdownOption` object). The menu closes immediately after. |\n| placement | `'bottom-start' \\| 'bottom-end' \\| 'top-start' \\| 'top-end'` | `'bottom-start'` | Where to anchor the menu panel relative to the trigger. - `'bottom-start'` -- below, aligned to left edge - `'bottom-end'` -- below, aligned to right edge - `'top-start'` -- above, aligned to left edge - `'top-end'` -- above, aligned to right edge |\n| disabled | `boolean` | - | When `true`, the trigger shows `cursor: not-allowed` and clicking it does not open the menu. |\n\n**Example:**\n```tsx\n```tsx\n<Dropdown\n trigger={<Button variant=\"outline\">Sort by</Button>}\n options={[\n { value: 'name', label: 'Name' },\n { value: 'date', label: 'Date created' },\n { value: 'delete', label: 'Delete', danger: true },\n ]}\n value={sortBy}\n onChange={setSortBy}\n placement=\"bottom-end\"\n/>\n```\n```\n\n### Autocomplete\n\nA text input with a filterable suggestion dropdown, keyboard navigation,\nand loading/empty states.\n\nComposes: `Input` primitive (with `label`, `error`, `placeholder` forwarded),\n`Spinner` (loading state).\n\nFiltering: options are filtered client-side by case-insensitive substring\nmatch against both `option.label` and `option.value`.\n\nKeyboard support:\n- **ArrowDown / ArrowUp** -- move highlight through filtered options\n (opens dropdown if closed)\n- **Enter** -- selects the highlighted option\n- **Escape** -- closes the dropdown\n\nOn selection, `onChange` is called with `option.label` (the display text)\nand `onSelect` is called with the full `AutocompleteOption` object.\n\nDropdown panel: `colors.white` bg, `colors.gray[200]` border, `radius.lg`\nborder-radius, `shadow.lg`, `zIndex.dropdown`, max-height 240px with\noverflow scroll.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| value | `string` | `''` | Current text in the input field. On selection, this is set to the selected option's `label`. |\n| onChange | `(value: string) => void` | - | Called on every keystroke with the new input string (value directly, not a React event). Also called on selection with `option.label`. |\n| onSelect | `(option: AutocompleteOption) => void` | - | Called when the user selects an option (click or Enter on highlighted item). Receives the full `AutocompleteOption` object, not just the value string. |\n| options | `AutocompleteOption[]` | - | The full list of available options. Filtering is handled internally via case-insensitive substring match on `label` and `value`. |\n| placeholder | `string` | - | Placeholder text forwarded to the inner `Input` primitive. |\n| label | `string` | - | Label text forwarded to the inner `Input` primitive. |\n| loading | `boolean` | - | When `true`, the dropdown shows a centered `Spinner` instead of the option list. The input remains interactive. |\n| disabled | `boolean` | - | When `true`, the inner `Input` is disabled and the dropdown does not open. |\n| error | `string` | - | Error message forwarded to the inner `Input` primitive. |\n| noResultsText | `string` | `'No results found'` | Text shown in the dropdown when filtering produces zero matches. Rendered centered in `colors.gray[500]` / `fontSize.sm`. |\n\n**Example:**\n```tsx\n```tsx\n<Autocomplete\n label=\"Country\"\n value={country}\n onChange={setCountry}\n onSelect={(opt) => setCountryCode(opt.value)}\n options={countries}\n placeholder=\"Type to search...\"\n noResultsText=\"No countries found\"\n/>\n```\n```\n\n### Breadcrumb\n\nA horizontal navigation trail showing the user's location within a\nhierarchy. Renders a `<nav aria-label=\"Breadcrumb\">`.\n\nComposes: `Link` primitive (for items with `href`).\n\nRendering rules per item:\n- **Last item**: static `<span>` with `colors.gray[900]`, `fontWeight: 500`,\n and `aria-current=\"page\"`.\n- **Non-last with `href`**: `Link` in `colors.gray[500]` with\n `underline=\"hover\"`. If `onItemClick` is provided, `e.preventDefault()`\n is called and the handler fires instead of navigating.\n- **Non-last without `href`**: unstyled `<button>` in `colors.gray[500]`.\n\nLayout: flexbox row, `8px` gap, `fontSize.sm`.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| items | `BreadcrumbItem[]` | - | Ordered array of breadcrumb segments from root to current page. |\n| separator | `ReactNode` | `'/'` | Separator rendered between each pair of items. Can be a string (e.g., `\"/\"`, `\">\"`) or a ReactNode (e.g., an `Icon`). Rendered in `colors.gray[400]`. |\n| onItemClick | `(item: BreadcrumbItem, index: number) => void` | - | Called when a non-last item is clicked. Receives the `BreadcrumbItem` and its zero-based `index`. When provided on items that have `href`, the default navigation is prevented via `e.preventDefault()`. |\n\n**Example:**\n```tsx\n```tsx\n<Breadcrumb\n items={[\n { label: 'Home', href: '/' },\n { label: 'Projects', href: '/projects' },\n { label: 'ggui' },\n ]}\n separator=\"/\"\n onItemClick={(item) => router.push(item.href!)}\n/>\n```\n```\n\n### Pagination\n\nPage navigation controls with previous/next arrows, numbered page buttons,\nand optional first/last jumps. Renders a `<nav aria-label=\"Pagination\">`.\n\nComposes: `Button` (ghost variant for prev/next/first/last arrows),\n`Icon` (`chevron-left`, `chevron-right`).\n\nBuilt-in transition: `all` over `var(--ggui-motion-duration-fast)` / `var(--ggui-motion-easing-standard)` on page number buttons (ggui#1106).\n\nPage windowing: when `totalPages > maxVisible`, the component shows the\nfirst page, last page, a window of pages around `currentPage`, and\nellipsis (\"...\") markers for gaps. The window adjusts when near the\nstart or end of the range.\n\nActive page button: `colors.primary[600]` bg, `colors.white` text,\n`fontWeight.medium`. Inactive: transparent bg, `colors.gray[700]` text.\n\nArrow buttons are automatically disabled at boundary pages (first/last).\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| currentPage | `number` | - | Current active page. **1-indexed** (first page is `1`). |\n| totalPages | `number` | - | Total number of pages. Determines when last-page / next-page buttons disable. |\n| onPageChange | `(page: number) => void` | - | Called when the user clicks a page number, arrow, or first/last button. Receives the target page number (1-indexed) directly. |\n| showFirstLast | `boolean` | `true` | When `true`, renders double-chevron buttons for jumping to the first and last page. These buttons are disabled when already on the respective boundary. |\n| maxVisible | `number` | `5` | Maximum number of page buttons visible at once (including the first and last page, but excluding ellipsis markers). When `totalPages` exceeds this value, ellipsis gaps appear. |\n| size | `'sm' \\| 'md' \\| 'lg'` | `'md'` | Controls button dimensions and icon sizes. - `'sm'` -- 28px buttons, 14px icons, Button size `xs` - `'md'` -- 32px buttons, 16px icons, Button size `sm` - `'lg'` -- 40px buttons, 20px icons, Button size `md` |\n| disabled | `boolean` | - | When `true`, all page buttons and arrows are visually dimmed (`opacity: 0.5`) and clicks are suppressed. |\n\n**Example:**\n```tsx\n```tsx\n<Pagination\n currentPage={page}\n totalPages={20}\n onPageChange={setPage}\n maxVisible={7}\n size=\"md\"\n/>\n```\n```\n\n### EmptyState\n\nEmptyState -- placeholder for a region with no data: empty lists,\nzero search results, an error fallback. Render it instead of\nnothing whenever a data array could be empty \u2014 a list that shows\nnothing when empty looks broken.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| icon | `string \\| ReactNode` | - | A Lucide icon name (kebab-case), rendered large and subtle above the title, or a custom node. Omit for a text-only empty state. |\n| title | `string` | - | The headline, e.g. \"No results found\". |\n| description | `string` | - | Optional supporting line below the title. |\n| action | `ReactNode` | - | Optional call-to-action, typically a `<Button>`. |\n\n**Example:**\n```tsx\n{results.length === 0\n ? <EmptyState icon=\"search-x\" title=\"No matches\" description=\"Try a broader query.\" />\n : results.map((r) => <Row key={r.id}>\u2026</Row>)}\n```\n\n### Stat\n\nStat -- a single KPI / metric: a label, a large value, an optional\ntrend-coloured delta and icon. Reach for it whenever the UI is\n\"show a number\" \u2014 dashboards, weather and price cards, analytics\ntiles. Drop several into a `<Grid>` for a stat grid.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| label | `string` | - | The metric name, e.g. \"Revenue\". Rendered small and uppercase above the value. |\n| value | `string \\| number` | - | The headline value \u2014 the big number. A number, or a pre-formatted string (`\"$48.2k\"`, `\"18\xB0C\"`). |\n| delta | `string` | - | Optional change indicator, pre-formatted, e.g. `\"+12.5%\"` or `\"-3\"`. |\n| trend | `'up' \\| 'down' \\| 'neutral'` | `'neutral'` | Direction of `delta` \u2014 colours it: `'up'` success, `'down'` error, `'neutral'` muted. |\n| icon | `string \\| ReactNode` | - | Optional Lucide icon name (kebab-case) or custom node, shown next to the label. |\n\n**Example:**\n```tsx\n<Stat label=\"Revenue\" value=\"$48.2k\" delta=\"+12.5%\" trend=\"up\" icon=\"trending-up\" />\n```\n\n### Stepper\n\nStepper -- a display-only step indicator for multi-step flows\n(wizards, checkouts, onboarding): numbered markers joined by\nconnector lines, with completed (check), current (filled), and\nupcoming (outlined) states styled distinctly.\n\nStepper renders step state; it never owns it. Declare the step\nlabels as a top-level `const`, track the current index in\n`useState`, and advance it from your own Next/Back buttons (or\n`onStepClick`).\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| steps | `string[]` | - | Ordered step labels, one per step. Declare as a top-level `const` array \u2014 never as state. |\n| current | `number` | - | Zero-based index of the active step. Steps before it render as completed (check mark), steps after it as upcoming. |\n| orientation | `'horizontal' \\| 'vertical'` | `'horizontal'` | Flow direction. `'horizontal'` joins the markers with connector lines in a row; `'vertical'` stacks the steps with short connector columns \u2014 better for sidebars or long step labels. |\n| onStepClick | `(index: number) => void` | - | When provided, each step becomes a real button and clicks receive the step's zero-based index. Typical use: jumping back to a completed step; guard forward jumps in the handler if the flow validates per step. |\n\n**Example:**\n```tsx\nconst STEPS = ['Account', 'Profile', 'Review'];\n// In the component: const [step, setStep] = useState(0);\n<Stack gap=\"lg\">\n <Stepper steps={STEPS} current={step} />\n {step === 0 && <AccountFields />}\n <Row gap=\"sm\" justify=\"end\">\n <Button variant=\"ghost\" disabled={step === 0} onClick={() => setStep(step - 1)}>Back</Button>\n <Button onClick={() => setStep(step + 1)}>Next</Button>\n </Row>\n</Stack>\n```\n\n### Markdown\n\nMarkdown -- renders markdown-formatted text as styled content:\nheadings, paragraphs, **bold** / *italic*, `inline code`, fenced\ncode blocks, bulleted and numbered lists, pipe tables, and links.\n\nUse it whenever a prop or context slot carries prose the agent\nauthors in markdown -- article bodies, AI-generated explanations,\ndescriptions, notes, help text. Pass the raw markdown string\nstraight through; never pre-parse it, never split it into per-line\n`Text` elements, and never rebuild formatting with nested\n`<strong>`/`<em>` markup yourself.\n\nSafe by construction: raw HTML in the source displays as literal\ntext (never markup), and links render inert unless their scheme is\nhttp(s)/mailto. Streaming-tolerant: a mid-stream prefix parses\ncleanly and completed constructs never change shape, so binding a\ngrowing string re-renders correctly.\n\nFor a single line of formatted text INSIDE another element (a table\ncell, a list row, a caption), use `MarkdownInline` instead -- same\n`markdown` prop, inline-level constructs only (no headings, lists,\nor code fences), renders inside the parent's typography.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| markdown | `string` | - | Markdown source text, passed through verbatim. Supports the conversational subset: `#`-`###` headings, paragraphs, bold, italic, inline code, fenced code blocks, `-`/`1.` lists, `\\|` pipe tables, and `[label](url)` links. Bind stateful or streamed prose directly. |\n\n**Example:**\n```tsx\n<Stack gap=\"md\">\n <Markdown markdown={recipe.instructions} />\n</Stack>\n```\n\n### MarkdownInline\n\nMarkdownInline -- renders ONE line of inline-level markdown (bold,\nitalic, inline code, links) inside the parent's typography -- a table\ncell, a list row, a caption, a summary line. Same `markdown` prop as\n`Markdown`; block constructs (headings, lists, code fences) are not\nrendered -- reach for `Markdown` for multi-paragraph bodies.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| markdown | `string` | - | Inline markdown source -- bold, italic, inline code, and `[label](url)` links. Block-level syntax renders as plain text. |\n\n**Example:**\n```tsx\n<Row gap=\"sm\">\n <Badge variant=\"success\">stable</Badge>\n <MarkdownInline markdown={release.summary} />\n</Row>\n```\n\n### Support Types\n\n**DropdownOption:**\n\nA single option inside a `Dropdown`. Each option maps to one `MenuItem`\ninternally.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| value | `string` | Unique identifier returned to `onChange` when this option is selected. |\n| label | `string` | Human-readable text shown in the menu row. |\n| icon | `ReactNode` | Optional icon rendered to the left of the label via `MenuItem.icon`. |\n| disabled | `boolean` | When `true`, the option is visible but non-interactive. |\n| danger | `boolean` | When `true`, the option uses destructive (red) styling via `MenuItem.danger`. |\n\n**AutocompleteOption:**\n\nA single option in the `Autocomplete` suggestion list.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| value | `string` | Unique identifier for this option. Also used for case-insensitive filtering against the input value. |\n| label | `string` | Primary display text. Also used for case-insensitive filtering and is written into the input on selection. |\n| description | `string` | Secondary description rendered below the label in `fontSize.xs` / `colors.gray[500]`. |\n| icon | `ReactNode` | Icon rendered to the left of the label/description block. Flex-shrink 0. |\n| disabled | `boolean` | When `true`, the option is visible but non-interactive (`cursor: not-allowed`, `colors.gray[400]` text). |\n\n**BreadcrumbItem:**\n\nA single segment in a `Breadcrumb` trail. Items with `href` render as\n`Link` primitives; items without render as plain `<button>` elements.\nThe last item in the array is always rendered as static text with\n`aria-current=\"page\"`.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| label | `string` | Display text for this breadcrumb segment. |\n| href | `string` | URL for this segment. When provided (and this is not the last item), the segment renders as a `Link` primitive with `underline=\"hover\"`. When omitted, it renders as a `<button>`. |\n| icon | `ReactNode` | Icon rendered immediately before the label. Its color follows the segment's text color: `colors.gray[500]` for navigable items, `colors.gray[900]` for the current (last) item. |\n\n\n## Compositions\n\nImport: `import { Component } from '@ggui-ai/design'`\n\n### Header\n\nProps for the `Header` composition.\n\nA horizontal page header that arranges a logo, navigation, and action slots\nin a flex row (`justify-content: space-between`). Internally renders a `<header>` element;\ndoes not compose other ggui primitives.\n\nWhen `sticky` is true the header gets `position: sticky; top: 0` with `zIndex.sticky`\nand a `shadow.sm` box-shadow.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| logo | `ReactNode` | - | Logo or brand element rendered at the start (flex-shrink: 0). |\n| navigation | `ReactNode` | - | Navigation content rendered in a `<nav>` element with `flex: 1` and a 32 px left margin. |\n| actions | `ReactNode` | - | Right-side action elements (buttons, avatar, etc.) rendered with a 12 px gap. |\n| sticky | `boolean` | `false` | When true, the header becomes `position: sticky` at the top of its scroll container with `zIndex.sticky` and `shadow.sm`. |\n| background | `string` | `colors.white` | Background color of the header. |\n| bordered | `boolean` | `true` | When true, renders a 1 px bottom border in `colors.gray[200]`. |\n\n**Example:**\n```tsx\n```tsx\n<Header\n logo={<img src=\"/logo.svg\" alt=\"Acme\" />}\n navigation={<a href=\"/docs\">Docs</a>}\n actions={<Button size=\"sm\">Sign In</Button>}\n sticky\n bordered\n/>\n```\n```\n\n### Sidebar\n\nProps for the `Sidebar` composition.\n\nA vertical navigation panel that composes the `Icon` primitive for chevron indicators.\nItems are rendered as `<button>` elements inside a scrollable `<nav>`. Nested items\nare indented 16 px per depth level. The sidebar animates width changes with a 200 ms\nCSS transition. Active items are highlighted with `colors.primary[50]` background\nand `colors.primary[700]` text.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| items | `SidebarItem[]` | - | Array of navigation items to render. |\n| activeId | `string` | - | ID of the currently active item. Matched items get a highlighted background and bold text. |\n| onItemClick | `(item: SidebarItem) => void` | - | Called when any item (including parent items with children) is clicked. |\n| collapsed | `boolean` | `false` | When true, hides labels and badges; only icons remain visible, centered in the collapsed width. Nested children are hidden entirely. |\n| header | `ReactNode` | - | Content rendered above the item list, separated by a bottom border. |\n| footer | `ReactNode` | - | Content rendered below the item list, separated by a top border. |\n| width | `number` | `256` | Width in pixels when expanded. |\n| collapsedWidth | `number` | `64` | Width in pixels when collapsed. |\n\n**Example:**\n```tsx\n```tsx\n<Sidebar\n items={[\n { id: 'home', label: 'Home', icon: <Icon name=\"home\" /> },\n { id: 'settings', label: 'Settings', icon: <Icon name=\"settings\" />,\n children: [\n { id: 'profile', label: 'Profile' },\n { id: 'billing', label: 'Billing' },\n ]},\n ]}\n activeId=\"home\"\n onItemClick={(item) => navigate(item.href)}\n collapsed={false}\n width={256}\n/>\n```\n```\n\n### CardGrid\n\nProps for the `CardGrid` composition.\n\nA CSS Grid wrapper that arranges children in equal-width columns. When `columns`\nis a number, it produces `repeat(N, 1fr)`. When it is a responsive object,\nit falls back to `repeat(auto-fit, minmax(280px, 1fr))` for fluid responsive behavior.\n\nDoes not compose any ggui primitives internally \u2014 it is a pure layout container.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| children | `ReactNode` | - | Card elements to arrange in the grid. |\n| columns | `number \\| { sm?: number; md?: number; lg?: number }` | `3` | Number of columns, or a responsive breakpoint map. - `number` \u2014 fixed column count via `repeat(N, 1fr)`. - `{ sm?, md?, lg? }` \u2014 triggers `repeat(auto-fit, minmax(280px, 1fr))` for fluid layout. |\n| gap | `number` | `16` | Gap between grid items in pixels. |\n\n**Example:**\n```tsx\n```tsx\n<CardGrid columns={3} gap={24}>\n <Card>A</Card>\n <Card>B</Card>\n <Card>C</Card>\n</CardGrid>\n```\n```\n\n### CommentThread\n\nProps for the `CommentThread` composition.\n\nA threaded comment section that composes `Avatar`, `Button`, `TextArea`, and `Spinner`\nprimitives. Comments are rendered recursively with 40 px indentation per nesting level.\nEach comment shows author avatar, name, timestamp, content, reactions, and a \"Reply\" toggle.\nWhen `currentUser` is provided, a new-comment input with avatar and submit button is shown\nabove the thread.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| comments | `Comment[]` | - | Array of top-level comments to render. Replies are nested within each comment. |\n| currentUser | `{ /** Display name for the current user's avatar. */ name: string; /** Avatar image URL for the current user. */ avatar?: string; }` | - | Current user info. When provided, a new-comment input area is rendered above the thread. |\n| onAddComment | `(content: string, parentId?: string) => void` | - | Called when the user submits a new top-level comment. |\n| onReply | `(commentId: string, content: string) => void` | - | Called when the user submits a reply to an existing comment. |\n| onReaction | `(commentId: string, emoji: string) => void` | - | Called when the user clicks an emoji reaction on a comment. |\n| loading | `boolean` | - | When true, shows a centered `Spinner` instead of the comment list. |\n\n**Example:**\n```tsx\n```tsx\n<CommentThread\n comments={[\n { id: '1', author: { name: 'Alice' }, content: 'Great work!', timestamp: new Date(),\n replies: [{ id: '2', author: { name: 'Bob' }, content: 'Thanks!', timestamp: new Date() }] }\n ]}\n currentUser={{ name: 'Alice', avatar: '/alice.jpg' }}\n onAddComment={(content) => post(content)}\n onReply={(commentId, content) => reply(commentId, content)}\n onReaction={(commentId, emoji) => react(commentId, emoji)}\n/>\n```\n```\n\n### DataTable\n\nProps for the `DataTable` composition.\n\nA sortable, selectable data table that composes `Checkbox`, `Spinner`, and `Icon`\nprimitives. Renders a `<table>` inside a bordered container with 8 px border-radius.\nThe header row has a `colors.gray[50]` background. Sortable columns show a chevron\nicon on click (toggles asc/desc). Selected rows are highlighted with `colors.primary[50]`.\nRow background transitions use a 150 ms ease. The \"select all\" checkbox supports an\nindeterminate state when a subset of rows is selected.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| columns | `DataTableColumn<T>[]` | - | Column definitions that control header, alignment, sorting, and rendering. |\n| data | `T[]` | - | Row data array. Each entry corresponds to one table row. |\n| rowKey | `string \\| ((row: T) => string)` | `'id'` | Property name or function used to derive a unique key for each row. |\n| loading | `boolean` | - | When true, shows a centered `Spinner` instead of table body rows. |\n| emptyText | `string` | `'No data'` | Text shown when `data` is empty and not loading. |\n| onSort | `(key: string, direction: 'asc' \\| 'desc') => void` | - | Called when a sortable column header is clicked. Toggles direction automatically (asc -> desc) if the same column is clicked again. |\n| sortKey | `string` | - | The column key currently being sorted. |\n| sortDirection | `'asc' \\| 'desc'` | - | The current sort direction. |\n| onRowClick | `(row: T, index: number) => void` | - | Called when a row is clicked. Rows get `cursor: pointer` when this handler is provided. |\n| selectable | `boolean` | - | When true, adds a checkbox column at the start of each row. |\n| selectedKeys | `string[]` | `[]` | Array of currently selected row keys. |\n| onSelectionChange | `(keys: string[]) => void` | - | Called when the set of selected row keys changes (via row checkbox or select-all). |\n\n**Example:**\n```tsx\n```tsx\n<DataTable\n columns={[\n { key: 'name', header: 'Name', sortable: true },\n { key: 'email', header: 'Email' },\n { key: 'role', header: 'Role', render: (v) => <Badge>{v}</Badge> },\n ]}\n data={users}\n rowKey=\"id\"\n selectable\n selectedKeys={selected}\n onSelectionChange={setSelected}\n onSort={(key, dir) => sort(key, dir)}\n sortKey=\"name\"\n sortDirection=\"asc\"\n/>\n```\n```\n\n### ChatWindow\n\nProps for the `ChatWindow` composition.\n\nA messaging interface that composes `Avatar`, `Button`, `Spinner`, and `Icon` primitives.\nLayout is a flex column filling 100% height with a bordered `radius.lg` container.\nMessages from the current user align right with `colors.primary[600]` bubbles and white text.\nOther users' messages align left with `colors.gray[100]` bubbles. The message area\nauto-scrolls to the bottom on new messages via `scrollIntoView({ behavior: 'smooth' })`.\nThe text input sends on Enter (Shift+Enter for newline).\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| messages | `ChatMessage[]` | - | Array of chat messages to display in chronological order. |\n| currentUserId | `string` | - | ID of the current user. Messages from this user render right-aligned with a primary color bubble. |\n| onSendMessage | `(content: string) => void` | - | Called when the user submits a message (Enter key or send button). |\n| loading | `boolean` | - | When true, shows a centered `Spinner` instead of the message list. |\n| typing | `{ name: string } \\| null` | - | When non-null, displays a typing indicator below the last message (e.g., \"Alice is typing...\"). |\n| placeholder | `string` | `'Type a message...'` | Placeholder text for the message input field. |\n| header | `ReactNode` | - | Optional header content rendered above the message area, separated by a bottom border. |\n\n**Example:**\n```tsx\n```tsx\n<ChatWindow\n messages={messages}\n currentUserId=\"user-1\"\n onSendMessage={(content) => send(content)}\n typing={{ name: 'Alice' }}\n placeholder=\"Type a message...\"\n header={<h3>Chat with Alice</h3>}\n/>\n```\n```\n\n### NavigationBar\n\nProps for the `NavigationBar` composition.\n\nA horizontal or vertical navigation menu. Does not compose other ggui primitives\n(uses plain `<button>` and `<a>` elements). Active items are styled per variant:\n\n- `'default'` \u2014 active item gets `colors.primary[600]` text and medium font weight.\n- `'pills'` \u2014 active item gets a `radius.full` pill with `colors.primary[100]` background.\n- `'underline'` \u2014 active item gets a 2 px bottom border in `colors.primary[600]`.\n When horizontal, the entire nav also has a 1 px bottom border.\n\nAll items have a 150 ms transition on all properties.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| items | `NavItem[]` | - | Array of navigation items to render. |\n| activeId | `string` | - | ID of the currently active item. Controls visual highlighting per variant style. |\n| onItemClick | `(item: NavItem) => void` | - | Called when a non-disabled item is clicked. For `<a>` elements, `preventDefault` is called first. |\n| orientation | `'horizontal' \\| 'vertical'` | `'horizontal'` | Layout direction. - `'horizontal'` \u2014 flex-row with 4 px gap. - `'vertical'` \u2014 flex-column with 2 px gap. |\n| variant | `'default' \\| 'pills' \\| 'underline'` | `'default'` | Visual style for active/inactive items. - `'default'` \u2014 text color change only. - `'pills'` \u2014 rounded pill background on active items. - `'underline'` \u2014 bottom border on active items. |\n\n**Example:**\n```tsx\n```tsx\n<NavigationBar\n items={[\n { id: 'home', label: 'Home', icon: <Icon name=\"home\" /> },\n { id: 'about', label: 'About' },\n { id: 'contact', label: 'Contact' },\n ]}\n activeId=\"home\"\n onItemClick={(item) => navigate(item.id)}\n orientation=\"horizontal\"\n variant=\"pills\"\n/>\n```\n```\n\n### FileUploader\n\nProps for the `FileUploader` composition.\n\nA drag-and-drop file upload area that composes `Button`, `Progress`, and `Icon` primitives.\nThe drop zone is a dashed-border container that highlights in `colors.primary[400]`/`colors.primary[50]`\non drag-over. Below the drop zone, each file in `files` is listed with its name, size,\noptional progress bar (for uploading status), and a remove button.\n\nFile validation (max size, max count) is applied client-side before calling `onFilesSelected`.\nFiles exceeding `maxSize` are silently filtered out; files exceeding `maxFiles` are truncated.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| files | `UploadedFile[]` | `[]` | Array of files currently in the upload queue, shown below the drop zone. |\n| onFilesSelected | `(files: File[]) => void` | - | Called when the user selects files via click or drag-and-drop. Receives native `File` objects after client-side filtering (maxSize, maxFiles). |\n| onFileRemove | `(fileId: string) => void` | - | Called when the user clicks the remove button on a file entry. |\n| accept | `string` | - | Accepted file types passed to the hidden `<input type=\"file\" accept=\"...\">`. E.g., `'image/*,.pdf'`. |\n| multiple | `boolean` | `true` | When true, allows selecting multiple files at once. |\n| maxSize | `number` | - | Maximum file size in bytes. Files exceeding this are silently excluded from the selection. |\n| maxFiles | `number` | - | Maximum number of files. Excess files beyond `maxFiles - files.length` are truncated. |\n| disabled | `boolean` | - | When true, the drop zone is visually dimmed (opacity 0.5) and non-interactive. |\n| dragDrop | `boolean` | `true` | When true, enables drag-and-drop on the drop zone. When false, the prompt text changes to \"Click to browse files\". |\n\n**Example:**\n```tsx\n```tsx\n<FileUploader\n files={uploadedFiles}\n onFilesSelected={(files) => startUpload(files)}\n onFileRemove={(id) => removeFile(id)}\n accept=\"image/*,.pdf\"\n multiple\n maxSize={5 * 1024 * 1024}\n maxFiles={10}\n dragDrop\n/>\n```\n```\n\n### NotificationCenter\n\nProps for the `NotificationCenter` composition.\n\nA notification list with a header bar that composes `Button`, `Spinner`, and `Icon`\nprimitives. The header shows a \"Notifications\" title, an unread count badge\n(pill in `colors.primary[100]`), and \"Mark all read\" / \"Clear all\" buttons.\nEach notification item shows a colored status dot, title, message, timestamp,\n\"Mark as read\" link, and optional action. The list is scrollable (`overflowY: auto`).\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| notifications | `Notification[]` | - | Array of notifications to display, in the order provided. |\n| onMarkAsRead | `(id: string) => void` | - | Called when the user clicks \"Mark as read\" on an individual notification. |\n| onMarkAllAsRead | `() => void` | - | Called when the user clicks the \"Mark all read\" header button. Only shown when there are unread items. |\n| onDismiss | `(id: string) => void` | - | Called when the user clicks the dismiss (X) button on an individual notification. |\n| onClearAll | `() => void` | - | Called when the user clicks the \"Clear all\" header button. Only shown when there are any notifications. |\n| emptyText | `string` | `'No notifications'` | Text shown when `notifications` is empty and not loading. |\n| loading | `boolean` | - | When true, shows a centered `Spinner` instead of the notification list. |\n\n**Example:**\n```tsx\n```tsx\n<NotificationCenter\n notifications={[\n { id: '1', title: 'Deployment complete', type: 'success', timestamp: new Date(), read: false },\n { id: '2', title: 'Build failed', type: 'error', message: 'Lint errors', timestamp: new Date() },\n ]}\n onMarkAsRead={(id) => markRead(id)}\n onMarkAllAsRead={() => markAllRead()}\n onDismiss={(id) => dismiss(id)}\n onClearAll={() => clearAll()}\n/>\n```\n```\n\n### Modal\n\nProps for the `Modal` composition.\n\nA dialog overlay that composes `Button`, `Icon`, and `Heading` primitives.\nThe overlay uses `animation.fadeIn` (`ggui-fadeIn`) and the dialog panel uses\n`animation.scaleIn` (`ggui-scaleIn`) \u2014 both GPU-composited (opacity + transform).\nWhen open, `document.body.style.overflow` is set to `'hidden'` to prevent background\nscrolling, and restored on close. The dialog has `role=\"dialog\"` and `aria-modal=\"true\"`.\n\nSize widths: `sm` = 400 px, `md` = 500 px, `lg` = 640 px, `xl` = 800 px,\n`full` = 100vw (no border-radius, no padding).\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| open | `boolean` | - | Controls modal visibility. When false, the component renders nothing. |\n| onClose | `() => void` | - | Called to close the modal (overlay click, escape key, or close button). |\n| title | `string` | - | Optional title rendered in the modal header via the `Heading` primitive (level 4). |\n| children | `ReactNode` | - | Modal body content rendered in a scrollable area (`overflowY: auto`). |\n| footer | `ReactNode` | - | Footer content rendered below the body, right-aligned with an 8 px gap, separated by a top border. |\n| size | `'sm' \\| 'md' \\| 'lg' \\| 'xl' \\| 'full'` | `'md'` | Controls the width of the modal panel. - `'sm'` \u2014 400 px - `'md'` \u2014 500 px - `'lg'` \u2014 640 px - `'xl'` \u2014 800 px - `'full'` \u2014 100vw, no border-radius, stretches to fill viewport |\n| closeOnOverlayClick | `boolean` | `true` | When true, clicking the semi-transparent overlay behind the modal calls `onClose`. |\n| closeOnEscape | `boolean` | `true` | When true, pressing the Escape key calls `onClose`. |\n| showCloseButton | `boolean` | `true` | When true, renders a ghost close button (X icon) in the modal header. |\n\n**Example:**\n```tsx\n```tsx\n<Modal\n open={isOpen}\n onClose={() => setOpen(false)}\n title=\"Confirm Action\"\n size=\"md\"\n footer={\n <>\n <Button variant=\"ghost\" onClick={() => setOpen(false)}>Cancel</Button>\n <Button onClick={handleConfirm}>Confirm</Button>\n </>\n }\n>\n <p>Are you sure you want to proceed?</p>\n</Modal>\n```\n```\n\n### CommandPalette\n\nProps for the `CommandPalette` composition.\n\nA searchable command menu (Cmd+K / Ctrl+K pattern) that composes `Spinner` and `Icon`\nprimitives. Appears as a centered overlay at 15vh from the top. Commands are filtered\nby label and description (case-insensitive substring match). Results are grouped under\nuppercase section headers. Keyboard navigation is fully supported:\nArrow Up/Down to navigate, Enter to select, Escape to close.\n\nWhen `recentIds` are provided and the search query is empty, matching commands appear\nin a \"Recent\" section at the top (deduplicated from their original groups).\n\nThe footer shows navigation hints: \"Up/Down Navigate\", \"Enter Select\", \"Esc Close\".\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| open | `boolean` | - | Controls palette visibility. When false, the component renders nothing. |\n| onClose | `() => void` | - | Called to close the palette (overlay click, Escape key, or after command selection). |\n| commands | `Command[]` | - | Full array of available commands. Filtered client-side by the search query. |\n| onSelect | `(command: Command) => void` | - | Called when a non-disabled command is selected (Enter key or click). The palette auto-closes after selection. |\n| placeholder | `string` | `'Search commands...'` | Placeholder text for the search input. |\n| recentIds | `string[]` | `[]` | IDs of recently used commands. When the query is empty, these appear in a \"Recent\" section at the top of the results. |\n| loading | `boolean` | - | When true, shows a centered `Spinner` instead of the command list. |\n\n**Example:**\n```tsx\n```tsx\n<CommandPalette\n open={isOpen}\n onClose={() => setOpen(false)}\n commands={[\n { id: 'new', label: 'New File', shortcut: 'Ctrl+N', group: 'File' },\n { id: 'save', label: 'Save', shortcut: 'Ctrl+S', group: 'File' },\n { id: 'theme', label: 'Toggle Theme', group: 'Preferences' },\n ]}\n onSelect={(cmd) => executeCommand(cmd.id)}\n recentIds={['save']}\n placeholder=\"Search commands...\"\n/>\n```\n```\n\n### Footer\n\nProps for the `Footer` composition.\n\nA site footer with `role=\"contentinfo\"` that lays out a brand slot, link columns,\nsocial icons, and a bottom bar. Does not compose other ggui primitives (uses plain\nHTML elements). Content is constrained to `max-width: 1280px` with auto margins.\nLink columns use a responsive flex layout (`flex: 0 1 180px`). The bottom bar\nincludes copyright text, social links, and bottom-bar links separated by a top border.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| brand | `ReactNode` | - | Brand element (logo, tagline) rendered in a flexible column (`flex: 1 1 280px`). |\n| columns | `FooterColumn[]` | - | Array of link columns rendered in a flex-wrap layout with 48 px gap. |\n| socialLinks | `FooterSocialLink[]` | - | Social media icon links rendered in the bottom bar. |\n| bottomText | `string` | - | Text displayed at the start of the bottom bar (e.g., copyright notice). |\n| bottomLinks | `FooterLink[]` | - | Links displayed in the bottom bar after social icons (e.g., Privacy, Terms). |\n| background | `string` | `colors.gray[50]` | Background color of the footer. |\n| bordered | `boolean` | `true` | When true, renders a 1 px top border in `colors.gray[200]`. |\n\n**Example:**\n```tsx\n```tsx\n<Footer\n brand={<img src=\"/logo.svg\" alt=\"Acme\" />}\n columns={[\n { title: 'Product', links: [{ label: 'Features', href: '/features' }] },\n { title: 'Company', links: [{ label: 'About', href: '/about' }] },\n ]}\n socialLinks={[\n { label: 'Twitter', href: 'https://twitter.com/acme', icon: <TwitterIcon /> },\n ]}\n bottomText=\"© 2026 Acme Inc.\"\n bottomLinks={[{ label: 'Privacy', href: '/privacy' }]}\n bordered\n/>\n```\n```\n\n### Hero\n\nProps for the `Hero` composition.\n\nA prominent landing-page hero section that renders heading, description, CTA buttons,\nand an optional media slot. Does not compose other ggui primitives (uses plain HTML\nelements styled with design tokens). Content is constrained to `max-width: 1280px`.\n\nLayout modes:\n- `align='center'` \u2014 single-column centered layout with `max-width: 800px` text area.\n- `align='left'` \u2014 two-column side-by-side layout (50/50 split with media slot).\n\nSize controls vertical padding and font sizes:\n- `'sm'` \u2014 48 px vertical padding, 3xl heading, lg description.\n- `'md'` \u2014 80 px vertical padding, 4xl heading, xl description.\n- `'lg'` \u2014 120 px vertical padding, 5xl heading, xl description.\n\nThe primary action button uses `colors.primary[600]` fill; the secondary action uses\nan outlined style. When `overlay` is true with a `backgroundImage`, text switches to white\nand borders become semi-transparent.\n\n**Props:**\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| heading | `string` | - | Main heading text rendered as an `<h1>` with bold weight and tight line-height. |\n| description | `string` | - | Description paragraph rendered below the heading with relaxed line-height. |\n| primaryAction | `HeroAction` | - | Primary CTA button rendered with `colors.primary[600]` background and white text. |\n| secondaryAction | `HeroAction` | - | Secondary CTA button rendered with a transparent background and a 1 px border. |\n| media | `ReactNode` | - | Media element (image, video, illustration) rendered beside or below the text content. |\n| align | `'center' \\| 'left'` | `'center'` | Text and layout alignment. - `'center'` \u2014 centered single-column layout. - `'left'` \u2014 left-aligned text with media in a right column (50/50 split). |\n| size | `'sm' \\| 'md' \\| 'lg'` | `'md'` | Controls vertical padding and heading/description font sizes. - `'sm'` \u2014 compact (48 px padding, 3xl/lg fonts). - `'md'` \u2014 standard (80 px padding, 4xl/xl fonts). - `'lg'` \u2014 spacious (120 px padding, 5xl/xl fonts). |\n| background | `string` | `colors.white (when no backgroundImage is set)` | Background color of the hero section. |\n| backgroundImage | `string` | - | Background image URL applied as `background-size: cover; background-position: center`. |\n| overlay | `boolean` | `false` | When true and `backgroundImage` is set, renders a semi-transparent black overlay (`rgba(0,0,0,0.5)`) and switches text to white/semi-transparent white for contrast. |\n\n**Example:**\n```tsx\n```tsx\n<Hero\n heading=\"Build Better UIs, Faster\"\n description=\"The universal interface layer between AI agents and humans.\"\n primaryAction={{ label: 'Get Started', onClick: () => navigate('/signup') }}\n secondaryAction={{ label: 'Learn More', href: '/docs' }}\n media={<img src=\"/hero.png\" alt=\"Hero\" />}\n align=\"left\"\n size=\"lg\"\n/>\n```\n```\n\n### Support Types\n\n**SidebarItem:**\n\nA single navigation entry in a `Sidebar`. Supports nested children for\ncollapsible sub-menus and an optional badge slot.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| id | `string` | Unique identifier used for active-state matching and React keys. |\n| label | `string` | Display label for the item. Hidden when the sidebar is collapsed. |\n| icon | `ReactNode` | Leading icon rendered before the label. Remains visible when collapsed. |\n| href | `string` | Optional URL associated with this item (not rendered as a link by default). |\n| badge | `ReactNode` | Trailing badge element (e.g., unread count). Hidden when collapsed. |\n| children | `SidebarItem[]` | Nested child items. When present, the item acts as a collapsible section (chevron indicator shown). |\n| disabled | `boolean` | When true, the item is visually dimmed and non-interactive (`cursor: not-allowed`). |\n\n**Comment:**\n\nA single comment entry in a `CommentThread`. Supports nested replies\nand emoji reactions with counts.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| id | `string` | Unique identifier for this comment. |\n| author | `{ /** Display name of the author. */ name: string; /** URL for the author's avatar image. Passed to the `Avatar` primitive. */ avatar?: string; }` | Comment author metadata. |\n| content | `string` | The comment body text. |\n| timestamp | `string \\| Date` | Timestamp of the comment. Rendered via `toLocaleString()` when a `Date` object. |\n| replies | `Comment[]` | Nested reply comments. Each reply is rendered indented 40 px deeper. |\n| reactions | `{ emoji: string; count: number }[]` | Emoji reactions with their aggregated counts (e.g., `{ emoji: \"\u{1F44D}\", count: 3 }`). |\n\n**DataTableColumn:**\n\nColumn definition for a `DataTable`. Controls header text, width, alignment,\nsorting, and custom cell rendering.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| key | `string` | Property key on the row object used to extract cell values. Also serves as the sort key. |\n| header | `string` | Column header text displayed in the `<thead>`. |\n| width | `number \\| string` | Column width as a CSS value (number for pixels, string for any CSS unit). |\n| sortable | `boolean` | When true, the column header is clickable and triggers `onSort`. An arrow icon indicates direction. |\n| render | `(value: unknown, row: T, index: number) => ReactNode` | Custom cell renderer. When omitted, the raw value is stringified via `String()`. |\n| align | `'left' \\| 'center' \\| 'right'` | Text alignment for both header and body cells. |\n\n**ChatMessage:**\n\nA single message in a `ChatWindow`. Includes sender metadata, delivery status,\nand a timestamp.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| id | `string` | Unique identifier for this message. |\n| content | `string` | The message body text. |\n| sender | `{ /** Unique ID of the sender. Compared to `currentUserId` to determine alignment. */ id: string; /** Display name of the sender. */ name: string; /** Avatar image URL. Only shown for non-current-user messages (xs size). */ avatar?: string; }` | Sender metadata used for avatar rendering and alignment. |\n| timestamp | `string \\| Date` | Message timestamp. Rendered as `HH:MM` via `toLocaleTimeString` when a `Date` object. |\n| status | `'sending' \\| 'sent' \\| 'delivered' \\| 'read' \\| 'error'` | Delivery status indicator shown on the current user's messages. - `'sending'` \u2014 shows a dot bullet - `'sent'` \u2014 shows a single checkmark - `'delivered'` \u2014 shows double checkmarks - `'read'` \u2014 shows double checkmarks (same visual as delivered) - `'error'` \u2014 shows an exclamation mark |\n\n**NavItem:**\n\nA single navigation entry in a `NavigationBar`. Supports nested children\nfor sub-menus (rendered by the parent via dropdown, not built-in).\n\n| Property | Type | Description |\n|----------|------|-------------|\n| id | `string` | Unique identifier used for active-state matching and React keys. |\n| label | `string` | Display label for the navigation link. |\n| href | `string` | URL for the item. When provided, renders an `<a>` element instead of `<button>`. |\n| icon | `ReactNode` | Optional icon rendered before the label. |\n| children | `NavItem[]` | Nested child items (for sub-menu structures; rendering is consumer-defined). |\n| disabled | `boolean` | When true, the item is visually dimmed (opacity 0.5) and non-interactive. |\n\n**UploadedFile:**\n\nA file entry in the `FileUploader` composition. Tracks upload progress,\nstatus, and optional error messages.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| id | `string` | Unique identifier for this file entry. Used as a key and for removal callbacks. |\n| name | `string` | Original file name. Rendered with text-overflow ellipsis when too long. |\n| size | `number` | File size in bytes. Formatted as B/KB/MB/GB for display. |\n| type | `string` | MIME type of the file (e.g., `'image/png'`). |\n| progress | `number` | Upload progress as a percentage (0-100). Shown via the `Progress` primitive when status is `'uploading'`. |\n| status | `'pending' \\| 'uploading' \\| 'success' \\| 'error'` | Current upload lifecycle status. - `'pending'` \u2014 file selected but upload not started. - `'uploading'` \u2014 upload in progress; `progress` bar is shown. - `'success'` \u2014 upload completed. - `'error'` \u2014 upload failed; `error` message is shown in `colors.error[500]`. |\n| error | `string` | Error message displayed when status is `'error'`. |\n| url | `string` | The remote URL of the uploaded file after successful upload. |\n\n**Notification:**\n\nA single notification entry in the `NotificationCenter`. Supports semantic type coloring,\nread state, and an optional inline action button.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| id | `string` | Unique identifier for this notification. |\n| title | `string` | Notification title rendered in medium weight. |\n| message | `string` | Optional body text rendered below the title in a smaller font. |\n| timestamp | `string \\| Date` | Timestamp of the notification. Rendered via `toLocaleString()` when a `Date` object. |\n| read | `boolean` | Read state. Unread notifications get a `colors.primary[50]` background and a colored status dot matching the notification type. |\n| type | `'info' \\| 'success' \\| 'warning' \\| 'error'` | Semantic type that controls the status dot color on unread notifications. - `'info'` \u2014 `colors.info[500]` (blue) - `'success'` \u2014 `colors.success[500]` (green) - `'warning'` \u2014 `colors.warning[500]` (amber) - `'error'` \u2014 `colors.error[500]` (red) |\n| icon | `ReactNode` | Optional icon rendered alongside the notification (not used by the default implementation). |\n| action | `{ /** Button label text. */ label: string; /** Click handler for the action. */ onClick: () => void; }` | Optional inline action button rendered next to the timestamp. |\n\n**Command:**\n\nA single command entry in a `CommandPalette`. Commands can be grouped,\nhave keyboard shortcuts, and support a disabled state.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| id | `string` | Unique identifier for this command. |\n| label | `string` | Display label for the command. Searchable by the palette's query filter. |\n| description | `string` | Optional description text shown below the label. Also searchable. |\n| icon | `ReactNode` | Icon rendered at the start of the command row. |\n| shortcut | `string` | Keyboard shortcut hint displayed at the end of the row in a `<kbd>` element. |\n| group | `string` | Group name for visual sectioning. Commands with the same group are rendered under a shared header. Defaults to `'Commands'` if omitted. |\n| disabled | `boolean` | When true, the command is visually dimmed and cannot be selected. |\n\n**FooterLink:**\n\nA single link entry in a footer column or the bottom bar. Supports both\n`href` navigation and `onClick` handlers (onClick takes precedence via `preventDefault`).\n\n| Property | Type | Description |\n|----------|------|-------------|\n| label | `string` | Display text for the link. |\n| href | `string` | URL for the link. |\n| onClick | `() => void` | Click handler. When provided, `preventDefault` is called on the anchor click. |\n\n**FooterColumn:**\n\nA named column of links in the `Footer` layout. Each column has an optional title\nand a list of links rendered as a vertical stack with 10 px gap.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| title | `string` | Column heading rendered as an `<h4>` with semibold weight. |\n| links | `FooterLink[]` | Links displayed in this column. |\n\n**FooterSocialLink:**\n\nA social media link in the `Footer` bottom bar. Rendered as an icon-only anchor\nwith `aria-label` for accessibility.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| label | `string` | Accessible label for the social link (used as `aria-label`). |\n| href | `string` | URL for the social media profile or page. |\n| icon | `ReactNode` | Icon element rendered inside the anchor (typically an SVG or `Icon` primitive). |\n\n**HeroAction:**\n\nA call-to-action button definition for the `Hero` composition.\nUsed for both the primary (filled) and secondary (outlined) action buttons.\n\n| Property | Type | Description |\n|----------|------|-------------|\n| label | `string` | Button label text. |\n| onClick | `() => void` | Click handler for the button. |\n| href | `string` | Optional URL (not used by the default implementation; available for consumer routing). |\n\n\n## System Conventions\n\n### onChange Behavior (CRITICAL)\n\nAll form control onChange handlers receive the VALUE DIRECTLY, not a React event object.\n\n```tsx\n// CORRECT \u2014 onChange receives value directly\n<Input value={name} onChange={setName} />\n<Input value={email} onChange={(value) => setEmail(value)} />\n<Select value={country} onChange={setCountry} options={countries} />\n<Checkbox checked={agreed} onChange={setAgreed} />\n\n// WRONG \u2014 DO NOT use e.target.value!\n<Input value={name} onChange={(e) => setName(e.target.value)} /> // WILL BREAK\n```\n\nApplies to: Input, TextArea, Select, Checkbox, RadioGroup, Slider, Tabs, Accordion.\n\n### Available Motion & Animation\n\nRender `<MotionKeyframes />` once (anywhere in tree) to enable all keyframes.\n\n**Entrance/exit:** fadeIn, fadeOut, slideInUp, slideInDown, scaleIn, scaleOut\n**State feedback:** flash (background-color highlight), pulse (opacity breathing), bounce (scale overshoot)\n**Easing:** linear, easeIn, easeOut, easeInOut, spring (bouncy)\n**Durations:** instant(0ms), fast(100ms), normal(200ms), slow(300ms), slower(500ms)\n\n```tsx\n// Entrance animation on mount\n<div style={{ animation: 'ggui-fadeIn 200ms ease-out' }}>Content</div>\n\n// Stagger list items\n{items.map((item, i) => (\n <div key={item.id} style={{ animation: \\`ggui-slideInUp 300ms ease-out \\${i * 50}ms both\\` }}>\n {item.name}\n </div>\n))}\n\n// Flash highlight when data changes (e.g., stock price update)\n// useAnimationKey returns a key that increments when dep changes \u2192 remounts element \u2192 replays animation\nconst priceKey = useAnimationKey(stock.price);\n<div key={priceKey} style={{\n animation: animation.flash,\n '--ggui-flash-color': stock.change > 0 ? 'var(--ggui-color-success-100)' : 'var(--ggui-color-error-100)',\n} as React.CSSProperties}>\n {stock.price}\n</div>\n\n// Respect reduced-motion preference\nconst { motionEnabled } = useMotion();\n<div style={motionEnabled ? { animation: 'ggui-scaleIn 200ms ease-out' } : undefined}>\n Content\n</div>\n```\n\n### Elevation System\n\n6 levels mapping shadow intensity to z-index for layering:\n- Level 0: flat (no shadow, z: auto) \u2014 inline content\n- Level 1: sm shadow (z: auto) \u2014 cards, sections\n- Level 2: md shadow (z: 1000) \u2014 dropdowns, popovers\n- Level 3: lg shadow (z: 1200) \u2014 sticky banners\n- Level 4: xl shadow (z: 1400) \u2014 modals, dialogs\n- Level 5: 2xl shadow (z: 1800) \u2014 tooltips, toasts\n\n### Import Constraints\n\nOnly these imports are allowed:\n- `react`\n- `@ggui-ai/design` \u2014 the whole design system (primitives, components, compositions, and the `Clickable` / `Hoverable` / `Pressable` traits) is one import; there are no subpaths\n- `@ggui-ai/wire` (wire hooks)\n\nNo external libraries (lodash, date-fns, etc.). No fetch(). No eval().";
|
|
1557
|
-
var VALID_PRIMITIVES = [
|
|
1558
|
-
"Container",
|
|
1559
|
-
"Card",
|
|
1560
|
-
"Stack",
|
|
1561
|
-
"Row",
|
|
1562
|
-
"Grid",
|
|
1563
|
-
"Box",
|
|
1564
|
-
"Divider",
|
|
1565
|
-
"Spacer",
|
|
1566
|
-
"Text",
|
|
1567
|
-
"Heading",
|
|
1568
|
-
"Button",
|
|
1569
|
-
"Input",
|
|
1570
|
-
"TextArea",
|
|
1571
|
-
"Select",
|
|
1572
|
-
"Checkbox",
|
|
1573
|
-
"Toggle",
|
|
1574
|
-
"RadioGroup",
|
|
1575
|
-
"Slider",
|
|
1576
|
-
"Badge",
|
|
1577
|
-
"Spinner",
|
|
1578
|
-
"Skeleton",
|
|
1579
|
-
"Avatar",
|
|
1580
|
-
"Alert",
|
|
1581
|
-
"Progress",
|
|
1582
|
-
"Image",
|
|
1583
|
-
"Icon",
|
|
1584
|
-
"Link",
|
|
1585
|
-
"Tooltip",
|
|
1586
|
-
"Table",
|
|
1587
|
-
"Tabs",
|
|
1588
|
-
"Toast",
|
|
1589
|
-
"Accordion",
|
|
1590
|
-
"MotionKeyframes",
|
|
1591
|
-
"SearchField",
|
|
1592
|
-
"FormField",
|
|
1593
|
-
"MenuItem",
|
|
1594
|
-
"Tag",
|
|
1595
|
-
"Dropdown",
|
|
1596
|
-
"Autocomplete",
|
|
1597
|
-
"Breadcrumb",
|
|
1598
|
-
"Pagination",
|
|
1599
|
-
"EmptyState",
|
|
1600
|
-
"Stat",
|
|
1601
|
-
"Stepper",
|
|
1602
|
-
"Markdown",
|
|
1603
|
-
"MarkdownInline",
|
|
1604
|
-
"Header",
|
|
1605
|
-
"Sidebar",
|
|
1606
|
-
"CardGrid",
|
|
1607
|
-
"CommentThread",
|
|
1608
|
-
"DataTable",
|
|
1609
|
-
"ChatWindow",
|
|
1610
|
-
"NavigationBar",
|
|
1611
|
-
"FileUploader",
|
|
1612
|
-
"NotificationCenter",
|
|
1613
|
-
"Modal",
|
|
1614
|
-
"CommandPalette",
|
|
1615
|
-
"Footer",
|
|
1616
|
-
"Hero"
|
|
1617
|
-
];
|
|
1618
|
-
var ALLOWED_IMPORT_BASES = [
|
|
1619
|
-
"react",
|
|
1620
|
-
"react-dom",
|
|
1621
|
-
"@ggui-ai/design",
|
|
1622
|
-
"@ggui-ai/wire",
|
|
1623
|
-
"@ggui-ai/gadgets"
|
|
1624
|
-
];
|
|
1625
|
-
function isAllowedImport(specifier, gadgetPackages) {
|
|
1626
|
-
if (FORBIDDEN_IMPORT_SPECIFIERS.includes(specifier)) return false;
|
|
1627
|
-
for (const base of ALLOWED_IMPORT_BASES) {
|
|
1628
|
-
if (specifier === base || specifier.startsWith(`${base}/`)) return true;
|
|
1629
|
-
}
|
|
1630
|
-
return gadgetPackages?.has(specifier) ?? false;
|
|
1631
|
-
}
|
|
1632
|
-
function describeAllowedImports() {
|
|
1633
|
-
return "react, @ggui-ai/design, @ggui-ai/wire, @ggui-ai/gadgets, or a gadget package declared on the contract \u2014 never @ggui-ai/wire/internal (the writer side of the wire; components read useRender().isConnected)";
|
|
1634
|
-
}
|
|
1635
|
-
var MAX_FILE_SIZE = 50 * 1024;
|
|
1636
|
-
var MAX_LINE_COUNT = 500;
|
|
1637
|
-
var DANGEROUS_PATTERNS = DANGEROUS_PATTERNS$1;
|
|
1638
|
-
function getLineNumber(code, match) {
|
|
1639
|
-
const upToMatch = code.substring(0, match.index);
|
|
1640
|
-
return upToMatch.split("\n").length;
|
|
1641
|
-
}
|
|
1642
|
-
function extractImports(code) {
|
|
1643
|
-
const imports = [];
|
|
1644
|
-
const importRegex = /import\s+(?:[\w\s{},*]+\s+from\s+)?['"]([^'"]+)['"]/g;
|
|
1645
|
-
let match;
|
|
1646
|
-
while ((match = importRegex.exec(code)) !== null) {
|
|
1647
|
-
imports.push({
|
|
1648
|
-
source: match[1],
|
|
1649
|
-
line: getLineNumber(code, match)
|
|
1650
|
-
});
|
|
1651
|
-
}
|
|
1652
|
-
return imports;
|
|
1653
|
-
}
|
|
1654
|
-
function extractPrimitivesUsed(code) {
|
|
1655
|
-
const jsxTagRegex = /<([A-Z][a-zA-Z0-9]*)/g;
|
|
1656
|
-
const used = /* @__PURE__ */ new Set();
|
|
1657
|
-
let match;
|
|
1658
|
-
while ((match = jsxTagRegex.exec(code)) !== null) {
|
|
1659
|
-
used.add(match[1]);
|
|
1660
|
-
}
|
|
1661
|
-
return Array.from(used);
|
|
1662
|
-
}
|
|
1663
|
-
function validateComponentDetailed(code, options = {}) {
|
|
1664
|
-
const errors = [];
|
|
1665
|
-
const warnings = [];
|
|
1666
|
-
const suggestions = [];
|
|
1667
|
-
const lines = code.split("\n");
|
|
1668
|
-
const lineCount = lines.length;
|
|
1669
|
-
const charCount = code.length;
|
|
1670
|
-
if (!options.skipSizeLimits) {
|
|
1671
|
-
if (charCount > MAX_FILE_SIZE) {
|
|
1672
|
-
errors.push({
|
|
1673
|
-
type: "size",
|
|
1674
|
-
message: `Component is too large: ${(charCount / 1024).toFixed(1)}KB exceeds ${MAX_FILE_SIZE / 1024}KB limit`,
|
|
1675
|
-
suggestion: "Split the component into smaller sub-components or simplify the implementation."
|
|
1676
|
-
});
|
|
1677
|
-
}
|
|
1678
|
-
if (lineCount > MAX_LINE_COUNT) {
|
|
1679
|
-
errors.push({
|
|
1680
|
-
type: "size",
|
|
1681
|
-
message: `Component has too many lines: ${lineCount} exceeds ${MAX_LINE_COUNT} line limit`,
|
|
1682
|
-
suggestion: "Split the component into smaller sub-components."
|
|
1683
|
-
});
|
|
1684
|
-
}
|
|
1685
|
-
}
|
|
1686
|
-
const imports = extractImports(code);
|
|
1687
|
-
if (!options.skipImportValidation) {
|
|
1688
|
-
for (const imp of imports) {
|
|
1689
|
-
const isAllowed = isAllowedImport(imp.source);
|
|
1690
|
-
const isAppComponents = imp.source === "@app/components" || imp.source.startsWith("@app/components/");
|
|
1691
|
-
if (!isAllowed && !isAppComponents) {
|
|
1692
|
-
errors.push({
|
|
1693
|
-
type: "import",
|
|
1694
|
-
message: `Invalid import: "${imp.source}" is not allowed`,
|
|
1695
|
-
line: imp.line,
|
|
1696
|
-
suggestion: `Only import from: ${describeAllowedImports()}. Remove this import and use ggui primitives instead.`
|
|
1697
|
-
});
|
|
1698
|
-
}
|
|
1699
|
-
}
|
|
1700
|
-
if (!imports.some((i) => i.source === "react")) {
|
|
1701
|
-
if (/\buseState\b|\buseEffect\b|\buseMemo\b|\buseCallback\b|\buseRef\b/.test(code)) {
|
|
1702
|
-
warnings.push({
|
|
1703
|
-
type: "best-practice",
|
|
1704
|
-
message: "React hooks are used but react is not explicitly imported",
|
|
1705
|
-
suggestion: "Add: import { useState } from 'react';"
|
|
1706
|
-
});
|
|
1707
|
-
}
|
|
1708
|
-
}
|
|
1709
|
-
if (!imports.some((i) => i.source === "@ggui-ai/design")) {
|
|
1710
|
-
warnings.push({
|
|
1711
|
-
type: "best-practice",
|
|
1712
|
-
message: "No primitives imported from @ggui-ai/design",
|
|
1713
|
-
suggestion: "Import primitives: import { Container, Card, Stack, Text, Button } from '@ggui-ai/design';"
|
|
1714
|
-
});
|
|
1715
|
-
}
|
|
1716
|
-
}
|
|
1717
|
-
const primitivesUsed = extractPrimitivesUsed(code);
|
|
1718
|
-
const hasAppComponentImport = imports.some((i) => i.source.startsWith("@app/components"));
|
|
1719
|
-
const importedComponentNames = /* @__PURE__ */ new Set();
|
|
1720
|
-
if (hasAppComponentImport) {
|
|
1721
|
-
const namedImportRegex = /import\s*\{([^}]+)\}\s*from\s*['"]@app\/components['"]/g;
|
|
1722
|
-
let match;
|
|
1723
|
-
while ((match = namedImportRegex.exec(code)) !== null) {
|
|
1724
|
-
const names = match[1].split(",").map((n) => n.trim().split(" as ")[0].trim());
|
|
1725
|
-
for (const name of names) {
|
|
1726
|
-
if (name) importedComponentNames.add(name);
|
|
1727
|
-
}
|
|
1728
|
-
}
|
|
1729
|
-
const defaultImportRegex = /import\s+(\w+)\s+from\s*['"]@app\/components\/[^'"]+['"]/g;
|
|
1730
|
-
while ((match = defaultImportRegex.exec(code)) !== null) {
|
|
1731
|
-
importedComponentNames.add(match[1]);
|
|
1732
|
-
}
|
|
1733
|
-
}
|
|
1734
|
-
for (const primitive of primitivesUsed) {
|
|
1735
|
-
if (!VALID_PRIMITIVES.includes(primitive)) {
|
|
1736
|
-
if (importedComponentNames.has(primitive)) {
|
|
1737
|
-
continue;
|
|
1738
|
-
}
|
|
1739
|
-
const isImported = code.includes(`import`) && code.includes(primitive);
|
|
1740
|
-
if (!isImported) {
|
|
1741
|
-
errors.push({
|
|
1742
|
-
type: "primitive",
|
|
1743
|
-
message: `Unknown component: "${primitive}" is not a valid ggui primitive`,
|
|
1744
|
-
suggestion: `Use one of the valid primitives: ${VALID_PRIMITIVES.slice(0, 10).join(", ")}... or import from @app/components, or define it within this component.`
|
|
1745
|
-
});
|
|
1746
|
-
}
|
|
1747
|
-
}
|
|
1748
|
-
}
|
|
1749
|
-
if (!options.skipSecurityPatterns) {
|
|
1750
|
-
for (const { pattern, name, suggestion } of DANGEROUS_PATTERNS) {
|
|
1751
|
-
const match = pattern.exec(code);
|
|
1752
|
-
if (match) {
|
|
1753
|
-
errors.push({
|
|
1754
|
-
type: "security",
|
|
1755
|
-
message: `Security violation: ${name} is not allowed`,
|
|
1756
|
-
line: getLineNumber(code, match),
|
|
1757
|
-
suggestion,
|
|
1758
|
-
code: match[0]
|
|
1759
|
-
});
|
|
1760
|
-
}
|
|
1761
|
-
}
|
|
1762
|
-
}
|
|
1763
|
-
if (!code.includes("export default")) {
|
|
1764
|
-
errors.push({
|
|
1765
|
-
type: "structure",
|
|
1766
|
-
message: "Component must have a default export",
|
|
1767
|
-
suggestion: 'Add "export default" before your main component function.'
|
|
1768
|
-
});
|
|
1769
|
-
}
|
|
1770
|
-
if (/class\s+\w+\s+extends\s+(React\.)?Component/.test(code)) {
|
|
1771
|
-
errors.push({
|
|
1772
|
-
type: "structure",
|
|
1773
|
-
message: "Class components are not allowed",
|
|
1774
|
-
suggestion: "Convert to a functional component using hooks."
|
|
1775
|
-
});
|
|
1776
|
-
}
|
|
1777
|
-
if (!code.includes("interface") && !code.includes("type ") && code.includes("Props")) {
|
|
1778
|
-
warnings.push({
|
|
1779
|
-
type: "best-practice",
|
|
1780
|
-
message: "Props are used but no TypeScript interface is defined",
|
|
1781
|
-
suggestion: "Define a Props interface: interface Props { onSubmit: (data: FormData) => void; }"
|
|
1782
|
-
});
|
|
1783
|
-
}
|
|
1784
|
-
if (/e\.target\.value|event\.target\.value/.test(code)) {
|
|
1785
|
-
errors.push({
|
|
1786
|
-
type: "syntax",
|
|
1787
|
-
message: "Using e.target.value with ggui primitives will fail - onChange receives value directly",
|
|
1788
|
-
suggestion: "Change from onChange={(e) => setValue(e.target.value)} to onChange={setValue} or onChange={(value) => setValue(value)}"
|
|
1789
|
-
});
|
|
1790
|
-
}
|
|
1791
|
-
if (code.includes(".map(") && !code.includes("key=")) {
|
|
1792
|
-
warnings.push({
|
|
1793
|
-
type: "best-practice",
|
|
1794
|
-
message: "List rendering detected but no key prop found",
|
|
1795
|
-
suggestion: "Add key prop to mapped elements: {items.map(item => <Card key={item.id}>...)}"
|
|
1796
|
-
});
|
|
1797
|
-
}
|
|
1798
|
-
if (code.includes("<Image") && !code.includes("alt=")) {
|
|
1799
|
-
warnings.push({
|
|
1800
|
-
type: "accessibility",
|
|
1801
|
-
message: "Image without alt attribute",
|
|
1802
|
-
suggestion: 'Add alt attribute to Image: <Image src={...} alt="Description" />'
|
|
1803
|
-
});
|
|
1804
|
-
}
|
|
1805
|
-
const hasInputs = /<Input\b/.test(code) || /<TextArea\b/.test(code) || /<Select\b/.test(code);
|
|
1806
|
-
if (hasInputs) {
|
|
1807
|
-
const hasLabels = /label=/.test(code) || /htmlFor=/.test(code) || /aria-label=/.test(code) || /aria-labelledby=/.test(code);
|
|
1808
|
-
if (!hasLabels) {
|
|
1809
|
-
warnings.push({
|
|
1810
|
-
type: "accessibility",
|
|
1811
|
-
message: "Form inputs detected without labels",
|
|
1812
|
-
suggestion: 'Add label prop to inputs or associate with <Text is="label" htmlFor="id">. Screen readers need labels to identify form fields.'
|
|
1813
|
-
});
|
|
1814
|
-
}
|
|
1815
|
-
}
|
|
1816
|
-
if ((code.includes("onSubmit") || code.includes('role="form"')) && !code.includes("aria-label")) {
|
|
1817
|
-
warnings.push({
|
|
1818
|
-
type: "accessibility",
|
|
1819
|
-
message: "Form without aria-label",
|
|
1820
|
-
suggestion: 'Add aria-label to your form container: <Stack role="form" aria-label="Contact form">'
|
|
1821
|
-
});
|
|
1822
|
-
}
|
|
1823
|
-
const iconButtonPattern = /<Button(?![^>]*aria-label)[^>]*>\s*.\s*<\/Button>/;
|
|
1824
|
-
if (iconButtonPattern.test(code)) {
|
|
1825
|
-
warnings.push({
|
|
1826
|
-
type: "accessibility",
|
|
1827
|
-
message: "Icon-only button detected without text content",
|
|
1828
|
-
suggestion: 'Add aria-label to icon-only buttons: <Button aria-label="Close">\xD7</Button>'
|
|
1829
|
-
});
|
|
1830
|
-
}
|
|
1831
|
-
if (code.includes("<Button") && !/disabled=|loading=/.test(code)) {
|
|
1832
|
-
if (code.includes("onSubmit") || code.includes("submit")) {
|
|
1833
|
-
warnings.push({
|
|
1834
|
-
type: "best-practice",
|
|
1835
|
-
message: "Submit button without disabled state",
|
|
1836
|
-
suggestion: "Consider adding disabled={isSubmitting || !isValid} to prevent double submission"
|
|
1837
|
-
});
|
|
1838
|
-
}
|
|
1839
|
-
}
|
|
1840
|
-
if (errors.length > 0) {
|
|
1841
|
-
suggestions.push("Fix all errors before compiling - the component will not work with errors.");
|
|
1842
|
-
}
|
|
1843
|
-
if (errors.some((e) => e.type === "import")) {
|
|
1844
|
-
suggestions.push(
|
|
1845
|
-
"Only react and @ggui-ai/design imports are allowed. All UI should be built with primitives."
|
|
1846
|
-
);
|
|
1847
|
-
}
|
|
1848
|
-
if (errors.some((e) => e.type === "security")) {
|
|
1849
|
-
suggestions.push("Avoid browser APIs - use props and callbacks for data flow.");
|
|
1850
|
-
}
|
|
1851
|
-
return {
|
|
1852
|
-
valid: errors.length === 0,
|
|
1853
|
-
errors,
|
|
1854
|
-
warnings,
|
|
1855
|
-
suggestions,
|
|
1856
|
-
stats: {
|
|
1857
|
-
lineCount,
|
|
1858
|
-
charCount,
|
|
1859
|
-
importCount: imports.length,
|
|
1860
|
-
primitiveCount: primitivesUsed.filter(
|
|
1861
|
-
(p) => VALID_PRIMITIVES.includes(p)
|
|
1862
|
-
).length
|
|
1863
|
-
}
|
|
1864
|
-
};
|
|
1865
|
-
}
|
|
1866
|
-
function formatValidationResultForClaude(result) {
|
|
1867
|
-
if (result.valid && result.warnings.length === 0) {
|
|
1868
|
-
return "Validation passed. Component is ready for compilation.";
|
|
1869
|
-
}
|
|
1870
|
-
const parts = [];
|
|
1871
|
-
if (!result.valid) {
|
|
1872
|
-
parts.push("## Validation Errors (must fix)\n");
|
|
1873
|
-
for (const error of result.errors) {
|
|
1874
|
-
const lineInfo = error.line ? ` (line ${error.line})` : "";
|
|
1875
|
-
parts.push(`- **${error.type.toUpperCase()}**${lineInfo}: ${error.message}`);
|
|
1876
|
-
parts.push(` - Fix: ${error.suggestion}`);
|
|
1877
|
-
if (error.code) {
|
|
1878
|
-
parts.push(` - Code: \`${error.code}\``);
|
|
1879
|
-
}
|
|
1880
|
-
}
|
|
1881
|
-
}
|
|
1882
|
-
if (result.warnings.length > 0) {
|
|
1883
|
-
parts.push("\n## Warnings (recommended to fix)\n");
|
|
1884
|
-
for (const warning of result.warnings) {
|
|
1885
|
-
const lineInfo = warning.line ? ` (line ${warning.line})` : "";
|
|
1886
|
-
parts.push(`- **${warning.type}**${lineInfo}: ${warning.message}`);
|
|
1887
|
-
parts.push(` - Suggestion: ${warning.suggestion}`);
|
|
1888
|
-
}
|
|
1889
|
-
}
|
|
1890
|
-
if (result.suggestions.length > 0) {
|
|
1891
|
-
parts.push("\n## General Suggestions\n");
|
|
1892
|
-
for (const suggestion of result.suggestions) {
|
|
1893
|
-
parts.push(`- ${suggestion}`);
|
|
1894
|
-
}
|
|
1895
|
-
}
|
|
1896
|
-
parts.push(
|
|
1897
|
-
`
|
|
1898
|
-
## Stats: ${result.stats.lineCount} lines, ${result.stats.primitiveCount} primitives used`
|
|
1899
|
-
);
|
|
1900
|
-
return parts.join("\n");
|
|
1901
|
-
}
|
|
1902
|
-
|
|
1903
|
-
// src/design-system-docs.ts
|
|
1904
|
-
var DEFAULT_DESIGN_SYSTEM_DOCS = `# Design System - Default Light Theme
|
|
1905
|
-
|
|
1906
|
-
**IMPORTANT:** Always use CSS variables (var(--ggui-*)) for styling to ensure components respect the app theme.
|
|
1907
|
-
|
|
1908
|
-
## Colors
|
|
1909
|
-
|
|
1910
|
-
### Primary
|
|
1911
|
-
- var(--ggui-color-primary-50) - #f0f9ff
|
|
1912
|
-
- var(--ggui-color-primary-100) - #e0f2fe
|
|
1913
|
-
- var(--ggui-color-primary-200) - #bae6fd
|
|
1914
|
-
- var(--ggui-color-primary-300) - #7dd3fc
|
|
1915
|
-
- var(--ggui-color-primary-400) - #38bdf8
|
|
1916
|
-
- var(--ggui-color-primary-500) - #0ea5e9
|
|
1917
|
-
- var(--ggui-color-primary-600) - #0284c7 (main action FILL \u2014 buttons, borders, icon fills; accent TEXT takes the link role below)
|
|
1918
|
-
- var(--ggui-color-primary-700) - #0369a1
|
|
1919
|
-
- var(--ggui-color-primary-800) - #075985
|
|
1920
|
-
- var(--ggui-color-primary-900) - #0c4a6e
|
|
1921
|
-
|
|
1922
|
-
### Semantic Surface & Text Colors (REQUIRED for theme compatibility)
|
|
1923
|
-
These tokens adapt automatically to any theme (light, dark, branded). **ALWAYS use these for surfaces and text \u2014 never use raw neutral-* scale values.**
|
|
1924
|
-
|
|
1925
|
-
| Token | CSS Variable | Default | Role |
|
|
1926
|
-
|-------|-------------|---------|------|
|
|
1927
|
-
| ground | var(--ggui-color-ground) | The page / canvas behind everything |
|
|
1928
|
-
| onGround | var(--ggui-color-onGround) | Text on the canvas |
|
|
1929
|
-
| container | var(--ggui-color-container) | A card, a bubble, a panel \u2014 the unit of content |
|
|
1930
|
-
| onContainer | var(--ggui-color-onContainer) | Body text on a card |
|
|
1931
|
-
| elevated | var(--ggui-color-elevated) | Menus, popovers, modals, toasts \u2014 floats above a card |
|
|
1932
|
-
| onElevated | var(--ggui-color-onElevated) | Text on an elevated surface |
|
|
1933
|
-
| heroGround | var(--ggui-color-heroGround) | A hero / greeting panel's ground \u2014 brand-tinted on a light host, the ink pair on a dark one (Card surface="hero") |
|
|
1934
|
-
| onHeroGround | var(--ggui-color-onHeroGround) | Text on the hero ground |
|
|
1935
|
-
| sunken | var(--ggui-color-sunken) | Wells, inputs at rest, code blocks \u2014 recessed inside a card |
|
|
1936
|
-
| onSunken | var(--ggui-color-onSunken) | Muted / secondary text |
|
|
1937
|
-
| link | var(--ggui-color-link) | Accent TEXT \u2014 eyebrows, taglines, links, labels, inline arrows: the brand's readable ink, derived per mode to clear 4.5:1 on the container and the ground |
|
|
1938
|
-
| outline | var(--ggui-color-outline) | Borders, dividers |
|
|
1939
|
-
| outlineVariant | var(--ggui-color-outlineVariant) | Subtle borders |
|
|
1940
|
-
| controlOutline | var(--ggui-color-controlOutline) | A control's edge \u2014 clears 3:1 on its surface; kit controls draw it themselves |
|
|
1941
|
-
|
|
1942
|
-
**Usage pattern:**
|
|
1943
|
-
- Page/section background \u2192 \`var(--ggui-color-ground)\`
|
|
1944
|
-
- Body text \u2192 \`var(--ggui-color-onContainer)\`
|
|
1945
|
-
- Card/panel background \u2192 \`var(--ggui-color-container)\`; recessed wells / inputs \u2192 \`var(--ggui-color-sunken)\`
|
|
1946
|
-
- Secondary/muted text \u2192 \`var(--ggui-color-onSunken)\`
|
|
1947
|
-
- Accent / branded text (eyebrow, tagline, link, label, inline arrow) \u2192 \`var(--ggui-color-link)\` or \`<Text tone="emphasized">\` \u2014 never a bare \`primary-<stop>\` as a text color
|
|
1948
|
-
- Branded section/header \u2192 \`var(--ggui-color-container)\` bg + \`var(--ggui-color-onContainer)\` text
|
|
1949
|
-
- Borders/dividers \u2192 \`var(--ggui-color-outline)\` or \`var(--ggui-color-outlineVariant)\`
|
|
1950
|
-
|
|
1951
|
-
### State Colors
|
|
1952
|
-
Semantic families ship as SCALES; the \`500\` stop is the role color (per-mode brightness), \`50\` the tint, \`800\` the on-tint text:
|
|
1953
|
-
- var(--ggui-color-success-500) \u2014 success states (tint bg: success-50, text on tint: success-800)
|
|
1954
|
-
- var(--ggui-color-warning-500) \u2014 warning states (warning-50 / warning-800)
|
|
1955
|
-
- var(--ggui-color-error-500) \u2014 error states, destructive actions (error-50 / error-800)
|
|
1956
|
-
- var(--ggui-color-info-500) \u2014 informational (info-50 / info-800)
|
|
1957
|
-
Prefer the primitives' \`tone="success|warning|error|info"\` prop over hand-written vars \u2014 it resolves to the same stops.
|
|
1958
|
-
|
|
1959
|
-
### IMPORTANT: Color Rules
|
|
1960
|
-
- **NEVER** use hardcoded hex colors. ONLY use var(--ggui-color-*) tokens.
|
|
1961
|
-
- **NEVER** use rgba(), hsl(), or other CSS color functions with hardcoded values.
|
|
1962
|
-
- **NEVER** use raw neutral-* or gray-* scale tokens (neutral-50, neutral-900, etc.) \u2014 these are internal to the theme and break in dark mode.
|
|
1963
|
-
- **ALWAYS** use semantic tokens for text and backgrounds:
|
|
1964
|
-
- Text: \`var(--ggui-color-onContainer)\` or \`var(--ggui-color-onSunken)\`
|
|
1965
|
-
- Backgrounds: \`var(--ggui-color-container)\` or \`var(--ggui-color-sunken)\`
|
|
1966
|
-
- Borders: \`var(--ggui-color-outline)\` or \`var(--ggui-color-outlineVariant)\`
|
|
1967
|
-
- For branded elements use \`var(--ggui-color-primary-*)\` scale tokens \u2014 these ARE safe because primary adapts per theme.
|
|
1968
|
-
- For card backgrounds use \`var(--ggui-color-container)\` or \`var(--ggui-color-primary-50)\`
|
|
1969
|
-
|
|
1970
|
-
## Spacing
|
|
1971
|
-
|
|
1972
|
-
Use \`var(--ggui-spacing-N)\` for all padding, gap, and margin values. **Never use raw numbers** like \`padding={16}\` \u2014 always use the token: \`padding="var(--ggui-spacing-4)"\`.
|
|
1973
|
-
|
|
1974
|
-
| Token | Value | Common use |
|
|
1975
|
-
|-------|-------|------------|
|
|
1976
|
-
| var(--ggui-spacing-1) | 4px | Icon gaps, tight spacing |
|
|
1977
|
-
| var(--ggui-spacing-2) | 8px | Button padding, small gaps |
|
|
1978
|
-
| var(--ggui-spacing-3) | 12px | List item spacing, form gaps |
|
|
1979
|
-
| var(--ggui-spacing-4) | 16px | Card padding, section gaps |
|
|
1980
|
-
| var(--ggui-spacing-5) | 20px | Medium padding |
|
|
1981
|
-
| var(--ggui-spacing-6) | 24px | Container padding, large gaps |
|
|
1982
|
-
| var(--ggui-spacing-8) | 32px | Section spacing |
|
|
1983
|
-
| var(--ggui-spacing-10) | 40px | Page margins |
|
|
1984
|
-
| var(--ggui-spacing-12) | 48px | Hero/large section spacing |
|
|
1985
|
-
|
|
1986
|
-
**Quick lookup (px \u2192 token):** 4\u21921, 8\u21922, 12\u21923, 16\u21924, 20\u21925, 24\u21926, 28\u21927, 32\u21928, 36\u21929, 40\u219210, 48\u219212
|
|
1987
|
-
|
|
1988
|
-
**Usage on primitives:**
|
|
1989
|
-
\`\`\`tsx
|
|
1990
|
-
<Container padding="var(--ggui-spacing-6)">
|
|
1991
|
-
<Stack gap="var(--ggui-spacing-4)">
|
|
1992
|
-
<Card padding="var(--ggui-spacing-4)">
|
|
1993
|
-
<Row gap="var(--ggui-spacing-2)">...</Row>
|
|
1994
|
-
</Card>
|
|
1995
|
-
</Stack>
|
|
1996
|
-
</Container>
|
|
1997
|
-
\`\`\`
|
|
1998
|
-
|
|
1999
|
-
## Typography
|
|
2000
|
-
|
|
2001
|
-
### Font Sizes
|
|
2002
|
-
- var(--ggui-font-size-xs) - 12px
|
|
2003
|
-
- var(--ggui-font-size-sm) - 14px
|
|
2004
|
-
- var(--ggui-font-size-base) - 16px
|
|
2005
|
-
- var(--ggui-font-size-lg) - 18px
|
|
2006
|
-
- var(--ggui-font-size-xl) - 20px
|
|
2007
|
-
- var(--ggui-font-size-2xl) - 24px
|
|
2008
|
-
- var(--ggui-font-size-3xl) - 30px
|
|
2009
|
-
- var(--ggui-font-size-4xl) - 36px
|
|
2010
|
-
|
|
2011
|
-
### Font Weights
|
|
2012
|
-
- var(--ggui-font-weight-normal) - 400
|
|
2013
|
-
- var(--ggui-font-weight-medium) - 500
|
|
2014
|
-
- var(--ggui-font-weight-semibold) - 600
|
|
2015
|
-
- var(--ggui-font-weight-bold) - 700
|
|
2016
|
-
|
|
2017
|
-
## Border Radius
|
|
2018
|
-
- var(--ggui-shape-radius-sm) - 4px
|
|
2019
|
-
- var(--ggui-shape-radius-md) - 8px
|
|
2020
|
-
- var(--ggui-shape-radius-lg) - 12px
|
|
2021
|
-
- var(--ggui-shape-radius-xl) - 16px
|
|
2022
|
-
- var(--ggui-shape-radius-full) - 9999px
|
|
2023
|
-
|
|
2024
|
-
## Shadows
|
|
2025
|
-
- var(--ggui-shape-shadow-sm) - 0 1px 2px rgba(0,0,0,0.05)
|
|
2026
|
-
- var(--ggui-shape-shadow-md) - 0 4px 6px -1px rgba(0,0,0,0.1)
|
|
2027
|
-
- var(--ggui-shape-shadow-lg) - 0 10px 15px -3px rgba(0,0,0,0.1)
|
|
2028
|
-
- var(--ggui-shape-shadow-xl) - 0 20px 25px -5px rgba(0,0,0,0.1)
|
|
2029
|
-
|
|
2030
|
-
## Usage Examples (always use ggui primitives \u2014 never raw <div>, <button>, <input>)
|
|
2031
|
-
|
|
2032
|
-
### Branded section header
|
|
2033
|
-
\`\`\`tsx
|
|
2034
|
-
<Box padding="var(--ggui-spacing-4)" surface="accent">
|
|
2035
|
-
<Heading level={2} tone="emphasized">Contact Us</Heading>
|
|
2036
|
-
<Text tone="emphasized">We'd love to hear from you</Text>
|
|
2037
|
-
</Box>
|
|
2038
|
-
\`\`\`
|
|
2039
|
-
|
|
2040
|
-
### Form input
|
|
2041
|
-
\`\`\`tsx
|
|
2042
|
-
<Input label="Email" placeholder="you@example.com" />
|
|
2043
|
-
\`\`\`
|
|
2044
|
-
|
|
2045
|
-
### Buttons
|
|
2046
|
-
\`\`\`tsx
|
|
2047
|
-
<Button variant="primary">Submit</Button>
|
|
2048
|
-
<Button variant="outline">Cancel</Button>
|
|
2049
|
-
<Button variant="ghost">Skip</Button>
|
|
2050
|
-
\`\`\`
|
|
2051
|
-
|
|
2052
|
-
### Card with spacing tokens
|
|
2053
|
-
\`\`\`tsx
|
|
2054
|
-
<Card padding="var(--ggui-spacing-4)" shadow="md">
|
|
2055
|
-
<Stack gap="var(--ggui-spacing-3)">
|
|
2056
|
-
<Heading level={3}>Title</Heading>
|
|
2057
|
-
<Text tone="muted">Description</Text>
|
|
2058
|
-
</Stack>
|
|
2059
|
-
</Card>
|
|
2060
|
-
\`\`\`
|
|
2061
|
-
|
|
2062
|
-
### Color usage guide
|
|
2063
|
-
- **Layering roles** (ground, container, elevated, sunken + their on* inks; outline): one kind of AREA each \u2014 use them for every background/text/border decision; they adapt to any theme
|
|
2064
|
-
- **primary-50/100**: Section backgrounds, highlight strips, card headers
|
|
2065
|
-
- **primary-200/300**: Dividers and section rules \u2014 never a control's border: kit controls draw their own edge (\`controlOutline\` / \`controlAccentOutline\`), so set no inline border on them
|
|
2066
|
-
- **primary-500/600**: Filled buttons, CTAs, badges, icon fills, active indicators \u2014 fills and borders, NOT a text color
|
|
2067
|
-
- **link**: Accent TEXT \u2014 eyebrows, taglines, links, labels, inline arrows; the brand's readable ink per mode (a bare \`primary-300\u2026600\` as a text color fails tier-0: \`universal.accent_text_ink\`)
|
|
2068
|
-
- **primary-700/800/900**: Headings and text on light primary backgrounds
|
|
2069
|
-
- **neutral-***: Only when you need a specific shade that semantic tokens don't cover
|
|
2070
|
-
|
|
2071
|
-
The primary palette is the app's brand \u2014 use it throughout (headers, accents, borders, interactive elements), not just on the submit button.
|
|
2072
|
-
|
|
2073
|
-
**Note:** Do NOT add fallback values to var() (e.g., var(--ggui-color-container, #fafafa)). Just use var(--ggui-color-container) \u2014 the theme provides all values.
|
|
2074
|
-
|
|
2075
|
-
## Motion & Animation
|
|
2076
|
-
|
|
2077
|
-
### Duration Scale
|
|
2078
|
-
- \`instant\`: 0ms
|
|
2079
|
-
- \`fast\`: 100ms
|
|
2080
|
-
- \`normal\`: 200ms
|
|
2081
|
-
- \`slow\`: 300ms
|
|
2082
|
-
- \`slower\`: 500ms
|
|
2083
|
-
|
|
2084
|
-
### Easing Curves
|
|
2085
|
-
- \`linear\`: linear
|
|
2086
|
-
- \`easeIn\`: cubic-bezier(0.4, 0, 1, 1)
|
|
2087
|
-
- \`easeOut\`: cubic-bezier(0, 0, 0.2, 1)
|
|
2088
|
-
- \`easeInOut\`: cubic-bezier(0.4, 0, 0.2, 1)
|
|
2089
|
-
- \`spring\`: cubic-bezier(0.175, 0.885, 0.32, 1.275)
|
|
2090
|
-
|
|
2091
|
-
### Transition Presets (import from '@ggui-ai/design/tokens')
|
|
2092
|
-
\`\`\`tsx
|
|
2093
|
-
import { duration, easing, transition } from '@ggui-ai/design/tokens';
|
|
2094
|
-
// transition.fast \u2192 "100ms cubic-bezier(0.4, 0, 0.2, 1)"
|
|
2095
|
-
// transition.normal \u2192 "200ms cubic-bezier(0.4, 0, 0.2, 1)"
|
|
2096
|
-
// transition.slow \u2192 "300ms cubic-bezier(0.4, 0, 0.2, 1)"
|
|
2097
|
-
// transition.colors \u2192 color + background-color + border-color (200ms each)
|
|
2098
|
-
// transition.opacity \u2192 opacity 200ms
|
|
2099
|
-
// transition.transform \u2192 transform 200ms
|
|
2100
|
-
\`\`\`
|
|
2101
|
-
|
|
2102
|
-
### Animation Keyframes
|
|
2103
|
-
Use \`<MotionKeyframes />\` once in your component to inject all keyframes, then reference by name.
|
|
2104
|
-
|
|
2105
|
-
**Entrance / exit** (GPU-composited, transform + opacity):
|
|
2106
|
-
- \`ggui-fadeIn\` / \`ggui-fadeOut\`
|
|
2107
|
-
- \`ggui-slideInUp\` / \`ggui-slideInDown\`
|
|
2108
|
-
- \`ggui-scaleIn\` / \`ggui-scaleOut\`
|
|
2109
|
-
|
|
2110
|
-
**State feedback** (color-based, for data-change highlights):
|
|
2111
|
-
- \`ggui-flash\` \u2014 background-color highlight that fades out. Set \`--ggui-flash-color\` on the element (default: \`var(--ggui-color-primary-100)\`)
|
|
2112
|
-
- \`ggui-pulse\` \u2014 gentle opacity breathing (infinite, for "live" indicators)
|
|
2113
|
-
- \`ggui-bounce\` \u2014 subtle scale overshoot (one-shot, for confirmations)
|
|
2114
|
-
|
|
2115
|
-
\`\`\`tsx
|
|
2116
|
-
import { MotionKeyframes, useMotion, useAnimationKey } from '@ggui-ai/design';
|
|
2117
|
-
import { animation } from '@ggui-ai/design/tokens';
|
|
2118
|
-
|
|
2119
|
-
function MyComponent() {
|
|
2120
|
-
const { motionEnabled } = useMotion(); // respects prefers-reduced-motion
|
|
2121
|
-
return (
|
|
2122
|
-
<>
|
|
2123
|
-
<MotionKeyframes />
|
|
2124
|
-
{/* Entrance animation */}
|
|
2125
|
-
<div style={{ animation: motionEnabled ? animation.slideInUp : 'none' }}>
|
|
2126
|
-
Content slides in
|
|
2127
|
-
</div>
|
|
2128
|
-
</>
|
|
2129
|
-
);
|
|
2130
|
-
}
|
|
2131
|
-
\`\`\`
|
|
2132
|
-
|
|
2133
|
-
### Retriggering Animations on Data Changes
|
|
2134
|
-
When data updates (e.g., stock price from a stream), CSS animations don't replay automatically.
|
|
2135
|
-
Use \`useAnimationKey(dep)\` \u2014 returns a key that increments when \`dep\` changes, causing React to remount the element and replay the animation.
|
|
2136
|
-
|
|
2137
|
-
\`\`\`tsx
|
|
2138
|
-
import { MotionKeyframes, useAnimationKey } from '@ggui-ai/design';
|
|
2139
|
-
import { animation } from '@ggui-ai/design/tokens';
|
|
2140
|
-
|
|
2141
|
-
// Flash a stock card green/red when the price changes
|
|
2142
|
-
const priceKey = useAnimationKey(stock.price);
|
|
2143
|
-
<div
|
|
2144
|
-
key={priceKey}
|
|
2145
|
-
style={{
|
|
2146
|
-
animation: animation.flash,
|
|
2147
|
-
'--ggui-flash-color': stock.change > 0
|
|
2148
|
-
? 'var(--ggui-color-success-100)'
|
|
2149
|
-
: 'var(--ggui-color-error-100)',
|
|
2150
|
-
} as React.CSSProperties}
|
|
2151
|
-
>
|
|
2152
|
-
{stock.price}
|
|
2153
|
-
</div>
|
|
2154
|
-
\`\`\`
|
|
2155
|
-
|
|
2156
|
-
## Chart / Data Visualization Colors
|
|
2157
|
-
Semantic chart tokens for data visualizations:
|
|
2158
|
-
- \`var(--ggui-color-primary-600)\` \u2014 primary series
|
|
2159
|
-
- \`var(--ggui-color-success-500)\` \u2014 positive / success
|
|
2160
|
-
- \`var(--ggui-color-error-500)\` \u2014 negative / error
|
|
2161
|
-
- \`var(--ggui-color-warning-500)\` \u2014 warning / caution
|
|
2162
|
-
- \`var(--ggui-color-info-500)\` \u2014 informational
|
|
2163
|
-
- \`var(--ggui-color-neutral-400)\` \u2014 neutral series
|
|
2164
|
-
- \`var(--ggui-color-neutral-200)\` \u2014 light background series
|
|
2165
|
-
- \`var(--ggui-color-neutral-600)\` \u2014 dark series
|
|
2166
|
-
|
|
2167
|
-
## Accessibility Tokens
|
|
2168
|
-
|
|
2169
|
-
### Focus Ring (for keyboard focus states)
|
|
2170
|
-
- Color: \`var(--ggui-color-primary-600)\`
|
|
2171
|
-
- Width: 2px
|
|
2172
|
-
- Offset: 2px
|
|
2173
|
-
- Style: solid
|
|
2174
|
-
\`\`\`tsx
|
|
2175
|
-
// Apply to focusable elements:
|
|
2176
|
-
outline: '2px solid var(--ggui-color-primary-600)',
|
|
2177
|
-
outlineOffset: '2px',
|
|
2178
|
-
\`\`\`
|
|
2179
|
-
|
|
2180
|
-
### Reduced Motion
|
|
2181
|
-
Use \`useMotion()\` hook to check user preference. If disabled, set animation/transition to \`none\`.
|
|
2182
|
-
|
|
2183
|
-
## Elevation System
|
|
2184
|
-
Semantic depth levels combining shadow + z-index:
|
|
2185
|
-
| Level | Shadow | Z-Index | Use For |
|
|
2186
|
-
|-------|--------|---------|---------|
|
|
2187
|
-
| 0 | none | 0 | Flat content |
|
|
2188
|
-
| 1 | sm | auto | Cards, slight lift |
|
|
2189
|
-
| 2 | md | 1000 | Dropdowns, popovers |
|
|
2190
|
-
| 3 | lg | 1200 | Banners, sticky bars |
|
|
2191
|
-
| 4 | xl | 1400 | Modals, dialogs |
|
|
2192
|
-
| 5 | 2xl | 1800 | Tooltips, toasts |
|
|
2193
|
-
|
|
2194
|
-
\`\`\`tsx
|
|
2195
|
-
import { elevation } from '@ggui-ai/design/tokens';
|
|
2196
|
-
// elevation.level1 \u2192 { shadow: 'var(--ggui-shape-shadow-sm)', zIndex: 'auto' }
|
|
2197
|
-
// elevation.level2 \u2192 { shadow: 'var(--ggui-shape-shadow-md)', zIndex: 1000 }
|
|
2198
|
-
<div style={{ boxShadow: elevation.level1.shadow, zIndex: elevation.level1.zIndex }}>
|
|
2199
|
-
Card content
|
|
2200
|
-
</div>
|
|
2201
|
-
\`\`\`
|
|
2202
|
-
|
|
2203
|
-
## Typography Presets
|
|
2204
|
-
|
|
2205
|
-
### Heading Styles (import { headingStyles } from '@ggui-ai/design/tokens')
|
|
2206
|
-
| Level | Size | Weight | Line Height | Letter Spacing |
|
|
2207
|
-
|-------|------|--------|-------------|----------------|
|
|
2208
|
-
| h1 | 36px | bold (700) | 1.25 | -0.025em |
|
|
2209
|
-
| h2 | 30px | bold (700) | 1.25 | -0.025em |
|
|
2210
|
-
| h3 | 24px | semibold (600) | 1.375 | 0 |
|
|
2211
|
-
| h4 | 20px | semibold (600) | 1.375 | 0 |
|
|
2212
|
-
| h5 | 18px | semibold (600) | 1.5 | 0 |
|
|
2213
|
-
| h6 | 16px | semibold (600) | 1.5 | 0 |
|
|
2214
|
-
|
|
2215
|
-
### Text Sizing
|
|
2216
|
-
\`<Text>\` composes from \`size\` / \`weight\` / \`tone\` (+ \`caps\` for the
|
|
2217
|
-
uppercase eyebrow look) \u2014 there is no preset text-style table. Line
|
|
2218
|
-
height derives from \`size\` automatically (1.5 for xs-base, 1.625 at lg,
|
|
2219
|
-
tighter on display sizes).
|
|
2220
|
-
|
|
2221
|
-
### Letter Spacing Scale
|
|
2222
|
-
- \`tighter\`: -0.05em
|
|
2223
|
-
- \`tight\`: -0.025em
|
|
2224
|
-
- \`normal\`: 0
|
|
2225
|
-
- \`wide\`: 0.025em
|
|
2226
|
-
- \`wider\`: 0.05em
|
|
2227
|
-
- \`widest\`: 0.1em
|
|
2228
|
-
|
|
2229
|
-
### Line Height Scale
|
|
2230
|
-
- \`none\`: 1
|
|
2231
|
-
- \`tight\`: 1.25
|
|
2232
|
-
- \`snug\`: 1.375
|
|
2233
|
-
- \`normal\`: 1.5
|
|
2234
|
-
- \`relaxed\`: 1.625
|
|
2235
|
-
- \`loose\`: 2`;
|
|
2236
|
-
|
|
2237
|
-
// src/boilerplate/json-schema-ts.ts
|
|
2238
|
-
function jsonSchemaTypeToTs(schema) {
|
|
2239
|
-
const unionMembers = schema.oneOf ?? schema.anyOf;
|
|
2240
|
-
if (unionMembers?.length) {
|
|
2241
|
-
const types = [...new Set(unionMembers.map((s) => jsonSchemaTypeToTs(s)))];
|
|
2242
|
-
return types.length === 1 ? types[0] : types.join(" | ");
|
|
2243
|
-
}
|
|
2244
|
-
if (schema.const !== void 0) {
|
|
2245
|
-
return typeof schema.const === "string" ? `'${schema.const}'` : String(schema.const);
|
|
2246
|
-
}
|
|
2247
|
-
if (schema.enum?.length) {
|
|
2248
|
-
return schema.enum.map((v) => typeof v === "string" ? `'${v}'` : String(v)).join(" | ");
|
|
2249
|
-
}
|
|
2250
|
-
if (Array.isArray(schema.type)) {
|
|
2251
|
-
const { nullable: _nullable, ...rest } = schema;
|
|
2252
|
-
const members = [...new Set(schema.type)].map(
|
|
2253
|
-
(member) => jsonSchemaTypeToTs({ ...rest, type: member })
|
|
2254
|
-
);
|
|
2255
|
-
const unique = [...new Set(members)];
|
|
2256
|
-
if (schema.nullable && !unique.includes("null")) unique.push("null");
|
|
2257
|
-
return unique.join(" | ");
|
|
2258
|
-
}
|
|
2259
|
-
let result;
|
|
2260
|
-
switch (schema.type) {
|
|
2261
|
-
case "string":
|
|
2262
|
-
result = "string";
|
|
2263
|
-
break;
|
|
2264
|
-
case "number":
|
|
2265
|
-
case "integer":
|
|
2266
|
-
result = "number";
|
|
2267
|
-
break;
|
|
2268
|
-
case "boolean":
|
|
2269
|
-
result = "boolean";
|
|
2270
|
-
break;
|
|
2271
|
-
case "null":
|
|
2272
|
-
return "null";
|
|
2273
|
-
case "array": {
|
|
2274
|
-
if (schema.items) {
|
|
2275
|
-
const itemType = jsonSchemaTypeToTs(schema.items);
|
|
2276
|
-
const itemsDeclareObject = Array.isArray(schema.items.type) ? schema.items.type.includes("object") : schema.items.type === "object";
|
|
2277
|
-
result = itemsDeclareObject && schema.items.properties ? `Array<${itemType}>` : itemType.includes("|") ? `(${itemType})[]` : `${itemType}[]`;
|
|
2278
|
-
} else {
|
|
2279
|
-
result = "unknown[]";
|
|
2280
|
-
}
|
|
2281
|
-
break;
|
|
2282
|
-
}
|
|
2283
|
-
case "object": {
|
|
2284
|
-
if (schema.properties) {
|
|
2285
|
-
const required = schema.required ?? [];
|
|
2286
|
-
const fields = Object.entries(schema.properties).map(([key, prop]) => {
|
|
2287
|
-
const opt = !required.includes(key);
|
|
2288
|
-
return `${key}${opt ? "?" : ""}: ${jsonSchemaTypeToTs(prop)}`;
|
|
2289
|
-
}).join("; ");
|
|
2290
|
-
result = `{ ${fields} }`;
|
|
2291
|
-
} else if (schema.additionalProperties && typeof schema.additionalProperties === "object") {
|
|
2292
|
-
result = `Record<string, ${jsonSchemaTypeToTs(schema.additionalProperties)}>`;
|
|
2293
|
-
} else {
|
|
2294
|
-
result = "Record<string, unknown>";
|
|
2295
|
-
}
|
|
2296
|
-
break;
|
|
2297
|
-
}
|
|
2298
|
-
default:
|
|
2299
|
-
result = "unknown";
|
|
2300
|
-
}
|
|
2301
|
-
if (schema.nullable && result !== "unknown") {
|
|
2302
|
-
return `${result} | null`;
|
|
2303
|
-
}
|
|
2304
|
-
return result;
|
|
2305
|
-
}
|
|
2306
|
-
|
|
2307
|
-
// src/check/contract-validation.ts
|
|
2308
|
-
function extractPropsInterface(code) {
|
|
2309
|
-
const sf = ts3.createSourceFile("component.tsx", code, ts3.ScriptTarget.Latest, true, ts3.ScriptKind.TSX);
|
|
2310
|
-
const props = [];
|
|
2311
|
-
function visitMembers(members) {
|
|
2312
|
-
for (const member of members) {
|
|
2313
|
-
if (ts3.isPropertySignature(member) && member.name) {
|
|
2314
|
-
const name = member.name.getText(sf);
|
|
2315
|
-
const type = member.type ? member.type.getText(sf) : "unknown";
|
|
2316
|
-
const optional = !!member.questionToken;
|
|
2317
|
-
props.push({ name, type, optional });
|
|
2318
|
-
}
|
|
2319
|
-
}
|
|
2320
|
-
}
|
|
2321
|
-
function visit(node) {
|
|
2322
|
-
if (ts3.isInterfaceDeclaration(node) && node.name.text === "Props") {
|
|
2323
|
-
visitMembers(node.members);
|
|
2324
|
-
return;
|
|
2325
|
-
}
|
|
2326
|
-
if (ts3.isTypeAliasDeclaration(node) && node.name.text === "Props") {
|
|
2327
|
-
if (ts3.isTypeLiteralNode(node.type)) {
|
|
2328
|
-
visitMembers(node.type.members);
|
|
2329
|
-
}
|
|
2330
|
-
return;
|
|
2331
|
-
}
|
|
2332
|
-
ts3.forEachChild(node, visit);
|
|
2333
|
-
}
|
|
2334
|
-
visit(sf);
|
|
2335
|
-
return props.length > 0 ? props : null;
|
|
2336
|
-
}
|
|
2337
|
-
function validatePropsAgainstSchema(code, spec) {
|
|
2338
|
-
const issues = [];
|
|
2339
|
-
const extracted = extractPropsInterface(code);
|
|
2340
|
-
if (!extracted) {
|
|
2341
|
-
return [];
|
|
2342
|
-
}
|
|
2343
|
-
const extractedMap = new Map(extracted.map((p) => [p.name, p]));
|
|
2344
|
-
for (const [propName, entry] of Object.entries(spec.properties)) {
|
|
2345
|
-
const extractedProp = extractedMap.get(propName);
|
|
2346
|
-
if (!extractedProp) {
|
|
2347
|
-
if (entry.required) {
|
|
2348
|
-
issues.push({
|
|
2349
|
-
severity: "error",
|
|
2350
|
-
field: propName,
|
|
2351
|
-
message: `Props interface is missing required field '${propName}' from the data contract`,
|
|
2352
|
-
fix: `Add \`${propName}${entry.required ? "" : "?"}: ${jsonSchemaTypeToTs(entry.schema)}\` to your Props interface`
|
|
2353
|
-
});
|
|
2354
|
-
} else {
|
|
2355
|
-
issues.push({
|
|
2356
|
-
severity: "warning",
|
|
2357
|
-
field: propName,
|
|
2358
|
-
message: `Props interface is missing optional field '${propName}' from the data contract`,
|
|
2359
|
-
fix: `Consider adding \`${propName}?: ${jsonSchemaTypeToTs(entry.schema)}\` to your Props interface`
|
|
2360
|
-
});
|
|
2361
|
-
}
|
|
2362
|
-
continue;
|
|
2363
|
-
}
|
|
2364
|
-
if (extractedProp.type !== "unknown") {
|
|
2365
|
-
const expectedTsType = jsonSchemaTypeToTs(entry.schema);
|
|
2366
|
-
if (!isTypeCompatible(extractedProp.type, expectedTsType, entry.schema)) {
|
|
2367
|
-
issues.push({
|
|
2368
|
-
severity: "warning",
|
|
2369
|
-
field: propName,
|
|
2370
|
-
message: `Field '${propName}' has type '${extractedProp.type}' but contract expects '${expectedTsType}'`,
|
|
2371
|
-
fix: `Change \`${propName}\` type to \`${expectedTsType}\``
|
|
2372
|
-
});
|
|
2373
|
-
}
|
|
2374
|
-
}
|
|
2375
|
-
}
|
|
2376
|
-
return issues;
|
|
2377
|
-
}
|
|
2378
|
-
function isTypeCompatible(tsType, expectedTsType, schema) {
|
|
2379
|
-
const normalized = tsType.replace(/\s/g, "").toLowerCase();
|
|
2380
|
-
switch (schema.type) {
|
|
2381
|
-
case "string":
|
|
2382
|
-
return normalized.includes("string");
|
|
2383
|
-
case "number":
|
|
2384
|
-
case "integer":
|
|
2385
|
-
return normalized.includes("number");
|
|
2386
|
-
case "boolean":
|
|
2387
|
-
return normalized.includes("boolean");
|
|
2388
|
-
case "array":
|
|
2389
|
-
return normalized.includes("[]") || normalized.includes("array");
|
|
2390
|
-
case "object":
|
|
2391
|
-
return !["string", "number", "boolean"].some((t) => normalized === t);
|
|
2392
|
-
default:
|
|
2393
|
-
return true;
|
|
2394
|
-
}
|
|
2395
|
-
}
|
|
2396
|
-
function validateStreamSpecConformance(code, spec) {
|
|
2397
|
-
const issues = [];
|
|
2398
|
-
const usesWireStream = code.includes("useStream");
|
|
2399
|
-
if (!usesWireStream) {
|
|
2400
|
-
issues.push({
|
|
2401
|
-
severity: "error",
|
|
2402
|
-
field: "__streamSpec__",
|
|
2403
|
-
message: "Component does not handle stream events \u2014 use useStream() from the boilerplate wire hooks",
|
|
2404
|
-
fix: "Use the useStream('eventName') hook from the boilerplate to receive real-time data from the agent"
|
|
2405
|
-
});
|
|
2406
|
-
return issues;
|
|
2407
|
-
}
|
|
2408
|
-
for (const [channelName, entry] of Object.entries(spec)) {
|
|
2409
|
-
if (!code.includes(`'${channelName}'`) && !code.includes(`"${channelName}"`)) {
|
|
2410
|
-
issues.push({
|
|
2411
|
-
severity: "warning",
|
|
2412
|
-
field: channelName,
|
|
2413
|
-
message: `StreamSpec declares channel '${channelName}' but component doesn't reference it`,
|
|
2414
|
-
fix: `Add useStream('${channelName}') to receive ${entry.description || channelName} events`
|
|
2415
|
-
});
|
|
2416
|
-
}
|
|
2417
|
-
}
|
|
2418
|
-
return issues;
|
|
2419
|
-
}
|
|
2420
|
-
function validateActionSpecConformance(code, spec) {
|
|
2421
|
-
const issues = [];
|
|
2422
|
-
for (const [actionId, entry] of Object.entries(spec)) {
|
|
2423
|
-
const idReferenced = code.includes(`'${actionId}'`) || code.includes(`"${actionId}"`);
|
|
2424
|
-
const labelReferenced = code.includes(entry.label);
|
|
2425
|
-
const callbackName = `on${actionId.charAt(0).toUpperCase()}${actionId.slice(1)}`;
|
|
2426
|
-
const callbackReferenced = code.includes(callbackName);
|
|
2427
|
-
if (!idReferenced && !labelReferenced && !callbackReferenced) {
|
|
2428
|
-
issues.push({
|
|
2429
|
-
severity: "error",
|
|
2430
|
-
field: actionId,
|
|
2431
|
-
message: `ActionSpec declares action '${actionId}' ("${entry.label}") but component doesn't wire it`,
|
|
2432
|
-
fix: `Use the useAction('${actionId}') hook from the boilerplate and wire it to a button or form submit`
|
|
2433
|
-
});
|
|
2434
|
-
}
|
|
2435
|
-
}
|
|
2436
|
-
return issues;
|
|
2437
|
-
}
|
|
2438
|
-
function validateAllContracts(code, contract) {
|
|
2439
|
-
const issues = [];
|
|
2440
|
-
if (contract.propsSpec) {
|
|
2441
|
-
issues.push(...validatePropsAgainstSchema(code, contract.propsSpec));
|
|
2442
|
-
}
|
|
2443
|
-
if (contract.streamSpec) {
|
|
2444
|
-
issues.push(...validateStreamSpecConformance(code, contract.streamSpec));
|
|
2445
|
-
}
|
|
2446
|
-
if (contract.actionSpec) {
|
|
2447
|
-
issues.push(...validateActionSpecConformance(code, contract.actionSpec));
|
|
2448
|
-
}
|
|
2449
|
-
return issues;
|
|
2450
|
-
}
|
|
2451
|
-
var BLOCKING_CODES = /* @__PURE__ */ new Set([
|
|
2452
|
-
2304,
|
|
2453
|
-
// Cannot find name
|
|
2454
|
-
// 2307 (Cannot find module) is NOT blocking — Lambda bundles code without
|
|
2455
|
-
// type declarations, so the VFS can't resolve react/@ggui-ai/design.
|
|
2456
|
-
// Forbidden imports are caught by runSelfChecks regex instead.
|
|
2457
|
-
2305,
|
|
2458
|
-
// Module has no exported member
|
|
2459
|
-
2322,
|
|
2460
|
-
// Type not assignable
|
|
2461
|
-
2339,
|
|
2462
|
-
// Property does not exist on type
|
|
2463
|
-
2741,
|
|
2464
|
-
// Missing required property
|
|
2465
|
-
2769,
|
|
2466
|
-
// No overload matches this call
|
|
2467
|
-
17004,
|
|
2468
|
-
// Cannot use JSX unless '--jsx' flag
|
|
2469
|
-
18047,
|
|
2470
|
-
// 'X' is possibly 'null' — causes runtime crash
|
|
2471
|
-
18048
|
|
2472
|
-
// 'X' is possibly 'undefined' — causes runtime crash
|
|
2473
|
-
]);
|
|
2474
|
-
function generateFix(code, message, sourceLine) {
|
|
2475
|
-
const sourceHint = sourceLine && sourceLine.length > 0 && sourceLine.length <= 140 ? ` Offending line: \`${sourceLine}\`` : "";
|
|
2476
|
-
if ((code === 2322 || code === 2339) && message && /onClick|onDoubleClick|onMouseEnter|onMouseLeave|onPress/.test(message)) {
|
|
2477
|
-
return `This structural primitive has no event handlers of its own \u2014 add the trait as a PROP: as={Clickable} (then onClick works), imported from @ggui-ai/design. Do NOT wrap it in <Clickable>\u2026</Clickable>; as is a prop, not a wrapper element.${sourceHint}`;
|
|
2478
|
-
}
|
|
2479
|
-
if (code === 2339 && message && /Property '_[a-zA-Z]/.test(message)) {
|
|
2480
|
-
return `You renamed a prop with a leading underscore to silence \`no-unused-vars\`, but the prop on \`Props\` doesn't have that prefix. Restore the original name; better, don't destructure props you won't render \u2014 access them via \`props.fieldName\` only when needed.${sourceHint}`;
|
|
2481
|
-
}
|
|
2482
|
-
if (code === 2304 && message && !message.includes("module") && !message.includes("import")) {
|
|
2483
|
-
return `This name is not defined in scope. Either you destructured props (use \`props.fieldName\` directly instead) OR you removed a helper declaration in this patch but kept a JSX/expression reference to it. Read your full patch and either restore the declaration or remove the reference.${sourceHint}`;
|
|
2484
|
-
}
|
|
2485
|
-
if ((code === 2322 || code === 2769) && message && /unknown.*ReactNode|ReactNode.*unknown/.test(message)) {
|
|
2486
|
-
return `This value has type 'unknown' and cannot be rendered in JSX. Cast it: String(value) or add a type annotation.${sourceHint}`;
|
|
2487
|
-
}
|
|
2488
|
-
switch (code) {
|
|
2489
|
-
case 2307:
|
|
2490
|
-
return `Only these imports are allowed: ${describeAllowedImports()}${sourceHint}`;
|
|
2491
|
-
case 2322:
|
|
2492
|
-
case 2769:
|
|
2493
|
-
return `Type mismatch on this expression. Check the offending line below \u2014 the prop name in JSX is what TypeScript is rejecting; the message tells you the expected type.${sourceHint}`;
|
|
2494
|
-
case 2339:
|
|
2495
|
-
return `This prop doesn't exist on this component \u2014 check the available props on the component's interface (visible at the top of the file, or in the design-system reference).${sourceHint}`;
|
|
2496
|
-
case 2305:
|
|
2497
|
-
return `This name is not defined. Check your imports and variable declarations.${sourceHint}`;
|
|
2498
|
-
case 2741:
|
|
2499
|
-
return `A required prop is missing. Check the component's Props interface.${sourceHint}`;
|
|
2500
|
-
case 18047:
|
|
2501
|
-
case 18048:
|
|
2502
|
-
return `This value might be null/undefined. Every dereference on the same nullable still needs \`?.\` \u2014 \`x?.foo && x?.bar\`, NOT \`x?.foo && x.bar\`. Or hoist: \`const v = x; if (!v) return null;\` then access \`v.foo\`/\`v.bar\` unguarded.${sourceHint}`;
|
|
2503
|
-
default:
|
|
2504
|
-
return `Review the TypeScript error and fix the type issue.${sourceHint}`;
|
|
2505
|
-
}
|
|
2506
|
-
}
|
|
2507
|
-
var vfsCache = null;
|
|
2508
|
-
function parseAndStore(vfs, virtualPath, content) {
|
|
2509
|
-
const sourceFile = ts3.createSourceFile(
|
|
2510
|
-
virtualPath,
|
|
2511
|
-
content,
|
|
2512
|
-
ts3.ScriptTarget.ES2020,
|
|
2513
|
-
true,
|
|
2514
|
-
virtualPath.endsWith(".tsx") ? ts3.ScriptKind.TSX : ts3.ScriptKind.TS
|
|
2515
|
-
);
|
|
2516
|
-
vfs.set(virtualPath, { content, sourceFile });
|
|
2517
|
-
}
|
|
2518
|
-
function walkDir(dir, filter) {
|
|
2519
|
-
const results = [];
|
|
2520
|
-
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
2521
|
-
const full = path.join(dir, entry.name);
|
|
2522
|
-
if (entry.isDirectory()) {
|
|
2523
|
-
results.push(...walkDir(full, filter));
|
|
2524
|
-
} else if (filter(full)) {
|
|
2525
|
-
results.push(full);
|
|
2526
|
-
}
|
|
2527
|
-
}
|
|
2528
|
-
return results;
|
|
2529
|
-
}
|
|
2530
|
-
function findReactTypesDir() {
|
|
2531
|
-
try {
|
|
2532
|
-
const indexDts = createRequire(import.meta.url).resolve("@types/react/index.d.ts");
|
|
2533
|
-
return path.dirname(indexDts);
|
|
2534
|
-
} catch {
|
|
2535
|
-
return null;
|
|
2536
|
-
}
|
|
2537
|
-
}
|
|
2538
|
-
function findPackageDistDir(pkg) {
|
|
2539
|
-
try {
|
|
2540
|
-
const pkgJson = createRequire(import.meta.url).resolve(`${pkg}/package.json`);
|
|
2541
|
-
const dist = path.join(path.dirname(pkgJson), "dist");
|
|
2542
|
-
return fs.existsSync(dist) ? dist : null;
|
|
2543
|
-
} catch {
|
|
2544
|
-
return null;
|
|
2545
|
-
}
|
|
2546
|
-
}
|
|
2547
|
-
async function loadVfs() {
|
|
2548
|
-
if (vfsCache) return vfsCache;
|
|
2549
|
-
const vfs = /* @__PURE__ */ new Map();
|
|
2550
|
-
const require_ = createRequire(import.meta.url);
|
|
2551
|
-
const tsDir = path.dirname(require_.resolve("typescript/lib/typescript.js"));
|
|
2552
|
-
const libFiles = fs.readdirSync(tsDir).filter((f) => /^lib\..*\.d\.ts$/.test(f));
|
|
2553
|
-
for (const file of libFiles) {
|
|
2554
|
-
const content = fs.readFileSync(path.join(tsDir, file), "utf-8");
|
|
2555
|
-
parseAndStore(vfs, file, content);
|
|
2556
|
-
}
|
|
2557
|
-
const reactDir = findReactTypesDir();
|
|
2558
|
-
if (reactDir) {
|
|
2559
|
-
const reactDts = fs.readdirSync(reactDir).filter((f) => f.endsWith(".d.ts"));
|
|
2560
|
-
for (const file of reactDts) {
|
|
2561
|
-
const content = fs.readFileSync(path.join(reactDir, file), "utf-8");
|
|
2562
|
-
parseAndStore(vfs, `node_modules/@types/react/${file}`, content);
|
|
2563
|
-
}
|
|
2564
|
-
}
|
|
2565
|
-
const designDist = findPackageDistDir("@ggui-ai/design");
|
|
2566
|
-
if (designDist) {
|
|
2567
|
-
const dtsFiles = walkDir(designDist, (f) => f.endsWith(".d.ts") && !f.endsWith(".d.ts.map"));
|
|
2568
|
-
for (const file of dtsFiles) {
|
|
2569
|
-
const rel = path.relative(designDist, file);
|
|
2570
|
-
const content = fs.readFileSync(file, "utf-8");
|
|
2571
|
-
parseAndStore(vfs, `node_modules/@ggui-ai/design/${rel}`, content);
|
|
2572
|
-
}
|
|
2573
|
-
}
|
|
2574
|
-
const wireDist = findPackageDistDir("@ggui-ai/wire");
|
|
2575
|
-
if (wireDist) {
|
|
2576
|
-
const dtsFiles = walkDir(wireDist, (f) => f.endsWith(".d.ts") && !f.endsWith(".d.ts.map"));
|
|
2577
|
-
for (const file of dtsFiles) {
|
|
2578
|
-
const rel = path.relative(wireDist, file);
|
|
2579
|
-
const content = fs.readFileSync(file, "utf-8");
|
|
2580
|
-
parseAndStore(vfs, `node_modules/@ggui-ai/wire/${rel}`, content);
|
|
2581
|
-
}
|
|
2582
|
-
}
|
|
2583
|
-
const clientLibsDist = findPackageDistDir("@ggui-ai/gadgets");
|
|
2584
|
-
if (clientLibsDist) {
|
|
2585
|
-
const dtsFiles = walkDir(
|
|
2586
|
-
clientLibsDist,
|
|
2587
|
-
(f) => f.endsWith(".d.ts") && !f.endsWith(".d.ts.map")
|
|
2588
|
-
);
|
|
2589
|
-
for (const file of dtsFiles) {
|
|
2590
|
-
const rel = path.relative(clientLibsDist, file);
|
|
2591
|
-
const content = fs.readFileSync(file, "utf-8");
|
|
2592
|
-
parseAndStore(vfs, `node_modules/@ggui-ai/gadgets/${rel}`, content);
|
|
2593
|
-
}
|
|
2594
|
-
}
|
|
2595
|
-
vfsCache = vfs;
|
|
2596
|
-
return vfs;
|
|
2597
|
-
}
|
|
2598
|
-
function resolveRelativeInVfs(vfs, containingFile, importPath) {
|
|
2599
|
-
const normalized = containingFile.startsWith("/") ? containingFile.slice(1) : containingFile;
|
|
2600
|
-
const dir = path.posix.dirname(normalized);
|
|
2601
|
-
const specifier = importPath.replace(/\.(?:m|c)?js$/, "");
|
|
2602
|
-
const resolved2 = path.posix.normalize(`${dir}/${specifier}`);
|
|
2603
|
-
const withDts = `${resolved2}.d.ts`;
|
|
2604
|
-
if (vfs.has(withDts)) return withDts;
|
|
2605
|
-
const withIndexDts = `${resolved2}/index.d.ts`;
|
|
2606
|
-
if (vfs.has(withIndexDts)) return withIndexDts;
|
|
2607
|
-
const withTs = `${resolved2}.ts`;
|
|
2608
|
-
if (vfs.has(withTs)) return withTs;
|
|
2609
|
-
if (vfs.has(resolved2)) return resolved2;
|
|
2610
|
-
return void 0;
|
|
2611
|
-
}
|
|
2612
|
-
var COMPILER_OPTIONS = {
|
|
2613
|
-
target: ts3.ScriptTarget.ES2020,
|
|
2614
|
-
module: ts3.ModuleKind.ESNext,
|
|
2615
|
-
// Classic React JSX mode. The synthetic prefix (SYNTHETIC_PREFIX)
|
|
2616
|
-
// supplies `import React from 'react'` plus a `declare global` JSX
|
|
2617
|
-
// namespace shim: `@types/react` v19 removed the *global* `JSX`
|
|
2618
|
-
// namespace (it lives at `React.JSX` now), which classic mode needs
|
|
2619
|
-
// for `JSX.IntrinsicElements` and the `key`/`ref` carve-out. Without
|
|
2620
|
-
// the shim, `<div>` degrades to `any` and every typed component
|
|
2621
|
-
// falsely rejects the intrinsic `key` prop.
|
|
2622
|
-
jsx: ts3.JsxEmit.React,
|
|
2623
|
-
moduleResolution: ts3.ModuleResolutionKind.Bundler,
|
|
2624
|
-
strict: false,
|
|
2625
|
-
strictNullChecks: true,
|
|
2626
|
-
// Catch undefined.foo() errors that cause runtime crashes
|
|
2627
|
-
noEmit: true,
|
|
2628
|
-
skipLibCheck: true,
|
|
2629
|
-
noImplicitAny: true,
|
|
2630
|
-
types: [],
|
|
2631
|
-
esModuleInterop: true
|
|
2632
|
-
};
|
|
2633
|
-
function normalizeVfsPath(f) {
|
|
2634
|
-
if (f.startsWith("/")) {
|
|
2635
|
-
return f.slice(1);
|
|
2636
|
-
}
|
|
2637
|
-
return null;
|
|
2638
|
-
}
|
|
2639
|
-
function resolveModuleName(vfs, name, containingFile) {
|
|
2640
|
-
if (name === "react") {
|
|
2641
|
-
return resolved("node_modules/@types/react/index.d.ts");
|
|
2642
|
-
}
|
|
2643
|
-
if (name === "react/jsx-runtime") {
|
|
2644
|
-
return resolved("node_modules/@types/react/jsx-runtime.d.ts");
|
|
2645
|
-
}
|
|
2646
|
-
if (name === "react/jsx-dev-runtime") {
|
|
2647
|
-
const p = "node_modules/@types/react/jsx-dev-runtime.d.ts";
|
|
2648
|
-
if (vfs.has(p)) return resolved(p);
|
|
2649
|
-
return resolved("node_modules/@types/react/jsx-runtime.d.ts");
|
|
2650
|
-
}
|
|
2651
|
-
const designPrefix = "@ggui-ai/design/";
|
|
2652
|
-
if (name.startsWith(designPrefix)) {
|
|
2653
|
-
const subpath = name.slice(designPrefix.length);
|
|
2654
|
-
const indexPath = `node_modules/@ggui-ai/design/${subpath}/index.d.ts`;
|
|
2655
|
-
if (vfs.has(indexPath)) return resolved(indexPath);
|
|
2656
|
-
const directPath = `node_modules/@ggui-ai/design/${subpath}.d.ts`;
|
|
2657
|
-
if (vfs.has(directPath)) return resolved(directPath);
|
|
2658
|
-
}
|
|
2659
|
-
if (name === "@ggui-ai/design") {
|
|
2660
|
-
return resolved("node_modules/@ggui-ai/design/index.d.ts");
|
|
2661
|
-
}
|
|
2662
|
-
if (name === "@ggui-ai/wire") {
|
|
2663
|
-
return resolved("node_modules/@ggui-ai/wire/index.d.ts");
|
|
2664
|
-
}
|
|
2665
|
-
if (name === "@ggui-ai/gadgets") {
|
|
2666
|
-
return resolved("node_modules/@ggui-ai/gadgets/index.d.ts");
|
|
2667
|
-
}
|
|
2668
|
-
if (name.startsWith("./") || name.startsWith("../")) {
|
|
2669
|
-
const resolvedPath = resolveRelativeInVfs(vfs, containingFile, name);
|
|
2670
|
-
if (resolvedPath) return resolved(resolvedPath);
|
|
2671
|
-
}
|
|
2672
|
-
const bareIndex = `node_modules/${name}/index.d.ts`;
|
|
2673
|
-
if (vfs.has(bareIndex)) return resolved(bareIndex);
|
|
2674
|
-
return { resolvedModule: void 0 };
|
|
2675
|
-
}
|
|
2676
|
-
function createVfsHost(vfs, componentCode) {
|
|
2677
|
-
const componentFile = ts3.createSourceFile(
|
|
2678
|
-
"Component.tsx",
|
|
2679
|
-
componentCode,
|
|
2680
|
-
ts3.ScriptTarget.ES2020,
|
|
2681
|
-
true,
|
|
2682
|
-
ts3.ScriptKind.TSX
|
|
2683
|
-
);
|
|
2684
|
-
const host = {
|
|
2685
|
-
getSourceFile(fileName) {
|
|
2686
|
-
if (fileName === "Component.tsx") return componentFile;
|
|
2687
|
-
const entry = vfs.get(fileName);
|
|
2688
|
-
if (entry) return entry.sourceFile;
|
|
2689
|
-
const normalized = normalizeVfsPath(fileName);
|
|
2690
|
-
if (normalized) return vfs.get(normalized)?.sourceFile;
|
|
2691
|
-
return void 0;
|
|
2692
|
-
},
|
|
2693
|
-
getDefaultLibFileName() {
|
|
2694
|
-
return "lib.es2020.full.d.ts";
|
|
2695
|
-
},
|
|
2696
|
-
writeFile() {
|
|
2697
|
-
},
|
|
2698
|
-
getCurrentDirectory() {
|
|
2699
|
-
return "/";
|
|
2700
|
-
},
|
|
2701
|
-
getCanonicalFileName(f) {
|
|
2702
|
-
return f;
|
|
2703
|
-
},
|
|
2704
|
-
useCaseSensitiveFileNames() {
|
|
2705
|
-
return true;
|
|
2706
|
-
},
|
|
2707
|
-
getNewLine() {
|
|
2708
|
-
return "\n";
|
|
2709
|
-
},
|
|
2710
|
-
fileExists(f) {
|
|
2711
|
-
if (f === "Component.tsx" || vfs.has(f)) return true;
|
|
2712
|
-
const normalized = normalizeVfsPath(f);
|
|
2713
|
-
if (normalized && vfs.has(normalized)) return true;
|
|
2714
|
-
return false;
|
|
2715
|
-
},
|
|
2716
|
-
readFile(f) {
|
|
2717
|
-
if (f === "Component.tsx") return componentCode;
|
|
2718
|
-
const direct = vfs.get(f);
|
|
2719
|
-
if (direct) return direct.content;
|
|
2720
|
-
const normalized = normalizeVfsPath(f);
|
|
2721
|
-
if (normalized) return vfs.get(normalized)?.content;
|
|
2722
|
-
return void 0;
|
|
2723
|
-
},
|
|
2724
|
-
resolveModuleNameLiterals(moduleLiterals, containingFile) {
|
|
2725
|
-
return moduleLiterals.map(
|
|
2726
|
-
(literal) => resolveModuleName(vfs, literal.text, containingFile)
|
|
2727
|
-
);
|
|
2728
|
-
}
|
|
2729
|
-
};
|
|
2730
|
-
return host;
|
|
2731
|
-
}
|
|
2732
|
-
function resolved(resolvedFileName) {
|
|
2733
|
-
return {
|
|
2734
|
-
resolvedModule: {
|
|
2735
|
-
resolvedFileName,
|
|
2736
|
-
isExternalLibraryImport: true,
|
|
2737
|
-
extension: ts3.Extension.Dts
|
|
2738
|
-
}
|
|
2739
|
-
};
|
|
2740
|
-
}
|
|
2741
|
-
async function typecheck(code, dtsMap) {
|
|
2742
|
-
const vfs = await loadVfs();
|
|
2743
|
-
const effectiveVfs = (() => {
|
|
2744
|
-
const dtsEntries = [];
|
|
2745
|
-
if (dtsEntries.length === 0) {
|
|
2746
|
-
return vfs;
|
|
2747
|
-
}
|
|
2748
|
-
const overlay = new Map(vfs);
|
|
2749
|
-
for (const [pkg, content] of dtsEntries) {
|
|
2750
|
-
parseAndStore(overlay, `node_modules/${pkg}/index.d.ts`, content);
|
|
2751
|
-
}
|
|
2752
|
-
return overlay;
|
|
2753
|
-
})();
|
|
2754
|
-
const globalJsxShim = "declare global { namespace JSX { type ElementType = string | ((props: any) => any) | (new (props: any) => any); interface Element { type: any; props: any; key: string | number | null; } interface ElementClass { render(): any; } interface ElementAttributesProperty { props: object; } interface ElementChildrenAttribute { children: object; } interface IntrinsicAttributes { key?: string | number | bigint | null; } interface IntrinsicClassAttributes<T> { ref?: any; } interface IntrinsicElements { [elem: string]: any; } } }\n";
|
|
2755
|
-
const SYNTHETIC_PREFIX = "import React from 'react';\n" + globalJsxShim;
|
|
2756
|
-
const prefixedCode = SYNTHETIC_PREFIX + code;
|
|
2757
|
-
const lineOffset = SYNTHETIC_PREFIX.split("\n").length - 1;
|
|
2758
|
-
const host = createVfsHost(effectiveVfs, prefixedCode);
|
|
2759
|
-
const program = ts3.createProgram(["Component.tsx"], COMPILER_OPTIONS, host);
|
|
2760
|
-
const diagnostics = ts3.getPreEmitDiagnostics(program);
|
|
2761
|
-
const errors = [];
|
|
2762
|
-
const warnings = [];
|
|
2763
|
-
for (const diag of diagnostics) {
|
|
2764
|
-
if (diag.file && diag.file.fileName !== "Component.tsx") continue;
|
|
2765
|
-
if (!diag.file) continue;
|
|
2766
|
-
const diagLine = ts3.getLineAndCharacterOfPosition(diag.file, diag.start ?? 0).line;
|
|
2767
|
-
if (diagLine < lineOffset) continue;
|
|
2768
|
-
const rawLine = diag.file ? ts3.getLineAndCharacterOfPosition(diag.file, diag.start ?? 0).line + 1 : 0;
|
|
2769
|
-
const line = Math.max(1, rawLine - lineOffset);
|
|
2770
|
-
const message = ts3.flattenDiagnosticMessageText(diag.messageText, "\n");
|
|
2771
|
-
const code_ = diag.code;
|
|
2772
|
-
const sourceLines = diag.file.text.split("\n");
|
|
2773
|
-
const sourceLine = rawLine >= 1 && rawLine <= sourceLines.length ? sourceLines[rawLine - 1]?.trim() ?? "" : "";
|
|
2774
|
-
const entry = {
|
|
2775
|
-
code: code_,
|
|
2776
|
-
line,
|
|
2777
|
-
message,
|
|
2778
|
-
fix: generateFix(code_, message, sourceLine)
|
|
2779
|
-
};
|
|
2780
|
-
if (BLOCKING_CODES.has(code_)) {
|
|
2781
|
-
errors.push(entry);
|
|
2782
|
-
} else {
|
|
2783
|
-
warnings.push(entry);
|
|
2784
|
-
}
|
|
2785
|
-
}
|
|
2786
|
-
return { errors, warnings };
|
|
2787
|
-
}
|
|
2788
|
-
var linterInstance = null;
|
|
2789
|
-
async function getLinter() {
|
|
2790
|
-
if (!linterInstance) {
|
|
2791
|
-
linterInstance = new Linter();
|
|
2792
|
-
const tsParser = await import('@typescript-eslint/parser');
|
|
2793
|
-
linterInstance.defineParser("@typescript-eslint/parser", tsParser);
|
|
2794
|
-
const reactHooksPlugin = await import('eslint-plugin-react-hooks');
|
|
2795
|
-
const hooksRules = reactHooksPlugin.default?.rules ?? reactHooksPlugin.rules;
|
|
2796
|
-
for (const [name, rule] of Object.entries(hooksRules)) {
|
|
2797
|
-
linterInstance.defineRule(`react-hooks/${name}`, rule);
|
|
2798
|
-
}
|
|
2799
|
-
const reactPlugin = await import('eslint-plugin-react');
|
|
2800
|
-
const reactRules = reactPlugin.default?.rules ?? reactPlugin.rules;
|
|
2801
|
-
for (const [name, rule] of Object.entries(reactRules)) {
|
|
2802
|
-
linterInstance.defineRule(`react/${name}`, rule);
|
|
2803
|
-
}
|
|
2804
|
-
}
|
|
2805
|
-
return linterInstance;
|
|
2806
|
-
}
|
|
2807
|
-
async function lintReactHooks(code) {
|
|
2808
|
-
const linter = await getLinter();
|
|
2809
|
-
let messages;
|
|
2810
|
-
try {
|
|
2811
|
-
const config = {
|
|
2812
|
-
parser: "@typescript-eslint/parser",
|
|
2813
|
-
parserOptions: {
|
|
2814
|
-
ecmaVersion: 2022,
|
|
2815
|
-
sourceType: "module",
|
|
2816
|
-
ecmaFeatures: { jsx: true }
|
|
2817
|
-
},
|
|
2818
|
-
rules: {
|
|
2819
|
-
"react-hooks/rules-of-hooks": 2,
|
|
2820
|
-
"react-hooks/exhaustive-deps": 1,
|
|
2821
|
-
// React rules
|
|
2822
|
-
"react/jsx-no-undef": 2,
|
|
2823
|
-
// undefined JSX components
|
|
2824
|
-
"react/jsx-key": 1,
|
|
2825
|
-
// missing key in lists
|
|
2826
|
-
"react/no-direct-mutation-state": 2,
|
|
2827
|
-
// direct state mutation
|
|
2828
|
-
// An unused `const submit = useAction('submit')` is a
|
|
2829
|
-
// dead contract wire. Narrow the rule to variable bindings we
|
|
2830
|
-
// care about: skip function args (LLMs legitimately omit unused
|
|
2831
|
-
// params), skip destructured `rest` collectors, respect a `_`-
|
|
2832
|
-
// prefix escape hatch for intentionally-ignored declarations,
|
|
2833
|
-
// and silence the caught-error slot (async error handling can
|
|
2834
|
-
// leave `catch (err)` unused at a boundary).
|
|
2835
|
-
"no-unused-vars": [2, {
|
|
2836
|
-
vars: "all",
|
|
2837
|
-
args: "none",
|
|
2838
|
-
ignoreRestSiblings: true,
|
|
2839
|
-
varsIgnorePattern: "^_",
|
|
2840
|
-
caughtErrors: "none"
|
|
2841
|
-
}]
|
|
2842
|
-
},
|
|
2843
|
-
settings: {
|
|
2844
|
-
react: { version: "19.0" }
|
|
2845
|
-
}
|
|
2846
|
-
};
|
|
2847
|
-
messages = linter.verify(code, config, { filename: "component.tsx" });
|
|
2848
|
-
} catch {
|
|
2849
|
-
return [];
|
|
2850
|
-
}
|
|
2851
|
-
const diagnostics = [];
|
|
2852
|
-
const ADMITTED_RULES = (id) => id.startsWith("react-hooks/") || id.startsWith("react/") || id === "no-unused-vars";
|
|
2853
|
-
for (const msg of messages) {
|
|
2854
|
-
if (!msg.ruleId) continue;
|
|
2855
|
-
if (!ADMITTED_RULES(msg.ruleId)) continue;
|
|
2856
|
-
diagnostics.push({
|
|
2857
|
-
rule: msg.ruleId,
|
|
2858
|
-
line: msg.line,
|
|
2859
|
-
message: msg.message,
|
|
2860
|
-
fix: generateReactFix(msg.ruleId, msg.message),
|
|
2861
|
-
severity: resolveSeverity(msg, code)
|
|
2862
|
-
});
|
|
2863
|
-
}
|
|
2864
|
-
return diagnostics;
|
|
2865
|
-
}
|
|
2866
|
-
function resolveSeverity(msg, code) {
|
|
2867
|
-
const base = msg.severity === 2 ? "error" : "warning";
|
|
2868
|
-
if (msg.ruleId !== "no-unused-vars" || base !== "error") return base;
|
|
2869
|
-
const name = msg.message.match(/'([^']+)'/)?.[1];
|
|
2870
|
-
if (name === void 0) return "warning";
|
|
2871
|
-
const safe = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2872
|
-
const directRe = new RegExp(
|
|
2873
|
-
`\\bconst\\s+${safe}\\s*=\\s*use(Action|Stream|GguiContext)\\s*[<(]`
|
|
2874
|
-
);
|
|
2875
|
-
const destructuredRe = new RegExp(
|
|
2876
|
-
`\\bconst\\s+\\[[^\\]]*\\b${safe}\\b[^\\]]*\\]\\s*=\\s*use(Action|Stream|GguiContext)\\s*[<(]`
|
|
2877
|
-
);
|
|
2878
|
-
return directRe.test(code) || destructuredRe.test(code) ? "error" : "warning";
|
|
2879
|
-
}
|
|
2880
|
-
function generateReactFix(ruleId, message) {
|
|
2881
|
-
if (ruleId === "react-hooks/rules-of-hooks") {
|
|
2882
|
-
if (message.includes("called conditionally")) {
|
|
2883
|
-
return "Move this hook to the top level of the component, before any early returns or conditionals. Hooks must run in the same order every render.";
|
|
2884
|
-
}
|
|
2885
|
-
return "Hooks can only be called at the top level of a React function component or custom hook. Move it out of any conditional, loop, nested function, or callback.";
|
|
2886
|
-
}
|
|
2887
|
-
if (ruleId === "react-hooks/exhaustive-deps") {
|
|
2888
|
-
return "Add the missing dependencies to the dependency array, or remove the array to run on every render.";
|
|
2889
|
-
}
|
|
2890
|
-
if (ruleId === "react/jsx-no-undef") {
|
|
2891
|
-
const match = message.match(/'(\w+)'/);
|
|
2892
|
-
const name = match?.[1] ?? "Component";
|
|
2893
|
-
return `'${name}' is not defined. Import it from the design system or define it in the file.`;
|
|
2894
|
-
}
|
|
2895
|
-
if (ruleId === "react/jsx-key") {
|
|
2896
|
-
return 'Add a unique "key" prop to each element rendered inside a .map() or iterator.';
|
|
2897
|
-
}
|
|
2898
|
-
if (ruleId === "react/no-direct-mutation-state") {
|
|
2899
|
-
return "Do not mutate state directly. Use setState or the setter from useState instead.";
|
|
2900
|
-
}
|
|
2901
|
-
if (ruleId === "no-unused-vars") {
|
|
2902
|
-
const match = message.match(/'([^']+)'/);
|
|
2903
|
-
const name = match?.[1] ?? "variable";
|
|
2904
|
-
const isLikelyWireBinding = /\bconst\s+[A-Za-z_$][\w$]*\s*=\s*use(Action|Stream)\s*\(/.test(message);
|
|
2905
|
-
if (isLikelyWireBinding || /^(submit|cancel|search|progress|snapshot)$/.test(name)) {
|
|
2906
|
-
return `'${name}' is declared but never used. If this binding came from a wire hook (useAction / useStream) or a clientCapabilities hook (useGeolocation / useCamera / etc. from @ggui-ai/gadgets), consume it somewhere in the component \u2014 render its value in JSX, bind it to a callback prop, or use it in an effect. A contract-declared hook without consumption is a dead wire.`;
|
|
2907
|
-
}
|
|
2908
|
-
return `'${name}' is declared but never used. Remove the declaration, or consume it somewhere in the component. Prefix with '_' (e.g. '_${name}') to mark it intentionally unused.`;
|
|
2909
|
-
}
|
|
2910
|
-
return "Fix the React violation.";
|
|
2911
|
-
}
|
|
2912
|
-
var NOT_YET_TAUGHT_TOKENS = /* @__PURE__ */ new Set([]);
|
|
2913
|
-
consumedTokenManifest.filter(
|
|
2914
|
-
(token) => !NOT_YET_TAUGHT_TOKENS.has(token)
|
|
2915
|
-
);
|
|
2916
|
-
|
|
2917
|
-
// src/check/run-tier0.ts
|
|
2918
|
-
new Set(consumedTokenManifest);
|
|
2919
|
-
|
|
2920
|
-
// src/check/sample-props.ts
|
|
2921
|
-
function generateSampleProps(spec) {
|
|
2922
|
-
const props = {};
|
|
2923
|
-
for (const [name, entry] of Object.entries(spec.properties)) {
|
|
2924
|
-
if (entry.example !== void 0) {
|
|
2925
|
-
props[name] = entry.example;
|
|
2926
|
-
continue;
|
|
2927
|
-
}
|
|
2928
|
-
if (entry.default !== void 0) {
|
|
2929
|
-
props[name] = entry.default;
|
|
2930
|
-
continue;
|
|
2931
|
-
}
|
|
2932
|
-
props[name] = synthesizeFromSchema(entry.schema);
|
|
2933
|
-
}
|
|
2934
|
-
return props;
|
|
2935
|
-
}
|
|
2936
|
-
function synthesizeFromSchema(schema) {
|
|
2937
|
-
const declared = Array.isArray(schema.type) ? schema.type.find((t) => t !== "null") : schema.type;
|
|
2938
|
-
switch (declared) {
|
|
2939
|
-
case "string":
|
|
2940
|
-
return "sample";
|
|
2941
|
-
case "number":
|
|
2942
|
-
case "integer":
|
|
2943
|
-
return 0;
|
|
2944
|
-
case "boolean":
|
|
2945
|
-
return false;
|
|
2946
|
-
case "null":
|
|
2947
|
-
return null;
|
|
2948
|
-
case "array": {
|
|
2949
|
-
if (schema.items) return [synthesizeFromSchema(schema.items) ?? null];
|
|
2950
|
-
return [];
|
|
2951
|
-
}
|
|
2952
|
-
case "object": {
|
|
2953
|
-
const obj = {};
|
|
2954
|
-
if (schema.properties) {
|
|
2955
|
-
for (const [k, v] of Object.entries(schema.properties)) {
|
|
2956
|
-
obj[k] = synthesizeFromSchema(v);
|
|
2957
|
-
}
|
|
2958
|
-
}
|
|
2959
|
-
return obj;
|
|
2960
|
-
}
|
|
2961
|
-
default:
|
|
2962
|
-
return void 0;
|
|
2963
|
-
}
|
|
2964
|
-
}
|
|
2965
|
-
|
|
2966
|
-
// src/internal/verdict-line.ts
|
|
2967
|
-
var VERDICT_PREFIX = "@@ggui-render-check-verdict@@";
|
|
2968
|
-
function parseVerdictLine(stdout) {
|
|
2969
|
-
const lines = stdout.split("\n");
|
|
2970
|
-
for (let i = lines.length - 1; i >= 0; i -= 1) {
|
|
2971
|
-
const line = lines[i];
|
|
2972
|
-
if (line.startsWith(`${VERDICT_PREFIX} `)) return JSON.parse(line.slice(VERDICT_PREFIX.length + 1));
|
|
2973
|
-
}
|
|
2974
|
-
return void 0;
|
|
2975
|
-
}
|
|
2976
|
-
|
|
2977
|
-
// src/tools/render-check.ts
|
|
2978
|
-
var RENDER_TIMEOUT_MS = 12e3;
|
|
2979
|
-
var RENDER_STDOUT_CAP = 512 * 1024;
|
|
2980
|
-
var RENDER_NODE_HEAP_MB = 256;
|
|
2981
|
-
function resolveWorkerSpawn() {
|
|
2982
|
-
const jsCandidates = [
|
|
2983
|
-
new URL("./render-check-worker.js", import.meta.url),
|
|
2984
|
-
new URL("../tools/render-check-worker.js", import.meta.url)
|
|
2985
|
-
];
|
|
2986
|
-
const tsCandidates = [
|
|
2987
|
-
new URL("./render-check-worker.ts", import.meta.url),
|
|
2988
|
-
new URL("../tools/render-check-worker.ts", import.meta.url)
|
|
2989
|
-
];
|
|
2990
|
-
for (const jsUrl of jsCandidates) {
|
|
2991
|
-
const jsPath = fileURLToPath(jsUrl);
|
|
2992
|
-
if (existsSync(jsPath)) {
|
|
2993
|
-
return { command: process.execPath, args: [jsPath] };
|
|
2994
|
-
}
|
|
2995
|
-
}
|
|
2996
|
-
for (const tsUrl of tsCandidates) {
|
|
2997
|
-
const tsPath = fileURLToPath(tsUrl);
|
|
2998
|
-
if (existsSync(tsPath)) {
|
|
2999
|
-
const require_ = createRequire(import.meta.url);
|
|
3000
|
-
const tsxLoader = pathToFileURL(require_.resolve("tsx")).href;
|
|
3001
|
-
return {
|
|
3002
|
-
command: process.execPath,
|
|
3003
|
-
args: ["--import", tsxLoader, tsPath]
|
|
3004
|
-
};
|
|
3005
|
-
}
|
|
3006
|
-
}
|
|
3007
|
-
const tried = [...jsCandidates, ...tsCandidates].map((u) => fileURLToPath(u)).join(", ");
|
|
3008
|
-
throw new Error(
|
|
3009
|
-
`render-check: worker not found at any of: ${tried}. Did \`pnpm build\` run?`
|
|
3010
|
-
);
|
|
3011
|
-
}
|
|
3012
|
-
async function tryRender(compiledCode, sourceCode, sampleProps) {
|
|
3013
|
-
const payload = JSON.stringify({ sourceCode, sampleProps });
|
|
3014
|
-
const spawn = resolveWorkerSpawn();
|
|
3015
|
-
const result = await runSandboxed({
|
|
3016
|
-
command: spawn.command,
|
|
3017
|
-
args: spawn.args,
|
|
3018
|
-
timeoutMs: RENDER_TIMEOUT_MS,
|
|
3019
|
-
maxStdoutBytes: RENDER_STDOUT_CAP,
|
|
3020
|
-
nodeHeapMb: RENDER_NODE_HEAP_MB,
|
|
3021
|
-
stdin: payload,
|
|
3022
|
-
// Forward only what the worker needs. NODE_ENV lets React pick
|
|
3023
|
-
// production vs development builds; everything else stays at the
|
|
3024
|
-
// sandbox's default allowlist (PATH/HOME/TMPDIR bootstrap).
|
|
3025
|
-
env: {
|
|
3026
|
-
NODE_ENV: process.env.NODE_ENV ?? "production"
|
|
3027
|
-
}
|
|
3028
|
-
});
|
|
3029
|
-
if (result.outcome === "timeout") {
|
|
3030
|
-
return `Render timeout: component did not finish within ${RENDER_TIMEOUT_MS}ms (likely infinite loop or runaway recursion).`;
|
|
3031
|
-
}
|
|
3032
|
-
if (result.outcome === "overflow-stdout" || result.outcome === "overflow-stderr") {
|
|
3033
|
-
return `Render error: worker produced excessive output (${result.outcome}). The component is likely in a pathological state.`;
|
|
3034
|
-
}
|
|
3035
|
-
if (result.outcome === "canceled") {
|
|
3036
|
-
return "Render error: smoke test was canceled before completing.";
|
|
3037
|
-
}
|
|
3038
|
-
if (result.outcome === "spawn-error") {
|
|
3039
|
-
return `Render error: failed to start worker \u2014 ${result.errorMessage}`;
|
|
3040
|
-
}
|
|
3041
|
-
if (result.outcome !== "exit") {
|
|
3042
|
-
return `Render error: unexpected sandbox outcome '${result.outcome}'.`;
|
|
3043
|
-
}
|
|
3044
|
-
if (result.exitCode !== 0) {
|
|
3045
|
-
const tail = result.stderr.trim() || result.stdout.trim();
|
|
3046
|
-
return `Render error: worker exited ${result.exitCode}${tail ? ` \u2014 ${tail}` : ""}`;
|
|
3047
|
-
}
|
|
3048
|
-
let verdict;
|
|
3049
|
-
try {
|
|
3050
|
-
verdict = parseVerdictLine(result.stdout);
|
|
3051
|
-
} catch (err) {
|
|
3052
|
-
return `Render error: malformed worker verdict \u2014 ${err instanceof Error ? err.message : String(err)}`;
|
|
3053
|
-
}
|
|
3054
|
-
if (verdict === void 0) {
|
|
3055
|
-
return "Render error: worker exited without producing a verdict.";
|
|
3056
|
-
}
|
|
3057
|
-
return verdict.ok ? null : verdict.error;
|
|
3058
|
-
}
|
|
3059
|
-
|
|
3060
|
-
// src/adapters/tools.ts
|
|
3061
|
-
function createGeneratorTools(context = {}) {
|
|
3062
|
-
const tools = [
|
|
3063
|
-
// --- get_primitives ---
|
|
3064
|
-
{
|
|
3065
|
-
name: "get_primitives",
|
|
3066
|
-
description: "Get the list of available ggui UI primitives (Container, Card, Stack, Button, Input, etc.) that can be used in components. Call this first to understand what components are available.",
|
|
3067
|
-
inputSchema: z.object({}),
|
|
3068
|
-
handler: async () => ({
|
|
3069
|
-
content: [{ type: "text", text: PRIMITIVES_DOCUMENTATION }]
|
|
3070
|
-
})
|
|
3071
|
-
},
|
|
3072
|
-
// --- get_design_system ---
|
|
3073
|
-
{
|
|
3074
|
-
name: "get_design_system",
|
|
3075
|
-
description: "Get the design system tokens and CSS variables for this app. Use these CSS variables (var(--ggui-*)) for colors, spacing, typography, etc.",
|
|
3076
|
-
inputSchema: z.object({}),
|
|
3077
|
-
handler: async () => ({
|
|
3078
|
-
content: [{
|
|
3079
|
-
type: "text",
|
|
3080
|
-
text: context.designContext ? `# App Theme Configuration
|
|
3081
|
-
|
|
3082
|
-
${context.designContext}
|
|
3083
|
-
|
|
3084
|
-
**IMPORTANT:** Always use CSS variables (var(--ggui-*)) for colors, spacing, etc.` : DEFAULT_DESIGN_SYSTEM_DOCS
|
|
3085
|
-
}]
|
|
3086
|
-
})
|
|
3087
|
-
},
|
|
3088
|
-
// --- get_app_components ---
|
|
3089
|
-
{
|
|
3090
|
-
name: "get_app_components",
|
|
3091
|
-
description: "Get predefined reusable components specific to this app. These can be imported and used in your generated component.",
|
|
3092
|
-
inputSchema: z.object({}),
|
|
3093
|
-
handler: async () => ({
|
|
3094
|
-
content: [{
|
|
3095
|
-
type: "text",
|
|
3096
|
-
text: context.componentContext || "No predefined components available for this app."
|
|
3097
|
-
}]
|
|
3098
|
-
})
|
|
3099
|
-
},
|
|
3100
|
-
// --- validate_component ---
|
|
3101
|
-
{
|
|
3102
|
-
name: "validate_component",
|
|
3103
|
-
description: "Validate component code before compilation. Checks for security issues, syntax errors, and best practices. Returns detailed feedback.",
|
|
3104
|
-
inputSchema: z.object({
|
|
3105
|
-
code: z.string().describe("The TypeScript/TSX component code to validate")
|
|
3106
|
-
}),
|
|
3107
|
-
handler: async (args) => {
|
|
3108
|
-
const result = validateComponentDetailed(args.code);
|
|
3109
|
-
return {
|
|
3110
|
-
content: [
|
|
3111
|
-
{
|
|
3112
|
-
type: "text",
|
|
3113
|
-
text: formatValidationResultForClaude(result)
|
|
3114
|
-
}
|
|
3115
|
-
],
|
|
3116
|
-
isError: !result.valid
|
|
3117
|
-
};
|
|
3118
|
-
}
|
|
3119
|
-
},
|
|
3120
|
-
// --- self_check ---
|
|
3121
|
-
{
|
|
3122
|
-
name: "self_check",
|
|
3123
|
-
description: "Run deterministic quality checks on your code BEFORE compiling. Catches common issues instantly (zero cost). Returns pass/fail per check with line numbers and fix instructions. Call this after writing code, fix any failures, then compile.",
|
|
3124
|
-
inputSchema: z.object({
|
|
3125
|
-
code: z.string().describe("The TypeScript/TSX component code to check")
|
|
3126
|
-
}),
|
|
3127
|
-
handler: async (args) => {
|
|
3128
|
-
const code = args.code;
|
|
3129
|
-
const { issues, typeWarnings } = await runSelfChecks(code, context.contract);
|
|
3130
|
-
if (context.contract) {
|
|
3131
|
-
const contractIssues = validateAllContracts(code, context.contract);
|
|
3132
|
-
for (const ci of contractIssues) {
|
|
3133
|
-
issues.push({
|
|
3134
|
-
check: `contract:${ci.field}`,
|
|
3135
|
-
line: 0,
|
|
3136
|
-
message: `[${ci.severity}] ${ci.message}`,
|
|
3137
|
-
fix: ci.fix
|
|
3138
|
-
});
|
|
3139
|
-
}
|
|
3140
|
-
}
|
|
3141
|
-
if (issues.length === 0) {
|
|
3142
|
-
const warningText = typeWarnings.length > 0 ? `
|
|
3143
|
-
|
|
3144
|
-
Type warnings (non-blocking):
|
|
3145
|
-
${typeWarnings.map((w) => `[${w.check}] ${w.line ? `Line ${w.line}: ` : ""}${w.message}`).join("\n")}` : "";
|
|
3146
|
-
return {
|
|
3147
|
-
content: [{ type: "text", text: `All checks passed. Ready to compile.${warningText}` }]
|
|
3148
|
-
};
|
|
3149
|
-
}
|
|
3150
|
-
const report = issues.map((i) => `[${i.check}] ${i.line ? `Line ${i.line}: ` : ""}${i.message}
|
|
3151
|
-
Fix: ${i.fix}`).join("\n\n");
|
|
3152
|
-
return {
|
|
3153
|
-
content: [{ type: "text", text: `${issues.length} issue(s) found:
|
|
3154
|
-
|
|
3155
|
-
${report}` }],
|
|
3156
|
-
isError: true
|
|
3157
|
-
};
|
|
3158
|
-
}
|
|
3159
|
-
},
|
|
3160
|
-
// --- compile_component ---
|
|
3161
|
-
{
|
|
3162
|
-
name: "compile_component",
|
|
3163
|
-
description: "Compile a TypeScript/TSX component to JavaScript using esbuild. Returns the compiled code ready for browser execution. On failure, returns detailed error context with line numbers and fix suggestions.",
|
|
3164
|
-
inputSchema: z.object({
|
|
3165
|
-
code: z.string().describe("The TypeScript/TSX component code to compile"),
|
|
3166
|
-
filename: z.string().default("Component.tsx").describe("Filename for error messages")
|
|
3167
|
-
}),
|
|
3168
|
-
handler: async (args) => {
|
|
3169
|
-
const code = args.code;
|
|
3170
|
-
const filename = args.filename || "Component.tsx";
|
|
3171
|
-
const { issues: selfCheckIssues } = await runSelfChecks(code, context.contract);
|
|
3172
|
-
if (context.contract) {
|
|
3173
|
-
const contractIssues = validateAllContracts(code, context.contract);
|
|
3174
|
-
for (const ci of contractIssues) {
|
|
3175
|
-
selfCheckIssues.push({
|
|
3176
|
-
check: `contract:${ci.field}`,
|
|
3177
|
-
line: 0,
|
|
3178
|
-
message: `[${ci.severity}] ${ci.message}`,
|
|
3179
|
-
fix: ci.fix
|
|
3180
|
-
});
|
|
3181
|
-
}
|
|
3182
|
-
}
|
|
3183
|
-
if (selfCheckIssues.length > 0) {
|
|
3184
|
-
const report = selfCheckIssues.map((i) => `[${i.check}] ${i.line ? `Line ${i.line}: ` : ""}${i.message}
|
|
3185
|
-
Fix: ${i.fix}`).join("\n\n");
|
|
3186
|
-
return {
|
|
3187
|
-
content: [{
|
|
3188
|
-
type: "text",
|
|
3189
|
-
text: JSON.stringify({
|
|
3190
|
-
success: false,
|
|
3191
|
-
phase: "self_check",
|
|
3192
|
-
error: `${selfCheckIssues.length} issue(s) found \u2014 fix these before recompiling:
|
|
3193
|
-
|
|
3194
|
-
${report}`
|
|
3195
|
-
}, null, 2)
|
|
3196
|
-
}],
|
|
3197
|
-
isError: true
|
|
3198
|
-
};
|
|
3199
|
-
}
|
|
3200
|
-
const validation = validateComponentDetailed(code);
|
|
3201
|
-
if (!validation.valid) {
|
|
3202
|
-
return {
|
|
3203
|
-
content: [
|
|
3204
|
-
{
|
|
3205
|
-
type: "text",
|
|
3206
|
-
text: JSON.stringify(
|
|
3207
|
-
{
|
|
3208
|
-
success: false,
|
|
3209
|
-
phase: "validation",
|
|
3210
|
-
error: formatValidationResultForClaude(validation)
|
|
3211
|
-
},
|
|
3212
|
-
null,
|
|
3213
|
-
2
|
|
3214
|
-
)
|
|
3215
|
-
}
|
|
3216
|
-
],
|
|
3217
|
-
isError: true
|
|
3218
|
-
};
|
|
3219
|
-
}
|
|
3220
|
-
try {
|
|
3221
|
-
const result = await esbuild.transform(code, {
|
|
3222
|
-
loader: "tsx",
|
|
3223
|
-
target: "es2020",
|
|
3224
|
-
format: "esm",
|
|
3225
|
-
jsx: "automatic",
|
|
3226
|
-
jsxImportSource: "react",
|
|
3227
|
-
minify: true,
|
|
3228
|
-
sourcefile: filename
|
|
3229
|
-
});
|
|
3230
|
-
const warnings = [
|
|
3231
|
-
...result.warnings.map((w) => w.text),
|
|
3232
|
-
...validation.warnings.map(
|
|
3233
|
-
(w) => `[${w.type}] ${w.message}: ${w.suggestion}`
|
|
3234
|
-
)
|
|
3235
|
-
];
|
|
3236
|
-
if (context.contract) {
|
|
3237
|
-
const contractIssues = validateAllContracts(code, context.contract);
|
|
3238
|
-
const errors = contractIssues.filter((i) => i.severity === "error");
|
|
3239
|
-
const contractWarnings = contractIssues.filter((i) => i.severity === "warning");
|
|
3240
|
-
if (errors.length > 0) {
|
|
3241
|
-
const report = errors.map((i) => `- [${i.field}] ${i.message}
|
|
3242
|
-
Fix: ${i.fix}`).join("\n");
|
|
3243
|
-
return {
|
|
3244
|
-
content: [{
|
|
3245
|
-
type: "text",
|
|
3246
|
-
text: JSON.stringify({
|
|
3247
|
-
success: false,
|
|
3248
|
-
phase: "contract_validation",
|
|
3249
|
-
error: `Compilation succeeded but data contract validation failed:
|
|
3250
|
-
|
|
3251
|
-
${report}
|
|
3252
|
-
|
|
3253
|
-
Fix the Props interface to match the data contract, then recompile.`
|
|
3254
|
-
}, null, 2)
|
|
3255
|
-
}],
|
|
3256
|
-
isError: true
|
|
3257
|
-
};
|
|
3258
|
-
}
|
|
3259
|
-
warnings.push(...contractWarnings.map((i) => `[contract:${i.field}] ${i.message}`));
|
|
3260
|
-
}
|
|
3261
|
-
const sampleProps = context.sampleProps ?? (context.contract?.propsSpec ? generateSampleProps(context.contract.propsSpec) : void 0);
|
|
3262
|
-
const renderError = await tryRender(result.code, code, sampleProps);
|
|
3263
|
-
if (renderError) {
|
|
3264
|
-
return {
|
|
3265
|
-
content: [{
|
|
3266
|
-
type: "text",
|
|
3267
|
-
text: JSON.stringify({
|
|
3268
|
-
success: false,
|
|
3269
|
-
phase: "render_smoke_test",
|
|
3270
|
-
compiledCode: result.code,
|
|
3271
|
-
error: `${renderError}
|
|
3272
|
-
|
|
3273
|
-
The component compiled but crashes at runtime. Fix the null/undefined access and recompile.`,
|
|
3274
|
-
warnings
|
|
3275
|
-
}, null, 2)
|
|
3276
|
-
}],
|
|
3277
|
-
isError: true
|
|
3278
|
-
};
|
|
3279
|
-
}
|
|
3280
|
-
return {
|
|
3281
|
-
content: [
|
|
3282
|
-
{
|
|
3283
|
-
type: "text",
|
|
3284
|
-
text: JSON.stringify(
|
|
3285
|
-
{
|
|
3286
|
-
success: true,
|
|
3287
|
-
compiledCode: result.code,
|
|
3288
|
-
warnings
|
|
3289
|
-
},
|
|
3290
|
-
null,
|
|
3291
|
-
2
|
|
3292
|
-
)
|
|
3293
|
-
}
|
|
3294
|
-
]
|
|
3295
|
-
};
|
|
3296
|
-
} catch (error) {
|
|
3297
|
-
return {
|
|
3298
|
-
content: [
|
|
3299
|
-
{
|
|
3300
|
-
type: "text",
|
|
3301
|
-
text: JSON.stringify(
|
|
3302
|
-
{ success: false, phase: "compilation", error: formatEsbuildError(error, code) },
|
|
3303
|
-
null,
|
|
3304
|
-
2
|
|
3305
|
-
)
|
|
3306
|
-
}
|
|
3307
|
-
],
|
|
3308
|
-
isError: true
|
|
3309
|
-
};
|
|
3310
|
-
}
|
|
3311
|
-
}
|
|
3312
|
-
}
|
|
3313
|
-
];
|
|
3314
|
-
return tools;
|
|
3315
|
-
}
|
|
3316
|
-
function formatEsbuildError(error, sourceCode) {
|
|
3317
|
-
const parts = [];
|
|
3318
|
-
if (error && typeof error === "object" && "errors" in error && Array.isArray(error.errors)) {
|
|
3319
|
-
const esbuildError = error;
|
|
3320
|
-
for (const err of esbuildError.errors) {
|
|
3321
|
-
const line = err.location?.line;
|
|
3322
|
-
const col = err.location?.column;
|
|
3323
|
-
parts.push(`**Error:** ${err.text}`);
|
|
3324
|
-
if (line) {
|
|
3325
|
-
parts.push(`**Location:** Line ${line}, Column ${col ?? 0}`);
|
|
3326
|
-
const lines = sourceCode.split("\n");
|
|
3327
|
-
const start = Math.max(0, line - 3);
|
|
3328
|
-
const end = Math.min(lines.length, line + 2);
|
|
3329
|
-
const context = lines.slice(start, end).map((l, i) => {
|
|
3330
|
-
const ln = start + i + 1;
|
|
3331
|
-
return `${ln === line ? ">>> " : " "}${ln} | ${l}`;
|
|
3332
|
-
}).join("\n");
|
|
3333
|
-
parts.push(`**Code:**
|
|
3334
|
-
\`\`\`
|
|
3335
|
-
${context}
|
|
3336
|
-
\`\`\``);
|
|
3337
|
-
}
|
|
3338
|
-
}
|
|
3339
|
-
} else {
|
|
3340
|
-
parts.push(`**Error:** ${error instanceof Error ? error.message : "Compilation failed"}`);
|
|
3341
|
-
}
|
|
3342
|
-
parts.push("\n**How to fix:** Review the error above, fix the code, then call compile_component again.");
|
|
3343
|
-
return parts.join("\n");
|
|
3344
|
-
}
|
|
3345
|
-
var LABELED_COMPONENTS = /* @__PURE__ */ new Set(["Input", "TextArea", "Select"]);
|
|
3346
|
-
function checkReactRules(code) {
|
|
3347
|
-
const sf = ts3.createSourceFile("component.tsx", code, ts3.ScriptTarget.Latest, true, ts3.ScriptKind.TSX);
|
|
3348
|
-
const issues = [];
|
|
3349
|
-
function visit(node) {
|
|
3350
|
-
if (ts3.isJsxSelfClosingElement(node) || ts3.isJsxOpeningElement(node)) {
|
|
3351
|
-
const tagName = node.tagName.getText(sf);
|
|
3352
|
-
if (LABELED_COMPONENTS.has(tagName)) {
|
|
3353
|
-
const propNames = /* @__PURE__ */ new Set();
|
|
3354
|
-
let hasSpread = false;
|
|
3355
|
-
for (const attr of node.attributes.properties) {
|
|
3356
|
-
if (ts3.isJsxAttribute(attr)) {
|
|
3357
|
-
propNames.add(attr.name.getText(sf));
|
|
3358
|
-
} else if (ts3.isJsxSpreadAttribute(attr)) {
|
|
3359
|
-
hasSpread = true;
|
|
3360
|
-
}
|
|
3361
|
-
}
|
|
3362
|
-
if (!hasSpread && !propNames.has("label") && !propNames.has("aria-label")) {
|
|
3363
|
-
const line = sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;
|
|
3364
|
-
issues.push({
|
|
3365
|
-
check: "accessibility",
|
|
3366
|
-
line,
|
|
3367
|
-
message: `${tagName} missing label prop`,
|
|
3368
|
-
fix: `Add label="..." prop directly on the ${tagName} component. The label prop is built into the primitive.`
|
|
3369
|
-
});
|
|
3370
|
-
}
|
|
3371
|
-
}
|
|
3372
|
-
}
|
|
3373
|
-
ts3.forEachChild(node, visit);
|
|
3374
|
-
}
|
|
3375
|
-
visit(sf);
|
|
3376
|
-
return issues;
|
|
3377
|
-
}
|
|
3378
|
-
async function runSelfChecks(code, contract) {
|
|
3379
|
-
const issues = [];
|
|
3380
|
-
const lines = code.split("\n");
|
|
3381
|
-
const allowedGadgetPackages = new Set(
|
|
3382
|
-
Object.keys(contract?.clientCapabilities?.gadgets ?? {})
|
|
3383
|
-
);
|
|
3384
|
-
for (let i = 0; i < lines.length; i++) {
|
|
3385
|
-
const line = lines[i];
|
|
3386
|
-
const lineNum = i + 1;
|
|
3387
|
-
const hexMatch = line.match(/#[0-9a-fA-F]{3,8}\b/);
|
|
3388
|
-
if (hexMatch && !line.includes("var(--ggui-") && !line.includes("// fallback")) {
|
|
3389
|
-
issues.push({
|
|
3390
|
-
check: "hex-color",
|
|
3391
|
-
line: lineNum,
|
|
3392
|
-
message: `Hardcoded color "${hexMatch[0]}" \u2014 must use design tokens`,
|
|
3393
|
-
fix: `Replace "${hexMatch[0]}" with a primitive variant OR a bare token reference such as var(--ggui-color-primary-500) \u2014 never a literal fallback inside var()`
|
|
3394
|
-
});
|
|
3395
|
-
}
|
|
3396
|
-
const colorFnMatch = line.match(/\b(rgba?|hsla?)\s*\(/);
|
|
3397
|
-
if (colorFnMatch && !line.includes("var(--ggui-") && !line.includes("// fallback") && !line.includes("$value")) {
|
|
3398
|
-
issues.push({
|
|
3399
|
-
check: "hardcoded-color-fn",
|
|
3400
|
-
line: lineNum,
|
|
3401
|
-
message: `Hardcoded ${colorFnMatch[1]}() \u2014 use design tokens instead`,
|
|
3402
|
-
fix: `Replace with the layering roles: var(--ggui-color-container), var(--ggui-color-onContainer), var(--ggui-color-outline), etc.`
|
|
3403
|
-
});
|
|
3404
|
-
}
|
|
3405
|
-
if (/--ggui-color-neutral-50[^0-9]/.test(line) && /background/i.test(line)) {
|
|
3406
|
-
issues.push({
|
|
3407
|
-
check: "prefer-semantic",
|
|
3408
|
-
line: lineNum,
|
|
3409
|
-
message: `neutral-50 for background \u2014 prefer semantic token for dark-theme compatibility`,
|
|
3410
|
-
fix: `Replace with var(--ggui-color-container) or var(--ggui-color-sunken)`
|
|
3411
|
-
});
|
|
3412
|
-
}
|
|
3413
|
-
if (/--ggui-color-neutral-900[^0-9]/.test(line) && /color/i.test(line) && !/background/i.test(line)) {
|
|
3414
|
-
issues.push({
|
|
3415
|
-
check: "prefer-semantic",
|
|
3416
|
-
line: lineNum,
|
|
3417
|
-
message: `neutral-900 for text color \u2014 prefer semantic token for dark-theme compatibility`,
|
|
3418
|
-
fix: `Replace with var(--ggui-color-onContainer) or var(--ggui-color-onSunken)`
|
|
3419
|
-
});
|
|
3420
|
-
}
|
|
3421
|
-
const pxMatch = line.match(/(?:padding|margin|gap|borderRadius)\s*:\s*['"]?\d+px/);
|
|
3422
|
-
if (pxMatch && !line.includes("var(--ggui-")) {
|
|
3423
|
-
issues.push({
|
|
3424
|
-
check: "raw-pixels",
|
|
3425
|
-
line: lineNum,
|
|
3426
|
-
message: `Raw pixel value in spacing \u2014 must use design tokens`,
|
|
3427
|
-
fix: `Replace with a bare var(--ggui-spacing-*) token \u2014 no literal fallback \u2014 or the scale name on the primitive prop (gap="md", padding="lg")`
|
|
3428
|
-
});
|
|
3429
|
-
}
|
|
3430
|
-
if (/\beval\s*\(/.test(line)) {
|
|
3431
|
-
issues.push({ check: "security", line: lineNum, message: "eval() is forbidden", fix: "Remove eval() call entirely" });
|
|
3432
|
-
}
|
|
3433
|
-
if (/\bfetch\s*\(/.test(line)) {
|
|
3434
|
-
issues.push({ check: "security", line: lineNum, message: "fetch() is forbidden \u2014 use props for data", fix: "Remove fetch() and pass data via props" });
|
|
3435
|
-
}
|
|
3436
|
-
const importMatch = line.match(/import\s+.*from\s+['"]([^'"]+)['"]/);
|
|
3437
|
-
if (importMatch) {
|
|
3438
|
-
const pkg = importMatch[1];
|
|
3439
|
-
if (!isAllowedImport(pkg, allowedGadgetPackages)) {
|
|
3440
|
-
issues.push({
|
|
3441
|
-
check: "import",
|
|
3442
|
-
line: lineNum,
|
|
3443
|
-
message: `Import from "${pkg}" is not allowed`,
|
|
3444
|
-
fix: `Only import from: ${describeAllowedImports()}`
|
|
3445
|
-
});
|
|
3446
|
-
}
|
|
3447
|
-
}
|
|
3448
|
-
}
|
|
3449
|
-
try {
|
|
3450
|
-
const jsxIssues = checkReactRules(code);
|
|
3451
|
-
issues.push(...jsxIssues);
|
|
3452
|
-
} catch {
|
|
3453
|
-
}
|
|
3454
|
-
if (!code.includes("interface Props") && !code.includes("type Props")) {
|
|
3455
|
-
issues.push({
|
|
3456
|
-
check: "props-interface",
|
|
3457
|
-
line: 1,
|
|
3458
|
-
message: "No Props interface found \u2014 data is likely hardcoded",
|
|
3459
|
-
fix: "Add interface Props { ... } with typed fields and default values in the function signature"
|
|
3460
|
-
});
|
|
3461
|
-
}
|
|
3462
|
-
if (!code.includes("export default function")) {
|
|
3463
|
-
issues.push({
|
|
3464
|
-
check: "export",
|
|
3465
|
-
line: 1,
|
|
3466
|
-
message: "Missing default export function",
|
|
3467
|
-
fix: "Add export default function GeneratedComponent(props: Props) { ... }"
|
|
3468
|
-
});
|
|
3469
|
-
}
|
|
3470
|
-
const typeWarnings = [];
|
|
3471
|
-
const [typeResult, reactResult] = await Promise.all([
|
|
3472
|
-
typecheck(code).catch((err) => {
|
|
3473
|
-
console.warn("[runSelfChecks] TypeChecker failed:", err instanceof Error ? err.message : String(err));
|
|
3474
|
-
return null;
|
|
3475
|
-
}),
|
|
3476
|
-
lintReactHooks(code).catch((err) => {
|
|
3477
|
-
console.warn("[runSelfChecks] React linter failed:", err instanceof Error ? err.message : String(err));
|
|
3478
|
-
return [];
|
|
3479
|
-
})
|
|
3480
|
-
]);
|
|
3481
|
-
if (typeResult) {
|
|
3482
|
-
for (const error of typeResult.errors) {
|
|
3483
|
-
issues.push({
|
|
3484
|
-
check: `ts${error.code}`,
|
|
3485
|
-
line: error.line,
|
|
3486
|
-
message: error.message,
|
|
3487
|
-
fix: error.fix
|
|
3488
|
-
});
|
|
3489
|
-
}
|
|
3490
|
-
for (const warning of typeResult.warnings) {
|
|
3491
|
-
typeWarnings.push({
|
|
3492
|
-
check: `ts${warning.code}`,
|
|
3493
|
-
line: warning.line,
|
|
3494
|
-
message: warning.message,
|
|
3495
|
-
fix: warning.fix
|
|
3496
|
-
});
|
|
3497
|
-
}
|
|
3498
|
-
}
|
|
3499
|
-
const hasStateSetter = /\b(set[A-Z]\w*|dispatch)\s*\(/.test(code);
|
|
3500
|
-
const isSetterLoopRisk = (diag) => {
|
|
3501
|
-
if (diag.rule !== "react-hooks/exhaustive-deps") return false;
|
|
3502
|
-
if (!hasStateSetter) return false;
|
|
3503
|
-
return /missing dependenc|changes on every render|object makes the dependencies|array makes the dependencies/i.test(
|
|
3504
|
-
diag.message
|
|
3505
|
-
);
|
|
3506
|
-
};
|
|
3507
|
-
for (const diag of reactResult) {
|
|
3508
|
-
const blocking = diag.severity === "error" || isSetterLoopRisk(diag);
|
|
3509
|
-
if (blocking) {
|
|
3510
|
-
issues.push({
|
|
3511
|
-
check: diag.rule,
|
|
3512
|
-
line: diag.line,
|
|
3513
|
-
message: isSetterLoopRisk(diag) ? `${diag.message} (promoted to error: effect mutates state \u2014 missing/unstable deps cause infinite render loops)` : diag.message,
|
|
3514
|
-
fix: diag.fix
|
|
3515
|
-
});
|
|
3516
|
-
} else {
|
|
3517
|
-
typeWarnings.push({
|
|
3518
|
-
check: diag.rule,
|
|
3519
|
-
line: diag.line,
|
|
3520
|
-
message: diag.message,
|
|
3521
|
-
fix: diag.fix
|
|
3522
|
-
});
|
|
3523
|
-
}
|
|
3524
|
-
}
|
|
3525
|
-
const lineMap = /* @__PURE__ */ new Map();
|
|
3526
|
-
for (const i of issues) {
|
|
3527
|
-
const list = lineMap.get(i.line) ?? [];
|
|
3528
|
-
list.push(i);
|
|
3529
|
-
lineMap.set(i.line, list);
|
|
3530
|
-
}
|
|
3531
|
-
const deduped = [];
|
|
3532
|
-
for (const [, group] of lineMap) {
|
|
3533
|
-
if (group.length === 1) {
|
|
3534
|
-
deduped.push(group[0]);
|
|
3535
|
-
continue;
|
|
3536
|
-
}
|
|
3537
|
-
const primary = group.find((i) => !i.check.startsWith("ts")) ?? group[0];
|
|
3538
|
-
const others = group.filter((i) => i !== primary);
|
|
3539
|
-
if (others.length > 0) {
|
|
3540
|
-
const alsoTags = others.map((o) => o.check).join(", ");
|
|
3541
|
-
deduped.push({
|
|
3542
|
-
...primary,
|
|
3543
|
-
message: `${primary.message} [also flagged by: ${alsoTags}]`
|
|
3544
|
-
});
|
|
3545
|
-
} else {
|
|
3546
|
-
deduped.push(primary);
|
|
3547
|
-
}
|
|
3548
|
-
}
|
|
3549
|
-
return { issues: deduped, typeWarnings };
|
|
3550
|
-
}
|
|
3551
|
-
|
|
3552
|
-
// src/adapters/index.ts
|
|
3553
|
-
init_tool_bridge();
|
|
3554
|
-
init_raw();
|
|
3555
|
-
init_sdk();
|
|
3556
|
-
init_raw2();
|
|
3557
|
-
init_sdk2();
|
|
3558
|
-
init_raw3();
|
|
3559
|
-
init_sdk3();
|
|
3560
|
-
|
|
3561
|
-
export { ClaudeRawAdapter, ClaudeSdkAdapter, GeneratorAdapter, GoogleRawAdapter, GoogleSdkAdapter, OpenAiRawAdapter, OpenAiSdkAdapter, PROVIDER_DISPLAY_NAMES, createGeneratorTools, getAdapter, listAdapters, zodToJsonSchema };
|
|
1
|
+
export { getAdapter, listAdapters } from '../chunk-MKMDQFZ7.js';
|
|
2
|
+
export { OpenAiSdkAdapter } from '../chunk-PJFH7QWA.js';
|
|
3
|
+
export { GoogleRawAdapter } from '../chunk-6VDRWAP6.js';
|
|
4
|
+
export { GoogleSdkAdapter } from '../chunk-PBOYHGSD.js';
|
|
5
|
+
export { ClaudeRawAdapter } from '../chunk-3ZSSDV3L.js';
|
|
6
|
+
export { ClaudeSdkAdapter } from '../chunk-XGLO5LGG.js';
|
|
7
|
+
export { OpenAiRawAdapter } from '../chunk-AOU33EFS.js';
|
|
8
|
+
import '../chunk-YJZTUY7B.js';
|
|
9
|
+
export { GeneratorAdapter } from '../chunk-XRBCRKA2.js';
|
|
10
|
+
export { createGeneratorTools } from '../chunk-3HSGA6NI.js';
|
|
11
|
+
export { PROVIDER_DISPLAY_NAMES } from '../chunk-A375NNWN.js';
|
|
12
|
+
import '../chunk-56NJFD55.js';
|
|
13
|
+
import '../chunk-HD6ABIK7.js';
|
|
14
|
+
import '../chunk-FWJIMKFZ.js';
|
|
15
|
+
import '../chunk-33B3BAWS.js';
|
|
16
|
+
import '../chunk-GAJI7Y3P.js';
|
|
17
|
+
import '../chunk-QLXXPGTV.js';
|
|
18
|
+
import '../chunk-JDH5EGNZ.js';
|
|
19
|
+
import '../chunk-OVLH5ICV.js';
|
|
20
|
+
export { zodToJsonSchema } from '../chunk-7QE3AHLE.js';
|
|
21
|
+
import '../chunk-FLRNMZV2.js';
|
|
22
|
+
import '../chunk-Z3CXME3K.js';
|
|
23
|
+
import '../chunk-PUH4CXGZ.js';
|
|
24
|
+
import '../chunk-3T2HMTON.js';
|
|
25
|
+
import '../chunk-G3PMV62Z.js';
|
|
3562
26
|
//# sourceMappingURL=index.js.map
|
|
3563
27
|
//# sourceMappingURL=index.js.map
|