@databricks/appkit-ui 0.92.0 → 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 (65) hide show
  1. package/CLAUDE.md +2 -0
  2. package/dist/cli/commands/plugin/add/add.js +398 -0
  3. package/dist/cli/commands/plugin/add/add.js.map +1 -0
  4. package/dist/cli/commands/plugin/add/plan.js +216 -0
  5. package/dist/cli/commands/plugin/add/plan.js.map +1 -0
  6. package/dist/cli/commands/plugin/add/resolve.js +45 -0
  7. package/dist/cli/commands/plugin/add/resolve.js.map +1 -0
  8. package/dist/cli/commands/plugin/index.js +4 -1
  9. package/dist/cli/commands/plugin/index.js.map +1 -1
  10. package/dist/cli/commands/registry/add.js +3 -2
  11. package/dist/cli/commands/registry/add.js.map +1 -1
  12. package/dist/cli/commands/registry/config-plan.js +1 -1
  13. package/dist/cli/commands/registry/config-plan.js.map +1 -1
  14. package/dist/cli/commands/registry/config-writer.js +77 -9
  15. package/dist/cli/commands/registry/config-writer.js.map +1 -1
  16. package/dist/cli/commands/registry/env-writer.js +1 -1
  17. package/dist/cli/commands/registry/env-writer.js.map +1 -1
  18. package/dist/cli/commands/registry/server-register.js +62 -26
  19. package/dist/cli/commands/registry/server-register.js.map +1 -1
  20. package/dist/cli/commands/registry/workspace-picker.js +1 -1
  21. package/dist/cli/deploy-config.js.map +1 -1
  22. package/dist/cli/index.js +1 -1
  23. package/dist/react/beta.d.ts +3 -1
  24. package/dist/react/beta.js +3 -1
  25. package/dist/react/charts/base.d.ts +1 -1
  26. package/dist/react/charts/base.d.ts.map +1 -1
  27. package/dist/react/charts/base.js +5 -3
  28. package/dist/react/charts/base.js.map +1 -1
  29. package/dist/react/charts/constants.js +13 -1
  30. package/dist/react/charts/constants.js.map +1 -1
  31. package/dist/react/charts/create-chart.js +1 -1
  32. package/dist/react/charts/create-chart.js.map +1 -1
  33. package/dist/react/charts/index.d.ts +1 -1
  34. package/dist/react/charts/types.d.ts +7 -3
  35. package/dist/react/charts/types.d.ts.map +1 -1
  36. package/dist/react/charts/types.js.map +1 -1
  37. package/dist/react/charts/wrapper.d.ts +1 -1
  38. package/dist/react/charts/wrapper.d.ts.map +1 -1
  39. package/dist/react/charts/wrapper.js +12 -5
  40. package/dist/react/charts/wrapper.js.map +1 -1
  41. package/dist/react/design-page.d.ts +33 -0
  42. package/dist/react/design-page.d.ts.map +1 -0
  43. package/dist/react/design-page.js +173 -0
  44. package/dist/react/design-page.js.map +1 -0
  45. package/dist/react/hooks/use-design-ready.d.ts +19 -0
  46. package/dist/react/hooks/use-design-ready.d.ts.map +1 -0
  47. package/dist/react/hooks/use-design-ready.js +33 -0
  48. package/dist/react/hooks/use-design-ready.js.map +1 -0
  49. package/dist/react/index.d.ts +2 -2
  50. package/dist/shared/src/plugin.d.ts.map +1 -1
  51. package/docs/api/appkit/Variable.design.md +6 -0
  52. package/docs/api/appkit-ui/data/AreaChart.md +2 -2
  53. package/docs/api/appkit-ui/data/BarChart.md +2 -2
  54. package/docs/api/appkit-ui/data/DonutChart.md +2 -2
  55. package/docs/api/appkit-ui/data/HeatmapChart.md +2 -2
  56. package/docs/api/appkit-ui/data/LineChart.md +2 -2
  57. package/docs/api/appkit-ui/data/PieChart.md +2 -2
  58. package/docs/api/appkit-ui/data/RadarChart.md +2 -2
  59. package/docs/api/appkit-ui/data/ScatterChart.md +2 -2
  60. package/docs/api/appkit.md +1 -0
  61. package/docs/plugins/analytics.md +8 -0
  62. package/docs/plugins/design.md +233 -0
  63. package/llms.txt +2 -0
  64. package/package.json +1 -1
  65. package/sbom.cdx.json +1 -1
