@dench.com/cli 2.9.5-staging.239 → 2.9.6-staging.252

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.
@@ -0,0 +1,469 @@
1
+ /**
2
+ * `dench apps validate` — static checks for a `.dench.app` folder.
3
+ *
4
+ * Pure: takes the manifest text and the app's text files, returns findings.
5
+ * The CLI (`cli/apps.ts`) reads the folder (disk or workspace) and prints.
6
+ *
7
+ * What it catches — every one of these has shipped as a broken app before:
8
+ * • a `dench.<ns>.<method>(` call that does not exist on `window.dench`
9
+ * (with the namespace's real methods as the hint),
10
+ * • a call whose permission the manifest does not declare,
11
+ * • `dench.api.call("<id>")` / `dench.api.a.b.c(` for an id that is not a
12
+ * public `/api/v1` operation (or is CLI-local),
13
+ * • removed APIs (`dench.db.*`), deprecated aliases (`dench.apps.send`),
14
+ * • unknown permission scopes in the manifest,
15
+ * • same-origin `fetch("/api/…")` (bypasses the bridge) and external
16
+ * `<script src>` / `<link href>` (blocked by CSP).
17
+ */
18
+ import {
19
+ APP_SDK_LOCAL_OPERATIONS,
20
+ APP_SDK_METHODS,
21
+ APP_SDK_OPERATIONS,
22
+ APP_SDK_SCOPES,
23
+ appSdkOperation,
24
+ } from "./app-sdk-catalog.generated";
25
+
26
+ export type ValidationFinding = {
27
+ level: "error" | "warning";
28
+ code:
29
+ | "manifest_missing"
30
+ | "manifest_name"
31
+ | "manifest_entry_missing"
32
+ | "manifest_unknown_permission"
33
+ | "unknown_method"
34
+ | "unknown_operation"
35
+ | "local_operation"
36
+ | "missing_permission"
37
+ | "deprecated_method"
38
+ | "same_origin_fetch"
39
+ | "external_resource"
40
+ | "no_bridge_calls";
41
+ message: string;
42
+ file?: string;
43
+ line?: number;
44
+ };
45
+
46
+ export type ValidationResult = {
47
+ ok: boolean;
48
+ errors: ValidationFinding[];
49
+ warnings: ValidationFinding[];
50
+ /** Every distinct `dench.*` call found (for `--json` consumers). */
51
+ calls: string[];
52
+ /** Permissions the code needs, whether or not declared. */
53
+ requiredPermissions: string[];
54
+ };
55
+
56
+ export type AppFile = { path: string; content: string };
57
+
58
+ /** Minimal `.dench.yaml` reader: top-level scalars + block/inline lists. */
59
+ export function parseAppManifest(yaml: string): Record<string, unknown> {
60
+ const out: Record<string, unknown> = {};
61
+ const lines = yaml.split(/\r?\n/);
62
+ const indentOf = (s: string) => s.length - s.trimStart().length;
63
+ const coerce = (raw: string): string => {
64
+ const v = raw.trim();
65
+ if (
66
+ (v.startsWith('"') && v.endsWith('"')) ||
67
+ (v.startsWith("'") && v.endsWith("'"))
68
+ ) {
69
+ return v.slice(1, -1);
70
+ }
71
+ return v;
72
+ };
73
+ let i = 0;
74
+ while (i < lines.length) {
75
+ const line = lines[i];
76
+ i += 1;
77
+ if (!line.trim() || line.trim().startsWith("#") || indentOf(line) !== 0)
78
+ continue;
79
+ const m = line.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);
80
+ if (!m) continue;
81
+ const key = m[1];
82
+ const val = m[2].replace(/\s+#.*$/, "").trim();
83
+ if (val.startsWith("[") && val.endsWith("]")) {
84
+ out[key] = val
85
+ .slice(1, -1)
86
+ .split(",")
87
+ .map((s) => coerce(s))
88
+ .filter(Boolean);
89
+ continue;
90
+ }
91
+ if (val) {
92
+ out[key] = coerce(val);
93
+ continue;
94
+ }
95
+ const items: string[] = [];
96
+ let sawList = false;
97
+ while (i < lines.length) {
98
+ const next = lines[i];
99
+ if (!next.trim()) {
100
+ i += 1;
101
+ continue;
102
+ }
103
+ if (indentOf(next) === 0) break;
104
+ if (next.trim().startsWith("- ")) {
105
+ sawList = true;
106
+ items.push(coerce(next.trim().slice(2)));
107
+ }
108
+ i += 1;
109
+ }
110
+ if (sawList) out[key] = items;
111
+ }
112
+ return out;
113
+ }
114
+
115
+ export type DenchCall = {
116
+ /** `ns.method`, or for dench.api: `api.call` / `api.<path>`. */
117
+ method: string;
118
+ /** Operation id when the call targets dench.api. */
119
+ operationId?: string;
120
+ file: string;
121
+ line: number;
122
+ };
123
+
124
+ const CALL_RE =
125
+ /\bdench\.([A-Za-z_$][\w$]*)((?:\.[A-Za-z_$][\w$]*)+)\s*\(\s*(?:(["'`])([^"'`]+)\3)?/g;
126
+
127
+ /** Every `dench.<ns>.<method>(` (and `dench.api…`) call in a text file. */
128
+ export function scanDenchCalls(file: AppFile): DenchCall[] {
129
+ const calls: DenchCall[] = [];
130
+ const text = file.content;
131
+ for (const match of text.matchAll(CALL_RE)) {
132
+ const ns = match[1];
133
+ const rest = match[2].slice(1).split(".");
134
+ const line = text.slice(0, match.index).split("\n").length;
135
+ if (ns === "api") {
136
+ if (rest[0] === "call") {
137
+ calls.push({
138
+ method: "api.call",
139
+ operationId: match[4] ?? undefined,
140
+ file: file.path,
141
+ line,
142
+ });
143
+ } else if (rest[0] === "operations") {
144
+ calls.push({ method: "api.operations", file: file.path, line });
145
+ } else {
146
+ const path = rest.filter((p) => p !== "$call");
147
+ calls.push({
148
+ method: `api.${path.join(".")}`,
149
+ operationId: path.join("."),
150
+ file: file.path,
151
+ line,
152
+ });
153
+ }
154
+ continue;
155
+ }
156
+ calls.push({ method: `${ns}.${rest[0]}`, file: file.path, line });
157
+ }
158
+ return calls;
159
+ }
160
+
161
+ const LEGACY_PERMISSION_NAMES = new Set([
162
+ "objects",
163
+ "database",
164
+ "database:write",
165
+ "read:crm",
166
+ "write:crm",
167
+ "db.read",
168
+ "db.write",
169
+ "files",
170
+ "store",
171
+ "http",
172
+ "integrations",
173
+ "agent",
174
+ "chat:create",
175
+ "chat",
176
+ "events",
177
+ "cron",
178
+ "webhooks",
179
+ "clipboard",
180
+ "apps",
181
+ "memory",
182
+ "events",
183
+ "events:subscribe",
184
+ ]);
185
+
186
+ function scopeGranted(granted: Set<string>, required: string | null): boolean {
187
+ if (required === null) return true;
188
+ if (granted.has(required)) return true;
189
+ const idx = required.indexOf(":");
190
+ const group = idx === -1 ? required : required.slice(0, idx);
191
+ const access = idx === -1 ? null : required.slice(idx + 1);
192
+ if (granted.has(group)) return true;
193
+ if (access === "read" && granted.has(`${group}:write`)) return true;
194
+ const legacy: Record<string, string[]> = {
195
+ "crm:read": [
196
+ "objects",
197
+ "database",
198
+ "database:write",
199
+ "read:crm",
200
+ "write:crm",
201
+ ],
202
+ "crm:write": ["objects", "database:write", "write:crm"],
203
+ "ai:chat": ["agent", "chat", "chat:create"],
204
+ "agent:invoke": ["agent"],
205
+ "memory:read": ["agent:invoke", "agent", "memory"],
206
+ "memory:write": ["agent:invoke", "agent", "memory"],
207
+ "cron:schedule": ["cron", "routines"],
208
+ "webhooks:receive": ["webhooks"],
209
+ "http:external": ["http"],
210
+ "apps:message": ["apps"],
211
+ };
212
+ return (legacy[required] ?? []).some((n) => granted.has(n));
213
+ }
214
+
215
+ function isTextCode(path: string) {
216
+ return /\.(html?|js|mjs|cjs|ts|jsx|tsx)$/i.test(path);
217
+ }
218
+
219
+ export function validateApp(input: {
220
+ manifestYaml: string | null;
221
+ files: AppFile[];
222
+ }): ValidationResult {
223
+ const errors: ValidationFinding[] = [];
224
+ const warnings: ValidationFinding[] = [];
225
+ const push = (f: ValidationFinding) =>
226
+ (f.level === "error" ? errors : warnings).push(f);
227
+
228
+ // ── Manifest ─────────────────────────────────────────────────────────
229
+ let permissions: string[] = [];
230
+ let entry = "index.html";
231
+ if (input.manifestYaml === null) {
232
+ push({
233
+ level: "error",
234
+ code: "manifest_missing",
235
+ message: "Missing .dench.yaml at the app root.",
236
+ file: ".dench.yaml",
237
+ });
238
+ } else {
239
+ const manifest = parseAppManifest(input.manifestYaml);
240
+ if (typeof manifest.name !== "string" || !manifest.name.trim()) {
241
+ push({
242
+ level: "error",
243
+ code: "manifest_name",
244
+ message: "`name` is required in .dench.yaml.",
245
+ file: ".dench.yaml",
246
+ });
247
+ }
248
+ if (typeof manifest.entry === "string" && manifest.entry.trim()) {
249
+ entry = manifest.entry.trim();
250
+ }
251
+ permissions = Array.isArray(manifest.permissions)
252
+ ? (manifest.permissions as unknown[]).map(String)
253
+ : [];
254
+ const known = new Set<string>(APP_SDK_SCOPES);
255
+ for (const scope of permissions) {
256
+ if (known.has(scope)) continue;
257
+ if (LEGACY_PERMISSION_NAMES.has(scope)) {
258
+ warnings.push({
259
+ level: "warning",
260
+ code: "manifest_unknown_permission",
261
+ message: `Permission "${scope}" is a legacy name; prefer ${suggestScope(scope)}.`,
262
+ file: ".dench.yaml",
263
+ });
264
+ continue;
265
+ }
266
+ push({
267
+ level: "error",
268
+ code: "manifest_unknown_permission",
269
+ message: `Unknown permission "${scope}". Valid scopes: ${APP_SDK_SCOPES.join(", ")}.`,
270
+ file: ".dench.yaml",
271
+ });
272
+ }
273
+ }
274
+ if (!input.files.some((f) => f.path === entry)) {
275
+ push({
276
+ level: "error",
277
+ code: "manifest_entry_missing",
278
+ message: `Entry file "${entry}" not found in the app folder.`,
279
+ file: entry,
280
+ });
281
+ }
282
+ const granted = new Set(permissions.map((p) => p.trim()));
283
+
284
+ // ── Calls ────────────────────────────────────────────────────────────
285
+ const calls = input.files
286
+ .filter((f) => isTextCode(f.path))
287
+ .flatMap(scanDenchCalls);
288
+ const seen = new Set<string>();
289
+ const required = new Set<string>();
290
+ const need = (permission: string | null, call: DenchCall, label: string) => {
291
+ if (!permission) return;
292
+ required.add(permission);
293
+ if (!scopeGranted(granted, permission)) {
294
+ push({
295
+ level: "error",
296
+ code: "missing_permission",
297
+ message: `${label} needs "${permission}" — add it to .dench.yaml permissions.`,
298
+ file: call.file,
299
+ line: call.line,
300
+ });
301
+ }
302
+ };
303
+
304
+ for (const call of calls) {
305
+ seen.add(
306
+ call.operationId ? `${call.method}(${call.operationId})` : call.method,
307
+ );
308
+
309
+ if (call.method === "api.call" || call.method.startsWith("api.")) {
310
+ if (call.method === "api.operations") continue;
311
+ if (!call.operationId) {
312
+ // dench.api.call(variable) — cannot check statically.
313
+ continue;
314
+ }
315
+ const op = appSdkOperation(call.operationId);
316
+ if (!op) {
317
+ const isLocal = APP_SDK_LOCAL_OPERATIONS.includes(call.operationId);
318
+ push({
319
+ level: "error",
320
+ code: isLocal ? "local_operation" : "unknown_operation",
321
+ message: isLocal
322
+ ? `dench.api: "${call.operationId}" only exists in the CLI (local state) and cannot be called from an app.`
323
+ : `dench.api: "${call.operationId}" is not a public /api/v1 operation. ${nearestOperations(call.operationId)}`,
324
+ file: call.file,
325
+ line: call.line,
326
+ });
327
+ continue;
328
+ }
329
+ if (op.deprecated) {
330
+ warnings.push({
331
+ level: "warning",
332
+ code: "deprecated_method",
333
+ message: `Operation "${op.id}" is deprecated.`,
334
+ file: call.file,
335
+ line: call.line,
336
+ });
337
+ }
338
+ need(op.permission, call, `dench.api "${op.id}"`);
339
+ continue;
340
+ }
341
+
342
+ const info = APP_SDK_METHODS[call.method];
343
+ if (!info) {
344
+ const ns = call.method.split(".")[0];
345
+ const available = Object.keys(APP_SDK_METHODS)
346
+ .filter((m) => m.startsWith(`${ns}.`))
347
+ .map((m) => m.slice(ns.length + 1));
348
+ push({
349
+ level: "error",
350
+ code: "unknown_method",
351
+ message:
352
+ available.length > 0
353
+ ? `dench.${call.method} does not exist. dench.${ns}.* has: ${available.join(", ")}.`
354
+ : `dench.${call.method} does not exist (no "${ns}" namespace). Namespaces: ${[...new Set(Object.keys(APP_SDK_METHODS).map((m) => m.split(".")[0]))].join(", ")}. Anything else is dench.api.call(<operationId>) — see dench.api.operations().`,
355
+ file: call.file,
356
+ line: call.line,
357
+ });
358
+ continue;
359
+ }
360
+ if (info.deprecated) {
361
+ push({
362
+ level: call.method.startsWith("db.") ? "error" : "warning",
363
+ code: "deprecated_method",
364
+ message: `dench.${call.method}: ${info.deprecated}`,
365
+ file: call.file,
366
+ line: call.line,
367
+ });
368
+ if (call.method.startsWith("db.")) continue;
369
+ }
370
+ need(info.permission, call, `dench.${call.method}`);
371
+ }
372
+
373
+ // ── Bridge bypasses / CSP ────────────────────────────────────────────
374
+ for (const file of input.files) {
375
+ if (!isTextCode(file.path)) continue;
376
+ for (const m of file.content.matchAll(
377
+ /\bfetch\(\s*(["'`])(\/api\/[^"'`]*)\1/g,
378
+ )) {
379
+ push({
380
+ level: "error",
381
+ code: "same_origin_fetch",
382
+ message: `fetch("${m[2]}") bypasses the bridge and breaks when apps move to their own origin. Use dench.api.call / the dench.* aliases.`,
383
+ file: file.path,
384
+ line: file.content.slice(0, m.index).split("\n").length,
385
+ });
386
+ }
387
+ for (const m of file.content.matchAll(
388
+ /<(script|link)\b[^>]*\b(?:src|href)\s*=\s*["'](https?:)?\/\/[^"']+["']/gi,
389
+ )) {
390
+ push({
391
+ level: "error",
392
+ code: "external_resource",
393
+ message: `External <${m[1].toLowerCase()}> is blocked by the app CSP — inline it.`,
394
+ file: file.path,
395
+ line: file.content.slice(0, m.index).split("\n").length,
396
+ });
397
+ }
398
+ }
399
+
400
+ if (calls.length === 0 && input.files.some((f) => isTextCode(f.path))) {
401
+ warnings.push({
402
+ level: "warning",
403
+ code: "no_bridge_calls",
404
+ message:
405
+ "No window.dench calls found — the app does not use any workspace data.",
406
+ });
407
+ }
408
+
409
+ return {
410
+ ok: errors.length === 0,
411
+ errors,
412
+ warnings,
413
+ calls: [...seen].sort(),
414
+ requiredPermissions: [...required].sort(),
415
+ };
416
+ }
417
+
418
+ function suggestScope(legacy: string): string {
419
+ const map: Record<string, string> = {
420
+ objects: "crm:read / crm:write",
421
+ database: "crm:read",
422
+ "database:write": "crm:write",
423
+ files: "files:read / files:write",
424
+ store: "store:read / store:write",
425
+ http: "http:external",
426
+ integrations: "integrations:read / integrations:write",
427
+ agent: "ai:chat / agent:invoke",
428
+ chat: "ai:chat",
429
+ "chat:create": "ai:chat",
430
+ events: "(no permission needed — remove it)",
431
+ "events:subscribe": "(no permission needed — remove it)",
432
+ cron: "cron:schedule",
433
+ webhooks: "webhooks:receive",
434
+ clipboard: "clipboard:read / clipboard:write",
435
+ apps: "apps:message (bus) or apps:read / apps:write (store)",
436
+ memory: "memory:read / memory:write",
437
+ };
438
+ return map[legacy] ?? "a canonical scope";
439
+ }
440
+
441
+ function nearestOperations(id: string): string {
442
+ const prefix = id.split(".")[0];
443
+ const same = APP_SDK_OPERATIONS.filter((o) => o.id.startsWith(`${prefix}.`))
444
+ .map((o) => o.id)
445
+ .slice(0, 12);
446
+ return same.length
447
+ ? `Operations under "${prefix}": ${same.join(", ")}.`
448
+ : "List operations with dench.api.operations() or `dench help`.";
449
+ }
450
+
451
+ /** Human-readable report. */
452
+ export function formatValidation(
453
+ result: ValidationResult,
454
+ appPath: string,
455
+ ): string {
456
+ const lines: string[] = [];
457
+ const where = (f: ValidationFinding) =>
458
+ f.file ? ` (${f.file}${f.line ? `:${f.line}` : ""})` : "";
459
+ lines.push(
460
+ result.ok
461
+ ? `✔ ${appPath} is valid — ${result.calls.length} dench.* call(s), permissions needed: ${result.requiredPermissions.join(", ") || "none"}`
462
+ : `✖ ${appPath} has ${result.errors.length} error(s)`,
463
+ );
464
+ for (const e of result.errors)
465
+ lines.push(` error ${e.message}${where(e)}`);
466
+ for (const w of result.warnings)
467
+ lines.push(` warning ${w.message}${where(w)}`);
468
+ return lines.join("\n");
469
+ }
@@ -3213,6 +3213,20 @@ const rawApiOperations = [
3213
3213
  responseSchema: anyResponse,
3214
3214
  backend: custom("filesMove", "bearer"),
3215
3215
  }),
3216
+ op({
3217
+ id: "files.mkdir",
3218
+ group: "files",
3219
+ summary:
3220
+ "Create a workspace directory (and any missing parents). Idempotent.",
3221
+ cli: "dench files mkdir",
3222
+ method: "POST",
3223
+ path: "/files/mkdir",
3224
+ requestSchema: anyObject,
3225
+ responseSchema: anyResponse,
3226
+ backend: convex("mutation", "functions/files:recordDirCreate", "bearer", {
3227
+ tokenArg: "apiKey",
3228
+ }),
3229
+ }),
3216
3230
  op({
3217
3231
  id: "files.stage",
3218
3232
  group: "files",
@@ -3528,6 +3542,65 @@ const rawApiOperations = [
3528
3542
  responseSchema: anyResponse,
3529
3543
  backend: convex("mutation", "functions/appStore:setPinned"),
3530
3544
  }),
3545
+ op({
3546
+ id: "apps.validate",
3547
+ group: "apps",
3548
+ summary:
3549
+ "Validate a .dench.app folder: manifest, permissions, and every window.dench call it makes.",
3550
+ cli: "dench apps validate",
3551
+ method: "POST",
3552
+ path: "/local/apps/validate",
3553
+ requestSchema: anyObject,
3554
+ responseSchema: anyResponse,
3555
+ backend: local(
3556
+ "Validation reads the app folder on the caller's disk. In the browser, the same catalog is window.dench.api.operations().",
3557
+ ),
3558
+ }),
3559
+ op({
3560
+ id: "apps.webhooks.register",
3561
+ group: "apps",
3562
+ summary:
3563
+ "Register an inbound webhook for an app. Returns the URL and signing secret ONCE.",
3564
+ cli: "dench apps webhooks register",
3565
+ method: "POST",
3566
+ path: "/apps/{slug}/webhooks",
3567
+ requestSchema: anyObject,
3568
+ responseSchema: anyResponse,
3569
+ backend: convex("mutation", "functions/appWebhooks:register"),
3570
+ }),
3571
+ op({
3572
+ id: "apps.webhooks.list",
3573
+ group: "apps",
3574
+ summary: "List an app's registered webhooks (URLs, never secrets).",
3575
+ cli: "dench apps webhooks list",
3576
+ method: "GET",
3577
+ path: "/apps/{slug}/webhooks",
3578
+ requestSchema: anyObject,
3579
+ responseSchema: anyResponse,
3580
+ backend: convex("query", "functions/appWebhooks:list"),
3581
+ }),
3582
+ op({
3583
+ id: "apps.webhooks.poll",
3584
+ group: "apps",
3585
+ summary: "Read events an app webhook received since a timestamp.",
3586
+ cli: "dench apps webhooks poll",
3587
+ method: "GET",
3588
+ path: "/apps/{slug}/webhooks/{hookName}/events",
3589
+ requestSchema: anyObject,
3590
+ responseSchema: anyResponse,
3591
+ backend: convex("query", "functions/appWebhooks:poll"),
3592
+ }),
3593
+ op({
3594
+ id: "apps.webhooks.delete",
3595
+ group: "apps",
3596
+ summary: "Remove an app webhook and every event it stored.",
3597
+ cli: "dench apps webhooks delete",
3598
+ method: "DELETE",
3599
+ path: "/apps/{slug}/webhooks/{hookName}",
3600
+ requestSchema: anyObject,
3601
+ responseSchema: anyResponse,
3602
+ backend: convex("mutation", "functions/appWebhooks:remove"),
3603
+ }),
3531
3604
  op({
3532
3605
  id: "tool.status",
3533
3606
  group: "gateway",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dench.com/cli",
3
- "version": "2.9.5-staging.239",
3
+ "version": "2.9.6-staging.252",
4
4
  "description": "Dench agent workspace CLI.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -48,8 +48,16 @@
48
48
  "session.ts",
49
49
  "lib/organizationSelector.ts",
50
50
  "lib/",
51
+ "app-sdk.d.ts",
51
52
  "README.md"
52
53
  ],
54
+ "exports": {
55
+ "./app-sdk": {
56
+ "types": "./app-sdk.d.ts"
57
+ },
58
+ "./package.json": "./package.json",
59
+ "./*": "./*"
60
+ },
53
61
  "engines": {
54
62
  "node": ">=20.0.0"
55
63
  },