@databricks/appkit-ui 0.91.3 → 0.93.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.
Files changed (81) hide show
  1. package/CLAUDE.md +2 -0
  2. package/NOTICE.md +3 -3
  3. package/dist/cli/commands/doctor/checks-existence.js +15 -0
  4. package/dist/cli/commands/doctor/checks-existence.js.map +1 -1
  5. package/dist/cli/commands/plugin/add/add.js +398 -0
  6. package/dist/cli/commands/plugin/add/add.js.map +1 -0
  7. package/dist/cli/commands/plugin/add/plan.js +216 -0
  8. package/dist/cli/commands/plugin/add/plan.js.map +1 -0
  9. package/dist/cli/commands/plugin/add/resolve.js +45 -0
  10. package/dist/cli/commands/plugin/add/resolve.js.map +1 -0
  11. package/dist/cli/commands/plugin/create/resource-defaults.js +4 -0
  12. package/dist/cli/commands/plugin/create/resource-defaults.js.map +1 -1
  13. package/dist/cli/commands/plugin/index.js +4 -1
  14. package/dist/cli/commands/plugin/index.js.map +1 -1
  15. package/dist/cli/commands/plugin/schema-resources.js +2 -1
  16. package/dist/cli/commands/plugin/schema-resources.js.map +1 -1
  17. package/dist/cli/commands/registry/add.js +3 -2
  18. package/dist/cli/commands/registry/add.js.map +1 -1
  19. package/dist/cli/commands/registry/config-plan.js +1 -1
  20. package/dist/cli/commands/registry/config-plan.js.map +1 -1
  21. package/dist/cli/commands/registry/config-writer.js +77 -9
  22. package/dist/cli/commands/registry/config-writer.js.map +1 -1
  23. package/dist/cli/commands/registry/env-writer.js +15 -2
  24. package/dist/cli/commands/registry/env-writer.js.map +1 -1
  25. package/dist/cli/commands/registry/server-register.js +62 -26
  26. package/dist/cli/commands/registry/server-register.js.map +1 -1
  27. package/dist/cli/commands/registry/workspace-picker.js +47 -2
  28. package/dist/cli/commands/registry/workspace-picker.js.map +1 -1
  29. package/dist/cli/deploy-config.js.map +1 -1
  30. package/dist/cli/index.js +1 -1
  31. package/dist/react/beta.d.ts +3 -1
  32. package/dist/react/beta.js +3 -1
  33. package/dist/react/charts/base.d.ts +1 -1
  34. package/dist/react/charts/base.d.ts.map +1 -1
  35. package/dist/react/charts/base.js +5 -3
  36. package/dist/react/charts/base.js.map +1 -1
  37. package/dist/react/charts/constants.js +13 -1
  38. package/dist/react/charts/constants.js.map +1 -1
  39. package/dist/react/charts/create-chart.js +1 -1
  40. package/dist/react/charts/create-chart.js.map +1 -1
  41. package/dist/react/charts/index.d.ts +1 -1
  42. package/dist/react/charts/types.d.ts +7 -3
  43. package/dist/react/charts/types.d.ts.map +1 -1
  44. package/dist/react/charts/types.js.map +1 -1
  45. package/dist/react/charts/wrapper.d.ts +1 -1
  46. package/dist/react/charts/wrapper.d.ts.map +1 -1
  47. package/dist/react/charts/wrapper.js +12 -5
  48. package/dist/react/charts/wrapper.js.map +1 -1
  49. package/dist/react/design-page.d.ts +33 -0
  50. package/dist/react/design-page.d.ts.map +1 -0
  51. package/dist/react/design-page.js +173 -0
  52. package/dist/react/design-page.js.map +1 -0
  53. package/dist/react/hooks/use-design-ready.d.ts +19 -0
  54. package/dist/react/hooks/use-design-ready.d.ts.map +1 -0
  55. package/dist/react/hooks/use-design-ready.js +33 -0
  56. package/dist/react/hooks/use-design-ready.js.map +1 -0
  57. package/dist/react/index.d.ts +2 -2
  58. package/dist/schemas/manifest.d.ts +79 -0
  59. package/dist/schemas/manifest.d.ts.map +1 -1
  60. package/dist/schemas/manifest.js +10 -1
  61. package/dist/schemas/manifest.js.map +1 -1
  62. package/dist/shared/src/plugin.d.ts.map +1 -1
  63. package/docs/api/appkit/Enumeration.ResourceType.md +9 -0
  64. package/docs/api/appkit/TypeAlias.ResourcePermission.md +1 -0
  65. package/docs/api/appkit/Variable.design.md +6 -0
  66. package/docs/api/appkit-ui/data/AreaChart.md +2 -2
  67. package/docs/api/appkit-ui/data/BarChart.md +2 -2
  68. package/docs/api/appkit-ui/data/DonutChart.md +2 -2
  69. package/docs/api/appkit-ui/data/HeatmapChart.md +2 -2
  70. package/docs/api/appkit-ui/data/LineChart.md +2 -2
  71. package/docs/api/appkit-ui/data/PieChart.md +2 -2
  72. package/docs/api/appkit-ui/data/RadarChart.md +2 -2
  73. package/docs/api/appkit-ui/data/ScatterChart.md +2 -2
  74. package/docs/api/appkit.md +1 -0
  75. package/docs/plugins/agents.md +3 -3
  76. package/docs/plugins/analytics.md +8 -0
  77. package/docs/plugins/design.md +233 -0
  78. package/docs/plugins/manifest.md +1 -0
  79. package/llms.txt +2 -0
  80. package/package.json +1 -1
  81. package/sbom.cdx.json +1 -1
@@ -18,6 +18,17 @@ function findServerFile(serverRoot) {
18
18
  }
19
19
  return null;
20
20
  }
21
+ /** `{ a, b }` of a value import from `module`; type-only imports are erased at compile time. */
22
+ function namedImportsFrom(stmts, module) {
23
+ for (const stmt of stmts) {
24
+ const source = stmt.field("source")?.text().slice(1, -1);
25
+ const typeOnly = stmt.children().some((c) => c.kind() === "type" && !c.isNamed());
26
+ if (source !== module || typeOnly) continue;
27
+ const named = stmt.find({ rule: { kind: "named_imports" } });
28
+ if (named) return named;
29
+ }
30
+ return null;
31
+ }
21
32
  /** The `plugins: [...]` array node inside a createApp call, if present. */