@@ -0,0 +1,216 @@
1
+ import { DABS_BINDING_BY_TYPE } from "../../../../schemas/manifest.js";
2
+ import { isValidEnvName } from "../../registry/requirements.js";
3
+
4
+ //#region src/cli/commands/plugin/add/plan.ts
5
+ const AUTH_MODE_SP = "sp";
6
+ const AUTH_MODE_OBO = "obo";
7
+ const AUTH_MODE_BOTH = "both";
8
+ /** Reserved --set field that selects a resource's auth mode. */
9
+ const AUTH_MODE_FIELD = "authMode";
10
+ /** The manifest's binding, else the built-in one for the type (as the CLI generator does). */
11
+ function bindingOf(r) {
12
+ return r.binding ?? DABS_BINDING_BY_TYPE[r.type];
13
+ }
14
+ /** Same identity as resource de-duplication: type + key. */
15
+ function authKey(r) {
16
+ return `${r.type}:${r.resourceKey}`;
17
+ }
18
+ /** Keys `resourceKey.field`, as the CLI's resourceValues map. */
19
+ function valueKey(r, field) {
20
+ return `${r.resourceKey}.${field}`;
21
+ }
22
+ function fieldNames(r) {
23
+ return Object.keys(r.fields ?? {}).sort();
24
+ }
25
+ function allResources(p) {
26
+ return [...p.resources.required, ...p.resources.optional];
27
+ }
28
+ /** Manifest fields the resource's databricks.yml binding references. */
29
+ function bindingVarFields(r) {
30
+ return (bindingOf(r)?.varFields ?? []).map(([f]) => f);
31
+ }
32
+ /** The --set keys the manifest declares (authMode only for non-app-only resources). */
33
+ function validSetKeys(plugin) {
34
+ const keys = /* @__PURE__ */ new Set();
35
+ for (const r of allResources(plugin)) {
36
+ const prefix = `${plugin.name}.${r.resourceKey}.`;
37
+ for (const f of [...fieldNames(r), ...bindingVarFields(r)]) keys.add(prefix + f);
38
+ if (!r.appOnly) keys.add(prefix + AUTH_MODE_FIELD);
39
+ }
40
+ return keys;
41
+ }
42
+ /** The error for a --set key the plugin manifest doesn't declare. */
43
+ function undeclaredKey(plugin, sv) {
44
+ const keys = validSetKeys(plugin);
45
+ return /* @__PURE__ */ new Error(`--set "${sv}" does not match a resource declared by plugin "${plugin.name}"; valid keys: ${[...keys].join(", ") || "(none, the plugin declares no resources)"}`);
46
+ }
47
+ function splitSetKey(sv) {
48
+ const eq = sv.indexOf("=");
49
+ const key = eq === -1 ? "" : sv.slice(0, eq);
50
+ if (!key) throw new Error(`invalid --set format "${sv}", expected plugin.resourceKey.field=value`);
51
+ const parts = key.split(".");
52
+ if (parts.length < 3) throw new Error(`invalid --set key "${key}", expected plugin.resourceKey.field`);
53
+ return {
54
+ pluginName: parts[0],
55
+ resourceKey: parts[1],
56
+ field: parts.slice(2).join("."),
57
+ value: sv.slice(eq + 1)
58
+ };
59
+ }
60
+ /** `--set plugin.resourceKey.field=value` → `resourceKey.field` → value; authMode pairs are skipped. */
61
+ function parseSetValues(setValues, plugin) {
62
+ const rv = {};
63
+ for (const sv of setValues) {
64
+ const { pluginName, resourceKey, field, value } = splitSetKey(sv);
65
+ if (field === AUTH_MODE_FIELD) continue;
66
+ if (pluginName !== plugin.name) throw new Error(`unknown plugin "${pluginName}" in --set "${sv}"; this command adds "${plugin.name}"`);
67
+ if (!validSetKeys(plugin).has(`${pluginName}.${resourceKey}.${field}`)) throw undeclaredKey(plugin, sv);
68
+ rv[`${resourceKey}.${field}`] = value;
69
+ }
70
+ for (const r of allResources(plugin)) {
71
+ const checkable = fieldNames(r).filter((f) => !r.fields?.[f].bundleIgnore && !r.fields?.[f].localOnly);
72
+ if (checkable.length <= 1) continue;
73
+ const missing = checkable.filter((f) => !rv[valueKey(r, f)]);
74
+ if (missing.length > 0 && missing.length < checkable.length) throw new Error(`incomplete resource "${r.resourceKey}": missing fields [${missing.map((f) => valueKey(r, f)).join(" ")}] (all fields must be set together)`);
75
+ }
76
+ return rv;
77
+ }
78
+ /** Parses `--set plugin.resourceKey.authMode=obo|sp|both` into authKey → mode. */
79
+ function parseSetAuthModes(setValues, plugin) {
80
+ const modes = {};
81
+ for (const sv of setValues) {
82
+ const { pluginName, resourceKey, field, value } = splitSetKey(sv);
83
+ if (field !== AUTH_MODE_FIELD) continue;
84
+ if (pluginName !== plugin.name) throw new Error(`unknown plugin "${pluginName}" in --set "${sv}"; this command adds "${plugin.name}"`);
85
+ const r = allResources(plugin).find((x) => x.resourceKey === resourceKey);
86
+ if (!r) throw undeclaredKey(plugin, sv);
87
+ if (value !== AUTH_MODE_SP && value !== AUTH_MODE_OBO && value !== AUTH_MODE_BOTH) throw new Error(`invalid auth mode "${value}" in --set "${sv}" (must be obo, sp, or both)`);
88
+ if (r.appOnly) throw new Error(`resource "${resourceKey}" of plugin "${plugin.name}" is always accessed by the app's service principal; remove --set ${sv}`);
89
+ if (value !== AUTH_MODE_SP && !r.scope) throw new Error(`resource "${resourceKey}" of plugin "${plugin.name}" cannot be accessed on behalf of the user; use ${plugin.name}.${resourceKey}.${AUTH_MODE_FIELD}=sp`);
90
+ modes[authKey(r)] = value;
91
+ }
92
+ return modes;
93
+ }
94
+ /** True when the resource can be accessed on behalf of the user. */
95
+ function oboCapable(r) {
96
+ return Boolean(r.scope) && !r.appOnly;
97
+ }
98
+ /** Precedence: --set authMode, prompt, --auth-mode, sp; obo/both only are stored. */
99
+ function resolveAuthModes(resources, setModes, promptedModes, defaultMode) {
100
+ const modes = {};
101
+ const keptSP = [];
102
+ for (const r of resources) {
103
+ let mode = setModes[authKey(r)] ?? promptedModes[authKey(r)];
104
+ if (mode === void 0 && defaultMode === AUTH_MODE_OBO) {
105
+ if (!oboCapable(r)) {
106
+ keptSP.push(r.resourceKey);
107
+ continue;
108
+ }
109
+ mode = AUTH_MODE_OBO;
110
+ }
111
+ if (mode === AUTH_MODE_OBO || mode === AUTH_MODE_BOTH) modes[authKey(r)] = mode;
112
+ }
113
+ return {
114
+ modes,
115
+ keptSP
116
+ };
117
+ }
118
+ /** True when any field value of the resource is set. */
119
+ function resourceConfigured(r, values) {
120
+ return [...fieldNames(r), ...bindingVarFields(r)].some((f) => values[valueKey(r, f)]);
121
+ }
122
+ /** Required resources plus optional ones that have a value. */
123
+ function selectResources(plugin, values) {
124
+ return [...plugin.resources.required, ...plugin.resources.optional.filter((r) => resourceConfigured(r, values))];
125
+ }
126
+ /** Unset values: binding fields (sp/both) or env fields (obo), plus resolver fields local .env needs. */
127
+ function findMissingValues(pluginName, resources, values, modes) {
128
+ const missing = [];
129
+ for (const r of resources) {
130
+ const fields = modes[authKey(r)] === AUTH_MODE_OBO ? fieldNames(r).filter((f) => r.fields?.[f].env && !r.fields[f].localOnly) : variableFields(r);
131
+ const resolved = fieldNames(r).filter((f) => r.fields?.[f].resolve);
132
+ for (const field of new Set([...fields, ...resolved])) {
133
+ if (values[valueKey(r, field)] || r.fields?.[field]?.value) continue;
134
+ missing.push({
135
+ resource: r,
136
+ field,
137
+ setKey: `${pluginName}.${r.resourceKey}.${field}`
138
+ });
139
+ }
140
+ }
141
+ return missing;
142
+ }
143
+ /** Fields that become bundle variables: manifest fields plus binding var fields. */
144
+ function variableFields(r) {
145
+ const out = fieldNames(r).filter((f) => !r.fields?.[f].bundleIgnore && !r.fields?.[f].localOnly);
146
+ const covered = new Set(fieldNames(r));
147
+ for (const f of bindingVarFields(r)) if (!covered.has(f)) out.push(f);
148
+ return out;
149
+ }
150
+ function varName(r, field) {
151
+ return `${r.resourceKey.replaceAll("-", "_")}_${field}`;
152
+ }
153
+ /** The file changes for the resources, as the CLI generator: OBO-only gets a literal value, no binding. */
154
+ function buildAddPlan(plugin, resources, values, modes) {
155
+ const dotEnv = [];
156
+ const appYamlEnv = [];
157
+ const bundleVariables = [];
158
+ const resourceBindings = [];
159
+ const unverifiedTypes = [];
160
+ const scopes = [];
161
+ for (const r of resources) {
162
+ const mode = modes[authKey(r)];
163
+ const oboOnly = mode === AUTH_MODE_OBO;
164
+ if ((mode === AUTH_MODE_OBO || mode === AUTH_MODE_BOTH) && r.scope) scopes.push(r.scope);
165
+ for (const f of fieldNames(r)) {
166
+ const field = r.fields?.[f] ?? {};
167
+ if (!field.env || !isValidEnvName(field.env)) continue;
168
+ const value = (values[valueKey(r, f)] || field.value || "").replace(/[\r\n]/g, "");
169
+ dotEnv.push({
170
+ env: field.env,
171
+ value
172
+ });
173
+ if (field.localOnly) continue;
174
+ appYamlEnv.push(oboOnly ? {
175
+ name: field.env,
176
+ value
177
+ } : {
178
+ name: field.env,
179
+ valueFrom: r.resourceKey
180
+ });
181
+ }
182
+ if (oboOnly) continue;
183
+ const binding = bindingOf(r);
184
+ if (!binding) {
185
+ unverifiedTypes.push(r.type);
186
+ continue;
187
+ }
188
+ for (const f of variableFields(r)) bundleVariables.push({
189
+ name: varName(r, f),
190
+ description: r.fields?.[f]?.description || r.description,
191
+ value: values[valueKey(r, f)] || r.fields?.[f]?.value || void 0
192
+ });
193
+ const fields = {};
194
+ for (const [mf, yf] of binding.varFields) fields[yf] = `\${var.${varName(r, mf)}}`;
195
+ for (const [yf, v] of binding.staticFields ?? []) fields[yf] = v;
196
+ resourceBindings.push({
197
+ name: r.resourceKey,
198
+ type: binding.yamlKey,
199
+ permission: r.permission,
200
+ fields
201
+ });
202
+ }
203
+ scopes.push(...plugin.scopes ?? []);
204
+ return {
205
+ dotEnv,
206
+ appYamlEnv,
207
+ bundleVariables,
208
+ resourceBindings,
209
+ unverifiedTypes,
210
+ userApiScopes: [...new Set(scopes)]
211
+ };
212
+ }
213
+
214
+ //#endregion
215
+ export { AUTH_MODE_BOTH, AUTH_MODE_FIELD, AUTH_MODE_OBO, AUTH_MODE_SP, authKey, buildAddPlan, findMissingValues, oboCapable, parseSetAuthModes, parseSetValues, resolveAuthModes, resourceConfigured, selectResources };
216
+ //# sourceMappingURL=plan.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plan.js","names":[],"sources":["../../../../../src/cli/commands/plugin/add/plan.ts"],"sourcesContent":["import { DABS_BINDING_BY_TYPE } from \"../../../../schemas/manifest\";\nimport type { AppYamlEnvEntry, ResourceBinding } from \"../../../deploy-config\";\nimport type { BundleVariable, ConfigPlan } from \"../../registry/config-plan\";\nimport { isValidEnvName } from \"../../registry/requirements\";\n\n// Port of the Databricks CLI's `apps init` resource handling (cmd/apps/init.go, libs/apps/generator).\n\nexport const AUTH_MODE_SP = \"sp\";\nexport const AUTH_MODE_OBO = \"obo\";\nexport const AUTH_MODE_BOTH = \"both\";\nexport type AuthMode =\n | typeof AUTH_MODE_SP\n | typeof AUTH_MODE_OBO\n | typeof AUTH_MODE_BOTH;\n\n/** Reserved --set field that selects a resource's auth mode. */\nexport const AUTH_MODE_FIELD = \"authMode\";\n\nexport interface ManifestField {\n env?: string;\n description?: string;\n value?: string;\n localOnly?: boolean;\n bundleIgnore?: boolean;\n /** Derived-value resolver key, e.g. \"postgres:host\" (see resolve.ts). */\n resolve?: string;\n}\n\nexport interface ManifestResource {\n type: string;\n alias: string;\n resourceKey: string;\n description?: string;\n permission?: string;\n fields?: Record<string, ManifestField>;\n scope?: string;\n appOnly?: boolean;\n binding?: Binding;\n}\n\ntype FieldPair = readonly [string, string];\ninterface Binding {\n yamlKey: string;\n varFields: readonly FieldPair[];\n staticFields?: readonly FieldPair[];\n}\n\n/** The manifest's binding, else the built-in one for the type (as the CLI generator does). */\nfunction bindingOf(r: ManifestResource): Binding | undefined {\n return (\n r.binding ??\n (DABS_BINDING_BY_TYPE as Record<string, Binding | undefined>)[r.type]\n );\n}\n\n/** A plugin entry of the app's appkit.plugins.json (the fields used here). */\nexport interface ManifestPlugin {\n name: string;\n package: string;\n stability?: string;\n scopes?: string[];\n resources: { required: ManifestResource[]; optional: ManifestResource[] };\n}\n\n/** Same identity as resource de-duplication: type + key. */\nexport function authKey(r: ManifestResource): string {\n return `${r.type}:${r.resourceKey}`;\n}\n\n/** Keys `resourceKey.field`, as the CLI's resourceValues map. */\nfunction valueKey(r: ManifestResource, field: string): string {\n return `${r.resourceKey}.${field}`;\n}\n\nfunction fieldNames(r: ManifestResource): string[] {\n return Object.keys(r.fields ?? {}).sort();\n}\n\nfunction allResources(p: ManifestPlugin): ManifestResource[] {\n return [...p.resources.required, ...p.resources.optional];\n}\n\n/** Manifest fields the resource's databricks.yml binding references. */\nfunction bindingVarFields(r: ManifestResource): string[] {\n return (bindingOf(r)?.varFields ?? []).map(([f]) => f);\n}\n\n/** The --set keys the manifest declares (authMode only for non-app-only resources). */\nexport function validSetKeys(plugin: ManifestPlugin): Set<string> {\n const keys = new Set<string>();\n for (const r of allResources(plugin)) {\n const prefix = `${plugin.name}.${r.resourceKey}.`;\n for (const f of [...fieldNames(r), ...bindingVarFields(r)])\n keys.add(prefix + f);\n if (!r.appOnly) keys.add(prefix + AUTH_MODE_FIELD);\n }\n return keys;\n}\n\n/** The error for a --set key the plugin manifest doesn't declare. */\nfunction undeclaredKey(plugin: ManifestPlugin, sv: string): Error {\n const keys = validSetKeys(plugin);\n return new Error(\n `--set \"${sv}\" does not match a resource declared by plugin \"${plugin.name}\"; valid keys: ${[...keys].join(\", \") || \"(none, the plugin declares no resources)\"}`,\n );\n}\n\nfunction splitSetKey(sv: string): {\n pluginName: string;\n resourceKey: string;\n field: string;\n value: string;\n} {\n const eq = sv.indexOf(\"=\");\n const key = eq === -1 ? \"\" : sv.slice(0, eq);\n if (!key) {\n throw new Error(\n `invalid --set format \"${sv}\", expected plugin.resourceKey.field=value`,\n );\n }\n const parts = key.split(\".\");\n if (parts.length < 3) {\n throw new Error(\n `invalid --set key \"${key}\", expected plugin.resourceKey.field`,\n );\n }\n return {\n pluginName: parts[0],\n resourceKey: parts[1],\n field: parts.slice(2).join(\".\"),\n value: sv.slice(eq + 1),\n };\n}\n\n/** `--set plugin.resourceKey.field=value` → `resourceKey.field` → value; authMode pairs are skipped. */\nexport function parseSetValues(\n setValues: string[],\n plugin: ManifestPlugin,\n): Record<string, string> {\n const rv: Record<string, string> = {};\n for (const sv of setValues) {\n const { pluginName, resourceKey, field, value } = splitSetKey(sv);\n if (field === AUTH_MODE_FIELD) continue;\n if (pluginName !== plugin.name) {\n throw new Error(\n `unknown plugin \"${pluginName}\" in --set \"${sv}\"; this command adds \"${plugin.name}\"`,\n );\n }\n if (!validSetKeys(plugin).has(`${pluginName}.${resourceKey}.${field}`)) {\n throw undeclaredKey(plugin, sv);\n }\n rv[`${resourceKey}.${field}`] = value;\n }\n\n for (const r of allResources(plugin)) {\n const checkable = fieldNames(r).filter(\n (f) => !r.fields?.[f].bundleIgnore && !r.fields?.[f].localOnly,\n );\n if (checkable.length <= 1) continue;\n const missing = checkable.filter((f) => !rv[valueKey(r, f)]);\n if (missing.length > 0 && missing.length < checkable.length) {\n throw new Error(\n `incomplete resource \"${r.resourceKey}\": missing fields [${missing.map((f) => valueKey(r, f)).join(\" \")}] (all fields must be set together)`,\n );\n }\n }\n return rv;\n}\n\n/** Parses `--set plugin.resourceKey.authMode=obo|sp|both` into authKey → mode. */\nexport function parseSetAuthModes(\n setValues: string[],\n plugin: ManifestPlugin,\n): Record<string, AuthMode> {\n const modes: Record<string, AuthMode> = {};\n for (const sv of setValues) {\n const { pluginName, resourceKey, field, value } = splitSetKey(sv);\n if (field !== AUTH_MODE_FIELD) continue;\n if (pluginName !== plugin.name) {\n throw new Error(\n `unknown plugin \"${pluginName}\" in --set \"${sv}\"; this command adds \"${plugin.name}\"`,\n );\n }\n const r = allResources(plugin).find((x) => x.resourceKey === resourceKey);\n if (!r) throw undeclaredKey(plugin, sv);\n if (\n value !== AUTH_MODE_SP &&\n value !== AUTH_MODE_OBO &&\n value !== AUTH_MODE_BOTH\n ) {\n throw new Error(\n `invalid auth mode \"${value}\" in --set \"${sv}\" (must be obo, sp, or both)`,\n );\n }\n if (r.appOnly) {\n throw new Error(\n `resource \"${resourceKey}\" of plugin \"${plugin.name}\" is always accessed by the app's service principal; remove --set ${sv}`,\n );\n }\n if (value !== AUTH_MODE_SP && !r.scope) {\n throw new Error(\n `resource \"${resourceKey}\" of plugin \"${plugin.name}\" cannot be accessed on behalf of the user; use ${plugin.name}.${resourceKey}.${AUTH_MODE_FIELD}=sp`,\n );\n }\n modes[authKey(r)] = value;\n }\n return modes;\n}\n\n/** True when the resource can be accessed on behalf of the user. */\nexport function oboCapable(r: ManifestResource): boolean {\n return Boolean(r.scope) && !r.appOnly;\n}\n\n/** Precedence: --set authMode, prompt, --auth-mode, sp; obo/both only are stored. */\nexport function resolveAuthModes(\n resources: ManifestResource[],\n setModes: Record<string, AuthMode>,\n promptedModes: Record<string, AuthMode>,\n defaultMode: string | undefined,\n): { modes: Record<string, AuthMode>; keptSP: string[] } {\n const modes: Record<string, AuthMode> = {};\n const keptSP: string[] = [];\n for (const r of resources) {\n let mode: AuthMode | undefined =\n setModes[authKey(r)] ?? promptedModes[authKey(r)];\n if (mode === undefined && defaultMode === AUTH_MODE_OBO) {\n if (!oboCapable(r)) {\n keptSP.push(r.resourceKey);\n continue;\n }\n mode = AUTH_MODE_OBO;\n }\n if (mode === AUTH_MODE_OBO || mode === AUTH_MODE_BOTH) {\n modes[authKey(r)] = mode;\n }\n }\n return { modes, keptSP };\n}\n\n/** True when any field value of the resource is set. */\nexport function resourceConfigured(\n r: ManifestResource,\n values: Record<string, string>,\n): boolean {\n return [...fieldNames(r), ...bindingVarFields(r)].some(\n (f) => values[valueKey(r, f)],\n );\n}\n\n/** Required resources plus optional ones that have a value. */\nexport function selectResources(\n plugin: ManifestPlugin,\n values: Record<string, string>,\n): ManifestResource[] {\n return [\n ...plugin.resources.required,\n ...plugin.resources.optional.filter((r) => resourceConfigured(r, values)),\n ];\n}\n\nexport interface MissingValue {\n resource: ManifestResource;\n field: string;\n /** The --set key that supplies it. */\n setKey: string;\n}\n\n/** Unset values: binding fields (sp/both) or env fields (obo), plus resolver fields local .env needs. */\nexport function findMissingValues(\n pluginName: string,\n resources: ManifestResource[],\n values: Record<string, string>,\n modes: Record<string, AuthMode>,\n): MissingValue[] {\n const missing: MissingValue[] = [];\n for (const r of resources) {\n const fields =\n modes[authKey(r)] === AUTH_MODE_OBO\n ? fieldNames(r).filter(\n (f) => r.fields?.[f].env && !r.fields[f].localOnly,\n )\n : variableFields(r);\n const resolved = fieldNames(r).filter((f) => r.fields?.[f].resolve);\n for (const field of new Set([...fields, ...resolved])) {\n if (values[valueKey(r, field)] || r.fields?.[field]?.value) continue;\n missing.push({\n resource: r,\n field,\n setKey: `${pluginName}.${r.resourceKey}.${field}`,\n });\n }\n }\n return missing;\n}\n\n/** Fields that become bundle variables: manifest fields plus binding var fields. */\nfunction variableFields(r: ManifestResource): string[] {\n const out = fieldNames(r).filter(\n (f) => !r.fields?.[f].bundleIgnore && !r.fields?.[f].localOnly,\n );\n const covered = new Set(fieldNames(r));\n for (const f of bindingVarFields(r)) {\n if (!covered.has(f)) out.push(f);\n }\n return out;\n}\n\nfunction varName(r: ManifestResource, field: string): string {\n return `${r.resourceKey.replaceAll(\"-\", \"_\")}_${field}`;\n}\n\nexport interface AddPlan extends ConfigPlan {\n /** .env lines to add (skipped later when the name is already present). */\n dotEnv: { env: string; value: string }[];\n}\n\n/** The file changes for the resources, as the CLI generator: OBO-only gets a literal value, no binding. */\nexport function buildAddPlan(\n plugin: ManifestPlugin,\n resources: ManifestResource[],\n values: Record<string, string>,\n modes: Record<string, AuthMode>,\n): AddPlan {\n const dotEnv: AddPlan[\"dotEnv\"] = [];\n const appYamlEnv: AppYamlEnvEntry[] = [];\n const bundleVariables: BundleVariable[] = [];\n const resourceBindings: ResourceBinding[] = [];\n const unverifiedTypes: string[] = [];\n const scopes: string[] = [];\n\n for (const r of resources) {\n const mode = modes[authKey(r)];\n const oboOnly = mode === AUTH_MODE_OBO;\n if ((mode === AUTH_MODE_OBO || mode === AUTH_MODE_BOTH) && r.scope) {\n scopes.push(r.scope);\n }\n\n for (const f of fieldNames(r)) {\n const field = r.fields?.[f] ?? {};\n if (!field.env || !isValidEnvName(field.env)) continue;\n const value = (values[valueKey(r, f)] || field.value || \"\").replace(\n /[\\r\\n]/g,\n \"\",\n );\n dotEnv.push({ env: field.env, value });\n if (field.localOnly) continue;\n appYamlEnv.push(\n oboOnly\n ? { name: field.env, value }\n : { name: field.env, valueFrom: r.resourceKey },\n );\n }\n\n if (oboOnly) continue;\n const binding = bindingOf(r);\n if (!binding) {\n unverifiedTypes.push(r.type);\n continue;\n }\n for (const f of variableFields(r)) {\n bundleVariables.push({\n name: varName(r, f),\n description: r.fields?.[f]?.description || r.description,\n value: values[valueKey(r, f)] || r.fields?.[f]?.value || undefined,\n });\n }\n const fields: Record<string, string> = {};\n for (const [mf, yf] of binding.varFields) {\n fields[yf] = `\\${var.${varName(r, mf)}}`;\n }\n for (const [yf, v] of binding.staticFields ?? []) fields[yf] = v;\n resourceBindings.push({\n name: r.resourceKey,\n type: binding.yamlKey,\n permission: r.permission,\n fields,\n });\n }\n\n // Plugin scopes (e.g. genie) cover always-OBO routes, whatever the resources' mode.\n scopes.push(...(plugin.scopes ?? []));\n return {\n dotEnv,\n appYamlEnv,\n bundleVariables,\n resourceBindings,\n unverifiedTypes,\n userApiScopes: [...new Set(scopes)],\n };\n}\n"],"mappings":";;;;AAOA,MAAa,eAAe;AAC5B,MAAa,gBAAgB;AAC7B,MAAa,iBAAiB;;AAO9B,MAAa,kBAAkB;;AAgC/B,SAAS,UAAU,GAA0C;AAC3D,QACE,EAAE,WACD,qBAA6D,EAAE;;;AAcpE,SAAgB,QAAQ,GAA6B;AACnD,QAAO,GAAG,EAAE,KAAK,GAAG,EAAE;;;AAIxB,SAAS,SAAS,GAAqB,OAAuB;AAC5D,QAAO,GAAG,EAAE,YAAY,GAAG;;AAG7B,SAAS,WAAW,GAA+B;AACjD,QAAO,OAAO,KAAK,EAAE,UAAU,EAAE,CAAC,CAAC,MAAM;;AAG3C,SAAS,aAAa,GAAuC;AAC3D,QAAO,CAAC,GAAG,EAAE,UAAU,UAAU,GAAG,EAAE,UAAU,SAAS;;;AAI3D,SAAS,iBAAiB,GAA+B;AACvD,SAAQ,UAAU,EAAE,EAAE,aAAa,EAAE,EAAE,KAAK,CAAC,OAAO,EAAE;;;AAIxD,SAAgB,aAAa,QAAqC;CAChE,MAAM,uBAAO,IAAI,KAAa;AAC9B,MAAK,MAAM,KAAK,aAAa,OAAO,EAAE;EACpC,MAAM,SAAS,GAAG,OAAO,KAAK,GAAG,EAAE,YAAY;AAC/C,OAAK,MAAM,KAAK,CAAC,GAAG,WAAW,EAAE,EAAE,GAAG,iBAAiB,EAAE,CAAC,CACxD,MAAK,IAAI,SAAS,EAAE;AACtB,MAAI,CAAC,EAAE,QAAS,MAAK,IAAI,SAAS,gBAAgB;;AAEpD,QAAO;;;AAIT,SAAS,cAAc,QAAwB,IAAmB;CAChE,MAAM,OAAO,aAAa,OAAO;AACjC,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ACnB,aAAa,EAAE,SAAS,IAAI,eAAe,EAAE;GAC7C,OAAO,OAAO,SAAS,GAAG,EAAE,KAAK,EAAE,SAAS,IAAI,SAAS;GAC1D,CAAC;EAEJ,MAAM,SAAiC,EAAE;AACzC,OAAK,MAAM,CAAC,IAAI,OAAO,QAAQ,UAC7B,QAAO,MAAM,UAAU,QAAQ,GAAG,GAAG,CAAC;AAExC,OAAK,MAAM,CAAC,IAAI,MAAM,QAAQ,gBAAgB,EAAE,CAAE,QAAO,MAAM;AAC/D,mBAAiB,KAAK;GACpB,MAAM,EAAE;GACR,MAAM,QAAQ;GACd,YAAY,EAAE;GACd;GACD,CAAC;;AAIJ,QAAO,KAAK,GAAI,OAAO,UAAU,EAAE,CAAE;AACrC,QAAO;EACL;EACA;EACA;EACA;EACA;EACA,eAAe,CAAC,GAAG,IAAI,IAAI,OAAO,CAAC;EACpC"}
@@ -0,0 +1,45 @@
1
+ //#region src/cli/commands/plugin/add/resolve.ts
2
+ /** Values for `postgres:*` resolver fields, as the Databricks CLI's ResolvePostgresValues. */
3
+ async function resolveDerivedValues(r, values, profile) {
4
+ const branch = values[`${r.resourceKey}.branch`];
5
+ const database = values[`${r.resourceKey}.database`];
6
+ const needs = Object.entries(r.fields ?? {}).some(([name, f]) => f.resolve?.startsWith("postgres:") && !values[`${r.resourceKey}.${name}`]);
7
+ if (r.type !== "postgres" || !needs || !branch) return {};
8
+ const { makeWorkspaceClient } = await import("../../registry/workspace-picker.js");
9
+ const pg = makeWorkspaceClient(profile).postgres;
10
+ const resolved = {};
11
+ for await (const ep of pg.listEndpointsIter({ parent: branch })) {
12
+ if (ep.status?.endpointType !== "ENDPOINT_TYPE_READ_WRITE") continue;
13
+ if (ep.name) resolved["postgres:endpointPath"] = ep.name;
14
+ if (ep.status.hosts?.host) resolved["postgres:host"] = ep.status.hosts.host;
15
+ break;
16
+ }
17
+ if (database) for await (const db of pg.listDatabasesIter({ parent: branch })) {
18
+ if (db.name !== database) continue;
19
+ if (db.status?.postgresDatabase) resolved["postgres:databaseName"] = db.status.postgresDatabase;
20
+ break;
21
+ }
22
+ const out = {};
23
+ for (const [name, field] of Object.entries(r.fields ?? {})) {
24
+ const v = field.resolve && resolved[field.resolve];
25
+ if (v) out[`${r.resourceKey}.${name}`] = v;
26
+ }
27
+ return out;
28
+ }
29
+ /** An AI Search index's synced source columns, minus embedding vectors. */
30
+ async function discoverIndexColumns(indexName, profile) {
31
+ const { makeWorkspaceClient } = await import("../../registry/workspace-picker.js");
32
+ const client = makeWorkspaceClient(profile);
33
+ const index = await client.vectorSearch.getVectorIndex({ name: indexName });
34
+ const spec = index.indexSpec?.$case === "deltaSyncIndexSpec" ? index.indexSpec.deltaSyncIndexSpec : void 0;
35
+ if (!spec?.sourceTable) throw new Error(`index ${indexName} has no Delta Sync source table`);
36
+ const excluded = new Set(spec.embeddingVectorColumns?.map((c) => c.name));
37
+ const table = await client.tables.getTable({ fullNameArg: spec.sourceTable });
38
+ const subset = spec.columnsToSync?.length ? spec.columnsToSync : spec.columnsToIndex;
39
+ const synced = subset?.length ? new Set(subset) : void 0;
40
+ return (table.columns ?? []).flatMap((c) => c.name && !excluded.has(c.name) && (!synced || synced.has(c.name)) ? [c.name] : []);
41
+ }
42
+
43
+ //#endregion
44
+ export { discoverIndexColumns, resolveDerivedValues };
45
+ //# sourceMappingURL=resolve.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolve.js","names":[],"sources":["../../../../../src/cli/commands/plugin/add/resolve.ts"],"sourcesContent":["import type { ManifestResource } from \"./plan\";\n\n/** Values for `postgres:*` resolver fields, as the Databricks CLI's ResolvePostgresValues. */\nexport async function resolveDerivedValues(\n r: ManifestResource,\n values: Record<string, string>,\n profile: string | undefined,\n): Promise<Record<string, string>> {\n const branch = values[`${r.resourceKey}.branch`];\n const database = values[`${r.resourceKey}.database`];\n const needs = Object.entries(r.fields ?? {}).some(\n ([name, f]) =>\n f.resolve?.startsWith(\"postgres:\") && !values[`${r.resourceKey}.${name}`],\n );\n if (r.type !== \"postgres\" || !needs || !branch) return {};\n\n const { makeWorkspaceClient } =\n await import(\"../../registry/workspace-picker.js\");\n const pg = makeWorkspaceClient(profile).postgres;\n const resolved: Record<string, string> = {};\n for await (const ep of pg.listEndpointsIter({ parent: branch })) {\n if (ep.status?.endpointType !== \"ENDPOINT_TYPE_READ_WRITE\") continue;\n if (ep.name) resolved[\"postgres:endpointPath\"] = ep.name;\n if (ep.status.hosts?.host) resolved[\"postgres:host\"] = ep.status.hosts.host;\n break;\n }\n if (database) {\n for await (const db of pg.listDatabasesIter({ parent: branch })) {\n if (db.name !== database) continue;\n if (db.status?.postgresDatabase) {\n resolved[\"postgres:databaseName\"] = db.status.postgresDatabase;\n }\n break;\n }\n }\n\n const out: Record<string, string> = {};\n for (const [name, field] of Object.entries(r.fields ?? {})) {\n const v = field.resolve && resolved[field.resolve];\n if (v) out[`${r.resourceKey}.${name}`] = v;\n }\n return out;\n}\n\n/** An AI Search index's synced source columns, minus embedding vectors. */\nexport async function discoverIndexColumns(\n indexName: string,\n profile: string | undefined,\n): Promise<string[]> {\n const { makeWorkspaceClient } =\n await import(\"../../registry/workspace-picker.js\");\n const client = makeWorkspaceClient(profile);\n const index = await client.vectorSearch.getVectorIndex({ name: indexName });\n const spec =\n index.indexSpec?.$case === \"deltaSyncIndexSpec\"\n ? index.indexSpec.deltaSyncIndexSpec\n : undefined;\n if (!spec?.sourceTable) {\n throw new Error(`index ${indexName} has no Delta Sync source table`);\n }\n const excluded = new Set(spec.embeddingVectorColumns?.map((c) => c.name));\n const table = await client.tables.getTable({ fullNameArg: spec.sourceTable });\n // columnsToIndex is the response's alias of columnsToSync.\n const subset = spec.columnsToSync?.length\n ? spec.columnsToSync\n : spec.columnsToIndex;\n const synced = subset?.length ? new Set(subset) : undefined;\n return (table.columns ?? []).flatMap((c) =>\n c.name && !excluded.has(c.name) && (!synced || synced.has(c.name))\n ? [c.name]\n : [],\n );\n}\n"],"mappings":";;AAGA,eAAsB,qBACp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AC;CAC3E,MAAM,OACJ,MAAM,WAAW,UAAU,uBACvB,MAAM,UAAU,qBAChB;AACN,KAAI,CAAC,MAAM,YACT,OAAM,IAAI,MAAM,SAAS,UAAU,iCAAiC;CAEtE,MAAM,WAAW,IAAI,IAAI,KAAK,wBAAwB,KAAK,MAAM,EAAE,KAAK,CAAC;CACzE,MAAM,QAAQ,MAAM,OAAO,OAAO,SAAS,EAAE,aAAa,KAAK,aAAa,CAAC;CAE7E,MAAM,SAAS,KAAK,eAAe,SAC/B,KAAK,gBACL,KAAK;CACT,MAAM,SAAS,QAAQ,SAAS,IAAI,IAAI,OAAO,GAAG;AAClD,SAAQ,MAAM,WAAW,EAAE,EAAE,SAAS,MACpC,EAAE,QAAQ,CAAC,SAAS,IAAI,EAAE,KAAK,KAAK,CAAC,UAAU,OAAO,IAAI,EAAE,KAAK,IAC7D,CAAC,EAAE,KAAK,GACR,EAAE,CACP"}
@@ -1,4 +1,5 @@
1
1
  import { pluginAddResourceCommand } from "./add-resource/add-resource.js";
2
+ import { pluginAddCommand } from "./add/add.js";
2
3
  import { pluginCreateCommand } from "./create/create.js";
3
4
  import { pluginListCommand } from "./list/list.js";
4
5
  import { pluginsSyncCommand } from "./sync/sync.js";
@@ -14,15 +15,17 @@ import { Command } from "commander";
14
15
  * - create: Scaffold a new plugin (interactive)
15
16
  * - validate: Validate manifest(s) against the JSON schema
16
17
  * - list: List plugins from appkit.plugins.json or a directory
18
+ * - add: Add a plugin to the app (server, .env, app.yaml, databricks.yml)
17
19
  * - add-resource: Add a resource requirement to a plugin manifest (interactive)
18
20
  * - promote: Promote a plugin to a higher stability tier
19
21
  */
20
- const pluginCommand = new Command("plugin").description("Plugin management commands").addCommand(pluginsSyncCommand).addCommand(pluginCreateCommand).addCommand(pluginValidateCommand).addCommand(pluginListCommand).addCommand(pluginAddResourceCommand).addCommand(pluginPromoteCommand).addHelpText("after", `
22
+ const pluginCommand = new Command("plugin").description("Plugin management commands").addCommand(pluginsSyncCommand).addCommand(pluginCreateCommand).addCommand(pluginValidateCommand).addCommand(pluginListCommand).addCommand(pluginAddCommand).addCommand(pluginAddResourceCommand).addCommand(pluginPromoteCommand).addHelpText("after", `
21
23
  Examples:
22
24
  $ appkit plugin sync --write
23
25
  $ appkit plugin create --placement in-repo --path plugins/my-plugin --name my-plugin --description "Does X"
24
26
  $ appkit plugin validate .
25
27
  $ appkit plugin list --json
28
+ $ appkit plugin add analytics --auth-mode obo --set analytics.sql-warehouse.id=abc123
26
29
  $ appkit plugin add-resource --path plugins/my-plugin --type sql_warehouse
27
30
  $ appkit plugin promote my-plugin --to ga`);
28
31
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../src/cli/commands/plugin/index.ts"],"sourcesContent":["import { Command } from \"commander\";\n\nimport { pluginAddResourceCommand } from \"./add-resource/add-resource\";\nimport { pluginCreateCommand } from \"./create/create\";\nimport { pluginListCommand } from \"./list/list\";\nimport { pluginPromoteCommand } from \"./promote/promote\";\nimport { pluginsSyncCommand } from \"./sync/sync\";\nimport { pluginValidateCommand } from \"./validate/validate\";\n\n/**\n * Parent command for plugin management operations.\n * Subcommands:\n * - sync: Aggregate plugin manifests into appkit.plugins.json\n * - create: Scaffold a new plugin (interactive)\n * - validate: Validate manifest(s) against the JSON schema\n * - list: List plugins from appkit.plugins.json or a directory\n * - add-resource: Add a resource requirement to a plugin manifest (interactive)\n * - promote: Promote a plugin to a higher stability tier\n */\nexport const pluginCommand = new Command(\"plugin\")\n .description(\"Plugin management commands\")\n .addCommand(pluginsSyncCommand)\n .addCommand(pluginCreateCommand)\n .addCommand(pluginValidateCommand)\n .addCommand(pluginListCommand)\n .addCommand(pluginAddResourceCommand)\n .addCommand(pluginPromoteCommand)\n .addHelpText(\n \"after\",\n `\nExamples:\n $ appkit plugin sync --write\n $ appkit plugin create --placement in-repo --path plugins/my-plugin --name my-plugin --description \"Does X\"\n $ appkit plugin validate .\n $ appkit plugin list --json\n $ appkit plugin add-resource --path plugins/my-plugin --type sql_warehouse\n $ appkit plugin promote my-plugin --to ga`,\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmBA,MAAa,gBAAgB,IAAI,QAAQ,SAAS,CAC/C,YAAY,6BAA6B,CACzC,WAAW,mBAAmB,CAC9B,WAAW,oBAAoB,CAC/B,WAAW,sBAAsB,CACjC,WAAW,kBAAkB,CAC7B,WAAW,yBAAyB,CACpC,WAAW,qBAAqB,CAChC,YACC,SACA;;;;;;;6CAQD"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../src/cli/commands/plugin/index.ts"],"sourcesContent":["import { Command } from \"commander\";\n\nimport { pluginAddResourceCommand } from \"./add-resource/add-resource\";\nimport { pluginAddCommand } from \"./add/add\";\nimport { pluginCreateCommand } from \"./create/create\";\nimport { pluginListCommand } from \"./list/list\";\nimport { pluginPromoteCommand } from \"./promote/promote\";\nimport { pluginsSyncCommand } from \"./sync/sync\";\nimport { pluginValidateCommand } from \"./validate/validate\";\n\n/**\n * Parent command for plugin management operations.\n * Subcommands:\n * - sync: Aggregate plugin manifests into appkit.plugins.json\n * - create: Scaffold a new plugin (interactive)\n * - validate: Validate manifest(s) against the JSON schema\n * - list: List plugins from appkit.plugins.json or a directory\n * - add: Add a plugin to the app (server, .env, app.yaml, databricks.yml)\n * - add-resource: Add a resource requirement to a plugin manifest (interactive)\n * - promote: Promote a plugin to a higher stability tier\n */\nexport const pluginCommand = new Command(\"plugin\")\n .description(\"Plugin management commands\")\n .addCommand(pluginsSyncCommand)\n .addCommand(pluginCreateCommand)\n .addCommand(pluginValidateCommand)\n .addCommand(pluginListCommand)\n .addCommand(pluginAddCommand)\n .addCommand(pluginAddResourceCommand)\n .addCommand(pluginPromoteCommand)\n .addHelpText(\n \"after\",\n `\nExamples:\n $ appkit plugin sync --write\n $ appkit plugin create --placement in-repo --path plugins/my-plugin --name my-plugin --description \"Does X\"\n $ appkit plugin validate .\n $ appkit plugin list --json\n $ appkit plugin add analytics --auth-mode obo --set analytics.sql-warehouse.id=abc123\n $ appkit plugin add-resource --path plugins/my-plugin --type sql_warehouse\n $ appkit plugin promote my-plugin --to ga`,\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAqBA,MAAa,gBAAgB,IAAI,QAAQ,SAAS,CAC/C,YAAY,6BAA6B,CACzC,WAAW,mBAAmB,CAC9B,WAAW,oBAAoB,CAC/B,WAAW,sBAAsB,CACjC,WAAW,kBAAkB,CAC7B,WAAW,iBAAiB,CAC5B,WAAW,yBAAyB,CACpC,WAAW,qBAAqB,CAChC,YACC,SACA;;;;;;;;6CASD"}
@@ -4,7 +4,7 @@ import { JS_IDENTIFIER, REGISTRY_REPO } from "./constants.js";
4
4
  import { fetchRegistryItem, fetchVerifiedNames, isValidItemName, stripNamespace } from "./client.js";