22
33
  function findPluginsArray(root) {
23
34
  for (const pair of root.findAll({ rule: { kind: "pair" } })) {
@@ -55,40 +66,54 @@ function importBindingNames(stmt) {
55
66
  }
56
67
  return names;
57
68
  }
58
- /**
59
- * Best-effort: register a plugin in the server entry's `createApp({ plugins })`
60
- * call by inserting the import and adding it to the array. Only edits the
61
- * standard shape (a `plugins: [...]` array literal); returns `skipped` otherwise
62
- * so the caller can fall back to printing manual instructions. Idempotent.
63
- */
64
- function registerPluginInServer(serverRoot, importPath, exportName) {
69
+ function registerPluginInServer(serverRoot, importPath, exportName, callArgs = "") {
70
+ return registerPluginsInServer(serverRoot, [{
71
+ importPath,
72
+ exportName,
73
+ callArgs
74
+ }])[0];
75
+ }
76
+ /** Registers the entries in order with a single write, so a dev server restarts once. */
77
+ function registerPluginsInServer(serverRoot, entries) {
78
+ const serverFile = findServerFile(serverRoot);
79
+ if (!serverFile) return entries.map(() => ({
80
+ status: "skipped",
81
+ reason: "no server entry file found"
82
+ }));
83
+ const file = path.relative(serverRoot, serverFile);
84
+ const lang = serverFile.endsWith(".tsx") ? Lang.Tsx : Lang.TypeScript;
85
+ const original = fs.readFileSync(serverFile, "utf-8");
86
+ let content = original;
87
+ const results = entries.map((e) => {
88
+ const { output, ...r } = registerInSource(content, lang, e);
89
+ if (output !== void 0) content = output;
90
+ return r.status === "skipped" ? r : {
91
+ ...r,
92
+ file
93
+ };
94
+ });
95
+ if (content !== original) fs.writeFileSync(serverFile, content);
96
+ return results;
97
+ }
98
+ /** Applies one entry to the server source; `output` is set when it changed. */
99
+ function registerInSource(content, lang, { importPath, exportName, callArgs = "" }) {
65
100
  if (!JS_IDENTIFIER.test(exportName)) return {
66
101
  status: "skipped",
67
102
  reason: "invalid plugin export name"
68
103
  };
69
- if (!/^[.][./A-Za-z0-9_-]*$/.test(importPath)) return {
104
+ if (!/^[.][./A-Za-z0-9_-]*$/.test(importPath) && !/^(@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*(\/[\w.-]+)*$/i.test(importPath)) return {
70
105
  status: "skipped",
71
106
  reason: "invalid plugin import path"
72
107
  };
73
- const serverFile = findServerFile(serverRoot);
74
- if (!serverFile) return {
75
- status: "skipped",
76
- reason: "no server entry file found"
77
- };
78
- const content = fs.readFileSync(serverFile, "utf-8");
79
- const root = parse(serverFile.endsWith(".tsx") ? Lang.Tsx : Lang.TypeScript, content).root();
108
+ const root = parse(lang, content).root();
80
109
  const arr = findPluginsArray(root);
81
110
  if (!arr) return {
82
111
  status: "skipped",
83
112
  reason: "no createApp({ plugins: [...] }) array found"
84
113
  };
85
- const file = path.relative(serverRoot, serverFile);
86
- if (arrayElementNames(arr).has(exportName)) return {
87
- status: "already",
88
- file
89
- };
114
+ if (arrayElementNames(arr).has(exportName)) return { status: "already" };
90
115
  const edits = [];
91
- const newElem = `${exportName}()`;
116
+ const newElem = `${exportName}(${callArgs})`;
92
117
  const elementKinds = [
93
118
  "identifier",
94
119
  "call_expression",
@@ -106,19 +131,30 @@ function registerPluginInServer(serverRoot, importPath, exportName) {
106
131
  const importStmts = root.findAll({ rule: { kind: "import_statement" } });
107
132
  const hasBinding = importStmts.some((s) => importBindingNames(s).has(exportName));
108
133
  const importLine = `import { ${exportName} } from "${importPath}";`;
109
- if (!hasBinding && importStmts.length > 0) {
134
+ const named = hasBinding ? null : namedImportsFrom(importStmts, importPath);
135
+ if (named) {
136
+ const specs = named.findAll({ rule: { kind: "import_specifier" } });
137
+ const lastSpec = specs[specs.length - 1];
138
+ if (!lastSpec) edits.push(named.replace(`{ ${exportName} }`));
139
+ else {
140
+ const startIdx = lastSpec.range().start.index;
141
+ const lineStart = content.lastIndexOf("\n", startIdx - 1);
142
+ const indent = content.slice(lineStart + 1, startIdx);
143
+ const sep = named.text().includes("\n") && /^[ \t]*$/.test(indent) ? `,\n${indent}` : ", ";
144
+ edits.push(lastSpec.replace(`${lastSpec.text()}${sep}${exportName}`));
145
+ }
146
+ } else if (!hasBinding && importStmts.length > 0) {
110
147
  const last = importStmts[importStmts.length - 1];
111
148
  edits.push(last.replace(`${last.text()}\n${importLine}`));
112
149
  }
113
150
  let output = root.commitEdits(edits);
114
- if (!hasBinding && importStmts.length === 0) output = `${importLine}\n${output}`;
115
- fs.writeFileSync(serverFile, output);
151
+ if (!hasBinding && !named && importStmts.length === 0) output = `${importLine}\n${output}`;
116
152
  return {
117
153
  status: "wired",
118
- file
154
+ output
119
155
  };
120
156
  }
121
157
 
122
158
  //#endregion
123
- export { registerPluginInServer };
159
+ export { findServerFile, registerPluginInServer, registerPluginsInServer };
124
160
  //# sourceMappingURL=server-register.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server-register.js","names":[],"sources":["../../../../src/cli/commands/registry/server-register.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport { Lang, parse, type SgNode } from \"@ast-grep/napi\";\n\nimport { JS_IDENTIFIER } from \"./constants\";\n\n/** Server entry candidates within the server root, in priority order. */\nconst SERVER_FILE_CANDIDATES = [\n \"server.ts\",\n \"index.ts\",\n \"src/server.ts\",\n \"src/index.ts\",\n];\n\nexport interface RegisterResult {\n /** wired = edited; already = plugin was present; skipped = couldn't safely edit. */\n status: \"wired\" | \"already\" | \"skipped\";\n file?: string;\n reason?: string;\n}\n\nfunction findServerFile(serverRoot: string): string | null {\n for (const candidate of SERVER_FILE_CANDIDATES) {\n const p = path.join(serverRoot, candidate);\n if (fs.existsSync(p)) return p;\n }\n return null;\n}\n\n/** The `plugins: [...]` array node inside a createApp call, if present. */\nfunction findPluginsArray(root: SgNode): SgNode | null {\n for (const pair of root.findAll({ rule: { kind: \"pair\" } })) {\n const key = pair.find({ rule: { kind: \"property_identifier\" } });\n if (key?.text() !== \"plugins\") continue;\n const arr = pair.find({ rule: { kind: \"array\" } });\n if (arr) return arr;\n }\n return null;\n}\n\nfunction arrayElementNames(arr: SgNode): Set<string> {\n const names = new Set<string>();\n for (const child of arr.children()) {\n if (child.kind() === \"identifier\") {\n names.add(child.text());\n } else if (child.kind() === \"call_expression\") {\n const callee = child.children()[0];\n if (callee?.kind() === \"identifier\") names.add(callee.text());\n }\n }\n return names;\n}\n\n/** Local binding names introduced by an import statement — default, namespace,\n * and named specifiers, with aliases resolved to the local name. */\nfunction importBindingNames(stmt: SgNode): Set<string> {\n const names = new Set<string>();\n const clause = stmt.find({ rule: { kind: \"import_clause\" } });\n if (!clause) return names;\n for (const child of clause.children()) {\n const kind = child.kind();\n if (kind === \"identifier\") {\n names.add(child.text());\n } else if (kind === \"namespace_import\") {\n const id = child.find({ rule: { kind: \"identifier\" } });\n if (id) names.add(id.text());\n } else if (kind === \"named_imports\") {\n for (const spec of child.findAll({\n rule: { kind: \"import_specifier\" },\n })) {\n const local = spec.field(\"alias\")?.text() ?? spec.field(\"name\")?.text();\n if (local) names.add(local);\n }\n }\n }\n return names;\n}\n\n/**\n * Best-effort: register a plugin in the server entry's `createApp({ plugins })`\n * call by inserting the import and adding it to the array. Only edits the\n * standard shape (a `plugins: [...]` array literal); returns `skipped` otherwise\n * so the caller can fall back to printing manual instructions. Idempotent.\n */\nexport function registerPluginInServer(\n serverRoot: string,\n importPath: string,\n exportName: string,\n): RegisterResult {\n // exportName and importPath are interpolated into the user's server source.\n // Registry items are untrusted, so refuse anything that isn't a plain JS\n // identifier / clean relative module path — prevents code injection via a\n // crafted export name or import path.\n if (!JS_IDENTIFIER.test(exportName)) {\n return { status: \"skipped\", reason: \"invalid plugin export name\" };\n }\n if (!/^[.][./A-Za-z0-9_-]*$/.test(importPath)) {\n return { status: \"skipped\", reason: \"invalid plugin import path\" };\n }\n\n const serverFile = findServerFile(serverRoot);\n if (!serverFile) {\n return { status: \"skipped\", reason: \"no server entry file found\" };\n }\n\n const content = fs.readFileSync(serverFile, \"utf-8\");\n const lang = serverFile.endsWith(\".tsx\") ? Lang.Tsx : Lang.TypeScript;\n const root = parse(lang, content).root();\n\n const arr = findPluginsArray(root);\n if (!arr) {\n return {\n status: \"skipped\",\n reason: \"no createApp({ plugins: [...] }) array found\",\n };\n }\n\n const file = path.relative(serverRoot, serverFile);\n if (arrayElementNames(arr).has(exportName)) {\n return { status: \"already\", file };\n }\n\n const edits = [];\n\n // toPlugin exports are factories, registered as a call: `hello()`.\n const newElem = `${exportName}()`;\n\n // Insert before the first element, matching its indentation so the array\n // formatting is preserved (or inline for a single-line array).\n const elementKinds = [\"identifier\", \"call_expression\", \"spread_element\"];\n const firstEl = arr\n .children()\n .find((c) => elementKinds.includes(c.kind() as string));\n if (!firstEl) {\n edits.push(arr.replace(`[${newElem}]`));\n } else {\n const startIdx = firstEl.range().start.index;\n const lineStart = content.lastIndexOf(\"\\n\", startIdx - 1);\n const indent = content.slice(lineStart + 1, startIdx);\n const multiline = lineStart !== -1 && /^[ \\t]*$/.test(indent);\n const sep = multiline ? `,\\n${indent}` : \", \";\n edits.push(firstEl.replace(`${newElem}${sep}${firstEl.text()}`));\n }\n\n // Add the import unless `exportName` is already bound by some import. De-dup\n // on the binding, not the module path: an existing import from the same path\n // under a different name (e.g. `import { HelloPlugin } from \"./plugins/hello\"`)\n // must not suppress this one, or the `${exportName}()` element just added to\n // the array would reference an unimported symbol and the server won't compile.\n const importStmts = root.findAll({ rule: { kind: \"import_statement\" } });\n const hasBinding = importStmts.some((s) =>\n importBindingNames(s).has(exportName),\n );\n const importLine = `import { ${exportName} } from \"${importPath}\";`;\n if (!hasBinding && importStmts.length > 0) {\n const last = importStmts[importStmts.length - 1];\n edits.push(last.replace(`${last.text()}\\n${importLine}`));\n }\n\n let output = root.commitEdits(edits);\n if (!hasBinding && importStmts.length === 0) {\n output = `${importLine}\\n${output}`;\n }\n fs.writeFileSync(serverFile, output);\n\n return { status: \"wired\", file };\n}\n"],"mappings":";;;;;;;AAQA,MAAM,yBAAyB;CAC7B;CACA;CACA;CACA;CACD;AASD,SAAS,eAAe,YAAmC;AACzD,MAAK,MAAM,aAAa,wBAAwB;EAC9C,MAAM,IAAI,KAAK,KAAK,YAAY,UAAU;AAC1C,MAAI,GAAG,WAAW,EAAE,CAAE,QAAO;;AAE/B,QAAO;;;AAIT,SAAS,iBAAiB,MAA6B;AACrD,MAAK,MAAM,QAAQ,KAAK,QAAQ,EAAE,MAAM,EAAE,MAAM,QAAQ,EAAE,CAAC,EAAE;AAE3D,MADY,KAAK,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,EAAE,CAAC,EACvD,MAAM,KAAK,UAAW;EAC/B,MAAM,MAAM,KAAK,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,EAAE,CAAC;AAClD,MAAI,IAAK,QAAO;;AAElB,QAAO;;AAGT,SAAS,kBAAkB,KAA0B;CACnD,MAAM,wBAAQ,IAAI,KAAa;AAC/B,MAAK,MAAM,SAAS,IAAI,UAAU,CAChC,KAAI,MAAM,MAAM,KAAK,aACnB,OAAM,IAAI,MAAM,MAAM,CAAC;UACd,MAAM,MAA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AI;AAE7B,IAAG,cAAc,YAAY,OAAO;AAEpC,QAAO;EAAE,QAAQ;EAAS;EAAM"}
1
+ {"version":3,"file":"server-register.js","names":[],"sources":["../../../../src/cli/commands/registry/server-register.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport { Lang, parse, type SgNode } from \"@ast-grep/napi\";\n\nimport { JS_IDENTIFIER } from \"./constants\";\n\n/** Server entry candidates within the server root, in priority order. */\nconst SERVER_FILE_CANDIDATES = [\n \"server.ts\",\n \"index.ts\",\n \"src/server.ts\",\n \"src/index.ts\",\n];\n\nexport interface RegisterResult {\n /** wired = edited; already = plugin was present; skipped = couldn't safely edit. */\n status: \"wired\" | \"already\" | \"skipped\";\n file?: string;\n reason?: string;\n}\n\nexport function findServerFile(serverRoot: string): string | null {\n for (const candidate of SERVER_FILE_CANDIDATES) {\n const p = path.join(serverRoot, candidate);\n if (fs.existsSync(p)) return p;\n }\n return null;\n}\n\n/** `{ a, b }` of a value import from `module`; type-only imports are erased at compile time. */\nfunction namedImportsFrom(stmts: SgNode[], module: string): SgNode | null {\n for (const stmt of stmts) {\n const source = stmt.field(\"source\")?.text().slice(1, -1);\n // `import type` shows as an unnamed `type` token, wherever comments sit.\n const typeOnly = stmt\n .children()\n .some((c) => c.kind() === \"type\" && !c.isNamed());\n if (source !== module || typeOnly) continue;\n const named = stmt.find({ rule: { kind: \"named_imports\" } });\n if (named) return named;\n }\n return null;\n}\n\n/** The `plugins: [...]` array node inside a createApp call, if present. */\nfunction findPluginsArray(root: SgNode): SgNode | null {\n for (const pair of root.findAll({ rule: { kind: \"pair\" } })) {\n const key = pair.find({ rule: { kind: \"property_identifier\" } });\n if (key?.text() !== \"plugins\") continue;\n const arr = pair.find({ rule: { kind: \"array\" } });\n if (arr) return arr;\n }\n return null;\n}\n\nfunction arrayElementNames(arr: SgNode): Set<string> {\n const names = new Set<string>();\n for (const child of arr.children()) {\n if (child.kind() === \"identifier\") {\n names.add(child.text());\n } else if (child.kind() === \"call_expression\") {\n const callee = child.children()[0];\n if (callee?.kind() === \"identifier\") names.add(callee.text());\n }\n }\n return names;\n}\n\n/** Local binding names introduced by an import statement — default, namespace,\n * and named specifiers, with aliases resolved to the local name. */\nfunction importBindingNames(stmt: SgNode): Set<string> {\n const names = new Set<string>();\n const clause = stmt.find({ rule: { kind: \"import_clause\" } });\n if (!clause) return names;\n for (const child of clause.children()) {\n const kind = child.kind();\n if (kind === \"identifier\") {\n names.add(child.text());\n } else if (kind === \"namespace_import\") {\n const id = child.find({ rule: { kind: \"identifier\" } });\n if (id) names.add(id.text());\n } else if (kind === \"named_imports\") {\n for (const spec of child.findAll({\n rule: { kind: \"import_specifier\" },\n })) {\n const local = spec.field(\"alias\")?.text() ?? spec.field(\"name\")?.text();\n if (local) names.add(local);\n }\n }\n }\n return names;\n}\n\n/**\n * Best-effort: register a plugin in the server entry's `createApp({ plugins })`\n * call by inserting the import and adding it to the array. Only edits the\n * standard shape (a `plugins: [...]` array literal); returns `skipped` otherwise\n * so the caller can fall back to printing manual instructions. Idempotent.\n */\n/** `import { exportName } from importPath`, registered as `exportName(callArgs)`. */\nexport interface RegisterEntry {\n importPath: string;\n exportName: string;\n /** CLI-built, never registry data. */\n callArgs?: string;\n}\n\nexport function registerPluginInServer(\n serverRoot: string,\n importPath: string,\n exportName: string,\n callArgs = \"\",\n): RegisterResult {\n return registerPluginsInServer(serverRoot, [\n { importPath, exportName, callArgs },\n ])[0];\n}\n\n/** Registers the entries in order with a single write, so a dev server restarts once. */\nexport function registerPluginsInServer(\n serverRoot: string,\n entries: RegisterEntry[],\n): RegisterResult[] {\n const serverFile = findServerFile(serverRoot);\n if (!serverFile) {\n return entries.map(() => ({\n status: \"skipped\",\n reason: \"no server entry file found\",\n }));\n }\n const file = path.relative(serverRoot, serverFile);\n const lang = serverFile.endsWith(\".tsx\") ? Lang.Tsx : Lang.TypeScript;\n const original = fs.readFileSync(serverFile, \"utf-8\");\n let content = original;\n const results = entries.map((e): RegisterResult => {\n const { output, ...r } = registerInSource(content, lang, e);\n if (output !== undefined) content = output;\n return r.status === \"skipped\" ? r : { ...r, file };\n });\n if (content !== original) fs.writeFileSync(serverFile, content);\n return results;\n}\n\n/** Applies one entry to the server source; `output` is set when it changed. */\nfunction registerInSource(\n content: string,\n lang: Lang,\n { importPath, exportName, callArgs = \"\" }: RegisterEntry,\n): RegisterResult & { output?: string } {\n // exportName and importPath are interpolated into the user's server source.\n // Registry items are untrusted, so refuse anything that isn't a plain JS\n // identifier / clean relative module path — prevents code injection via a\n // crafted export name or import path. npm plugins use a plain package specifier.\n if (!JS_IDENTIFIER.test(exportName)) {\n return { status: \"skipped\", reason: \"invalid plugin export name\" };\n }\n if (\n !/^[.][./A-Za-z0-9_-]*$/.test(importPath) &&\n !/^(@[a-z0-9][\\w.-]*\\/)?[a-z0-9][\\w.-]*(\\/[\\w.-]+)*$/i.test(importPath)\n ) {\n return { status: \"skipped\", reason: \"invalid plugin import path\" };\n }\n\n const root = parse(lang, content).root();\n\n const arr = findPluginsArray(root);\n if (!arr) {\n return {\n status: \"skipped\",\n reason: \"no createApp({ plugins: [...] }) array found\",\n };\n }\n\n if (arrayElementNames(arr).has(exportName)) {\n return { status: \"already\" };\n }\n\n const edits = [];\n\n // toPlugin exports are factories, registered as a call: `hello()`.\n const newElem = `${exportName}(${callArgs})`;\n\n // Insert before the first element, matching its indentation so the array\n // formatting is preserved (or inline for a single-line array).\n const elementKinds = [\"identifier\", \"call_expression\", \"spread_element\"];\n const firstEl = arr\n .children()\n .find((c) => elementKinds.includes(c.kind() as string));\n if (!firstEl) {\n edits.push(arr.replace(`[${newElem}]`));\n } else {\n const startIdx = firstEl.range().start.index;\n const lineStart = content.lastIndexOf(\"\\n\", startIdx - 1);\n const indent = content.slice(lineStart + 1, startIdx);\n const multiline = lineStart !== -1 && /^[ \\t]*$/.test(indent);\n const sep = multiline ? `,\\n${indent}` : \", \";\n edits.push(firstEl.replace(`${newElem}${sep}${firstEl.text()}`));\n }\n\n // Add the import unless `exportName` is already bound by some import. De-dup\n // on the binding, not the module path: an existing import from the same path\n // under a different name (e.g. `import { HelloPlugin } from \"./plugins/hello\"`)\n // must not suppress this one, or the `${exportName}()` element just added to\n // the array would reference an unimported symbol and the server won't compile.\n const importStmts = root.findAll({ rule: { kind: \"import_statement\" } });\n const hasBinding = importStmts.some((s) =>\n importBindingNames(s).has(exportName),\n );\n const importLine = `import { ${exportName} } from \"${importPath}\";`;\n const named = hasBinding ? null : namedImportsFrom(importStmts, importPath);\n if (named) {\n // Append after the last specifier, matching a multi-line list's layout.\n const specs = named.findAll({ rule: { kind: \"import_specifier\" } });\n const lastSpec = specs[specs.length - 1];\n if (!lastSpec) {\n edits.push(named.replace(`{ ${exportName} }`));\n } else {\n const startIdx = lastSpec.range().start.index;\n const lineStart = content.lastIndexOf(\"\\n\", startIdx - 1);\n const indent = content.slice(lineStart + 1, startIdx);\n const multiline = named.text().includes(\"\\n\") && /^[ \\t]*$/.test(indent);\n const sep = multiline ? `,\\n${indent}` : \", \";\n edits.push(lastSpec.replace(`${lastSpec.text()}${sep}${exportName}`));\n }\n } else if (!hasBinding && importStmts.length > 0) {\n const last = importStmts[importStmts.length - 1];\n edits.push(last.replace(`${last.text()}\\n${importLine}`));\n }\n\n let output = root.commitEdits(edits);\n if (!hasBinding && !named && importStmts.length === 0) {\n output = `${importLine}\\n${output}`;\n }\n return { status: \"wired\", output };\n}\n"],"mappings":";;;;;;;AAQA,MAAM,yBAAyB;CAC7B;CACA;CACA;CACA;CACD;AASD,SAAgB,eAAe,YAAmC;AAChE,MAAK,MAAM,aAAa,wBAAwB;EAC9C,MAAM,IAAI,KAAK,KAAK,YAAY,UAAU;AAC1C,MAAI,GAAG,WAAW,EAAE,CAAE,QAAO;;AAE/B,QAAO;;;AAIT,SAAS,iBAAiB,OAAiB,QAA+B;AACxE,MAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,SAAS,KAAK,MAAM,SAAS,EAAE,MAAM,CAAC,MAAM,GA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,MAAM,QAAQ,KAAK,WAAW,IAAI,CAAC;OACzC;GACL,MAAM,WAAW,SAAS,OAAO,CAAC,MAAM;GACxC,MAAM,YAAY,QAAQ,YAAY,MAAM,WAAW,EAAE;GACzD,MAAM,SAAS,QAAQ,MAAM,YAAY,GAAG,SAAS;GAErD,MAAM,MADY,MAAM,MAAM,CAAC,SAAS,KAAK,IAAI,WAAW,KAAK,OAAO,GAChD,MAAM,WAAW;AACzC,SAAM,KAAK,SAAS,QAAQ,GAAG,SAAS,MAAM,GAAG,MAAM,aAAa,CAAC;;YAE9D,CAAC,cAAc,YAAY,SAAS,GAAG;EAChD,MAAM,OAAO,YAAY,YAAY,SAAS;AAC9C,QAAM,KAAK,KAAK,QAAQ,GAAG,KAAK,MAAM,CAAC,IAAI,aAAa,CAAC;;CAG3D,IAAI,SAAS,KAAK,YAAY,MAAM;AACpC,KAAI,CAAC,cAAc,CAAC,SAAS,YAAY,WAAW,EAClD,UAAS,GAAG,WAAW,IAAI;AAE7B,QAAO;EAAE,QAAQ;EAAS;EAAQ"}
@@ -279,6 +279,41 @@ const PARENT_CONTEXT_CHAINS = {
279
279
  })
280
280
  }
281
281
  ],
282
+ model_service: [
283
+ {
284
+ key: "catalog",
285
+ list: () => ({
286
+ command: ["catalogs", "list"],
287
+ idField: "name",
288
+ labelField: "name"
289
+ })
290
+ },
291
+ {
292
+ key: "schema",
293
+ list: ([catalog]) => ({
294
+ command: [
295
+ "schemas",
296
+ "list",
297
+ catalog
298
+ ],
299
+ idField: "name",
300
+ labelField: "name"
301
+ })
302
+ },
303
+ {
304
+ key: "model service",
305
+ list: ([catalog, schema]) => ({
306
+ command: [
307
+ "ai-gateway",
308
+ "list-model-services",
309
+ "--parent",
310
+ `schemas/${catalog}.${schema}`
311
+ ],
312
+ idField: "name",
313
+ stripPrefix: "model-services/"
314
+ })
315
+ }
316
+ ],
282
317
  secret: [{
283
318
  key: "scope",
284
319
  list: () => ({
@@ -318,6 +353,8 @@ const PARENT_CONTEXT_CHAINS = {
318
353
  })
319
354
  }]
320
355
  };
356
+ /** Parents a drill-down opens on first; the full walk stays one pick away. */
357
+ const DEFAULT_PARENTS = { model_service: ["system", "ai"] };
321
358
  /** True when a resource type needs a parent-context drill-down to list. */
322
359
  function isParentContext(resourceType) {
323
360
  return resourceType in PARENT_CONTEXT_CHAINS;
@@ -336,9 +373,17 @@ function listParentContextStep(resourceType, stepIndex, parents, profile, runner
336
373
  choices: []
337
374
  };
338
375
  const spec = step.list(parents);
376
+ const choices = runList(spec.command, spec.idField, spec.labelField, profile, runner);
377
+ const prefix = spec.stripPrefix;
339
378
  return {
340
379
  key: step.key,
341
- choices: runList(spec.command, spec.idField, spec.labelField, profile, runner)
380
+ choices: prefix ? choices.map(({ value }) => {
381
+ const bare = value.startsWith(prefix) ? value.slice(prefix.length) : value;
382
+ return {
383
+ value: bare,
384
+ label: bare
385
+ };
386
+ }) : choices
342
387
  };
343
388
  }
344
389
  /** Number of drill-down steps for a parent-context type (0 if not one). */
@@ -359,5 +404,5 @@ function composeResourceId(resourceType, picks) {
359
404
  }
360
405
 
361
406
  //#endregion
362
- export { composeResourceId, isFlatListable, isParentContext, listParentContextStep, listWorkspaceResources, parentContextDepth };
407
+ export { DEFAULT_PARENTS, composeResourceId, isFlatListable, isParentContext, listParentContextStep, listWorkspaceResources, makeWorkspaceClient, parentContextDepth };
363
408
  //# sourceMappingURL=workspace-picker.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"workspace-picker.js","names":[],"sources":["../../../../src/cli/commands/registry/workspace-picker.ts"],"sourcesContent":["import { spawnSync } from \"node:child_process\";\n\nimport {\n createWorkspaceClient,\n type WorkspaceClient,\n} from \"../../../workspace-client\";\n\n/**\n * Lists a user's real Databricks workspace resources so `appkit add` can offer\n * a picker instead of blind free-text entry.\n *\n * Flat resource types are listed through the sanctioned `workspace-client`\n * facade's modular SDK clients.\n * Parent-context types (volume, uc_function, secret, vector_search_index) still\n * shell out to the `databricks` CLI for their drill-down. Every path fails\n * soft: any error returns an empty list and the caller drops to free-text entry.\n */\n\n/** A workspace resource choice surfaced in the picker. */\nexport interface WorkspaceChoice {\n /** Value written to the env var (the resource id/name). */\n value: string;\n /** Human label shown in the picker (name, falling back to value). */\n label: string;\n}\n\n/**\n * Per-type SDK lister: streams a resource type off the WorkspaceClient into\n * `{value,label}` choices. `list()` returns an async iterable of raw SDK\n * objects; `toChoice` maps each to a picker choice. The SDK auto-paginates, so\n * we simply iterate to completion.\n */\ninterface SdkLister {\n list: (client: WorkspaceClient) => AsyncIterable<unknown>;\n toChoice: (item: Record<string, unknown>) => WorkspaceChoice | null;\n}\n\n/** Builds a `{value,label}` from an id field and optional label field. */\nfunction choiceFrom(\n item: Record<string, unknown>,\n idField: string,\n labelField?: string,\n): WorkspaceChoice | null {\n const id = item[idField];\n if (id === undefined || id === null) return null;\n const value = String(id);\n const rawLabel = labelField ? item[labelField] : undefined;\n const label =\n typeof rawLabel === \"string\" && rawLabel.length > 0\n ? `${rawLabel} (${value})`\n : value;\n return { value, label };\n}\n\n/**\n * Follows page tokens until exhausted. The repeated-token guard avoids an\n * infinite loop if the API echoes a token back.\n */\nasync function* paginate(\n fetchPage: (\n pageToken?: string,\n ) => Promise<{ items?: unknown[]; next?: string }>,\n): AsyncIterable<unknown> {\n let pageToken: string | undefined;\n do {\n const { items, next } = await fetchPage(pageToken);\n for (const item of items ?? []) yield item;\n if (next && next === pageToken) break;\n pageToken = next;\n } while (pageToken);\n}\n\n/** listInferenceEndpoints is unpaginated; adapt its single page. */\nasync function* iterateServingEndpoints(\n client: WorkspaceClient,\n): AsyncIterable<unknown> {\n const res = await client.modelServing.listInferenceEndpoints({});\n yield* res.endpoints ?? [];\n}\n\n/** Genie listSpaces returns a single page; follow `nextPageToken`. */\nfunction iterateGenieSpaces(client: WorkspaceClient): AsyncIterable<unknown> {\n return paginate(async (pageToken) => {\n const res = await client.genie.genieListSpaces(\n pageToken ? { pageToken } : {},\n );\n return { items: res.spaces, next: res.nextPageToken };\n });\n}\n\n/** Flat, top-level listable resource types, backed by SDK services. */\nexport const SDK_LISTERS: Record<string, SdkLister> = {\n sql_warehouse: {\n list: (c) => c.warehouses.listWarehousesIter({}),\n toChoice: (i) => choiceFrom(i, \"id\", \"name\"),\n },\n job: {\n list: (c) => c.jobs.listJobsIter({}),\n // job name lives under settings.name; id is top-level jobId (a bigint)\n toChoice: (i) => {\n const settings = i.settings as { name?: string } | undefined;\n return choiceFrom({ ...i, name: settings?.name }, \"jobId\", \"name\");\n },\n },\n serving_endpoint: {\n list: iterateServingEndpoints,\n toChoice: (i) => choiceFrom(i, \"name\", \"name\"),\n },\n uc_connection: {\n list: (c) => c.connections.listConnectionsIter({}),\n toChoice: (i) => choiceFrom(i, \"name\", \"fullName\"),\n },\n database: {\n list: (c) => c.database.listDatabaseInstancesIter({}),\n toChoice: (i) => choiceFrom(i, \"name\", \"name\"),\n },\n genie_space: {\n list: iterateGenieSpaces,\n toChoice: (i) => choiceFrom(i, \"spaceId\", \"title\"),\n },\n experiment: {\n list: (c) => c.experiments.listExperimentsIter({}),\n toChoice: (i) => choiceFrom(i, \"experimentId\", \"name\"),\n },\n app: {\n list: (c) => c.apps.listAppsIter({}),\n toChoice: (i) => choiceFrom(i, \"name\", \"name\"),\n },\n};\n\n/** True when a resource type can be listed flat (no parent context). */\nexport function isFlatListable(resourceType: string): boolean {\n return resourceType in SDK_LISTERS;\n}\n\n/**\n * Constructs a workspace client for the given profile (or default resolution),\n * via the sanctioned `workspace-client` facade.\n */\nexport function makeWorkspaceClient(profile?: string): WorkspaceClient {\n return createWorkspaceClient(profile ? { profile } : {});\n}\n\n/**\n * Max resources fetched for the picker. `list()` paginates lazily, so on a large\n * workspace (5000+ warehouses) breaking out at the cap stops pagination early;\n * the picker's \"Enter manually\" option covers anything beyond it.\n */\nexport const MAX_PICKER_RESULTS = 200;\n\n/** A listing result plus whether it was truncated at the fetch cap. */\nexport interface WorkspaceListing {\n choices: WorkspaceChoice[];\n truncated: boolean;\n /** Short reason the listing failed (auth/config/network), if it did — lets\n * the caller distinguish a real error from a genuinely empty workspace. */\n error?: string;\n}\n\n/** First line of an error, capped, for a user-facing one-liner. */\nfunction shortErrorMessage(err: unknown): string {\n const msg = err instanceof Error ? err.message : String(err);\n return msg.split(\"\\n\")[0].trim().slice(0, 200);\n}\n\n/**\n * Lists workspace resources of a flat-listable type via the SDK, stopping at\n * MAX_PICKER_RESULTS so pagination doesn't drain a huge workspace. Returns an\n * empty listing on any failure (unknown type, auth/config error, network) so\n * the caller can fall back to free-text entry. `clientFactory` is injectable\n * for tests.\n */\nexport async function listWorkspaceResources(\n resourceType: string,\n profile?: string,\n clientFactory: (profile?: string) => WorkspaceClient = makeWorkspaceClient,\n): Promise<WorkspaceListing> {\n const lister = SDK_LISTERS[resourceType];\n if (!lister) return { choices: [], truncated: false };\n try {\n const client = clientFactory(profile);\n const choices: WorkspaceChoice[] = [];\n let truncated = false;\n for await (const item of lister.list(client)) {\n if (typeof item !== \"object\" || item === null) continue;\n const choice = lister.toChoice(item as Record<string, unknown>);\n if (!choice) continue;\n choices.push(choice);\n if (choices.length >= MAX_PICKER_RESULTS) {\n // Stop iterating — halts the async iterator, so no further pages fetch.\n truncated = true;\n break;\n }\n }\n return { choices, truncated };\n } catch (err) {\n // Don't swallow silently: return the reason so the caller can tell the user\n // the picker fell back because listing failed (typically auth/profile), not\n // because the workspace has none of this resource.\n return { choices: [], truncated: false, error: shortErrorMessage(err) };\n }\n}\n\n/** Runs a databricks CLI subcommand returning JSON; injectable for tests. */\nexport type CliRunner = (args: string[]) => {\n status: number | null;\n stdout: string;\n};\n\nconst defaultRunner: CliRunner = (args) => {\n // Parent-context lists can be large; raise maxBuffer well above the 1MB\n // default so a big JSON response isn't truncated into \"no resources found\".\n const res = spawnSync(\"databricks\", args, {\n encoding: \"utf-8\",\n maxBuffer: 64 * 1024 * 1024,\n });\n return { status: res.status, stdout: res.stdout ?? \"\" };\n};\n\n/**\n * Extracts `{value,label}` choices from a parsed CLI list response. The CLI\n * returns either a bare array or an object wrapping one; we scan for the first\n * array of objects. Items missing the id field are skipped.\n */\nexport function toChoices(\n parsed: unknown,\n idField: string,\n labelField?: string,\n): WorkspaceChoice[] {\n const arr = firstArray(parsed);\n const choices: WorkspaceChoice[] = [];\n for (const item of arr) {\n if (typeof item !== \"object\" || item === null) continue;\n const choice = choiceFrom(\n item as Record<string, unknown>,\n idField,\n labelField,\n );\n if (choice) choices.push(choice);\n }\n return choices;\n}\n\n/** Finds the first array in a CLI response (bare array or single wrapper key). */\nfunction firstArray(parsed: unknown): unknown[] {\n if (Array.isArray(parsed)) return parsed;\n if (parsed && typeof parsed === \"object\") {\n for (const v of Object.values(parsed)) {\n if (Array.isArray(v)) return v;\n }\n }\n return [];\n}\n\n/**\n * Runs a `databricks … list -o json` command and returns parsed choices, or\n * [] on any failure (CLI missing/errored, empty, non-JSON). `command` is the\n * argv after `databricks`; `-o json` and `-p <profile>` are appended.\n * Used for the parent-context drill-down (catalogs/schemas/scopes/endpoints).\n */\nexport function runList(\n command: string[],\n idField: string,\n labelField: string | undefined,\n profile: string | undefined,\n runner: CliRunner = defaultRunner,\n): WorkspaceChoice[] {\n const args = [...command, \"-o\", \"json\"];\n if (profile) args.push(\"-p\", profile);\n\n let result: { status: number | null; stdout: string };\n try {\n result = runner(args);\n } catch {\n return [];\n }\n if (result.status !== 0 || !result.stdout.trim()) return [];\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(result.stdout);\n } catch {\n return [];\n }\n return toChoices(parsed, idField, labelField);\n}\n\n/**\n * A drill-down step for a parent-context resource type. `list(parents)` builds\n * the CLI argv given the values picked in prior steps (e.g. [catalog] → schema\n * list command). `key` labels the step for prompts.\n */\nexport interface ParentContextStep {\n key: string;\n list: (parents: string[]) => {\n command: string[];\n idField: string;\n labelField?: string;\n };\n}\n\n/**\n * Drill-down chains for parent-context resource types. Each ends by listing\n * the resource itself; earlier steps list the parents to pick first.\n * Positional-arg CLI gotcha: `databricks schemas list <CATALOG>` etc. take the\n * parent as a positional, not a flag.\n */\nexport const PARENT_CONTEXT_CHAINS: Record<string, ParentContextStep[]> = {\n volume: [\n {\n key: \"catalog\",\n list: () => ({\n command: [\"catalogs\", \"list\"],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"schema\",\n list: ([catalog]) => ({\n command: [\"schemas\", \"list\", catalog],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"volume\",\n list: ([catalog, schema]) => ({\n command: [\"volumes\", \"list\", catalog, schema],\n idField: \"full_name\",\n labelField: \"name\",\n }),\n },\n ],\n uc_function: [\n {\n key: \"catalog\",\n list: () => ({\n command: [\"catalogs\", \"list\"],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"schema\",\n list: ([catalog]) => ({\n command: [\"schemas\", \"list\", catalog],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"function\",\n list: ([catalog, schema]) => ({\n command: [\"functions\", \"list\", catalog, schema],\n idField: \"full_name\",\n labelField: \"name\",\n }),\n },\n ],\n secret: [\n {\n key: \"scope\",\n list: () => ({\n command: [\"secrets\", \"list-scopes\"],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"key\",\n list: ([scope]) => ({\n command: [\"secrets\", \"list-secrets\", scope],\n idField: \"key\",\n labelField: \"key\",\n }),\n },\n ],\n vector_search_index: [\n {\n key: \"endpoint\",\n list: () => ({\n command: [\"vector-search-endpoints\", \"list-endpoints\"],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"index\",\n list: ([endpoint]) => ({\n command: [\"vector-search-indexes\", \"list-indexes\", endpoint],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n ],\n};\n\n/** True when a resource type needs a parent-context drill-down to list. */\nexport function isParentContext(resourceType: string): boolean {\n return resourceType in PARENT_CONTEXT_CHAINS;\n}\n\n/** One resolved step of a drill-down: the choices to present at this level. */\nexport interface DrillStep {\n key: string;\n choices: WorkspaceChoice[];\n}\n\n/**\n * Lists the choices for a single drill-down step given the values picked so\n * far. Returns [] on failure. The caller drives the interaction (present\n * `choices`, collect a pick, call again with it appended to `parents`).\n */\nexport function listParentContextStep(\n resourceType: string,\n stepIndex: number,\n parents: string[],\n profile?: string,\n runner: CliRunner = defaultRunner,\n): DrillStep | null {\n const chain = PARENT_CONTEXT_CHAINS[resourceType];\n if (!chain || stepIndex >= chain.length) return null;\n const step = chain[stepIndex];\n // Prior picks become positional CLI args; a value starting with `-` would be\n // parsed as a flag, so refuse it (empty step → free-text fallback). Real\n // catalog/schema/scope/endpoint names never start with `-`.\n if (parents.some((p) => p.startsWith(\"-\"))) {\n return { key: step.key, choices: [] };\n }\n const spec = step.list(parents);\n return {\n key: step.key,\n choices: runList(\n spec.command,\n spec.idField,\n spec.labelField,\n profile,\n runner,\n ),\n };\n}\n\n/** Number of drill-down steps for a parent-context type (0 if not one). */\nexport function parentContextDepth(resourceType: string): number {\n return PARENT_CONTEXT_CHAINS[resourceType]?.length ?? 0;\n}\n\n/**\n * Builds the final resource identifier from the values picked across a\n * drill-down. Most types end on a self-qualified id (volume/uc_function list\n * `full_name`; a vector-search index name is already catalog.schema-qualified),\n * so the last pick is the whole answer. A `secret` is addressed by both its\n * scope and key (`scope/key`) — returning only the key drops the scope and\n * yields a value that can't locate the secret — so its picks are joined.\n */\nexport function composeResourceId(\n resourceType: string,\n picks: string[],\n): string {\n if (resourceType === \"secret\") return picks.join(\"/\");\n return picks[picks.length - 1];\n}\n"],"mappings":";;;;;AAsCA,SAAS,WACP,MACA,SACA,YACwB;CACxB,MAAM,KAAK,KAAK;AAChB,KAAI,OAAO,UAAa,OAAO,KAAM,QAAO;CAC5C,MAAM,QAAQ,OAAO,GAAG;CACxB,MAAM,WAAW,aAAa,KAAK,cAAc;AAKjD,QAAO;EAAE;EAAO,OAHd,OAAO,aAAa,YAAY,SAAS,SAAS,IAC9C,GAAG,SAAS,IAAI,MAAM,KACtB;EACiB;;;;;;AAOzB,gBAAgB,SACd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,SACA,OACD;EACF;;;AAIH,SAAgB,mBAAmB,cAA8B;AAC/D,QAAO,sBAAsB,eAAe,UAAU;;;;;;;;;;AAWxD,SAAgB,kBACd,cACA,OACQ;AACR,KAAI,iBAAiB,SAAU,QAAO,MAAM,KAAK,IAAI;AACrD,QAAO,MAAM,MAAM,SAAS"}
1
+ {"version":3,"file":"workspace-picker.js","names":[],"sources":["../../../../src/cli/commands/registry/workspace-picker.ts"],"sourcesContent":["import { spawnSync } from \"node:child_process\";\n\nimport {\n createWorkspaceClient,\n type WorkspaceClient,\n} from \"../../../workspace-client\";\n\n/**\n * Lists a user's real Databricks workspace resources so `appkit add` can offer\n * a picker instead of blind free-text entry.\n *\n * Flat resource types are listed through the sanctioned `workspace-client`\n * facade's modular SDK clients.\n * Parent-context types (volume, uc_function, secret, vector_search_index) still\n * shell out to the `databricks` CLI for their drill-down. Every path fails\n * soft: any error returns an empty list and the caller drops to free-text entry.\n */\n\n/** A workspace resource choice surfaced in the picker. */\nexport interface WorkspaceChoice {\n /** Value written to the env var (the resource id/name). */\n value: string;\n /** Human label shown in the picker (name, falling back to value). */\n label: string;\n}\n\n/**\n * Per-type SDK lister: streams a resource type off the WorkspaceClient into\n * `{value,label}` choices. `list()` returns an async iterable of raw SDK\n * objects; `toChoice` maps each to a picker choice. The SDK auto-paginates, so\n * we simply iterate to completion.\n */\ninterface SdkLister {\n list: (client: WorkspaceClient) => AsyncIterable<unknown>;\n toChoice: (item: Record<string, unknown>) => WorkspaceChoice | null;\n}\n\n/** Builds a `{value,label}` from an id field and optional label field. */\nfunction choiceFrom(\n item: Record<string, unknown>,\n idField: string,\n labelField?: string,\n): WorkspaceChoice | null {\n const id = item[idField];\n if (id === undefined || id === null) return null;\n const value = String(id);\n const rawLabel = labelField ? item[labelField] : undefined;\n const label =\n typeof rawLabel === \"string\" && rawLabel.length > 0\n ? `${rawLabel} (${value})`\n : value;\n return { value, label };\n}\n\n/**\n * Follows page tokens until exhausted. The repeated-token guard avoids an\n * infinite loop if the API echoes a token back.\n */\nasync function* paginate(\n fetchPage: (\n pageToken?: string,\n ) => Promise<{ items?: unknown[]; next?: string }>,\n): AsyncIterable<unknown> {\n let pageToken: string | undefined;\n do {\n const { items, next } = await fetchPage(pageToken);\n for (const item of items ?? []) yield item;\n if (next && next === pageToken) break;\n pageToken = next;\n } while (pageToken);\n}\n\n/** listInferenceEndpoints is unpaginated; adapt its single page. */\nasync function* iterateServingEndpoints(\n client: WorkspaceClient,\n): AsyncIterable<unknown> {\n const res = await client.modelServing.listInferenceEndpoints({});\n yield* res.endpoints ?? [];\n}\n\n/** Genie listSpaces returns a single page; follow `nextPageToken`. */\nfunction iterateGenieSpaces(client: WorkspaceClient): AsyncIterable<unknown> {\n return paginate(async (pageToken) => {\n const res = await client.genie.genieListSpaces(\n pageToken ? { pageToken } : {},\n );\n return { items: res.spaces, next: res.nextPageToken };\n });\n}\n\n/** Flat, top-level listable resource types, backed by SDK services. */\nexport const SDK_LISTERS: Record<string, SdkLister> = {\n sql_warehouse: {\n list: (c) => c.warehouses.listWarehousesIter({}),\n toChoice: (i) => choiceFrom(i, \"id\", \"name\"),\n },\n job: {\n list: (c) => c.jobs.listJobsIter({}),\n // job name lives under settings.name; id is top-level jobId (a bigint)\n toChoice: (i) => {\n const settings = i.settings as { name?: string } | undefined;\n return choiceFrom({ ...i, name: settings?.name }, \"jobId\", \"name\");\n },\n },\n serving_endpoint: {\n list: iterateServingEndpoints,\n toChoice: (i) => choiceFrom(i, \"name\", \"name\"),\n },\n uc_connection: {\n list: (c) => c.connections.listConnectionsIter({}),\n toChoice: (i) => choiceFrom(i, \"name\", \"fullName\"),\n },\n database: {\n list: (c) => c.database.listDatabaseInstancesIter({}),\n toChoice: (i) => choiceFrom(i, \"name\", \"name\"),\n },\n genie_space: {\n list: iterateGenieSpaces,\n toChoice: (i) => choiceFrom(i, \"spaceId\", \"title\"),\n },\n experiment: {\n list: (c) => c.experiments.listExperimentsIter({}),\n toChoice: (i) => choiceFrom(i, \"experimentId\", \"name\"),\n },\n app: {\n list: (c) => c.apps.listAppsIter({}),\n toChoice: (i) => choiceFrom(i, \"name\", \"name\"),\n },\n};\n\n/** True when a resource type can be listed flat (no parent context). */\nexport function isFlatListable(resourceType: string): boolean {\n return resourceType in SDK_LISTERS;\n}\n\n/**\n * Constructs a workspace client for the given profile (or default resolution),\n * via the sanctioned `workspace-client` facade.\n */\nexport function makeWorkspaceClient(profile?: string): WorkspaceClient {\n return createWorkspaceClient(profile ? { profile } : {});\n}\n\n/**\n * Max resources fetched for the picker. `list()` paginates lazily, so on a large\n * workspace (5000+ warehouses) breaking out at the cap stops pagination early;\n * the picker's \"Enter manually\" option covers anything beyond it.\n */\nexport const MAX_PICKER_RESULTS = 200;\n\n/** A listing result plus whether it was truncated at the fetch cap. */\nexport interface WorkspaceListing {\n choices: WorkspaceChoice[];\n truncated: boolean;\n /** Short reason the listing failed (auth/config/network), if it did — lets\n * the caller distinguish a real error from a genuinely empty workspace. */\n error?: string;\n}\n\n/** First line of an error, capped, for a user-facing one-liner. */\nfunction shortErrorMessage(err: unknown): string {\n const msg = err instanceof Error ? err.message : String(err);\n return msg.split(\"\\n\")[0].trim().slice(0, 200);\n}\n\n/**\n * Lists workspace resources of a flat-listable type via the SDK, stopping at\n * MAX_PICKER_RESULTS so pagination doesn't drain a huge workspace. Returns an\n * empty listing on any failure (unknown type, auth/config error, network) so\n * the caller can fall back to free-text entry. `clientFactory` is injectable\n * for tests.\n */\nexport async function listWorkspaceResources(\n resourceType: string,\n profile?: string,\n clientFactory: (profile?: string) => WorkspaceClient = makeWorkspaceClient,\n): Promise<WorkspaceListing> {\n const lister = SDK_LISTERS[resourceType];\n if (!lister) return { choices: [], truncated: false };\n try {\n const client = clientFactory(profile);\n const choices: WorkspaceChoice[] = [];\n let truncated = false;\n for await (const item of lister.list(client)) {\n if (typeof item !== \"object\" || item === null) continue;\n const choice = lister.toChoice(item as Record<string, unknown>);\n if (!choice) continue;\n choices.push(choice);\n if (choices.length >= MAX_PICKER_RESULTS) {\n // Stop iterating — halts the async iterator, so no further pages fetch.\n truncated = true;\n break;\n }\n }\n return { choices, truncated };\n } catch (err) {\n // Don't swallow silently: return the reason so the caller can tell the user\n // the picker fell back because listing failed (typically auth/profile), not\n // because the workspace has none of this resource.\n return { choices: [], truncated: false, error: shortErrorMessage(err) };\n }\n}\n\n/** Runs a databricks CLI subcommand returning JSON; injectable for tests. */\nexport type CliRunner = (args: string[]) => {\n status: number | null;\n stdout: string;\n};\n\nconst defaultRunner: CliRunner = (args) => {\n // Parent-context lists can be large; raise maxBuffer well above the 1MB\n // default so a big JSON response isn't truncated into \"no resources found\".\n const res = spawnSync(\"databricks\", args, {\n encoding: \"utf-8\",\n maxBuffer: 64 * 1024 * 1024,\n });\n return { status: res.status, stdout: res.stdout ?? \"\" };\n};\n\n/**\n * Extracts `{value,label}` choices from a parsed CLI list response. The CLI\n * returns either a bare array or an object wrapping one; we scan for the first\n * array of objects. Items missing the id field are skipped.\n */\nexport function toChoices(\n parsed: unknown,\n idField: string,\n labelField?: string,\n): WorkspaceChoice[] {\n const arr = firstArray(parsed);\n const choices: WorkspaceChoice[] = [];\n for (const item of arr) {\n if (typeof item !== \"object\" || item === null) continue;\n const choice = choiceFrom(\n item as Record<string, unknown>,\n idField,\n labelField,\n );\n if (choice) choices.push(choice);\n }\n return choices;\n}\n\n/** Finds the first array in a CLI response (bare array or single wrapper key). */\nfunction firstArray(parsed: unknown): unknown[] {\n if (Array.isArray(parsed)) return parsed;\n if (parsed && typeof parsed === \"object\") {\n for (const v of Object.values(parsed)) {\n if (Array.isArray(v)) return v;\n }\n }\n return [];\n}\n\n/**\n * Runs a `databricks … list -o json` command and returns parsed choices, or\n * [] on any failure (CLI missing/errored, empty, non-JSON). `command` is the\n * argv after `databricks`; `-o json` and `-p <profile>` are appended.\n * Used for the parent-context drill-down (catalogs/schemas/scopes/endpoints).\n */\nexport function runList(\n command: string[],\n idField: string,\n labelField: string | undefined,\n profile: string | undefined,\n runner: CliRunner = defaultRunner,\n): WorkspaceChoice[] {\n const args = [...command, \"-o\", \"json\"];\n if (profile) args.push(\"-p\", profile);\n\n let result: { status: number | null; stdout: string };\n try {\n result = runner(args);\n } catch {\n return [];\n }\n if (result.status !== 0 || !result.stdout.trim()) return [];\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(result.stdout);\n } catch {\n return [];\n }\n return toChoices(parsed, idField, labelField);\n}\n\n/**\n * A drill-down step for a parent-context resource type. `list(parents)` builds\n * the CLI argv given the values picked in prior steps (e.g. [catalog] → schema\n * list command). `key` labels the step for prompts.\n */\nexport interface ParentContextStep {\n key: string;\n list: (parents: string[]) => {\n command: string[];\n idField: string;\n labelField?: string;\n /** Prefix stripped from each listed id (label and value). */\n stripPrefix?: string;\n };\n}\n\n/**\n * Drill-down chains for parent-context resource types. Each ends by listing\n * the resource itself; earlier steps list the parents to pick first.\n * Positional-arg CLI gotcha: `databricks schemas list <CATALOG>` etc. take the\n * parent as a positional, not a flag.\n */\nexport const PARENT_CONTEXT_CHAINS: Record<string, ParentContextStep[]> = {\n volume: [\n {\n key: \"catalog\",\n list: () => ({\n command: [\"catalogs\", \"list\"],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"schema\",\n list: ([catalog]) => ({\n command: [\"schemas\", \"list\", catalog],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"volume\",\n list: ([catalog, schema]) => ({\n command: [\"volumes\", \"list\", catalog, schema],\n idField: \"full_name\",\n labelField: \"name\",\n }),\n },\n ],\n uc_function: [\n {\n key: \"catalog\",\n list: () => ({\n command: [\"catalogs\", \"list\"],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"schema\",\n list: ([catalog]) => ({\n command: [\"schemas\", \"list\", catalog],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"function\",\n list: ([catalog, schema]) => ({\n command: [\"functions\", \"list\", catalog, schema],\n idField: \"full_name\",\n labelField: \"name\",\n }),\n },\n ],\n model_service: [\n {\n key: \"catalog\",\n list: () => ({\n command: [\"catalogs\", \"list\"],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"schema\",\n list: ([catalog]) => ({\n command: [\"schemas\", \"list\", catalog],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"model service\",\n list: ([catalog, schema]) => ({\n command: [\n \"ai-gateway\",\n \"list-model-services\",\n \"--parent\",\n `schemas/${catalog}.${schema}`,\n ],\n idField: \"name\",\n // Listed as model-services/{catalog}.{schema}.{name}; apps bind the full name.\n stripPrefix: \"model-services/\",\n }),\n },\n ],\n secret: [\n {\n key: \"scope\",\n list: () => ({\n command: [\"secrets\", \"list-scopes\"],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"key\",\n list: ([scope]) => ({\n command: [\"secrets\", \"list-secrets\", scope],\n idField: \"key\",\n labelField: \"key\",\n }),\n },\n ],\n vector_search_index: [\n {\n key: \"endpoint\",\n list: () => ({\n command: [\"vector-search-endpoints\", \"list-endpoints\"],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"index\",\n list: ([endpoint]) => ({\n command: [\"vector-search-indexes\", \"list-indexes\", endpoint],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n ],\n};\n\n/** Parents a drill-down opens on first; the full walk stays one pick away. */\nexport const DEFAULT_PARENTS: Record<string, string[]> = {\n model_service: [\"system\", \"ai\"],\n};\n\n/** True when a resource type needs a parent-context drill-down to list. */\nexport function isParentContext(resourceType: string): boolean {\n return resourceType in PARENT_CONTEXT_CHAINS;\n}\n\n/** One resolved step of a drill-down: the choices to present at this level. */\nexport interface DrillStep {\n key: string;\n choices: WorkspaceChoice[];\n}\n\n/**\n * Lists the choices for a single drill-down step given the values picked so\n * far. Returns [] on failure. The caller drives the interaction (present\n * `choices`, collect a pick, call again with it appended to `parents`).\n */\nexport function listParentContextStep(\n resourceType: string,\n stepIndex: number,\n parents: string[],\n profile?: string,\n runner: CliRunner = defaultRunner,\n): DrillStep | null {\n const chain = PARENT_CONTEXT_CHAINS[resourceType];\n if (!chain || stepIndex >= chain.length) return null;\n const step = chain[stepIndex];\n // Prior picks become positional CLI args; a value starting with `-` would be\n // parsed as a flag, so refuse it (empty step → free-text fallback). Real\n // catalog/schema/scope/endpoint names never start with `-`.\n if (parents.some((p) => p.startsWith(\"-\"))) {\n return { key: step.key, choices: [] };\n }\n const spec = step.list(parents);\n const choices = runList(\n spec.command,\n spec.idField,\n spec.labelField,\n profile,\n runner,\n );\n const prefix = spec.stripPrefix;\n return {\n key: step.key,\n choices: prefix\n ? choices.map(({ value }) => {\n const bare = value.startsWith(prefix)\n ? value.slice(prefix.length)\n : value;\n return { value: bare, label: bare };\n })\n : choices,\n };\n}\n\n/** Number of drill-down steps for a parent-context type (0 if not one). */\nexport function parentContextDepth(resourceType: string): number {\n return PARENT_CONTEXT_CHAINS[resourceType]?.length ?? 0;\n}\n\n/**\n * Builds the final resource identifier from the values picked across a\n * drill-down. Most types end on a self-qualified id (volume/uc_function list\n * `full_name`; a vector-search index name is already catalog.schema-qualified),\n * so the last pick is the whole answer. A `secret` is addressed by both its\n * scope and key (`scope/key`) — returning only the key drops the scope and\n * yields a value that can't locate the secret — so its picks are joined.\n */\nexport function composeResourceId(\n resourceType: string,\n picks: string[],\n): string {\n if (resourceType === \"secret\") return picks.join(\"/\");\n return picks[picks.length - 1];\n}\n"],"mappings":";;;;;AAsCA,SAAS,WACP,MACA,SACA,YACwB;CACxB,MAAM,KAAK,KAAK;AAChB,KAAI,OAAO,UAAa,OAAO,KAAM,QAAO;CAC5C,MAAM,QAAQ,OAAO,GAAG;CACxB,MAAM,WAAW,aAAa,KAAK,cAAc;AAKjD,QAAO;EAAE;EAAO,OAHd,OAAO,aAAa,YAAY,SAAS,SAAS,IAC9C,GAAG,SAAS,IAAI,MAAM,KACtB;EACiB;;;;;;AAOzB,gBAAgB,SACd,WAGwB;CACxB,IAAI;AACJ,IAAG;EACD,MAAM,E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ACd,cACA,WACA,SACA,SACA,SAAoB,eACF;CAClB,MAAM,QAAQ,sBAAsB;AACpC,KAAI,CAAC,SAAS,aAAa,MAAM,OAAQ,QAAO;CAChD,MAAM,OAAO,MAAM;AAInB,KAAI,QAAQ,MAAM,MAAM,EAAE,WAAW,IAAI,CAAC,CACxC,QAAO;EAAE,KAAK,KAAK;EAAK,SAAS,EAAE;EAAE;CAEvC,MAAM,OAAO,KAAK,KAAK,QAAQ;CAC/B,MAAM,UAAU,QACd,KAAK,SACL,KAAK,SACL,KAAK,YACL,SACA,OACD;CACD,MAAM,SAAS,KAAK;AACpB,QAAO;EACL,KAAK,KAAK;EACV,SAAS,SACL,QAAQ,KAAK,EAAE,YAAY;GACzB,MAAM,OAAO,MAAM,WAAW,OAAO,GACjC,MAAM,MAAM,OAAO,OAAO,GAC1B;AACJ,UAAO;IAAE,OAAO;IAAM,OAAO;IAAM;IACnC,GACF;EACL;;;AAIH,SAAgB,mBAAmB,cAA8B;AAC/D,QAAO,sBAAsB,eAAe,UAAU;;;;;;;;;;AAWxD,SAAgB,kBACd,cACA,OACQ;AACR,KAAI,iBAAiB,SAAU,QAAO,MAAM,KAAK,IAAI;AACrD,QAAO,MAAM,MAAM,SAAS"}
@@ -1 +1 @@
1
- {"version":3,"file":"deploy-config.js","names":[],"sources":["../../src/cli/deploy-config.ts"],"sourcesContent":["/**\n * Single source for the `app.yaml` + `databricks.yml` app-resource binding\n * contract, so the registry writer (`config-writer.ts`) and the doctor reader\n * (`bundle.ts`/`checks-wiring.ts`) on opposite ends of it can't drift apart.\n */\n\n/** Canonical Databricks bundle config file name. */\nexport const DATABRICKS_YML_FILE = \"databricks.yml\";\n\n/** Canonical Databricks Apps runtime config file name. */\nexport const APP_YAML_FILE = \"app.yaml\";\n\n/** An `app.yaml` env entry: `- name: <env>`, `valueFrom: <binding name>`. */\nexport interface AppYamlEnvEntry {\n name: string;\n valueFrom: string;\n}\n\n/**\n * A `databricks.yml` app-resource binding under `resources.apps.<app>.resources[]`,\n * serialized as `{ name, <type>: { ...fields, permission? } }` (see {@link bindingToNode}).\n */\nexport interface ResourceBinding {\n /** Binding name — the `valueFrom` join key (equals the resourceKey). */\n name: string;\n /** Resource type key, e.g. `sql_warehouse` / `postgres`. */\n type: string;\n permission?: string;\n /** Binding fields, typically `${var.<variable>}` references. */\n fields: Record<string, string>;\n}\n\n/**\n * Encodes a binding into its `databricks.yml` node: the type is the single\n * non-`name` object key. Inverse of {@link bindingTypeOf}.\n */\nexport function bindingToNode(\n binding: ResourceBinding,\n): Record<string, unknown> {\n const inner: Record<string, unknown> = { ...binding.fields };\n if (binding.permission) inner.permission = binding.permission;\n return { name: binding.name, [binding.type]: inner };\n}\n\n/**\n * Reads the type back out of a `databricks.yml` binding node — the single\n * non-`name` object-valued property; undefined if absent. See {@link bindingToNode}.\n */\nexport function bindingTypeOf(\n block: Record<string, unknown>,\n): string | undefined {\n for (const [k, v] of Object.entries(block)) {\n if (k === \"name\") continue;\n if (v && typeof v === \"object\") return k;\n }\n return undefined;\n}\n"],"mappings":";;;;;;;AAOA,MAAa,sBAAsB;;AAGnC,MAAa,gBAAgB;;;;;AA0B7B,SAAgB,cACd,SACyB;CACzB,MAAM,QAAiC,EAAE,GAAG,QAAQ,QAAQ;AAC5D,KAAI,QAAQ,WAAY,OAAM,aAAa,QAAQ;AACnD,QAAO;EAAE,MAAM,QAAQ;GAAO,QAAQ,OAAO;EAAO;;;;;;AAOtD,SAAgB,cACd,OACoB;AACpB,MAAK,MAAM,CAAC,GAAG,MAAM,OAAO,QAAQ,MAAM,EAAE;AAC1C,MAAI,MAAM,OAAQ;AAClB,MAAI,KAAK,OAAO,MAAM,SAAU,QAAO"}
1
+ {"version":3,"file":"deploy-config.js","names":[],"sources":["../../src/cli/deploy-config.ts"],"sourcesContent":["/**\n * Single source for the `app.yaml` + `databricks.yml` app-resource binding\n * contract, so the registry writer (`config-writer.ts`) and the doctor reader\n * (`bundle.ts`/`checks-wiring.ts`) on opposite ends of it can't drift apart.\n */\n\n/** Canonical Databricks bundle config file name. */\nexport const DATABRICKS_YML_FILE = \"databricks.yml\";\n\n/** Canonical Databricks Apps runtime config file name. */\nexport const APP_YAML_FILE = \"app.yaml\";\n\n/** An `app.yaml` env entry: `valueFrom` a binding, or a literal `value` (OBO-only resources). */\nexport type AppYamlEnvEntry =\n | { name: string; valueFrom: string }\n | { name: string; value: string };\n\n/**\n * A `databricks.yml` app-resource binding under `resources.apps.<app>.resources[]`,\n * serialized as `{ name, <type>: { ...fields, permission? } }` (see {@link bindingToNode}).\n */\nexport interface ResourceBinding {\n /** Binding name — the `valueFrom` join key (equals the resourceKey). */\n name: string;\n /** Resource type key, e.g. `sql_warehouse` / `postgres`. */\n type: string;\n permission?: string;\n /** Binding fields, typically `${var.<variable>}` references. */\n fields: Record<string, string>;\n}\n\n/**\n * Encodes a binding into its `databricks.yml` node: the type is the single\n * non-`name` object key. Inverse of {@link bindingTypeOf}.\n */\nexport function bindingToNode(\n binding: ResourceBinding,\n): Record<string, unknown> {\n const inner: Record<string, unknown> = { ...binding.fields };\n if (binding.permission) inner.permission = binding.permission;\n return { name: binding.name, [binding.type]: inner };\n}\n\n/**\n * Reads the type back out of a `databricks.yml` binding node — the single\n * non-`name` object-valued property; undefined if absent. See {@link bindingToNode}.\n */\nexport function bindingTypeOf(\n block: Record<string, unknown>,\n): string | undefined {\n for (const [k, v] of Object.entries(block)) {\n if (k === \"name\") continue;\n if (v && typeof v === \"object\") return k;\n }\n return undefined;\n}\n"],"mappings":";;;;;;;AAOA,MAAa,sBAAsB;;AAGnC,MAAa,gBAAgB;;;;;AAyB7B,SAAgB,cACd,SACyB;CACzB,MAAM,QAAiC,EAAE,GAAG,QAAQ,QAAQ;AAC5D,KAAI,QAAQ,WAAY,OAAM,aAAa,QAAQ;AACnD,QAAO;EAAE,MAAM,QAAQ;GAAO,QAAQ,OAAO;EAAO;;;;;;AAOtD,SAAgB,cACd,OACoB;AACpB,MAAK,MAAM,CAAC,GAAG,MAAM,OAAO,QAAQ,MAAM,EAAE;AAC1C,MAAI,MAAM,OAAQ;AAClB,MAAI,KAAK,OAAO,MAAM,SAAU,QAAO"}
package/dist/cli/index.js CHANGED
@@ -5,8 +5,8 @@ import { docsCommand } from "./commands/docs.js";
5
5
  import { doctorCommand } from "./commands/doctor/index.js";
6
6
  import { generateTypesCommand } from "./commands/generate-types.js";
7
7
  import { lintCommand } from "./commands/lint.js";
8
- import { pluginCommand } from "./commands/plugin/index.js";
9
8
  import { addCommand } from "./commands/registry/add.js";
9
+ import { pluginCommand } from "./commands/plugin/index.js";
10
10
  import { registryCommand } from "./commands/registry/index.js";
11
11
  import { setupCommand } from "./commands/setup.js";
12
12
  import "dotenv/config";
@@ -13,4 +13,6 @@ import { DatabaseRowShape, DatabaseShape, UseDatabaseReadOptions, UseDatabaseRea
13
13
  import { UseDatabaseListOptions, UseDatabaseListResult, useDatabaseList } from "./hooks/use-database-list.js";
14
14
  import { UseDatabaseRecordOptions, UseDatabaseRecordResult, useDatabaseRecord } from "./hooks/use-database-record.js";
15
15
  import { UseDatabaseUpdateOptions, UseDatabaseUpdateResult, useDatabaseUpdate } from "./hooks/use-database-update.js";
16
- export { type AiSearchClientConfig, type AiSearchIndexSummary, type AiSearchQueryType, type AiSearchRequest, type AiSearchResponse, type AiSearchResult, DatabaseApiError, type DatabaseApiErrorCode, type DatabaseEntity, type DatabaseErrorDetail, type DatabaseId, type DatabaseInsert, type DatabaseInvalidation, type DatabaseKeyedEntity, type DatabaseListPage, type DatabaseListParams, type DatabaseListRow, type DatabaseRecordParams, type DatabaseRecordRow, type DatabaseRow, type DatabaseRowShape, type DatabaseShape, type DatabaseUpdate, type UseAiSearchQueryOptions, type UseAiSearchQueryResult, type UseDatabaseCreateOptions, type UseDatabaseCreateResult, type UseDatabaseDeleteOptions, type UseDatabaseDeleteResult, type UseDatabaseListOptions, type UseDatabaseListResult, type UseDatabaseReadOptions, type UseDatabaseReadResult, type UseDatabaseRecordOptions, type UseDatabaseRecordResult, type UseDatabaseUpdateOptions, type UseDatabaseUpdateResult, type UseDatabaseWriteOptions, type UseDatabaseWriteState, invalidateDatabaseReads, serialized, useAiSearchQuery, useDatabaseCreate, useDatabaseDelete, useDatabaseList, useDatabaseRecord, useDatabaseUpdate };
16
+ import { useDesignReady } from "./hooks/use-design-ready.js";
17
+ import { DesignPage, DesignPageProps, DraftPlaceholder, DraftPlaceholderKind } from "./design-page.js";
18
+ export { type AiSearchClientConfig, type AiSearchIndexSummary, type AiSearchQueryType, type AiSearchRequest, type AiSearchResponse, type AiSearchResult, DatabaseApiError, type DatabaseApiErrorCode, type DatabaseEntity, type DatabaseErrorDetail, type DatabaseId, type DatabaseInsert, type DatabaseInvalidation, type DatabaseKeyedEntity, type DatabaseListPage, type DatabaseListParams, type DatabaseListRow, type DatabaseRecordParams, type DatabaseRecordRow, type DatabaseRow, type DatabaseRowShape, type DatabaseShape, type DatabaseUpdate, DesignPage, type DesignPageProps, DraftPlaceholder, type DraftPlaceholderKind, type UseAiSearchQueryOptions, type UseAiSearchQueryResult, type UseDatabaseCreateOptions, type UseDatabaseCreateResult, type UseDatabaseDeleteOptions, type UseDatabaseDeleteResult, type UseDatabaseListOptions, type UseDatabaseListResult, type UseDatabaseReadOptions, type UseDatabaseReadResult, type UseDatabaseRecordOptions, type UseDatabaseRecordResult, type UseDatabaseUpdateOptions, type UseDatabaseUpdateResult, type UseDatabaseWriteOptions, type UseDatabaseWriteState, invalidateDatabaseReads, serialized, useAiSearchQuery, useDatabaseCreate, useDatabaseDelete, useDatabaseList, useDatabaseRecord, useDatabaseUpdate, useDesignReady };
@@ -7,5 +7,7 @@ import { serialized } from "./hooks/use-database-read.js";
7
7
  import { useDatabaseList } from "./hooks/use-database-list.js";
8
8
  import { useDatabaseRecord } from "./hooks/use-database-record.js";
9
9
  import { useDatabaseUpdate } from "./hooks/use-database-update.js";
10
+ import { useDesignReady } from "./hooks/use-design-ready.js";
11
+ import { DesignPage, DraftPlaceholder } from "./design-page.js";
10
12
 
11
- export { DatabaseApiError, invalidateDatabaseReads, serialized, useAiSearchQuery, useDatabaseCreate, useDatabaseDelete, useDatabaseList, useDatabaseRecord, useDatabaseUpdate };
13
+ export { DatabaseApiError, DesignPage, DraftPlaceholder, invalidateDatabaseReads, serialized, useAiSearchQuery, useDatabaseCreate, useDatabaseDelete, useDatabaseList, useDatabaseRecord, useDatabaseUpdate, useDesignReady };
@@ -13,7 +13,7 @@ interface BaseChartProps {
13
13
  yKey?: string | string[];
14
14
  /** Chart orientation @default "vertical" */
15
15
  orientation?: Orientation;
16
- /** Chart height in pixels @default 300 */
16
+ /** Chart height in pixels. Defaults to filling its parent (see `chartSizeStyle`). */
17
17
  height?: number;
18
18
  /** Chart title */
19
19
  title?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"base.d.ts","names":[],"sources":["../../../src/react/charts/base.tsx"],"mappings":";;;;UAkHiB,cAAA;;EAEf,IAAA,EAAM,SAAA;EAFS;EAIf,SAAA,EAAW,SAAA;;EAEX,IAAA;EAFW;EAIX,IAAA;EAee;EAbf,WAAA,GAAc,WAAA;EAmDG;EAjDjB,MAAA;EA6DqC;EA3DrC,KAAA;EAZA;EAcA,UAAA;EAZA;;;;;;EAmBA,YAAA,GAAe,iBAAA;EATf;EAWA,MAAA;EAFA;EAIA,UAAA;EAFA;EAIA,MAAA;EAAA;EAEA,OAAA;EAEA;EAAA,UAAA;EAIA;EAFA,QAAA;EAMA;EAJA,WAAA;EAQA;EANA,UAAA;EAoBA;EAlBA,aAAA;EAoBA;EAlBA,QAAA;EAoBA;EAlBA,GAAA;EA4BsB;EA1BtB,GAAA;EA4BA;;;AAWF;;;;;;;;EA3BE,OAAA,GAAU,MAAA;EAkCV;EAhCA,cAAA,GAAiB,mBAAA;EAkCjB;EAhCA,SAAA;EAkCA;;;;;;;;;EAxBA,WAAA,IAAe,KAAA,EAAO,eAAA;EAkCtB;EAhCA,QAAA;AAAA;;;;;iBAWc,SAAA,CAAA;EACd,IAAA;EACA,SAAA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UAAA;EACA,QAAA;EACA,WAAA;EACA,UAAA;EACA,aAAA;EACA,QAAA;EACA,GAAA;EACA,GAAA;EACA,OAAA,EAAS,aAAA;EACT,cAAA;EACA,SAAA;EACA,WAAA;EACA;AAAA,GACC,cAAA,GAAc,kBAAA,CAAA,GAAA,CAAA,OAAA"}
@@ -1,3 +1,4 @@
1
+ import { chartSizeStyle } from "./constants.js";
1
2
  import { mapToDatum } from "./utils.js";
2
3
  import { normalizeChartData, normalizeHeatmapData } from "./normalize.js";
3
4
  import { applySelectionEmphasis, buildCartesianOption, buildHeatmapOption, buildHorizontalBarOption, buildPieOption, buildRadarOption } from "./options.js";
@@ -42,7 +43,7 @@ function getDefaultPalette(chartType) {
42
43
  * Base chart component that handles both Arrow and JSON data.
43
44
  * Renders using ECharts for consistent output across both formats.
44
45
  */
45
- function BaseChart({ data, chartType, xKey, yKey, orientation, height = 300, title, showLegend = true, colorPalette, colors: customColors, showSymbol = false, smooth = true, stacked = false, symbolSize = 8, showArea = true, innerRadius = 0, showLabels = true, labelPosition = "outside", yAxisKey, min, max, options: customOptions, valueFormatter, className, onDataClick, selected }) {
46
+ function BaseChart({ data, chartType, xKey, yKey, orientation, height, title, showLegend = true, colorPalette, colors: customColors, showSymbol = false, smooth = true, stacked = false, symbolSize = 8, showArea = true, innerRadius = 0, showLabels = true, labelPosition = "outside", yAxisKey, min, max, options: customOptions, valueFormatter, className, onDataClick, selected }) {
46
47
  const themeColors = useThemeColors(colorPalette ?? getDefaultPalette(chartType));
47
48
  const colors = customColors ?? themeColors;
48
49
  const ui = useChartUITokens();
@@ -147,14 +148,15 @@ function BaseChart({ data, chartType, xKey, yKey, orientation, height = 300, tit
147
148
  if (result && typeof result.then === "function") result.catch(() => {});
148
149
  } } : void 0, [interactive]);
149
150
  if (!option) return /* @__PURE__ */ jsx("div", {
150
- className: "flex items-center justify-center h-full text-muted-foreground",
151
+ className: "flex items-center justify-center text-muted-foreground",
152
+ style: chartSizeStyle(height),
151
153
  children: "No data"
152
154
  });
153
155
  return /* @__PURE__ */ jsx(ReactEChartsCore, {
154
156
  ref: chartRefCallback,
155
157
  echarts,
156
158
  option,
157
- style: { height },
159
+ style: chartSizeStyle(height),
158
160
  className,
159
161
  opts: { renderer: "canvas" },
160
162
  notMerge: false,
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","names":[],"sources":["../../../src/react/charts/base.tsx"],"sourcesContent":["// Type-only import: erased at compile time, does not pull the full echarts\n// bundle in. The `ECharts` type is used for the stored ECharts instance ref.\nimport type { ECharts } from \"echarts\";\n// Import the ESM core build, not `echarts-for-react/lib/core` (CJS). The package\n// has no `exports` map, so `/lib/core` resolves to the literal CommonJS file\n// whose default export is `module.exports`; under ESM default-import interop a\n// consumer's bundler hands back the whole `{ default, __esModule }` object rather\n// than the component, so `<ReactEChartsCore/>` renders an object and React throws\n// \"Element type is invalid\". `esm/core` is real ESM with a true `export default`.\nimport ReactEChartsCore from \"echarts-for-react/esm/core\";\nimport {\n BarChart,\n HeatmapChart,\n LineChart,\n PieChart,\n RadarChart,\n ScatterChart,\n} from \"echarts/charts\";\nimport {\n GridComponent,\n LegendComponent,\n TitleComponent,\n TooltipComponent,\n VisualMapComponent,\n} from \"echarts/components\";\nimport * as echarts from \"echarts/core\";\nimport { LegacyGridContainLabel } from \"echarts/features\";\nimport { CanvasRenderer } from \"echarts/renderers\";\nimport { useCallback, useMemo, useRef } from \"react\";\n\nimport { normalizeChartData, normalizeHeatmapData } from \"./normalize\";\nimport {\n applySelectionEmphasis,\n buildCartesianOption,\n buildHeatmapOption,\n buildHorizontalBarOption,\n buildPieOption,\n buildRadarOption,\n type OptionBuilderContext,\n} from \"./options\";\nimport { useChartUITokens, useThemeColors } from \"./theme\";\nimport type {\n ChartBaseProps,\n ChartClickDatum,\n ChartColorPalette,\n ChartData,\n ChartType,\n ChartValueFormatter,\n Orientation,\n} from \"./types\";\nimport { mapToDatum } from \"./utils\";\n\n// ============================================================================\n// ECharts Registration (modular imports for tree-shaking)\n// ============================================================================\n// Only the chart types and components used by the option builders in\n// `options.ts` are registered. Importing from `echarts/core` instead of the\n// full `echarts` entry keeps unused chart types (graph, sankey, gauge, ...)\n// out of consumer bundles.\n//\n// If you add a new chart type or use a new ECharts feature (e.g. dataZoom,\n// toolbox, markLine), register it here. Consumers passing custom `options`\n// that need extra features can register them in their own app via\n// `import { use } from \"echarts/core\"`.\n//\n// Note: tooltip-driven axisPointer is bundled with `TooltipComponent`, so no\n// explicit AxisPointerComponent registration is needed.\n//\n// This `use()` call must stay co-located in the same module as `BaseChart`:\n// `package.json#sideEffects` declares JS modules side-effect free, so moving\n// registration to a separate import-for-side-effect module would let bundlers\n// drop it during tree-shaking.\necharts.use([\n // Series types used by the option builders\n LineChart, // line + area charts (area = line with areaStyle)\n BarChart, // bar + horizontal bar charts\n PieChart, // pie + donut charts\n ScatterChart,\n HeatmapChart,\n RadarChart,\n // Components referenced by built options\n TitleComponent, // `title`\n TooltipComponent, // `tooltip`\n LegendComponent, // `legend`\n GridComponent, // `grid` / `xAxis` / `yAxis`\n VisualMapComponent, // `visualMap` (heatmap color scale)\n // Features\n LegacyGridContainLabel, // `grid.containLabel` (cartesian option builder)\n // Renderer (BaseChart always renders with `renderer: \"canvas\"`)\n CanvasRenderer,\n]);\n\n// ============================================================================\n// Palette Selection\n// ============================================================================\n\n/**\n * Determines the appropriate color palette for a chart type.\n * - Heatmaps use sequential (low → high intensity)\n * - All other charts use categorical (distinct categories)\n */\nfunction getDefaultPalette(chartType: ChartType): ChartColorPalette {\n switch (chartType) {\n case \"heatmap\":\n return \"sequential\";\n default:\n return \"categorical\";\n }\n}\n\n// ============================================================================\n// Component Props\n// ============================================================================\n\nexport interface BaseChartProps {\n /** Chart data (Arrow Table or JSON array) - format is auto-detected */\n data: ChartData;\n /** Chart type */\n chartType: ChartType;\n /** X-axis field key (auto-detected from schema if not provided) */\n xKey?: string;\n /** Y-axis field key(s) (auto-detected from schema if not provided) */\n yKey?: string | string[];\n /** Chart orientation @default \"vertical\" */\n orientation?: Orientation;\n /** Chart height in pixels @default 300 */\n height?: number;\n /** Chart title */\n title?: string;\n /** Show legend @default true */\n showLegend?: boolean;\n /**\n * Color palette to use. Auto-selected based on chart type if not specified.\n * - \"categorical\": Distinct colors for different categories (bar, pie, line)\n * - \"sequential\": Gradient for magnitude (heatmap)\n * - \"diverging\": Two-tone for positive/negative (correlation)\n */\n colorPalette?: ChartColorPalette;\n /** Custom colors (overrides colorPalette) */\n colors?: string[];\n /** Show data point symbols (line/area charts) @default false */\n showSymbol?: boolean;\n /** Smooth line curves (line/area charts) @default true */\n smooth?: boolean;\n /** Stack series @default false */\n stacked?: boolean;\n /** Symbol size for scatter charts @default 8 */\n symbolSize?: number;\n /** Show area fill for radar charts @default true */\n showArea?: boolean;\n /** Inner radius for pie/donut (0-100) @default 0 */\n innerRadius?: number;\n /** Show labels on pie/donut slices @default true */\n showLabels?: boolean;\n /** Label position for pie/donut @default \"outside\" */\n labelPosition?: \"outside\" | \"inside\" | \"center\";\n /** Y-axis field key for heatmap (the row dimension) */\n yAxisKey?: string;\n /** Min value for heatmap color scale */\n min?: number;\n /** Max value for heatmap color scale */\n max?: number;\n /**\n * Additional ECharts options to merge.\n *\n * Only the built-in feature set is registered by this package, so options\n * referencing extra ECharts features (`dataZoom`, `toolbox`, `markLine`,\n * `markArea`, `graphic`, `dataset`, top-level `axisPointer`, ...) require\n * registering them in your app via `import { use } from \"echarts/core\"`.\n * This only works when your `echarts` resolves to the same module\n * instance/version as this package's (the registry is a singleton;\n * duplicate echarts copies won't share registrations).\n */\n options?: Record<string, unknown>;\n /** Formats measure values. See {@link ChartBaseProps.valueFormatter}. */\n valueFormatter?: ChartValueFormatter;\n /** Additional CSS classes */\n className?: string;\n /**\n * Fired when a data element (bar, slice, point) is clicked. Fire-and-forget:\n * the return value is ignored (async handlers are fine — the chart never awaits).\n * The handler receives a normalized {@link ChartClickDatum}.\n *\n * Pointer-only: charts render to <canvas>, so this does not fire for keyboard\n * users. Provide a keyboard-accessible equivalent (e.g. a table row action) for\n * the same action.\n */\n onDataClick?: (datum: ChartClickDatum) => void;\n /** Controlled selection by category name. See {@link ChartBaseProps.selected}. */\n selected?: string | string[];\n}\n\n// ============================================================================\n// Base Chart Component\n// ============================================================================\n\n/**\n * Base chart component that handles both Arrow and JSON data.\n * Renders using ECharts for consistent output across both formats.\n */\nexport function BaseChart({\n data,\n chartType,\n xKey,\n yKey,\n orientation,\n height = 300,\n title,\n showLegend = true,\n colorPalette,\n colors: customColors,\n showSymbol = false,\n smooth = true,\n stacked = false,\n symbolSize = 8,\n showArea = true,\n innerRadius = 0,\n showLabels = true,\n labelPosition = \"outside\",\n yAxisKey,\n min,\n max,\n options: customOptions,\n valueFormatter,\n className,\n onDataClick,\n selected,\n}: BaseChartProps) {\n // Determine the appropriate color palette based on chart type\n const resolvedPalette = colorPalette ?? getDefaultPalette(chartType);\n const themeColors = useThemeColors(resolvedPalette);\n const colors = customColors ?? themeColors;\n\n const ui = useChartUITokens();\n\n // Handler presence enables line interaction and gates events. Tracking the\n // boolean keeps inline handler identities from rebuilding chart options.\n const interactive = !!onDataClick;\n\n // Keep the latest handler in a ref so `onEvents` can call the current\n // `onDataClick` without listing it as a dependency (see `onEvents` below).\n const onDataClickRef = useRef(onDataClick);\n onDataClickRef.current = onDataClick;\n\n // Store ECharts instance directly to avoid stale ref issues on unmount\n const echartsInstanceRef = useRef<ECharts | null>(null);\n\n // Callback ref pattern: captures the ECharts instance when ReactECharts mounts\n // This ensures we always have a stable reference to the actual instance\n const chartRefCallback = useCallback((node: ReactEChartsCore | null) => {\n // Dispose previous instance if component is being replaced\n if (\n echartsInstanceRef.current &&\n !echartsInstanceRef.current.isDisposed()\n ) {\n echartsInstanceRef.current.dispose();\n }\n\n // Store the new instance\n if (node) {\n echartsInstanceRef.current = node.getEchartsInstance();\n } else {\n // Component unmounting - dispose the stored instance\n if (\n echartsInstanceRef.current &&\n !echartsInstanceRef.current.isDisposed()\n ) {\n echartsInstanceRef.current.dispose();\n }\n echartsInstanceRef.current = null;\n }\n }, []);\n\n // Memoize data normalization\n const normalized = useMemo(\n () =>\n chartType === \"heatmap\"\n ? normalizeHeatmapData(data, xKey, yAxisKey, yKey)\n : normalizeChartData(data, xKey, yKey, orientation),\n [data, xKey, yKey, yAxisKey, orientation, chartType],\n );\n\n // Memoize option building\n const option = useMemo(() => {\n const { xData, yFields, xField, chartType: detectedChartType } = normalized;\n\n if (xData.length === 0) return null;\n\n // Determine chart mode first (needed to handle yDataMap)\n const isHeatmap = chartType === \"heatmap\";\n\n // Heatmaps use heatmapData instead of yDataMap\n // For other charts, yDataMap is required\n const yDataMap = \"yDataMap\" in normalized ? normalized.yDataMap : {};\n\n const baseCtx: OptionBuilderContext = {\n xData,\n yDataMap,\n yFields,\n colors,\n title,\n showLegend,\n xField,\n ui,\n valueFormatter,\n };\n const isPie = chartType === \"pie\" || chartType === \"donut\";\n const isRadar = chartType === \"radar\";\n const isHorizontal =\n !isPie &&\n !isRadar &&\n !isHeatmap &&\n (orientation === \"horizontal\" ||\n (detectedChartType === \"categorical\" &&\n !orientation &&\n chartType === \"bar\"));\n const isTimeSeries =\n detectedChartType === \"timeseries\" &&\n !isHorizontal &&\n !isRadar &&\n !isHeatmap;\n\n // Build option based on chart type\n let opt: Record<string, unknown>;\n\n if (isHeatmap && \"yAxisData\" in normalized && \"heatmapData\" in normalized) {\n const heatmapNorm = normalized as {\n yAxisData: (string | number)[];\n heatmapData: [number, number, number][];\n min: number;\n max: number;\n } & typeof normalized;\n opt = buildHeatmapOption({\n ...baseCtx,\n yAxisData: heatmapNorm.yAxisData,\n heatmapData: heatmapNorm.heatmapData,\n min: min ?? heatmapNorm.min,\n max: max ?? heatmapNorm.max,\n showLabels,\n });\n } else if (isRadar) {\n opt = buildRadarOption(baseCtx, showArea);\n } else if (isPie) {\n opt = buildPieOption(\n baseCtx,\n chartType as \"pie\" | \"donut\",\n innerRadius,\n showLabels,\n labelPosition,\n );\n } else if (isHorizontal) {\n opt = buildHorizontalBarOption(baseCtx, stacked);\n } else {\n opt = buildCartesianOption({\n ...baseCtx,\n chartType,\n isTimeSeries,\n stacked,\n smooth,\n showSymbol,\n symbolSize,\n interactive,\n });\n }\n\n // Apply selection after custom options; empty selection is a no-op.\n const merged = customOptions ? { ...opt, ...customOptions } : opt;\n return applySelectionEmphasis(merged, selected);\n }, [\n normalized,\n colors,\n ui,\n title,\n showLegend,\n chartType,\n orientation,\n innerRadius,\n showLabels,\n labelPosition,\n stacked,\n smooth,\n showSymbol,\n symbolSize,\n showArea,\n min,\n max,\n customOptions,\n valueFormatter,\n selected,\n interactive,\n ]);\n\n // Heatmap data uses axis indexes; preserve labels for click results instead\n // of exposing those raw positions.\n const axisLabels = useMemo(\n () => ({\n xLabels: normalized.xData,\n yLabels:\n \"yAxisData\" in normalized\n ? (normalized.yAxisData as (string | number)[])\n : undefined,\n }),\n [normalized],\n );\n\n // `onEvents` must not re-subscribe when the data changes (e.g. each SSE tick).\n const axisLabelsRef = useRef(axisLabels);\n axisLabelsRef.current = axisLabels;\n\n // Memoize by handler presence because echarts-for-react re-subscribes whenever\n // `onEvents` changes, while callers commonly pass a new inline callback on\n // every render. This also avoids churn during frequently changing data such\n // as SSE ticks.\n const onEvents = useMemo(\n () =>\n interactive\n ? {\n click: (params: unknown, instance: ECharts) => {\n const result = onDataClickRef.current?.(\n mapToDatum(params, axisLabelsRef.current, instance),\n ) as void | Promise<void>;\n if (\n result &&\n typeof (result as Promise<void>).then === \"function\"\n ) {\n (result as Promise<void>).catch(() => {});\n }\n },\n }\n : undefined,\n [interactive],\n );\n\n if (!option) {\n return (\n <div className=\"flex items-center justify-center h-full text-muted-foreground\">\n No data\n </div>\n );\n }\n\n return (\n <ReactEChartsCore\n ref={chartRefCallback}\n echarts={echarts}\n option={option}\n style={{ height }}\n className={className}\n opts={{ renderer: \"canvas\" }}\n notMerge={false}\n lazyUpdate={true}\n onEvents={onEvents}\n />\n );\n}\n"],"mappings":";;;;;;;;;;;;;;A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,UACA,OAAQ,OAAyB,SAAS,WAE1C,CAAC,OAAyB,YAAY,GAAG;IAG9C,GACD,QACN,CAAC,YAAY,CACd;AAED,KAAI,CAAC,OACH,QACE,oBAAC;EAAI,WAAU;YAAgE;GAEzE;AAIV,QACE,oBAAC;EACC,KAAK;EACI;EACD;EACR,OAAO,EAAE,QAAQ;EACN;EACX,MAAM,EAAE,UAAU,UAAU;EAC5B,UAAU;EACV,YAAY;EACF;GACV"}
1
+ {"version":3,"file":"base.js","names":[],"sources":["../../../src/react/charts/base.tsx"],"sourcesContent":["// Type-only import: erased at compile time, does not pull the full echarts\n// bundle in. The `ECharts` type is used for the stored ECharts instance ref.\nimport type { ECharts } from \"echarts\";\n// Import the ESM core build, not `echarts-for-react/lib/core` (CJS). The package\n// has no `exports` map, so `/lib/core` resolves to the literal CommonJS file\n// whose default export is `module.exports`; under ESM default-import interop a\n// consumer's bundler hands back the whole `{ default, __esModule }` object rather\n// than the component, so `<ReactEChartsCore/>` renders an object and React throws\n// \"Element type is invalid\". `esm/core` is real ESM with a true `export default`.\nimport ReactEChartsCore from \"echarts-for-react/esm/core\";\nimport {\n BarChart,\n HeatmapChart,\n LineChart,\n PieChart,\n RadarChart,\n ScatterChart,\n} from \"echarts/charts\";\nimport {\n GridComponent,\n LegendComponent,\n TitleComponent,\n TooltipComponent,\n VisualMapComponent,\n} from \"echarts/components\";\nimport * as echarts from \"echarts/core\";\nimport { LegacyGridContainLabel } from \"echarts/features\";\nimport { CanvasRenderer } from \"echarts/renderers\";\nimport { useCallback, useMemo, useRef } from \"react\";\n\nimport { chartSizeStyle } from \"./constants\";\nimport { normalizeChartData, normalizeHeatmapData } from \"./normalize\";\nimport {\n applySelectionEmphasis,\n buildCartesianOption,\n buildHeatmapOption,\n buildHorizontalBarOption,\n buildPieOption,\n buildRadarOption,\n type OptionBuilderContext,\n} from \"./options\";\nimport { useChartUITokens, useThemeColors } from \"./theme\";\nimport type {\n ChartBaseProps,\n ChartClickDatum,\n ChartColorPalette,\n ChartData,\n ChartType,\n ChartValueFormatter,\n Orientation,\n} from \"./types\";\nimport { mapToDatum } from \"./utils\";\n\n// ============================================================================\n// ECharts Registration (modular imports for tree-shaking)\n// ============================================================================\n// Only the chart types and components used by the option builders in\n// `options.ts` are registered. Importing from `echarts/core` instead of the\n// full `echarts` entry keeps unused chart types (graph, sankey, gauge, ...)\n// out of consumer bundles.\n//\n// If you add a new chart type or use a new ECharts feature (e.g. dataZoom,\n// toolbox, markLine), register it here. Consumers passing custom `options`\n// that need extra features can register them in their own app via\n// `import { use } from \"echarts/core\"`.\n//\n// Note: tooltip-driven axisPointer is bundled with `TooltipComponent`, so no\n// explicit AxisPointerComponent registration is needed.\n//\n// This `use()` call must stay co-located in the same module as `BaseChart`:\n// `package.json#sideEffects` declares JS modules side-effect free, so moving\n// registration to a separate import-for-side-effect module would let bundlers\n// drop it during tree-shaking.\necharts.use([\n // Series types used by the option builders\n LineChart, // line + area charts (area = line with areaStyle)\n BarChart, // bar + horizontal bar charts\n PieChart, // pie + donut charts\n ScatterChart,\n HeatmapChart,\n RadarChart,\n // Components referenced by built options\n TitleComponent, // `title`\n TooltipComponent, // `tooltip`\n LegendComponent, // `legend`\n GridComponent, // `grid` / `xAxis` / `yAxis`\n VisualMapComponent, // `visualMap` (heatmap color scale)\n // Features\n LegacyGridContainLabel, // `grid.containLabel` (cartesian option builder)\n // Renderer (BaseChart always renders with `renderer: \"canvas\"`)\n CanvasRenderer,\n]);\n\n// ============================================================================\n// Palette Selection\n// ============================================================================\n\n/**\n * Determines the appropriate color palette for a chart type.\n * - Heatmaps use sequential (low → high intensity)\n * - All other charts use categorical (distinct categories)\n */\nfunction getDefaultPalette(chartType: ChartType): ChartColorPalette {\n switch (chartType) {\n case \"heatmap\":\n return \"sequential\";\n default:\n return \"categorical\";\n }\n}\n\n// ============================================================================\n// Component Props\n// ============================================================================\n\nexport interface BaseChartProps {\n /** Chart data (Arrow Table or JSON array) - format is auto-detected */\n data: ChartData;\n /** Chart type */\n chartType: ChartType;\n /** X-axis field key (auto-detected from schema if not provided) */\n xKey?: string;\n /** Y-axis field key(s) (auto-detected from schema if not provided) */\n yKey?: string | string[];\n /** Chart orientation @default \"vertical\" */\n orientation?: Orientation;\n /** Chart height in pixels. Defaults to filling its parent (see `chartSizeStyle`). */\n height?: number;\n /** Chart title */\n title?: string;\n /** Show legend @default true */\n showLegend?: boolean;\n /**\n * Color palette to use. Auto-selected based on chart type if not specified.\n * - \"categorical\": Distinct colors for different categories (bar, pie, line)\n * - \"sequential\": Gradient for magnitude (heatmap)\n * - \"diverging\": Two-tone for positive/negative (correlation)\n */\n colorPalette?: ChartColorPalette;\n /** Custom colors (overrides colorPalette) */\n colors?: string[];\n /** Show data point symbols (line/area charts) @default false */\n showSymbol?: boolean;\n /** Smooth line curves (line/area charts) @default true */\n smooth?: boolean;\n /** Stack series @default false */\n stacked?: boolean;\n /** Symbol size for scatter charts @default 8 */\n symbolSize?: number;\n /** Show area fill for radar charts @default true */\n showArea?: boolean;\n /** Inner radius for pie/donut (0-100) @default 0 */\n innerRadius?: number;\n /** Show labels on pie/donut slices @default true */\n showLabels?: boolean;\n /** Label position for pie/donut @default \"outside\" */\n labelPosition?: \"outside\" | \"inside\" | \"center\";\n /** Y-axis field key for heatmap (the row dimension) */\n yAxisKey?: string;\n /** Min value for heatmap color scale */\n min?: number;\n /** Max value for heatmap color scale */\n max?: number;\n /**\n * Additional ECharts options to merge.\n *\n * Only the built-in feature set is registered by this package, so options\n * referencing extra ECharts features (`dataZoom`, `toolbox`, `markLine`,\n * `markArea`, `graphic`, `dataset`, top-level `axisPointer`, ...) require\n * registering them in your app via `import { use } from \"echarts/core\"`.\n * This only works when your `echarts` resolves to the same module\n * instance/version as this package's (the registry is a singleton;\n * duplicate echarts copies won't share registrations).\n */\n options?: Record<string, unknown>;\n /** Formats measure values. See {@link ChartBaseProps.valueFormatter}. */\n valueFormatter?: ChartValueFormatter;\n /** Additional CSS classes */\n className?: string;\n /**\n * Fired when a data element (bar, slice, point) is clicked. Fire-and-forget:\n * the return value is ignored (async handlers are fine — the chart never awaits).\n * The handler receives a normalized {@link ChartClickDatum}.\n *\n * Pointer-only: charts render to <canvas>, so this does not fire for keyboard\n * users. Provide a keyboard-accessible equivalent (e.g. a table row action) for\n * the same action.\n */\n onDataClick?: (datum: ChartClickDatum) => void;\n /** Controlled selection by category name. See {@link ChartBaseProps.selected}. */\n selected?: string | string[];\n}\n\n// ============================================================================\n// Base Chart Component\n// ============================================================================\n\n/**\n * Base chart component that handles both Arrow and JSON data.\n * Renders using ECharts for consistent output across both formats.\n */\nexport function BaseChart({\n data,\n chartType,\n xKey,\n yKey,\n orientation,\n height,\n title,\n showLegend = true,\n colorPalette,\n colors: customColors,\n showSymbol = false,\n smooth = true,\n stacked = false,\n symbolSize = 8,\n showArea = true,\n innerRadius = 0,\n showLabels = true,\n labelPosition = \"outside\",\n yAxisKey,\n min,\n max,\n options: customOptions,\n valueFormatter,\n className,\n onDataClick,\n selected,\n}: BaseChartProps) {\n // Determine the appropriate color palette based on chart type\n const resolvedPalette = colorPalette ?? getDefaultPalette(chartType);\n const themeColors = useThemeColors(resolvedPalette);\n const colors = customColors ?? themeColors;\n\n const ui = useChartUITokens();\n\n // Handler presence enables line interaction and gates events. Tracking the\n // boolean keeps inline handler identities from rebuilding chart options.\n const interactive = !!onDataClick;\n\n // Keep the latest handler in a ref so `onEvents` can call the current\n // `onDataClick` without listing it as a dependency (see `onEvents` below).\n const onDataClickRef = useRef(onDataClick);\n onDataClickRef.current = onDataClick;\n\n // Store ECharts instance directly to avoid stale ref issues on unmount\n const echartsInstanceRef = useRef<ECharts | null>(null);\n\n // Callback ref pattern: captures the ECharts instance when ReactECharts mounts\n // This ensures we always have a stable reference to the actual instance\n const chartRefCallback = useCallback((node: ReactEChartsCore | null) => {\n // Dispose previous instance if component is being replaced\n if (\n echartsInstanceRef.current &&\n !echartsInstanceRef.current.isDisposed()\n ) {\n echartsInstanceRef.current.dispose();\n }\n\n // Store the new instance\n if (node) {\n echartsInstanceRef.current = node.getEchartsInstance();\n } else {\n // Component unmounting - dispose the stored instance\n if (\n echartsInstanceRef.current &&\n !echartsInstanceRef.current.isDisposed()\n ) {\n echartsInstanceRef.current.dispose();\n }\n echartsInstanceRef.current = null;\n }\n }, []);\n\n // Memoize data normalization\n const normalized = useMemo(\n () =>\n chartType === \"heatmap\"\n ? normalizeHeatmapData(data, xKey, yAxisKey, yKey)\n : normalizeChartData(data, xKey, yKey, orientation),\n [data, xKey, yKey, yAxisKey, orientation, chartType],\n );\n\n // Memoize option building\n const option = useMemo(() => {\n const { xData, yFields, xField, chartType: detectedChartType } = normalized;\n\n if (xData.length === 0) return null;\n\n // Determine chart mode first (needed to handle yDataMap)\n const isHeatmap = chartType === \"heatmap\";\n\n // Heatmaps use heatmapData instead of yDataMap\n // For other charts, yDataMap is required\n const yDataMap = \"yDataMap\" in normalized ? normalized.yDataMap : {};\n\n const baseCtx: OptionBuilderContext = {\n xData,\n yDataMap,\n yFields,\n colors,\n title,\n showLegend,\n xField,\n ui,\n valueFormatter,\n };\n const isPie = chartType === \"pie\" || chartType === \"donut\";\n const isRadar = chartType === \"radar\";\n const isHorizontal =\n !isPie &&\n !isRadar &&\n !isHeatmap &&\n (orientation === \"horizontal\" ||\n (detectedChartType === \"categorical\" &&\n !orientation &&\n chartType === \"bar\"));\n const isTimeSeries =\n detectedChartType === \"timeseries\" &&\n !isHorizontal &&\n !isRadar &&\n !isHeatmap;\n\n // Build option based on chart type\n let opt: Record<string, unknown>;\n\n if (isHeatmap && \"yAxisData\" in normalized && \"heatmapData\" in normalized) {\n const heatmapNorm = normalized as {\n yAxisData: (string | number)[];\n heatmapData: [number, number, number][];\n min: number;\n max: number;\n } & typeof normalized;\n opt = buildHeatmapOption({\n ...baseCtx,\n yAxisData: heatmapNorm.yAxisData,\n heatmapData: heatmapNorm.heatmapData,\n min: min ?? heatmapNorm.min,\n max: max ?? heatmapNorm.max,\n showLabels,\n });\n } else if (isRadar) {\n opt = buildRadarOption(baseCtx, showArea);\n } else if (isPie) {\n opt = buildPieOption(\n baseCtx,\n chartType as \"pie\" | \"donut\",\n innerRadius,\n showLabels,\n labelPosition,\n );\n } else if (isHorizontal) {\n opt = buildHorizontalBarOption(baseCtx, stacked);\n } else {\n opt = buildCartesianOption({\n ...baseCtx,\n chartType,\n isTimeSeries,\n stacked,\n smooth,\n showSymbol,\n symbolSize,\n interactive,\n });\n }\n\n // Apply selection after custom options; empty selection is a no-op.\n const merged = customOptions ? { ...opt, ...customOptions } : opt;\n return applySelectionEmphasis(merged, selected);\n }, [\n normalized,\n colors,\n ui,\n title,\n showLegend,\n chartType,\n orientation,\n innerRadius,\n showLabels,\n labelPosition,\n stacked,\n smooth,\n showSymbol,\n symbolSize,\n showArea,\n min,\n max,\n customOptions,\n valueFormatter,\n selected,\n interactive,\n ]);\n\n // Heatmap data uses axis indexes; preserve labels for click results instead\n // of exposing those raw positions.\n const axisLabels = useMemo(\n () => ({\n xLabels: normalized.xData,\n yLabels:\n \"yAxisData\" in normalized\n ? (normalized.yAxisData as (string | number)[])\n : undefined,\n }),\n [normalized],\n );\n\n // `onEvents` must not re-subscribe when the data changes (e.g. each SSE tick).\n const axisLabelsRef = useRef(axisLabels);\n axisLabelsRef.current = axisLabels;\n\n // Memoize by handler presence because echarts-for-react re-subscribes whenever\n // `onEvents` changes, while callers commonly pass a new inline callback on\n // every render. This also avoids churn during frequently changing data such\n // as SSE ticks.\n const onEvents = useMemo(\n () =>\n interactive\n ? {\n click: (params: unknown, instance: ECharts) => {\n const result = onDataClickRef.current?.(\n mapToDatum(params, axisLabelsRef.current, instance),\n ) as void | Promise<void>;\n if (\n result &&\n typeof (result as Promise<void>).then === \"function\"\n ) {\n (result as Promise<void>).catch(() => {});\n }\n },\n }\n : undefined,\n [interactive],\n );\n\n if (!option) {\n return (\n <div\n className=\"flex items-center justify-center text-muted-foreground\"\n style={chartSizeStyle(height)}\n >\n No data\n </div>\n );\n }\n\n return (\n <ReactEChartsCore\n ref={chartRefCallback}\n echarts={echarts}\n option={option}\n style={chartSizeStyle(height)}\n className={className}\n opts={{ renderer: \"canvas\" }}\n notMerge={false}\n lazyUpdate={true}\n onEvents={onEvents}\n />\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;AAyEA,QAAQ,IAAI;CAEV;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CAEA;CAEA;CACD,CAAC;;;;;;AAWF,SAAS,kBAAkB,WAAyC;AAClE,SAAQ,WAAR;EACE,KAAK,UACH,QAAO;EACT,QACE,QAAO;;;;;;;AA8Fb,SAAgB,UAAU,EACxB,MACA,WACA,MACA,MACA,aACA,QACA,OACA,aAAa,MACb,cACA,QAAQ,cACR,aAAa,OACb,SAAS,MACT,UAAU,OACV,aAAa,GACb,WAAW,MACX,cAAc,GACd,aAAa,MACb,gBAAgB,WAChB,UACA,KACA,KACA,SAAS,eACT,gBACA,WACA,aACA,YACiB;CAGjB,MAAM,cAAc,eADI,gBAAgB,kBAAkB,UAAU,CACjB;CACnD,MAAM,SAAS,gBAAgB;CAE/B,MAAM,KAAK,kBAAkB;CAI7B,MAAM,cAAc,CAAC,CAAC;CAItB,MAAM,iBAAiB,OAAO,YAAY;AAC1C,gBAAe,UAAU;CAGzB,MAAM,qBAAqB,OAAuB,KAAK;CAIvD,MAAM,mBAAmB,aAAa,SAAkC;AAEtE,MACE,mBAAmB,WACnB,CAAC,mBAAmB,QAAQ,YAAY,CAExC,oBAAmB,QAAQ,SAAS;AAItC,MAAI,KACF,oBAAmB,UAAU,KAAK,oBAAoB;OACjD;AAEL,OACE,mBAAmB,WACnB,CAAC,mBAAmB,QAAQ,YAAY,CAExC,oBAAmB,QAAQ,SAAS;AAEtC,sBAAmB,UAAU;;IAE9B,EAAE,CAAC;CAGN,MAAM,aAAa,cAEf,cAAc,YACV,qBAAqB,MAAM,MAAM,UAAU,KAAK,GAChD,mBAAmB,MAAM,MAAM,MAAM,YAAY,EACvD;EAAC;EA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B,OAAO,WAAW;AACxC,eAAc,UAAU;CAMxB,MAAM,WAAW,cAEb,cACI,EACE,QAAQ,QAAiB,aAAsB;EAC7C,MAAM,SAAS,eAAe,UAC5B,WAAW,QAAQ,cAAc,SAAS,SAAS,CACpD;AACD,MACE,UACA,OAAQ,OAAyB,SAAS,WAE1C,CAAC,OAAyB,YAAY,GAAG;IAG9C,GACD,QACN,CAAC,YAAY,CACd;AAED,KAAI,CAAC,OACH,QACE,oBAAC;EACC,WAAU;EACV,OAAO,eAAe,OAAO;YAC9B;GAEK;AAIV,QACE,oBAAC;EACC,KAAK;EACI;EACD;EACR,OAAO,eAAe,OAAO;EAClB;EACX,MAAM,EAAE,UAAU,UAAU;EAC5B,UAAU;EACV,YAAY;EACF;GACV"}
@@ -92,7 +92,19 @@ const FALLBACK_UI_TOKENS = {
92
92
  grid: "hsla(240, 5%, 90%, 1)",
93
93
  tooltipBg: "hsla(0, 0%, 100%, 1)"
94
94
  };
95
+ /** Smallest height a chart takes when it fills its parent (no `height` prop). */
96
+ const CHART_MIN_HEIGHT = 160;
97
+ /**
98
+ * A chart's box: exactly `height` pixels, or its parent's height, at least
99
+ * {@link CHART_MIN_HEIGHT} when that comes from its content.
100
+ */
101
+ function chartSizeStyle(height) {
102
+ return height !== void 0 ? { height } : {
103
+ height: "100%",
104
+ minHeight: CHART_MIN_HEIGHT
105
+ };
106
+ }
95
107
 
96
108
  //#endregion
97
- export { CHART_COLOR_VARS, CHART_COLOR_VARS_CATEGORICAL, CHART_COLOR_VARS_DIVERGING, CHART_COLOR_VARS_SEQUENTIAL, CHART_UI_VARS, FALLBACK_COLORS_CATEGORICAL, FALLBACK_COLORS_DIVERGING, FALLBACK_COLORS_SEQUENTIAL, FALLBACK_UI_TOKENS };
109
+ export { CHART_COLOR_VARS, CHART_COLOR_VARS_CATEGORICAL, CHART_COLOR_VARS_DIVERGING, CHART_COLOR_VARS_SEQUENTIAL, CHART_UI_VARS, FALLBACK_COLORS_CATEGORICAL, FALLBACK_COLORS_DIVERGING, FALLBACK_COLORS_SEQUENTIAL, FALLBACK_UI_TOKENS, chartSizeStyle };
98
110
  //# sourceMappingURL=constants.js.map