5
5
  import { extractRequirements, renderRequirements } from "./requirements.js";
6
6
  import { buildConfigPlan, collectBindingValueNeeds, planHasContent } from "./config-plan.js";
7
- import { reportConfigWrite, validateBundle, writeConfig } from "./config-writer.js";
7
+ import { preflightConfig, reportConfigWrite, validateBundle, writeConfig } from "./config-writer.js";
8
8
  import { parseEnv } from "./env-reconcile.js";
9
9
  import { spawnSync } from "node:child_process";
10
10
  import fs from "node:fs";
@@ -313,6 +313,7 @@ async function runAdd(refs, opts) {
313
313
  process.exit(1);
314
314
  }
315
315
  }
316
+ if (opts.resources !== false && items.some((i) => extractRequirements(i).length > 0)) preflightConfig(cwd);
316
317
  const hasUi = items.some((i) => !isPluginItem(i));
317
318
  const hasPlugin = items.some(isPluginItem);
318
319
  const frontendRoot = hasUi ? findFrontendRoot(cwd) : cwd;
@@ -461,5 +462,5 @@ Examples:
461
462
  }));
462
463
 
463
464
  //#endregion
464
- export { addCommand };
465
+ export { addCommand, findServerRoot, profileFromEnv };
465
466
  //# sourceMappingURL=add.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"add.js","names":[],"sources":["../../../../src/cli/commands/registry/add.ts"],"sourcesContent":["import { spawnSync } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport process from \"node:process\";\n\nimport { Command } from \"commander\";\nimport pc from \"picocolors\";\n\nimport { SCOPE_BY_TYPE } from \"../../../schemas/manifest\";\nimport { detectPackageManager } from \"../../package-manager\";\nimport {\n fetchRegistryItem,\n fetchVerifiedNames,\n isValidItemName,\n type RegistryItem,\n type RegistryItemFile,\n stripNamespace,\n} from \"./client\";\nimport {\n buildConfigPlan,\n collectBindingValueNeeds,\n planHasContent,\n} from \"./config-plan\";\nimport {\n reportConfigWrite,\n validateBundle,\n writeConfig,\n} from \"./config-writer\";\nimport { JS_IDENTIFIER, REGISTRY_REPO } from \"./constants\";\nimport { parseEnv } from \"./env-reconcile\";\nimport {\n extractRequirements,\n type ResourceRequirementRow,\n renderRequirements,\n} from \"./requirements\";\n\n/** Subdirectories that commonly hold the frontend / server in an AppKit app. */\nconst FRONTEND_SUBDIRS = [\"client\", \"frontend\", \"web\", \"app\"];\nconst SERVER_SUBDIRS = [\"server\", \"api\", \"backend\"];\n\nfunction isDir(p: string): boolean {\n return fs.existsSync(p) && fs.statSync(p).isDirectory();\n}\n\n/** A registry item is a server plugin if it ships a manifest.json. */\nfunction isPluginItem(item: RegistryItem): boolean {\n return (item.files ?? []).some(\n (f) => path.basename(f.target ?? f.path) === \"manifest.json\",\n );\n}\n\n/**\n * Locates the frontend root for UI components. AppKit apps put the client in a\n * client/ subdir (with its own components.json + src/); the CLI is typically\n * run from the repo root. Prefer the dir with components.json, then a src/.\n */\nfunction findFrontendRoot(cwd: string): string {\n if (fs.existsSync(path.join(cwd, \"components.json\"))) return cwd;\n for (const sub of FRONTEND_SUBDIRS) {\n if (fs.existsSync(path.join(cwd, sub, \"components.json\"))) {\n return path.join(cwd, sub);\n }\n }\n if (isDir(path.join(cwd, \"src\"))) return cwd;\n for (const sub of FRONTEND_SUBDIRS) {\n if (isDir(path.join(cwd, sub, \"src\"))) return path.join(cwd, sub);\n }\n return cwd;\n}\n\n/** Locates the server root for plugins (the server/ subdir, else cwd). */\nfunction findServerRoot(cwd: string): string {\n for (const sub of SERVER_SUBDIRS) {\n if (isDir(path.join(cwd, sub))) return path.join(cwd, sub);\n }\n return cwd;\n}\n\n/** Nearest dir with a package.json, walking up from start (for dep install). */\nfunction findNearestPackageJson(start: string): string {\n let dir = start;\n for (;;) {\n if (fs.existsSync(path.join(dir, \"package.json\"))) return dir;\n const parent = path.dirname(dir);\n if (parent === dir) return start;\n dir = parent;\n }\n}\n\n/**\n * The Databricks profile the app is configured with, read from\n * `DATABRICKS_CONFIG_PROFILE` in `cwd/.env` via the same dotenv parser the app\n * loads its env with. The CLI's top-level `dotenv/config` only loads the launch\n * dir's `.env` into `process.env`; when `--cwd` points at a different app dir,\n * that file isn't loaded, so the workspace picker and bundle validate would\n * miss the app's profile — this reads it directly. Undefined if the file or key\n * is absent, so the SDK's own default resolution still applies.\n */\nexport function profileFromEnv(cwd: string): string | undefined {\n try {\n const content = fs.readFileSync(path.join(cwd, \".env\"), \"utf-8\");\n return parseEnv(content).DATABRICKS_CONFIG_PROFILE || undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Resolves a registry item's `target` under `base`, enforcing that the result\n * stays inside `base`. Registry items are untrusted remote data; a `target`\n * like `../../../.zshrc` or an absolute path could otherwise write files\n * anywhere on disk (arbitrary-write → RCE). Throws on any escape.\n */\nexport function resolveWithinBase(base: string, target: string): string {\n if (path.isAbsolute(target)) {\n throw new Error(`Refusing absolute file target from registry: ${target}`);\n }\n const baseResolved = path.resolve(base);\n const resolved = path.resolve(baseResolved, target);\n if (\n resolved !== baseResolved &&\n !resolved.startsWith(baseResolved + path.sep)\n ) {\n throw new Error(\n `Refusing file target that escapes the destination directory: ${target}`,\n );\n }\n return resolved;\n}\n\n/** UI file destination (relative to the frontend root): placed in src/ if present. */\nfunction uiTargetPath(base: string, file: RegistryItemFile): string {\n let target = file.target ?? path.join(\"components\", path.basename(file.path));\n if (!target.startsWith(\"src/\") && isDir(path.join(base, \"src\"))) {\n target = path.join(\"src\", target);\n }\n return target;\n}\n\n/** Best-effort: the `toPlugin` export name from the item's index.ts. Returns\n * null (caller falls back to printed instructions) unless the name is a plain\n * JS identifier — the item is untrusted remote content and the value is\n * interpolated into the user's server.ts. */\nexport function pluginExportName(item: RegistryItem): string | null {\n const index = (item.files ?? []).find(\n (f) => path.basename(f.target ?? f.path) === \"index.ts\",\n );\n const match = index?.content.match(/export\\s*\\{([^}]*)\\}/);\n if (!match) return null;\n const names = match[1].split(\",\").map((s) => s.trim());\n // Prefer the camelCase toPlugin instance over the PascalCase class.\n const chosen = names.find((n) => /^[a-z]/.test(n)) ?? names[0];\n return chosen && JS_IDENTIFIER.test(chosen) ? chosen : null;\n}\n\n/**\n * A safe npm dependency spec: `[@scope/]name` with an optional `@version`\n * range. Registry `dependencies` are untrusted remote data passed to the\n * package manager, so we reject anything that isn't a plain name+range —\n * blocks tarball/git URL specs (install-script RCE) and `-`-prefixed entries\n * that the PM would parse as flags (argument injection).\n */\nconst SAFE_DEP_SPEC =\n /^(@[a-z0-9][\\w.-]*\\/)?[a-z0-9][\\w.-]*(@[\\w.\\-+~^><=|* ]+)?$/i;\n\n/** Splits deps into safe (installable) and rejected (surfaced to the user). */\nexport function partitionDeps(deps: string[]): {\n safe: string[];\n rejected: string[];\n} {\n const safe: string[] = [];\n const rejected: string[] = [];\n for (const dep of deps) {\n if (dep.startsWith(\"-\") || !SAFE_DEP_SPEC.test(dep)) rejected.push(dep);\n else safe.push(dep);\n }\n return { safe, rejected };\n}\n\n/** Splits an npm spec into `name` and optional version `range`, handling the\n * leading `@` of scoped names (`@databricks/appkit-ui@^0.41.0` → name\n * `@databricks/appkit-ui`, range `^0.41.0`; `lodash` → no range). */\nexport function parseDepSpec(spec: string): { name: string; range?: string } {\n const at = spec.lastIndexOf(\"@\");\n // at <= 0 means either no `@` (bare name) or the scope's `@` at index 0.\n if (at <= 0) return { name: spec };\n return { name: spec.slice(0, at), range: spec.slice(at + 1) };\n}\n\n/**\n * Registry `dependencies` are floors (\"needs at least this version\"), not pins.\n * Against the versions already in the target `package.json`, returns which specs\n * to install: missing packages (as declared) and genuine upgrades (installed\n * floor below the requested floor). A package already at a same-or-newer version\n * is skipped so the package manager never downgrades it; ranges that can't be\n * compared (workspace:*, catalog:, git) are skipped for the same reason.\n *\n * `semver` is injected so the caller can lazy-load it (see `installDependencies`).\n */\nexport function reconcileDeps(\n specs: string[],\n installed: Record<string, string>,\n { gte, minVersion }: Pick<typeof import(\"semver\"), \"gte\" | \"minVersion\">,\n): { install: string[]; skipped: string[] } {\n // minVersion() throws on ranges it can't parse (workspace:*, catalog:, git);\n // treat those as uncomparable and skip rather than risk a downgrade.\n const floor = (range: string): string | null => {\n try {\n return minVersion(range)?.version ?? null;\n } catch {\n return null;\n }\n };\n const install: string[] = [];\n const skipped: string[] = [];\n for (const spec of specs) {\n const { name, range } = parseDepSpec(spec);\n const have = installed[name];\n if (!have) {\n install.push(spec); // missing → install as declared\n continue;\n }\n if (!range) {\n skipped.push(spec); // present, no version asked → keep what's there\n continue;\n }\n const reqFloor = floor(range);\n const haveFloor = floor(have);\n if (!reqFloor || !haveFloor) {\n skipped.push(spec); // can't compare safely → don't touch\n } else if (gte(haveFloor, reqFloor)) {\n skipped.push(spec); // installed is same-or-newer → keep (no downgrade)\n } else {\n install.push(spec); // installed is older than required → upgrade\n }\n }\n return { install, skipped };\n}\n\n/** Merged dependencies + devDependencies (name → declared range) of a\n * package.json, tolerating a missing/unreadable file (returns {}). */\nfunction readInstalledRanges(pkgPath: string): Record<string, string> {\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\")) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n return { ...pkg.dependencies, ...pkg.devDependencies };\n } catch {\n return {};\n }\n}\n\nasync function installDependencies(deps: string[], cwd: string): Promise<void> {\n if (deps.length === 0) return;\n\n const { safe, rejected } = partitionDeps(deps);\n if (rejected.length > 0) {\n console.warn(\n pc.yellow(\n `Skipping suspicious dependenc${rejected.length === 1 ? \"y\" : \"ies\"} from the registry (not a plain name@version): ${rejected.join(\", \")}. Install manually if you trust them.`,\n ),\n );\n }\n if (safe.length === 0) return;\n\n const pkgPath = path.join(cwd, \"package.json\");\n if (!fs.existsSync(pkgPath)) {\n console.warn(\n pc.yellow(\n `No package.json found — install these manually: ${safe.join(\" \")}`,\n ),\n );\n return;\n }\n\n // Lazy import: this file is loaded eagerly by the CLI entry, so keep semver\n // (only needed here) off the startup path — as with server-register/env-writer.\n const semver = await import(\"semver\");\n const { install, skipped } = reconcileDeps(\n safe,\n readInstalledRanges(pkgPath),\n semver,\n );\n if (skipped.length > 0) {\n console.log(\n pc.dim(\n `Keeping already-installed (registry asked for an older/equal range): ${skipped.join(\", \")}`,\n ),\n );\n }\n if (install.length === 0) return;\n\n const pm = detectPackageManager(cwd, \"npm\");\n const subcommand = pm === \"npm\" ? \"install\" : \"add\";\n console.log(`\\nInstalling dependencies with ${pm}: ${install.join(\" \")}`);\n // `--` stops the PM from parsing any dep as a flag (defense in depth).\n const result = spawnSync(pm, [subcommand, \"--\", ...install], {\n stdio: \"inherit\",\n cwd,\n });\n if (result.status !== 0) {\n console.warn(\n pc.yellow(\n `Dependency install exited with code ${result.status ?? \"unknown\"} — install manually if needed: ${install.join(\" \")}`,\n ),\n );\n }\n}\n\n/** Runs `appkit plugin sync --write` via this same CLI binary. */\nfunction runPluginSync(cwd: string): void {\n const result = spawnSync(\n process.execPath,\n [process.argv[1], \"plugin\", \"sync\", \"--write\"],\n { stdio: \"inherit\", cwd },\n );\n if (result.status !== 0) {\n console.warn(\n pc.yellow(\n \" Plugin sync did not complete cleanly — run `appkit plugin sync --write` manually.\",\n ),\n );\n }\n}\n\nfunction writeItemFile(\n base: string,\n target: string,\n content: string,\n force: boolean,\n cwd: string,\n): void {\n const dest = resolveWithinBase(base, target);\n const existed = fs.existsSync(dest);\n if (existed && !force) {\n console.error(\n pc.red(\n `Refusing to overwrite ${path.relative(cwd, dest)} — pass --force to replace it.`,\n ),\n );\n process.exit(1);\n }\n fs.mkdirSync(path.dirname(dest), { recursive: true });\n fs.writeFileSync(dest, content);\n const label = existed ? pc.yellow(\"Updated\") : pc.green(\"Created\");\n console.log(`${label} ${path.relative(cwd, dest)}`);\n}\n\ninterface PluginSummary {\n importPath: string;\n exportName: string | null;\n}\n\n/**\n * Fetches the requested items plus their transitive registryDependencies.\n * Dependencies are resolved breadth-first and de-duplicated by name, so a\n * plugin that depends on another registry item pulls the whole graph in one\n * `add`. Explicitly-requested items keep their request order and come first.\n */\nexport async function resolveItems(\n names: string[],\n fetchItem: (name: string) => Promise<RegistryItem> = fetchRegistryItem,\n): Promise<RegistryItem[]> {\n const seen = new Set<string>();\n const ordered: RegistryItem[] = [];\n // A name is both the fetch path and the on-disk `plugins/<name>` dir, so\n // reject non-slug refs (`/`, `..`, control chars) before they reach either.\n const enqueue = (ref: string): string => {\n const name = stripNamespace(ref);\n if (!isValidItemName(name)) {\n throw new Error(`Invalid registry item name: ${JSON.stringify(ref)}`);\n }\n return name;\n };\n // Breadth-first over the dependency graph, one level per iteration. Items in\n // a level are fetched concurrently (fetch latency is additive otherwise), but\n // levels stay ordered and dedup/cycle handling is unchanged: a name is marked\n // seen before its level is fetched, so it's never fetched or queued twice.\n let level = names.map(enqueue).filter((name) => {\n if (seen.has(name)) return false;\n seen.add(name);\n return true;\n });\n\n while (level.length > 0) {\n const items = await Promise.all(\n level.map(async (key) => {\n const item = await fetchItem(key);\n // Pin to the fetch key: the body's self-reported `name` is untrusted\n // and could claim a verified name to slip past the gate. The key is the\n // trustworthy identity the index keys `verified` on.\n item.name = key;\n return item;\n }),\n );\n ordered.push(...items);\n const next: string[] = [];\n for (const item of items) {\n for (const dep of item.registryDependencies ?? []) {\n const depName = enqueue(dep);\n if (seen.has(depName)) continue;\n seen.add(depName);\n next.push(depName);\n }\n }\n level = next;\n }\n\n return ordered;\n}\n\ninterface AddOptions {\n force?: boolean;\n cwd?: string;\n register?: boolean;\n /** false = don't reconcile resource env vars into .env. */\n resources?: boolean;\n /** true = never prompt; use --env flags or leave unset (agent/CI). */\n yes?: boolean;\n /** Pre-supplied env values from repeated --env KEY=VALUE flags. */\n env?: Record<string, string>;\n /** Databricks profile passed to `bundle validate` after writing config. */\n profile?: string;\n /** true = install items the registry index doesn't mark verified. */\n allowUnverified?: boolean;\n}\n\n/**\n * Splits requested names into verified and unverified against the index's\n * verified set. When `verified` is null the index couldn't be read — we can't\n * prove anything is verified, so every name is treated as unverified (the gate\n * then decides whether to warn-and-continue or block). Names are compared with\n * the namespace stripped, matching how items are fetched.\n */\nexport function partitionVerified(\n refs: string[],\n verified: Set<string> | null,\n): { verified: string[]; unverified: string[] } {\n const ok: string[] = [];\n const bad: string[] = [];\n for (const ref of refs) {\n const name = stripNamespace(ref);\n if (verified?.has(name)) ok.push(name);\n else bad.push(name);\n }\n return { verified: ok, unverified: bad };\n}\n\nasync function runAdd(refs: string[], opts: AddOptions): Promise<void> {\n const cwd = opts.cwd ? path.resolve(opts.cwd) : process.cwd();\n\n // Resolve the full graph and fetch the verified index concurrently (two\n // independent round-trips). Item resolution is read-only — nothing is written\n // or installed until after the gate below.\n const verifiedP = opts.allowUnverified\n ? Promise.resolve(null)\n : fetchVerifiedNames();\n const items = await resolveItems(refs);\n\n // Integrity gate over the *entire resolved set* (not just requested names, so\n // an unverified transitive dep can't ride in on a verified item). Fails closed:\n // a null verified set (unreadable index) makes every item count as unverified.\n if (!opts.allowUnverified) {\n const verified = await verifiedP;\n const { unverified } = partitionVerified(\n items.map((i) => i.name),\n verified,\n );\n if (unverified.length > 0) {\n const reason =\n verified === null\n ? \"could not read the registry index to verify these items\"\n : `not marked verified in ${REGISTRY_REPO}`;\n console.error(\n pc.red(\n `Refusing to add unverified item(s) (${reason}): ${unverified.join(\", \")}.`,\n ),\n );\n console.error(\n pc.dim(\n \" Re-run with --allow-unverified if you trust the source; unverified items run code in your app.\",\n ),\n );\n process.exit(1);\n }\n }\n\n const hasUi = items.some((i) => !isPluginItem(i));\n const hasPlugin = items.some(isPluginItem);\n const frontendRoot = hasUi ? findFrontendRoot(cwd) : cwd;\n const serverRoot = hasPlugin ? findServerRoot(cwd) : cwd;\n if (hasUi && frontendRoot !== cwd) {\n console.log(pc.dim(`UI components → ${path.relative(cwd, frontendRoot)}/`));\n }\n if (hasPlugin && serverRoot !== cwd) {\n console.log(pc.dim(`Plugins → ${path.relative(cwd, serverRoot)}/`));\n }\n\n const deps = new Set<string>();\n let wroteUi = false;\n const pluginSummaries: PluginSummary[] = [];\n const allRequirements: ResourceRequirementRow[] = [];\n\n for (const item of items) {\n for (const dep of item.dependencies ?? []) deps.add(dep);\n\n if (isPluginItem(item)) {\n let pluginRel = path.join(\"plugins\", item.name);\n for (const file of item.files ?? []) {\n const target =\n file.target ??\n path.join(\"plugins\", item.name, path.basename(file.path));\n writeItemFile(\n serverRoot,\n target,\n file.content,\n Boolean(opts.force),\n cwd,\n );\n if (path.basename(target) === \"manifest.json\") {\n pluginRel = path.dirname(target);\n }\n }\n const requirements = extractRequirements(item);\n if (requirements.length > 0) {\n console.log(`\\n${renderRequirements(item, requirements)}`);\n allRequirements.push(...requirements);\n }\n pluginSummaries.push({\n importPath: `./${pluginRel}`,\n exportName: pluginExportName(item),\n });\n } else {\n for (const file of item.files ?? []) {\n writeItemFile(\n frontendRoot,\n uiTargetPath(frontendRoot, file),\n file.content,\n Boolean(opts.force),\n cwd,\n );\n wroteUi = true;\n }\n }\n }\n\n await installDependencies([...deps], findNearestPackageJson(cwd));\n\n if (hasPlugin) {\n console.log(pc.dim(\"\\nRegistering plugins (appkit plugin sync)...\"));\n runPluginSync(cwd);\n }\n\n if (wroteUi) {\n console.log(\n pc.dim(\n '\\nReminder: import \"@databricks/appkit-ui/styles.css\" once at your app root so components are themed.',\n ),\n );\n }\n // Lazy import: server-register pulls in @ast-grep/napi (a native addon), and\n // this CLI is imported eagerly by index.ts, so a static import would make\n // every unrelated command pay that cost.\n const registerPluginInServer =\n opts.register !== false && pluginSummaries.some((s) => s.exportName)\n ? (await import(\"./server-register.js\")).registerPluginInServer\n : null;\n for (const s of pluginSummaries) {\n // Try to wire the plugin into the server's createApp call automatically;\n // fall back to printing the snippet when the shape isn't the standard one.\n let wired = false;\n // Why auto-registration was skipped, so the fallback can say so (an empty\n // reason means the user opted out via --no-register — no nag then).\n let skipReason: string | undefined;\n if (opts.register === false) {\n // opted out — print the snippet without a \"couldn't\" message\n } else if (!s.exportName) {\n skipReason =\n \"couldn't read a plugin export name from the item's index.ts\";\n } else if (registerPluginInServer) {\n const result = registerPluginInServer(\n serverRoot,\n s.importPath,\n s.exportName,\n );\n // result.file is relative to serverRoot; show it from cwd for the user.\n const shown =\n result.file && path.relative(cwd, path.join(serverRoot, result.file));\n if (result.status === \"wired\") {\n console.log(`\\n${pc.green(\"Registered\")} ${s.exportName} in ${shown}`);\n wired = true;\n } else if (result.status === \"already\") {\n console.log(\n pc.dim(`\\n${s.exportName} is already registered in ${shown}`),\n );\n wired = true;\n } else {\n skipReason = result.reason;\n }\n }\n if (!wired) {\n const imp = s.exportName ?? \"<plugin>\";\n if (skipReason) {\n console.log(\n pc.yellow(`\\nCouldn't auto-register ${imp} — ${skipReason}.`),\n );\n }\n console.log(\n `${pc.bold(\"Add this to your server's createApp call:\")}\\n` +\n pc.dim(\n ` import { ${imp} } from \"${s.importPath}\";\\n` +\n ` const app = await createApp({ plugins: [${imp}(), /* ... */] });`,\n ),\n );\n }\n }\n\n if (opts.resources !== false && allRequirements.length > 0) {\n // Lazy import (same reason as server-register above): env-writer pulls in\n // the workspace picker and, through it, the Databricks SDK.\n const { collectBindingValues, reportEnvResolutions, syncEnv } =\n await import(\"./env-writer.js\");\n // Without --profile, fall back to the app's configured profile so the\n // picker and bundle validate reach the workspace the app runs against.\n const profile = opts.profile ?? profileFromEnv(cwd);\n console.log(pc.dim(\"\\nReconciling resource env vars into .env...\"));\n const resolutions = await syncEnv(allRequirements, {\n cwd,\n nonInteractive: Boolean(opts.yes),\n values: opts.env,\n profile,\n });\n reportEnvResolutions(resolutions);\n\n // Deploy config (app.yaml + databricks.yml). Values come from what the\n // user supplied for env fields (flags or prompts); other fields fall back\n // to their manifest defaults inside buildConfigPlan.\n const values: Record<string, string> = { ...(opts.env ?? {}) };\n for (const r of resolutions) {\n if (r.value !== undefined) values[r.env] = r.value;\n }\n // Binding fields with no env name (e.g. postgres project/branch/database)\n // never flow through .env, so collect them separately — else their\n // databricks.yml bundle variables stay unassigned and bundle validate fails.\n const bindingNeeds = collectBindingValueNeeds(allRequirements);\n if (bindingNeeds.length > 0) {\n const bindingValues = await collectBindingValues(bindingNeeds, {\n cwd,\n nonInteractive: Boolean(opts.yes),\n values: opts.env,\n profile,\n });\n Object.assign(values, bindingValues);\n }\n const plan = buildConfigPlan(allRequirements, values);\n if (planHasContent(plan)) {\n const result = writeConfig(cwd, plan);\n reportConfigWrite(result);\n if (result.databricksYmlChanged) validateBundle(cwd, profile);\n }\n warnScopeNeeding(allRequirements);\n }\n}\n\n/**\n * v1 does not write `user_api_scopes` (deferred to the manifest scope\n * extension). Warn when an added plugin's resource type is known to need one,\n * so the user adds it before deploy.\n */\n/** Returns the user_api_scopes implied by a set of resource rows (deduped). */\nexport function scopesForResources(\n rows: ResourceRequirementRow[],\n): Map<string, string> {\n const needed = new Map<string, string>();\n for (const row of rows) {\n if (Object.hasOwn(SCOPE_BY_TYPE, row.type)) {\n needed.set(\n row.type,\n SCOPE_BY_TYPE[row.type as keyof typeof SCOPE_BY_TYPE],\n );\n }\n }\n return needed;\n}\n\nfunction warnScopeNeeding(rows: ResourceRequirementRow[]): void {\n const needed = scopesForResources(rows);\n if (needed.size === 0) return;\n const list = [...needed.entries()]\n .map(([type, scope]) => `${type} → ${scope}`)\n .join(\", \");\n console.warn(\n pc.yellow(\n `\\n Note: these resources may need a user_api_scope before deploy: ${list}.\\n` +\n \" Add it under resources.apps.app.user_api_scopes in databricks.yml.\",\n ),\n );\n}\n\n/** Commander reducer for repeatable `--env KEY=VALUE` flags. */\nfunction collectEnvFlag(\n raw: string,\n acc: Record<string, string>,\n): Record<string, string> {\n const eq = raw.indexOf(\"=\");\n if (eq === -1) {\n console.error(`Ignoring --env \"${raw}\" (expected KEY=VALUE).`);\n return acc;\n }\n const key = raw.slice(0, eq).trim();\n const value = raw.slice(eq + 1);\n if (key) acc[key] = value;\n return acc;\n}\n\nexport const addCommand = new Command(\"add\")\n .description(\"Add a UI component or server plugin from the AppKit registry\")\n .argument(\"<item...>\", \"Registry item name(s), e.g. metric-card or hello\")\n .option(\"-f, --force\", \"Overwrite existing files\")\n .option(\"-C, --cwd <dir>\", \"Run as if started in <dir>\")\n .option(\"--no-register\", \"Don't edit the server entry to register plugins\")\n .option(\"--no-resources\", \"Don't reconcile resource env vars into .env\")\n .option(\"-y, --yes\", \"Don't prompt; use --env values or leave vars unset\")\n .option(\n \"--env <KEY=VALUE>\",\n \"Pre-set a resource env var (repeatable)\",\n collectEnvFlag,\n {},\n )\n .option(\n \"-p, --profile <name>\",\n \"Databricks profile for the resource picker and bundle validate (defaults to the app's DATABRICKS_CONFIG_PROFILE)\",\n )\n .option(\n \"--allow-unverified\",\n \"Add items the registry doesn't mark verified (runs untrusted code)\",\n )\n .addHelpText(\n \"after\",\n `\nNo components.json is required. Item type is detected automatically:\n • UI components → <frontend>/src/components/appkit/ (client/ detected)\n • Server plugins → <server>/plugins/<name>/, runs plugin sync, and registers\n them in your createApp call (use --no-register to skip the server edit)\n\nServer plugins declare Databricks resources. On add, their env vars are\nreconciled into .env (and names into .env.example), and the deploy config\n(app.yaml + databricks.yml resource bindings) is patched to match — existing\nentries are never clobbered. Interactive by default; pass --yes for agents/CI\n(uses --env values, leaves the rest unset) and --env KEY=VALUE to supply\nvalues non-interactively. Pass --profile to validate the bundle after writing.\n\nThe frontend/server roots are detected from common layouts, so you can run\nthis from the repo root.\n\nExamples:\n $ appkit add metric-card # UI component\n $ appkit add hello # server plugin\n $ appkit add metric-card hello # mix in one call\n $ appkit add analytics --yes --env DAT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B,QAAO;;AAGT,MAAa,aAAa,IAAI,QAAQ,MAAM,CACzC,YAAY,+DAA+D,CAC3E,SAAS,aAAa,mDAAmD,CACzE,OAAO,eAAe,2BAA2B,CACjD,OAAO,mBAAmB,6BAA6B,CACvD,OAAO,iBAAiB,kDAAkD,CAC1E,OAAO,kBAAkB,8CAA8C,CACvE,OAAO,aAAa,qDAAqD,CACzE,OACC,qBACA,2CACA,gBACA,EAAE,CACH,CACA,OACC,wBACA,mHACD,CACA,OACC,sBACA,qEACD,CACA,YACC,SACA;;;;;;;;;;;;;;;;;;;;qEAqBD,CACA,QAAQ,OAAiB,SACxB,OAAO,OAAO,KAAK,CAAC,OAAO,QAAQ;AACjC,SAAQ,MAAM,IAAI;AAClB,SAAQ,KAAK,EAAE;EACf,CACH"}
1
+ {"version":3,"file":"add.js","names":[],"sources":["../../../../src/cli/commands/registry/add.ts"],"sourcesContent":["import { spawnSync } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport process from \"node:process\";\n\nimport { Command } from \"commander\";\nimport pc from \"picocolors\";\n\nimport { SCOPE_BY_TYPE } from \"../../../schemas/manifest\";\nimport { detectPackageManager } from \"../../package-manager\";\nimport {\n fetchRegistryItem,\n fetchVerifiedNames,\n isValidItemName,\n type RegistryItem,\n type RegistryItemFile,\n stripNamespace,\n} from \"./client\";\nimport {\n buildConfigPlan,\n collectBindingValueNeeds,\n planHasContent,\n} from \"./config-plan\";\nimport {\n preflightConfig,\n reportConfigWrite,\n validateBundle,\n writeConfig,\n} from \"./config-writer\";\nimport { JS_IDENTIFIER, REGISTRY_REPO } from \"./constants\";\nimport { parseEnv } from \"./env-reconcile\";\nimport {\n extractRequirements,\n type ResourceRequirementRow,\n renderRequirements,\n} from \"./requirements\";\n\n/** Subdirectories that commonly hold the frontend / server in an AppKit app. */\nconst FRONTEND_SUBDIRS = [\"client\", \"frontend\", \"web\", \"app\"];\nconst SERVER_SUBDIRS = [\"server\", \"api\", \"backend\"];\n\nfunction isDir(p: string): boolean {\n return fs.existsSync(p) && fs.statSync(p).isDirectory();\n}\n\n/** A registry item is a server plugin if it ships a manifest.json. */\nfunction isPluginItem(item: RegistryItem): boolean {\n return (item.files ?? []).some(\n (f) => path.basename(f.target ?? f.path) === \"manifest.json\",\n );\n}\n\n/**\n * Locates the frontend root for UI components. AppKit apps put the client in a\n * client/ subdir (with its own components.json + src/); the CLI is typically\n * run from the repo root. Prefer the dir with components.json, then a src/.\n */\nfunction findFrontendRoot(cwd: string): string {\n if (fs.existsSync(path.join(cwd, \"components.json\"))) return cwd;\n for (const sub of FRONTEND_SUBDIRS) {\n if (fs.existsSync(path.join(cwd, sub, \"components.json\"))) {\n return path.join(cwd, sub);\n }\n }\n if (isDir(path.join(cwd, \"src\"))) return cwd;\n for (const sub of FRONTEND_SUBDIRS) {\n if (isDir(path.join(cwd, sub, \"src\"))) return path.join(cwd, sub);\n }\n return cwd;\n}\n\n/** Locates the server root for plugins (the server/ subdir, else cwd). */\nexport function findServerRoot(cwd: string): string {\n for (const sub of SERVER_SUBDIRS) {\n if (isDir(path.join(cwd, sub))) return path.join(cwd, sub);\n }\n return cwd;\n}\n\n/** Nearest dir with a package.json, walking up from start (for dep install). */\nfunction findNearestPackageJson(start: string): string {\n let dir = start;\n for (;;) {\n if (fs.existsSync(path.join(dir, \"package.json\"))) return dir;\n const parent = path.dirname(dir);\n if (parent === dir) return start;\n dir = parent;\n }\n}\n\n/**\n * The Databricks profile the app is configured with, read from\n * `DATABRICKS_CONFIG_PROFILE` in `cwd/.env` via the same dotenv parser the app\n * loads its env with. The CLI's top-level `dotenv/config` only loads the launch\n * dir's `.env` into `process.env`; when `--cwd` points at a different app dir,\n * that file isn't loaded, so the workspace picker and bundle validate would\n * miss the app's profile — this reads it directly. Undefined if the file or key\n * is absent, so the SDK's own default resolution still applies.\n */\nexport function profileFromEnv(cwd: string): string | undefined {\n try {\n const content = fs.readFileSync(path.join(cwd, \".env\"), \"utf-8\");\n return parseEnv(content).DATABRICKS_CONFIG_PROFILE || undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Resolves a registry item's `target` under `base`, enforcing that the result\n * stays inside `base`. Registry items are untrusted remote data; a `target`\n * like `../../../.zshrc` or an absolute path could otherwise write files\n * anywhere on disk (arbitrary-write → RCE). Throws on any escape.\n */\nexport function resolveWithinBase(base: string, target: string): string {\n if (path.isAbsolute(target)) {\n throw new Error(`Refusing absolute file target from registry: ${target}`);\n }\n const baseResolved = path.resolve(base);\n const resolved = path.resolve(baseResolved, target);\n if (\n resolved !== baseResolved &&\n !resolved.startsWith(baseResolved + path.sep)\n ) {\n throw new Error(\n `Refusing file target that escapes the destination directory: ${target}`,\n );\n }\n return resolved;\n}\n\n/** UI file destination (relative to the frontend root): placed in src/ if present. */\nfunction uiTargetPath(base: string, file: RegistryItemFile): string {\n let target = file.target ?? path.join(\"components\", path.basename(file.path));\n if (!target.startsWith(\"src/\") && isDir(path.join(base, \"src\"))) {\n target = path.join(\"src\", target);\n }\n return target;\n}\n\n/** Best-effort: the `toPlugin` export name from the item's index.ts. Returns\n * null (caller falls back to printed instructions) unless the name is a plain\n * JS identifier — the item is untrusted remote content and the value is\n * interpolated into the user's server.ts. */\nexport function pluginExportName(item: RegistryItem): string | null {\n const index = (item.files ?? []).find(\n (f) => path.basename(f.target ?? f.path) === \"index.ts\",\n );\n const match = index?.content.match(/export\\s*\\{([^}]*)\\}/);\n if (!match) return null;\n const names = match[1].split(\",\").map((s) => s.trim());\n // Prefer the camelCase toPlugin instance over the PascalCase class.\n const chosen = names.find((n) => /^[a-z]/.test(n)) ?? names[0];\n return chosen && JS_IDENTIFIER.test(chosen) ? chosen : null;\n}\n\n/**\n * A safe npm dependency spec: `[@scope/]name` with an optional `@version`\n * range. Registry `dependencies` are untrusted remote data passed to the\n * package manager, so we reject anything that isn't a plain name+range —\n * blocks tarball/git URL specs (install-script RCE) and `-`-prefixed entries\n * that the PM would parse as flags (argument injection).\n */\nconst SAFE_DEP_SPEC =\n /^(@[a-z0-9][\\w.-]*\\/)?[a-z0-9][\\w.-]*(@[\\w.\\-+~^><=|* ]+)?$/i;\n\n/** Splits deps into safe (installable) and rejected (surfaced to the user). */\nexport function partitionDeps(deps: string[]): {\n safe: string[];\n rejected: string[];\n} {\n const safe: string[] = [];\n const rejected: string[] = [];\n for (const dep of deps) {\n if (dep.startsWith(\"-\") || !SAFE_DEP_SPEC.test(dep)) rejected.push(dep);\n else safe.push(dep);\n }\n return { safe, rejected };\n}\n\n/** Splits an npm spec into `name` and optional version `range`, handling the\n * leading `@` of scoped names (`@databricks/appkit-ui@^0.41.0` → name\n * `@databricks/appkit-ui`, range `^0.41.0`; `lodash` → no range). */\nexport function parseDepSpec(spec: string): { name: string; range?: string } {\n const at = spec.lastIndexOf(\"@\");\n // at <= 0 means either no `@` (bare name) or the scope's `@` at index 0.\n if (at <= 0) return { name: spec };\n return { name: spec.slice(0, at), range: spec.slice(at + 1) };\n}\n\n/**\n * Registry `dependencies` are floors (\"needs at least this version\"), not pins.\n * Against the versions already in the target `package.json`, returns which specs\n * to install: missing packages (as declared) and genuine upgrades (installed\n * floor below the requested floor). A package already at a same-or-newer version\n * is skipped so the package manager never downgrades it; ranges that can't be\n * compared (workspace:*, catalog:, git) are skipped for the same reason.\n *\n * `semver` is injected so the caller can lazy-load it (see `installDependencies`).\n */\nexport function reconcileDeps(\n specs: string[],\n installed: Record<string, string>,\n { gte, minVersion }: Pick<typeof import(\"semver\"), \"gte\" | \"minVersion\">,\n): { install: string[]; skipped: string[] } {\n // minVersion() throws on ranges it can't parse (workspace:*, catalog:, git);\n // treat those as uncomparable and skip rather than risk a downgrade.\n const floor = (range: string): string | null => {\n try {\n return minVersion(range)?.version ?? null;\n } catch {\n return null;\n }\n };\n const install: string[] = [];\n const skipped: string[] = [];\n for (const spec of specs) {\n const { name, range } = parseDepSpec(spec);\n const have = installed[name];\n if (!have) {\n install.push(spec); // missing → install as declared\n continue;\n }\n if (!range) {\n skipped.push(spec); // present, no version asked → keep what's there\n continue;\n }\n const reqFloor = floor(range);\n const haveFloor = floor(have);\n if (!reqFloor || !haveFloor) {\n skipped.push(spec); // can't compare safely → don't touch\n } else if (gte(haveFloor, reqFloor)) {\n skipped.push(spec); // installed is same-or-newer → keep (no downgrade)\n } else {\n install.push(spec); // installed is older than required → upgrade\n }\n }\n return { install, skipped };\n}\n\n/** Merged dependencies + devDependencies (name → declared range) of a\n * package.json, tolerating a missing/unreadable file (returns {}). */\nfunction readInstalledRanges(pkgPath: string): Record<string, string> {\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\")) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n return { ...pkg.dependencies, ...pkg.devDependencies };\n } catch {\n return {};\n }\n}\n\nasync function installDependencies(deps: string[], cwd: string): Promise<void> {\n if (deps.length === 0) return;\n\n const { safe, rejected } = partitionDeps(deps);\n if (rejected.length > 0) {\n console.warn(\n pc.yellow(\n `Skipping suspicious dependenc${rejected.length === 1 ? \"y\" : \"ies\"} from the registry (not a plain name@version): ${rejected.join(\", \")}. Install manually if you trust them.`,\n ),\n );\n }\n if (safe.length === 0) return;\n\n const pkgPath = path.join(cwd, \"package.json\");\n if (!fs.existsSync(pkgPath)) {\n console.warn(\n pc.yellow(\n `No package.json found — install these manually: ${safe.join(\" \")}`,\n ),\n );\n return;\n }\n\n // Lazy import: this file is loaded eagerly by the CLI entry, so keep semver\n // (only needed here) off the startup path — as with server-register/env-writer.\n const semver = await import(\"semver\");\n const { install, skipped } = reconcileDeps(\n safe,\n readInstalledRanges(pkgPath),\n semver,\n );\n if (skipped.length > 0) {\n console.log(\n pc.dim(\n `Keeping already-installed (registry asked for an older/equal range): ${skipped.join(\", \")}`,\n ),\n );\n }\n if (install.length === 0) return;\n\n const pm = detectPackageManager(cwd, \"npm\");\n const subcommand = pm === \"npm\" ? \"install\" : \"add\";\n console.log(`\\nInstalling dependencies with ${pm}: ${install.join(\" \")}`);\n // `--` stops the PM from parsing any dep as a flag (defense in depth).\n const result = spawnSync(pm, [subcommand, \"--\", ...install], {\n stdio: \"inherit\",\n cwd,\n });\n if (result.status !== 0) {\n console.warn(\n pc.yellow(\n `Dependency install exited with code ${result.status ?? \"unknown\"} — install manually if needed: ${install.join(\" \")}`,\n ),\n );\n }\n}\n\n/** Runs `appkit plugin sync --write` via this same CLI binary. */\nfunction runPluginSync(cwd: string): void {\n const result = spawnSync(\n process.execPath,\n [process.argv[1], \"plugin\", \"sync\", \"--write\"],\n { stdio: \"inherit\", cwd },\n );\n if (result.status !== 0) {\n console.warn(\n pc.yellow(\n \" Plugin sync did not complete cleanly — run `appkit plugin sync --write` manually.\",\n ),\n );\n }\n}\n\nfunction writeItemFile(\n base: string,\n target: string,\n content: string,\n force: boolean,\n cwd: string,\n): void {\n const dest = resolveWithinBase(base, target);\n const existed = fs.existsSync(dest);\n if (existed && !force) {\n console.error(\n pc.red(\n `Refusing to overwrite ${path.relative(cwd, dest)} — pass --force to replace it.`,\n ),\n );\n process.exit(1);\n }\n fs.mkdirSync(path.dirname(dest), { recursive: true });\n fs.writeFileSync(dest, content);\n const label = existed ? pc.yellow(\"Updated\") : pc.green(\"Created\");\n console.log(`${label} ${path.relative(cwd, dest)}`);\n}\n\ninterface PluginSummary {\n importPath: string;\n exportName: string | null;\n}\n\n/**\n * Fetches the requested items plus their transitive registryDependencies.\n * Dependencies are resolved breadth-first and de-duplicated by name, so a\n * plugin that depends on another registry item pulls the whole graph in one\n * `add`. Explicitly-requested items keep their request order and come first.\n */\nexport async function resolveItems(\n names: string[],\n fetchItem: (name: string) => Promise<RegistryItem> = fetchRegistryItem,\n): Promise<RegistryItem[]> {\n const seen = new Set<string>();\n const ordered: RegistryItem[] = [];\n // A name is both the fetch path and the on-disk `plugins/<name>` dir, so\n // reject non-slug refs (`/`, `..`, control chars) before they reach either.\n const enqueue = (ref: string): string => {\n const name = stripNamespace(ref);\n if (!isValidItemName(name)) {\n throw new Error(`Invalid registry item name: ${JSON.stringify(ref)}`);\n }\n return name;\n };\n // Breadth-first over the dependency graph, one level per iteration. Items in\n // a level are fetched concurrently (fetch latency is additive otherwise), but\n // levels stay ordered and dedup/cycle handling is unchanged: a name is marked\n // seen before its level is fetched, so it's never fetched or queued twice.\n let level = names.map(enqueue).filter((name) => {\n if (seen.has(name)) return false;\n seen.add(name);\n return true;\n });\n\n while (level.length > 0) {\n const items = await Promise.all(\n level.map(async (key) => {\n const item = await fetchItem(key);\n // Pin to the fetch key: the body's self-reported `name` is untrusted\n // and could claim a verified name to slip past the gate. The key is the\n // trustworthy identity the index keys `verified` on.\n item.name = key;\n return item;\n }),\n );\n ordered.push(...items);\n const next: string[] = [];\n for (const item of items) {\n for (const dep of item.registryDependencies ?? []) {\n const depName = enqueue(dep);\n if (seen.has(depName)) continue;\n seen.add(depName);\n next.push(depName);\n }\n }\n level = next;\n }\n\n return ordered;\n}\n\ninterface AddOptions {\n force?: boolean;\n cwd?: string;\n register?: boolean;\n /** false = don't reconcile resource env vars into .env. */\n resources?: boolean;\n /** true = never prompt; use --env flags or leave unset (agent/CI). */\n yes?: boolean;\n /** Pre-supplied env values from repeated --env KEY=VALUE flags. */\n env?: Record<string, string>;\n /** Databricks profile passed to `bundle validate` after writing config. */\n profile?: string;\n /** true = install items the registry index doesn't mark verified. */\n allowUnverified?: boolean;\n}\n\n/**\n * Splits requested names into verified and unverified against the index's\n * verified set. When `verified` is null the index couldn't be read — we can't\n * prove anything is verified, so every name is treated as unverified (the gate\n * then decides whether to warn-and-continue or block). Names are compared with\n * the namespace stripped, matching how items are fetched.\n */\nexport function partitionVerified(\n refs: string[],\n verified: Set<string> | null,\n): { verified: string[]; unverified: string[] } {\n const ok: string[] = [];\n const bad: string[] = [];\n for (const ref of refs) {\n const name = stripNamespace(ref);\n if (verified?.has(name)) ok.push(name);\n else bad.push(name);\n }\n return { verified: ok, unverified: bad };\n}\n\nasync function runAdd(refs: string[], opts: AddOptions): Promise<void> {\n const cwd = opts.cwd ? path.resolve(opts.cwd) : process.cwd();\n\n // Resolve the full graph and fetch the verified index concurrently (two\n // independent round-trips). Item resolution is read-only — nothing is written\n // or installed until after the gate below.\n const verifiedP = opts.allowUnverified\n ? Promise.resolve(null)\n : fetchVerifiedNames();\n const items = await resolveItems(refs);\n\n // Integrity gate over the *entire resolved set* (not just requested names, so\n // an unverified transitive dep can't ride in on a verified item). Fails closed:\n // a null verified set (unreadable index) makes every item count as unverified.\n if (!opts.allowUnverified) {\n const verified = await verifiedP;\n const { unverified } = partitionVerified(\n items.map((i) => i.name),\n verified,\n );\n if (unverified.length > 0) {\n const reason =\n verified === null\n ? \"could not read the registry index to verify these items\"\n : `not marked verified in ${REGISTRY_REPO}`;\n console.error(\n pc.red(\n `Refusing to add unverified item(s) (${reason}): ${unverified.join(\", \")}.`,\n ),\n );\n console.error(\n pc.dim(\n \" Re-run with --allow-unverified if you trust the source; unverified items run code in your app.\",\n ),\n );\n process.exit(1);\n }\n }\n\n // Before any write, and only when an item has resources (UI items don't).\n if (\n opts.resources !== false &&\n items.some((i) => extractRequirements(i).length > 0)\n ) {\n preflightConfig(cwd);\n }\n\n const hasUi = items.some((i) => !isPluginItem(i));\n const hasPlugin = items.some(isPluginItem);\n const frontendRoot = hasUi ? findFrontendRoot(cwd) : cwd;\n const serverRoot = hasPlugin ? findServerRoot(cwd) : cwd;\n if (hasUi && frontendRoot !== cwd) {\n console.log(pc.dim(`UI components → ${path.relative(cwd, frontendRoot)}/`));\n }\n if (hasPlugin && serverRoot !== cwd) {\n console.log(pc.dim(`Plugins → ${path.relative(cwd, serverRoot)}/`));\n }\n\n const deps = new Set<string>();\n let wroteUi = false;\n const pluginSummaries: PluginSummary[] = [];\n const allRequirements: ResourceRequirementRow[] = [];\n\n for (const item of items) {\n for (const dep of item.dependencies ?? []) deps.add(dep);\n\n if (isPluginItem(item)) {\n let pluginRel = path.join(\"plugins\", item.name);\n for (const file of item.files ?? []) {\n const target =\n file.target ??\n path.join(\"plugins\", item.name, path.basename(file.path));\n writeItemFile(\n serverRoot,\n target,\n file.content,\n Boolean(opts.force),\n cwd,\n );\n if (path.basename(target) === \"manifest.json\") {\n pluginRel = path.dirname(target);\n }\n }\n const requirements = extractRequirements(item);\n if (requirements.length > 0) {\n console.log(`\\n${renderRequirements(item, requirements)}`);\n allRequirements.push(...requirements);\n }\n pluginSummaries.push({\n importPath: `./${pluginRel}`,\n exportName: pluginExportName(item),\n });\n } else {\n for (const file of item.files ?? []) {\n writeItemFile(\n frontendRoot,\n uiTargetPath(frontendRoot, file),\n file.content,\n Boolean(opts.force),\n cwd,\n );\n wroteUi = true;\n }\n }\n }\n\n await installDependencies([...deps], findNearestPackageJson(cwd));\n\n if (hasPlugin) {\n console.log(pc.dim(\"\\nRegistering plugins (appkit plugin sync)...\"));\n runPluginSync(cwd);\n }\n\n if (wroteUi) {\n console.log(\n pc.dim(\n '\\nReminder: import \"@databricks/appkit-ui/styles.css\" once at your app root so components are themed.',\n ),\n );\n }\n // Lazy import: server-register pulls in @ast-grep/napi (a native addon), and\n // this CLI is imported eagerly by index.ts, so a static import would make\n // every unrelated command pay that cost.\n const registerPluginInServer =\n opts.register !== false && pluginSummaries.some((s) => s.exportName)\n ? (await import(\"./server-register.js\")).registerPluginInServer\n : null;\n for (const s of pluginSummaries) {\n // Try to wire the plugin into the server's createApp call automatically;\n // fall back to printing the snippet when the shape isn't the standard one.\n let wired = false;\n // Why auto-registration was skipped, so the fallback can say so (an empty\n // reason means the user opted out via --no-register — no nag then).\n let skipReason: string | undefined;\n if (opts.register === false) {\n // opted out — print the snippet without a \"couldn't\" message\n } else if (!s.exportName) {\n skipReason =\n \"couldn't read a plugin export name from the item's index.ts\";\n } else if (registerPluginInServer) {\n const result = registerPluginInServer(\n serverRoot,\n s.importPath,\n s.exportName,\n );\n // result.file is relative to serverRoot; show it from cwd for the user.\n const shown =\n result.file && path.relative(cwd, path.join(serverRoot, result.file));\n if (result.status === \"wired\") {\n console.log(`\\n${pc.green(\"Registered\")} ${s.exportName} in ${shown}`);\n wired = true;\n } else if (result.status === \"already\") {\n console.log(\n pc.dim(`\\n${s.exportName} is already registered in ${shown}`),\n );\n wired = true;\n } else {\n skipReason = result.reason;\n }\n }\n if (!wired) {\n const imp = s.exportName ?? \"<plugin>\";\n if (skipReason) {\n console.log(\n pc.yellow(`\\nCouldn't auto-register ${imp} — ${skipReason}.`),\n );\n }\n console.log(\n `${pc.bold(\"Add this to your server's createApp call:\")}\\n` +\n pc.dim(\n ` import { ${imp} } from \"${s.importPath}\";\\n` +\n ` const app = await createApp({ plugins: [${imp}(), /* ... */] });`,\n ),\n );\n }\n }\n\n if (opts.resources !== false && allRequirements.length > 0) {\n // Lazy import (same reason as server-register above): env-writer pulls in\n // the workspace picker and, through it, the Databricks SDK.\n const { collectBindingValues, reportEnvResolutions, syncEnv } =\n await import(\"./env-writer.js\");\n // Without --profile, fall back to the app's configured profile so the\n // picker and bundle validate reach the workspace the app runs against.\n const profile = opts.profile ?? profileFromEnv(cwd);\n console.log(pc.dim(\"\\nReconciling resource env vars into .env...\"));\n const resolutions = await syncEnv(allRequirements, {\n cwd,\n nonInteractive: Boolean(opts.yes),\n values: opts.env,\n profile,\n });\n reportEnvResolutions(resolutions);\n\n // Deploy config (app.yaml + databricks.yml). Values come from what the\n // user supplied for env fields (flags or prompts); other fields fall back\n // to their manifest defaults inside buildConfigPlan.\n const values: Record<string, string> = { ...(opts.env ?? {}) };\n for (const r of resolutions) {\n if (r.value !== undefined) values[r.env] = r.value;\n }\n // Binding fields with no env name (e.g. postgres project/branch/database)\n // never flow through .env, so collect them separately — else their\n // databricks.yml bundle variables stay unassigned and bundle validate fails.\n const bindingNeeds = collectBindingValueNeeds(allRequirements);\n if (bindingNeeds.length > 0) {\n const bindingValues = await collectBindingValues(bindingNeeds, {\n cwd,\n nonInteractive: Boolean(opts.yes),\n values: opts.env,\n profile,\n });\n Object.assign(values, bindingValues);\n }\n const plan = buildConfigPlan(allRequirements, values);\n if (planHasContent(plan)) {\n const result = writeConfig(cwd, plan);\n reportConfigWrite(result);\n if (result.databricksYmlChanged) validateBundle(cwd, profile);\n }\n warnScopeNeeding(allRequirements);\n }\n}\n\n/**\n * v1 does not write `user_api_scopes` (deferred to the manifest scope\n * extension). Warn when an added plugin's resource type is known to need one,\n * so the user adds it before deploy.\n */\n/** Returns the user_api_scopes implied by a set of resource rows (deduped). */\nexport function scopesForResources(\n rows: ResourceRequirementRow[],\n): Map<string, string> {\n const needed = new Map<string, string>();\n for (const row of rows) {\n if (Object.hasOwn(SCOPE_BY_TYPE, row.type)) {\n needed.set(\n row.type,\n SCOPE_BY_TYPE[row.type as keyof typeof SCOPE_BY_TYPE],\n );\n }\n }\n return needed;\n}\n\nfunction warnScopeNeeding(rows: ResourceRequirementRow[]): void {\n const needed = scopesForResources(rows);\n if (needed.size === 0) return;\n const list = [...needed.entries()]\n .map(([type, scope]) => `${type} → ${scope}`)\n .join(\", \");\n console.warn(\n pc.yellow(\n `\\n Note: these resources may need a user_api_scope before deploy: ${list}.\\n` +\n \" Add it under resources.apps.app.user_api_scopes in databricks.yml.\",\n ),\n );\n}\n\n/** Commander reducer for repeatable `--env KEY=VALUE` flags. */\nfunction collectEnvFlag(\n raw: string,\n acc: Record<string, string>,\n): Record<string, string> {\n const eq = raw.indexOf(\"=\");\n if (eq === -1) {\n console.error(`Ignoring --env \"${raw}\" (expected KEY=VALUE).`);\n return acc;\n }\n const key = raw.slice(0, eq).trim();\n const value = raw.slice(eq + 1);\n if (key) acc[key] = value;\n return acc;\n}\n\nexport const addCommand = new Command(\"add\")\n .description(\"Add a UI component or server plugin from the AppKit registry\")\n .argument(\"<item...>\", \"Registry item name(s), e.g. metric-card or hello\")\n .option(\"-f, --force\", \"Overwrite existing files\")\n .option(\"-C, --cwd <dir>\", \"Run as if started in <dir>\")\n .option(\"--no-register\", \"Don't edit the server entry to register plugins\")\n .option(\"--no-resources\", \"Don't reconcile resource env vars into .env\")\n .option(\"-y, --yes\", \"Don't prompt; use --env values or leave vars unset\")\n .option(\n \"--env <KEY=VALUE>\",\n \"Pre-set a resource env var (repeatable)\",\n collectEnvFlag,\n {},\n )\n .option(\n \"-p, --profile <name>\",\n \"Databricks profile for the resource picker and bundle validate (defaults to the app's DATABRICKS_CONFIG_PROFILE)\",\n )\n .option(\n \"--allow-unverified\",\n \"Add items the registry doesn't mark verified (runs untrusted code)\",\n )\n .addHelpText(\n \"after\",\n `\nNo components.json is required. Item type is detected automatically:\n • UI components → <frontend>/src/components/appkit/ (client/ detected)\n • Server plugins → <server>/plugins/<name>/, runs plugin sync, and registers\n them in your createApp call (use --no-register to skip the server edit)\n\nServer plugins declare Databricks resources. On add, their env vars are\nreconciled into .env (and names into .env.example), and the deploy config\n(app.yaml + databricks.yml resource bindings) is patched to match — existing\nentries are never clobbered. Interactive by default; pass --yes for agents/CI\n(uses --env values, leaves the rest unset) and --env KEY=VALUE to supply\nvalues non-interactively. Pass --profile to validate the bundle after writing.\n\nThe frontend/server roots are detected from common layouts, so you can run\nthis from the repo root.\n\nExamples:\n $ appkit add metric-card # UI component\n $ appkit add hello # server plugin\n $ appkit add metric-card hello # mix in one call\n $ appkit add analytics --yes --env DATABRICKS_WAREHOUSE_ID=abc123`,\n )\n .action((items: string[], opts: AddOptions) =>\n runAdd(items, opts).catch((err) => {\n console.error(err);\n process.exit(1);\n }),\n );\n"],"mappings":";;;;;;;;;;;;;;;;;AAsCA,MAAM,mBAAmB;CAAC;CAAU;CAAY;CAAO;CAAM;AAC7D,MAAM,iBAAiB;CAAC;CAAU;CAAO;CAAU;AAEnD,SAAS,MAAM,GAAoB;AACjC,QAAO,GAAG,WAAW,EAAE,IAAI,GAAG,SAAS,EAAE,CAAC,aAAa;;;AAIzD,SAAS,aAAa,MAA6B;AACjD,SAAQ,KAAK,SAAS,EAAE,EAAE,MACvB,MAAM,KAAK,SAAS,EAAE,UAAU,EAAE,KAAK,KAAK,gBAC9C;;;;;;;AAQH,SAAS,iBAAiB,KAAqB;AAC7C,KAAI,GAAG,WAAW,KAAK,KAAK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;AACjC,SAAQ,MAAM,IAAI;AAClB,SAAQ,KAAK,EAAE;EACf,CACH"}
@@ -102,7 +102,7 @@ function collectBindingValueNeeds(rows) {
102
102
  }
103
103
  /** True when the plan has any deploy-config content to write. */
104
104
  function planHasContent(plan) {
105
- return plan.appYamlEnv.length > 0 || plan.bundleVariables.length > 0 || plan.resourceBindings.length > 0;
105
+ return plan.appYamlEnv.length > 0 || plan.bundleVariables.length > 0 || plan.resourceBindings.length > 0 || (plan.userApiScopes?.length ?? 0) > 0;
106
106
  }
107
107
 
108
108
  //#endregion