@palettelab/cli 0.3.71 → 0.3.73
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +50 -12
- package/backend-sdk/palette_sdk/__init__.py +3 -1
- package/backend-sdk/palette_sdk/manifest.py +2 -2
- package/backend-sdk/palette_sdk/platform_services.py +254 -1
- package/backend-sdk/palette_sdk/plugin_context.py +8 -0
- package/backend-sdk/pyproject.toml +1 -1
- package/docs/python-backend-sdk.md +51 -4
- package/lib/agent-client.js +0 -9
- package/lib/bundler.js +32 -1
- package/lib/cli.js +7 -2
- package/lib/commands/agent.js +1 -102
- package/lib/commands/build.js +27 -12
- package/lib/commands/categories.js +25 -0
- package/lib/commands/check.js +1 -1
- package/lib/commands/doctor.js +2 -1
- package/lib/commands/platform.js +3 -2
- package/lib/commands/publish.js +7 -0
- package/lib/css-scope.js +90 -18
- package/lib/dev-simulator.js +8 -0
- package/lib/manifest.js +11 -1
- package/lib/migration_lint.py +128 -0
- package/package.json +1 -1
- package/template-fallback/README.md +2 -2
- package/template-fallback/package.json +1 -1
- package/template-fallback/templates/agent-tool/palette-plugin.json +1 -1
- package/template-fallback/templates/consumer-app/package.json +1 -1
- package/template-fallback/templates/dashboard/package.json +1 -1
- package/template-fallback/templates/database/package.json +1 -1
- package/template-fallback/templates/external-service/package.json +1 -1
- package/template-fallback/templates/external-service/palette-plugin.json +1 -1
- package/template-fallback/templates/frontend-only/package.json +1 -1
- package/template-fallback/templates/next/package.json +1 -1
- package/template-fallback/templates/palette-app/package.json +1 -1
- package/template-fallback/templates/provider-app/package.json +1 -1
package/lib/cli.js
CHANGED
|
@@ -19,6 +19,7 @@ const capabilities = require("./commands/capabilities")
|
|
|
19
19
|
const connections = require("./commands/connections")
|
|
20
20
|
const platform = require("./commands/platform")
|
|
21
21
|
const models = require("./commands/models")
|
|
22
|
+
const categories = require("./commands/categories")
|
|
22
23
|
const agent = require("./commands/agent")
|
|
23
24
|
const check = require("./commands/check")
|
|
24
25
|
|
|
@@ -77,6 +78,10 @@ const COMMANDS = {
|
|
|
77
78
|
run: models,
|
|
78
79
|
help: "List the chat/image/video/audio models this app can use in your workspace (ids, limits, why not)",
|
|
79
80
|
},
|
|
81
|
+
categories: {
|
|
82
|
+
run: categories,
|
|
83
|
+
help: "List the App Store categories a manifest can name; anything else is filed under Other",
|
|
84
|
+
},
|
|
80
85
|
services: {
|
|
81
86
|
run: services,
|
|
82
87
|
help: "Inspect / pull / scaffold OS-broker services (list, pull, scaffold)",
|
|
@@ -105,7 +110,7 @@ function printHelp() {
|
|
|
105
110
|
console.log(` ${name.padEnd(12)} ${help}`)
|
|
106
111
|
}
|
|
107
112
|
console.log("\nGlobal flags:")
|
|
108
|
-
console.log(" --json Emit machine-readable JSON output (status, logs, package, publish, test, check, update, version, login, dev --sandbox, platform, models, services, capabilities)")
|
|
113
|
+
console.log(" --json Emit machine-readable JSON output (status, logs, package, publish, test, check, update, version, login, dev --sandbox, platform, models, categories, services, capabilities)")
|
|
109
114
|
console.log(" -v, --version Show the installed pltt CLI version")
|
|
110
115
|
console.log("\nPublish flags:")
|
|
111
116
|
console.log(" --env <name> Target environment from ~/.palette/config.json (default: local)")
|
|
@@ -125,7 +130,7 @@ function printHelp() {
|
|
|
125
130
|
console.log(" --tail <n> Tail last n events (default 50)")
|
|
126
131
|
console.log(" -f, --follow Stream events (poll every 3s)")
|
|
127
132
|
console.log("\nPlatform services (ctx.* — the platform's own credentials):")
|
|
128
|
-
console.log(" pltt platform list # llm, media, storage, vector, redis, web")
|
|
133
|
+
console.log(" pltt platform list # llm, media, storage, vector, redis, web, email")
|
|
129
134
|
console.log(" pltt platform enable llm media # declare them in palette-plugin.json")
|
|
130
135
|
console.log(" pltt platform disable web")
|
|
131
136
|
console.log("\nModels (what ctx.llm / ctx.media will run for this app):")
|
package/lib/commands/agent.js
CHANGED
|
@@ -22,11 +22,6 @@ const USAGE = `usage:
|
|
|
22
22
|
pltt agent edit --app <id> "<change>" [--follow] start a change (steers the agent when it is working)
|
|
23
23
|
pltt agent attach <session> follow live, answer permission asks and questions,
|
|
24
24
|
type to steer, /exit to leave
|
|
25
|
-
pltt agent terminal <session> [--attach <terminal>]
|
|
26
|
-
an interactive shell in the session's build sandbox
|
|
27
|
-
(Ctrl-] closes it; needs Node 22 or later)
|
|
28
|
-
pltt agent terminals <session> [--read] [--lines <n>]
|
|
29
|
-
its terminals, or the newest one's last lines
|
|
30
25
|
pltt agent acp --app <id> Agent Client Protocol server on stdio (Zed and other editors)
|
|
31
26
|
pltt agent sessions --app <id> [--archived] [--limit <n>]
|
|
32
27
|
list an app's build sessions
|
|
@@ -184,8 +179,6 @@ function describe(event) {
|
|
|
184
179
|
return `moved to app ${d.to}`
|
|
185
180
|
case "skill.activated":
|
|
186
181
|
return `skill ${d.name}${d.by === "owner" ? " (you asked)" : ""}`
|
|
187
|
-
case "shell.ended":
|
|
188
|
-
return `you ran: ${String(d.command || "").slice(0, 120)}${d.failed ? " (failed)" : ""}`
|
|
189
182
|
case "cache.warmed":
|
|
190
183
|
return null
|
|
191
184
|
default:
|
|
@@ -343,79 +336,6 @@ async function attach(client, sessionId, { log }) {
|
|
|
343
336
|
}
|
|
344
337
|
}
|
|
345
338
|
|
|
346
|
-
// `terminal`: an interactive shell in the session's build sandbox. Keys go to it raw and its output is written as it
|
|
347
|
-
// comes, so the local terminal draws it; a resize follows the window. Ctrl-] closes it. A dropped connection (a proxy's
|
|
348
|
-
// connection limit, a network blip) reconnects and resumes after the last frame it showed, so nothing is drawn twice.
|
|
349
|
-
// Resolves with the shell's exit code (1 when it did not exit by itself).
|
|
350
|
-
async function terminal(client, sessionId, { attachTo, stdin, stdout, log, WS = globalThis.WebSocket, retries = 5, backoffMs = 500 }) {
|
|
351
|
-
if (typeof WS !== "function") throw new Error("pltt agent terminal needs Node 22 or later (its built-in WebSocket)")
|
|
352
|
-
const size = () => ({ cols: stdout.columns || 100, rows: stdout.rows || 30 })
|
|
353
|
-
let entry = { id: attachTo }
|
|
354
|
-
if (!attachTo) {
|
|
355
|
-
entry = await client.openTerminal(sessionId, size())
|
|
356
|
-
log(entry.start === "queued" ? "[pltt] the terminal opens when the app's running build ends"
|
|
357
|
-
: entry.start === "opening" ? "[pltt] the terminal opens at the agent's next step"
|
|
358
|
-
: "[pltt] starting the terminal (Ctrl-] closes it)")
|
|
359
|
-
}
|
|
360
|
-
let socket = null
|
|
361
|
-
let last = "0" // the stream id of the last frame shown: a reconnect resumes after it
|
|
362
|
-
let ended = null
|
|
363
|
-
const held = [] // keys typed while reconnecting: sent once the new connection opens, never dropped
|
|
364
|
-
const send = (frame) => {
|
|
365
|
-
if (socket && socket.readyState === 1) socket.send(JSON.stringify(frame))
|
|
366
|
-
else held.push(frame)
|
|
367
|
-
}
|
|
368
|
-
const onKey = (chunk) => {
|
|
369
|
-
const keys = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))
|
|
370
|
-
if (keys.length === 1 && keys[0] === 0x1d) return send({ t: "close" }) // Ctrl-]
|
|
371
|
-
send({ t: "in", d: keys.toString("utf8") })
|
|
372
|
-
}
|
|
373
|
-
const onResize = () => send({ t: "resize", ...size() })
|
|
374
|
-
if (stdin.isTTY) stdin.setRawMode(true)
|
|
375
|
-
stdin.on("data", onKey)
|
|
376
|
-
stdin.resume()
|
|
377
|
-
stdout.on("resize", onResize)
|
|
378
|
-
try {
|
|
379
|
-
for (let tries = 0; ;) {
|
|
380
|
-
const { ticket } = await client.terminalTicket(sessionId, entry.id)
|
|
381
|
-
const code = await new Promise((resolve) => {
|
|
382
|
-
socket = new WS(client.terminalUrl(sessionId, entry.id, ticket, last))
|
|
383
|
-
socket.onopen = () => {
|
|
384
|
-
tries = 0
|
|
385
|
-
onResize()
|
|
386
|
-
for (const frame of held.splice(0)) send(frame)
|
|
387
|
-
}
|
|
388
|
-
socket.onmessage = (message) => {
|
|
389
|
-
const frame = JSON.parse(typeof message.data === "string" ? message.data : Buffer.from(message.data).toString())
|
|
390
|
-
if (frame.i) last = frame.i
|
|
391
|
-
if (frame.t === "out") stdout.write(frame.d)
|
|
392
|
-
if (frame.t === "exit") {
|
|
393
|
-
ended = frame
|
|
394
|
-
socket.close()
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
socket.onerror = () => {} // onclose follows with the reason
|
|
398
|
-
socket.onclose = (event) => resolve(event.code)
|
|
399
|
-
})
|
|
400
|
-
if (ended) break
|
|
401
|
-
if (code === 4401) throw new Error("the terminal refused the connection: sign in again (pltt login)")
|
|
402
|
-
if (code === 4404) throw new Error(`no terminal ${entry.id} in session ${sessionId}`)
|
|
403
|
-
if (tries >= retries) break
|
|
404
|
-
tries += 1
|
|
405
|
-
await sleep(Math.min(8000, backoffMs * 2 ** tries))
|
|
406
|
-
}
|
|
407
|
-
} finally {
|
|
408
|
-
stdin.off("data", onKey)
|
|
409
|
-
stdout.off("resize", onResize)
|
|
410
|
-
if (stdin.isTTY) stdin.setRawMode(false)
|
|
411
|
-
stdin.pause()
|
|
412
|
-
}
|
|
413
|
-
const how = ended ? `ended (${ended.reason}${ended.code != null ? `, exit ${ended.code}` : ""})${ended.message ? `: ${ended.message}` : ""}`
|
|
414
|
-
: `connection lost (it may still be open: pltt agent terminal ${sessionId} --attach ${entry.id})`
|
|
415
|
-
log(`\r\n[pltt] terminal ${entry.id} ${how}`)
|
|
416
|
-
return ended && Number.isInteger(ended.code) && ended.reason === "exited" ? ended.code : 1
|
|
417
|
-
}
|
|
418
|
-
|
|
419
339
|
// `acp`: JSON-RPC on stdio. stdout carries protocol messages only; everything else goes to stderr.
|
|
420
340
|
async function serveAcp(client, app) {
|
|
421
341
|
let closed = false
|
|
@@ -451,7 +371,7 @@ function diffStat(data, log) {
|
|
|
451
371
|
log(` ${files.length} file${files.length === 1 ? "" : "s"} changed, +${data.additions} -${data.deletions}`)
|
|
452
372
|
}
|
|
453
373
|
|
|
454
|
-
async function run(argv, { cwd = process.cwd(), log = console.log
|
|
374
|
+
async function run(argv, { cwd = process.cwd(), log = console.log } = {}) {
|
|
455
375
|
const [sub, ...args] = argv
|
|
456
376
|
const { flags, rest } = parseFlags(args)
|
|
457
377
|
const json = flags.json
|
|
@@ -539,27 +459,6 @@ async function run(argv, { cwd = process.cwd(), log = console.log, stdin = proce
|
|
|
539
459
|
case "attach":
|
|
540
460
|
need(id)
|
|
541
461
|
return attach(client, id, { log })
|
|
542
|
-
case "terminal": {
|
|
543
|
-
const attachTo = option(rest, "--attach")
|
|
544
|
-
need(rest[0])
|
|
545
|
-
process.exitCode = await terminal(client, rest[0], { attachTo, stdin, stdout, log })
|
|
546
|
-
return
|
|
547
|
-
}
|
|
548
|
-
case "terminals": {
|
|
549
|
-
const read = flag(rest, "--read")
|
|
550
|
-
const lines = option(rest, "--lines")
|
|
551
|
-
need(rest[0])
|
|
552
|
-
if (read) {
|
|
553
|
-
const { data } = await client.readTerminal(rest[0], lines ? positiveInt(lines, "--lines") : 100)
|
|
554
|
-
if (json) return log(JSON.stringify(data))
|
|
555
|
-
return log(data ? data.text || "(nothing shown yet)" : "no terminal in this session")
|
|
556
|
-
}
|
|
557
|
-
const { terminals } = await client.terminals(rest[0])
|
|
558
|
-
if (json) return log(JSON.stringify(terminals))
|
|
559
|
-
if (!terminals.length) return log("no terminals")
|
|
560
|
-
for (const t of terminals) log(`${t.id} ${t.status}${t.reason ? ` (${t.reason})` : ""} ${t.cols}x${t.rows}${t.title ? ` ${t.title}` : ""}`)
|
|
561
|
-
return
|
|
562
|
-
}
|
|
563
462
|
case "acp": {
|
|
564
463
|
const app = option(rest, "--app")
|
|
565
464
|
need(app)
|
package/lib/commands/build.js
CHANGED
|
@@ -2,10 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
const fs = require("fs")
|
|
4
4
|
const path = require("path")
|
|
5
|
+
const { spawnSync } = require("child_process")
|
|
5
6
|
const { loadManifest, validateManifest } = require("../manifest")
|
|
6
7
|
|
|
7
|
-
//
|
|
8
|
-
//
|
|
8
|
+
// What a migration may not run is decided by the platform's own lint, lib/migration_lint.py (a byte-identical
|
|
9
|
+
// copy of the server's), run with python3 so `pltt check` and publish agree — GRANT counts only as a SQL
|
|
10
|
+
// statement, never as a word. Without a usable python3 these word patterns stand in: stricter, never laxer.
|
|
11
|
+
const LINT_PY = path.join(__dirname, "..", "migration_lint.py")
|
|
9
12
|
const BANNED_PATTERNS = [
|
|
10
13
|
{ re: /DROP\s+POLICY/i, reason: "DROP POLICY weakens RLS" },
|
|
11
14
|
{ re: /DISABLE\s+ROW\s+LEVEL\s+SECURITY/i, reason: "DISABLE ROW LEVEL SECURITY removes tenant isolation" },
|
|
@@ -59,17 +62,31 @@ function crossPluginSchemaRefs(src, allowedSchema) {
|
|
|
59
62
|
return [...refs].sort()
|
|
60
63
|
}
|
|
61
64
|
|
|
62
|
-
|
|
65
|
+
// { absPath: [[line, reason], ...] } from the platform lint, or null when python3 cannot run it.
|
|
66
|
+
function bannedOperations(files) {
|
|
67
|
+
if (!files.length) return {}
|
|
68
|
+
const res = spawnSync(process.env.PALETTE_PYTHON || "python3", ["-I", LINT_PY, ...files], { encoding: "utf8" })
|
|
69
|
+
try {
|
|
70
|
+
return res.status === 0 ? JSON.parse(res.stdout) : null
|
|
71
|
+
} catch {
|
|
72
|
+
return null
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function lintMigrationFile(absPath, pluginId, sharedTables = [], banned = bannedOperations([absPath])) {
|
|
63
77
|
const issues = []
|
|
64
78
|
const src = fs.readFileSync(absPath, "utf8")
|
|
65
79
|
const requiredPrefix = pluginId ? pluginTablePrefix(pluginId) : null
|
|
66
80
|
const allowedSchema = pluginId ? pluginSchema(pluginId) : null
|
|
67
81
|
const sharedTableNames = new Set(sharedTables || [])
|
|
68
82
|
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
83
|
+
const hits = banned?.[absPath] || BANNED_PATTERNS.flatMap(({ re, reason }) => {
|
|
84
|
+
const match = re.exec(src)
|
|
85
|
+
return match ? [[src.slice(0, match.index).split("\n").length, reason]] : []
|
|
86
|
+
})
|
|
87
|
+
for (const [line, reason] of hits) {
|
|
88
|
+
const file = path.basename(absPath)
|
|
89
|
+
issues.push(makeIssue(`${file} line ${line}: ${reason}`, null, { code: "banned_operation", file, line }))
|
|
73
90
|
}
|
|
74
91
|
|
|
75
92
|
for (const schema of crossPluginSchemaRefs(src, allowedSchema)) {
|
|
@@ -138,11 +155,9 @@ function lintMigrationsDir(migrationsDir, pluginId, sharedTables = []) {
|
|
|
138
155
|
errors.push(`migrations directory has no versions/ subfolder: ${migrationsDir}`)
|
|
139
156
|
return errors
|
|
140
157
|
}
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
errors.push(...lintMigrationFile(abs, pluginId, sharedTables))
|
|
145
|
-
}
|
|
158
|
+
const files = fs.readdirSync(versionsDir).filter((entry) => entry.endsWith(".py")).map((entry) => path.join(versionsDir, entry))
|
|
159
|
+
const banned = bannedOperations(files)
|
|
160
|
+
for (const abs of files) errors.push(...lintMigrationFile(abs, pluginId, sharedTables, banned))
|
|
146
161
|
return errors
|
|
147
162
|
}
|
|
148
163
|
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"use strict"
|
|
2
|
+
|
|
3
|
+
const { parseFlags, resolveEnvironment } = require("../environments")
|
|
4
|
+
|
|
5
|
+
// Superadmins keep the store's categories on the platform, so the list is
|
|
6
|
+
// read from it, never shipped with the CLI. A manifest `category` that names
|
|
7
|
+
// none of them (or no category at all) is filed under Other at publish.
|
|
8
|
+
async function run(argv, { cwd, log = console.log } = {}) {
|
|
9
|
+
const { flags } = parseFlags(argv)
|
|
10
|
+
const env = resolveEnvironment({ cwd, flags })
|
|
11
|
+
const url = `${env.url}/api/v1/appstore/categories`
|
|
12
|
+
const res = await fetch(url)
|
|
13
|
+
if (!res.ok) throw new Error(`GET ${url} → ${res.status}: ${await res.text()}`)
|
|
14
|
+
const { categories } = await res.json()
|
|
15
|
+
if (flags.json) {
|
|
16
|
+
log(JSON.stringify({ categories }, null, 2))
|
|
17
|
+
return categories
|
|
18
|
+
}
|
|
19
|
+
log(`App Store categories on ${env.name} (set "category" in palette-plugin.json to one of them):`)
|
|
20
|
+
for (const name of categories) log(` ${name}`)
|
|
21
|
+
log('Any other value, or none, is filed under "Other". A superadmin can move the app at any time.')
|
|
22
|
+
return categories
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
module.exports = run
|
package/lib/commands/check.js
CHANGED
|
@@ -62,7 +62,7 @@ function diagnosticsFor(result, cwd) {
|
|
|
62
62
|
}
|
|
63
63
|
if (result.file) {
|
|
64
64
|
const file = String(result.file).includes("/") || !result.code ? String(result.file) : `backend/migrations/versions/${result.file}`
|
|
65
|
-
return [{ ...base, file }]
|
|
65
|
+
return [{ ...base, file, ...(result.line ? { line: Number(result.line) } : {}) }]
|
|
66
66
|
}
|
|
67
67
|
return [base]
|
|
68
68
|
}
|
package/lib/commands/doctor.js
CHANGED
|
@@ -63,7 +63,8 @@ function reportPlatformServices(manifest, cwd) {
|
|
|
63
63
|
ok(`manifest declares ${names.length} platform service(s): ${names.join(", ")}`)
|
|
64
64
|
for (const name of names) {
|
|
65
65
|
const note = PLATFORM_SERVICE_DEV_NOTES[name]
|
|
66
|
-
|
|
66
|
+
const dev = note ? note(cwd) : PLATFORM_SERVICES.find((service) => service.name === name)?.dev
|
|
67
|
+
if (dev) console.log(` ctx.${name} — ${dev}`)
|
|
67
68
|
}
|
|
68
69
|
}
|
|
69
70
|
|
package/lib/commands/platform.js
CHANGED
|
@@ -37,7 +37,7 @@ function list(manifest, cwd, json) {
|
|
|
37
37
|
const rows = PLATFORM_SERVICES.map((service) => ({
|
|
38
38
|
...service,
|
|
39
39
|
declared: on.has(service.name),
|
|
40
|
-
dev: devNote(service.name, cwd),
|
|
40
|
+
dev: service.dev || devNote(service.name, cwd),
|
|
41
41
|
}))
|
|
42
42
|
// The other half of what `ctx` can do: clients switched on by a manifest
|
|
43
43
|
// permission rather than by platform_services. Printing them together is the
|
|
@@ -106,7 +106,8 @@ function enable(cwd, names) {
|
|
|
106
106
|
console.log(`[pltt] ${service.accessor} enabled — ${service.summary}`)
|
|
107
107
|
if (service.python) console.log(` ${service.python}`)
|
|
108
108
|
const key = DEV_KEYS[name]
|
|
109
|
-
if (
|
|
109
|
+
if (service.dev) console.log(` ${service.dev}`)
|
|
110
|
+
else if (key) console.log(` pltt dev stubs this unless ${key} is in .env.local`)
|
|
110
111
|
}
|
|
111
112
|
}
|
|
112
113
|
|
package/lib/commands/publish.js
CHANGED
|
@@ -503,6 +503,13 @@ async function run(argv, { cwd }) {
|
|
|
503
503
|
if (record.review_url && record.status !== "active") {
|
|
504
504
|
console.log(`[pltt] review queue: ${record.review_url}`)
|
|
505
505
|
}
|
|
506
|
+
// Where the store filed the app: a manifest category that names no store
|
|
507
|
+
// category lands in Other (older platforms send neither field).
|
|
508
|
+
if (record.category_note) {
|
|
509
|
+
console.log(`[pltt] ${record.category_note}`)
|
|
510
|
+
} else if (record.category) {
|
|
511
|
+
console.log(`[pltt] store category: ${record.category}`)
|
|
512
|
+
}
|
|
506
513
|
if (record.preview_url) {
|
|
507
514
|
console.log(`[pltt] preview: ${record.preview_url}`)
|
|
508
515
|
}
|
package/lib/css-scope.js
CHANGED
|
@@ -31,28 +31,80 @@ function isRootLike(node) {
|
|
|
31
31
|
)
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
34
|
+
// Selector lists that match when any branch matches (`:where(html)`, `:is(html, body)`).
|
|
35
|
+
const MATCHES_ANY = /^:(is|where|matches|-webkit-any|-moz-any)$/i
|
|
36
|
+
|
|
37
|
+
// Only this plugin's own root counts: a hand-written `[data-palette-plugin-root]` may be
|
|
38
|
+
// another app's root and keeps its prefix.
|
|
39
|
+
function isPluginRoot(node, root) {
|
|
40
|
+
return node.type === "attribute" && node.attribute === root.attribute && node.value === root.value
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function isChildStep(node) {
|
|
44
|
+
return node?.type === "combinator" && (node.value === " " || node.value === ">")
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function splitCompounds(selector) {
|
|
48
|
+
const compounds = [[]]
|
|
49
|
+
const combinators = []
|
|
50
|
+
for (const node of selector.nodes) {
|
|
51
|
+
if (node.type === "combinator") {
|
|
52
|
+
combinators.push(node)
|
|
53
|
+
compounds.push([])
|
|
54
|
+
} else {
|
|
55
|
+
compounds[compounds.length - 1].push(node)
|
|
56
|
+
}
|
|
37
57
|
}
|
|
58
|
+
return { compounds, combinators }
|
|
38
59
|
}
|
|
39
60
|
|
|
40
|
-
function
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
61
|
+
function isRootCompound(nodes, root) {
|
|
62
|
+
return nodes.some(
|
|
63
|
+
(node) =>
|
|
64
|
+
isPluginRoot(node, root) ||
|
|
65
|
+
(node.type === "pseudo" &&
|
|
66
|
+
MATCHES_ANY.test(node.value) &&
|
|
67
|
+
node.nodes.length > 0 &&
|
|
68
|
+
node.nodes.every((branch) => isInsideRoot(branch, root))),
|
|
69
|
+
)
|
|
48
70
|
}
|
|
49
71
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
72
|
+
// True when the subject can only be the plugin root or a descendant of it: walking left
|
|
73
|
+
// over descendant/child steps reaches a root compound. A root that only appears inside
|
|
74
|
+
// `:not(body)` or before `~`/`+` confines nothing, so such selectors still get prefixed.
|
|
75
|
+
function isInsideRoot(selector, root) {
|
|
76
|
+
const { compounds, combinators } = splitCompounds(selector)
|
|
77
|
+
for (let i = compounds.length - 1; i >= 0; i--) {
|
|
78
|
+
if (isRootCompound(compounds[i], root)) return true
|
|
79
|
+
if (!isChildStep(combinators[i - 1])) return false
|
|
80
|
+
}
|
|
81
|
+
return false
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// html, body and :root all become the one plugin root element, so `html body` or
|
|
85
|
+
// `:root[data-theme=x] > body` must merge into a single compound: a plugin root nested
|
|
86
|
+
// inside itself never matches.
|
|
87
|
+
function collapseRootChains(selector, root) {
|
|
88
|
+
const { compounds, combinators } = splitCompounds(selector)
|
|
89
|
+
for (let i = combinators.length - 1; i >= 0; i--) {
|
|
90
|
+
if (!isChildStep(combinators[i]) || !isRootCompound(compounds[i], root) || !isRootCompound(compounds[i + 1], root)) continue
|
|
91
|
+
combinators[i].remove()
|
|
92
|
+
for (const node of compounds[i + 1]) if (isPluginRoot(node, root)) node.remove()
|
|
55
93
|
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function confineSelector(selector, rootNode) {
|
|
97
|
+
if (!selector.nodes.length) return
|
|
98
|
+
collapseRootChains(selector, rootNode)
|
|
99
|
+
if (isInsideRoot(selector, rootNode)) return
|
|
100
|
+
// `body, .x { .card {} }` flattens to `:is(body, .x) .card`: scope each branch, since
|
|
101
|
+
// one outer prefix would need the root inside itself for the `body` branch.
|
|
102
|
+
const lists = splitCompounds(selector).compounds[0].filter(
|
|
103
|
+
(node) =>
|
|
104
|
+
node.type === "pseudo" && MATCHES_ANY.test(node.value) && node.nodes.some((branch) => isInsideRoot(branch, rootNode)),
|
|
105
|
+
)
|
|
106
|
+
for (const list of lists) list.each((branch) => confineSelector(branch, rootNode))
|
|
107
|
+
if (lists.length && isInsideRoot(selector, rootNode)) return
|
|
56
108
|
selector.prepend(selectorParser.combinator({ value: " " }))
|
|
57
109
|
selector.prepend(rootNode.clone())
|
|
58
110
|
}
|
|
@@ -66,10 +118,30 @@ function scopeSelectors(selector, pluginId) {
|
|
|
66
118
|
})
|
|
67
119
|
|
|
68
120
|
return selectorParser((selectors) => {
|
|
69
|
-
selectors.
|
|
121
|
+
selectors.walk((node) => {
|
|
122
|
+
if (isRootLike(node)) node.replaceWith(rootNode.clone())
|
|
123
|
+
})
|
|
124
|
+
selectors.each((sel) => confineSelector(sel, rootNode))
|
|
70
125
|
}).processSync(selector)
|
|
71
126
|
}
|
|
72
127
|
|
|
128
|
+
// A nested rule is matched relative to its parent, so scoping every level would ask for
|
|
129
|
+
// a plugin root inside the plugin root (`[root] .a { [root] .b {} }` never matches).
|
|
130
|
+
// Flatten nesting first with esbuild, which already bundles this CSS.
|
|
131
|
+
function flattenNesting(css, root) {
|
|
132
|
+
let nested = false
|
|
133
|
+
root.walk((node) => {
|
|
134
|
+
if (node.parent?.type === "rule" && (node.type === "rule" || node.type === "atrule")) nested = true
|
|
135
|
+
})
|
|
136
|
+
if (!nested) return root
|
|
137
|
+
const flat = require("esbuild").transformSync(css, {
|
|
138
|
+
loader: "css",
|
|
139
|
+
minifyWhitespace: true,
|
|
140
|
+
supported: { nesting: false },
|
|
141
|
+
})
|
|
142
|
+
return postcss.parse(flat.code)
|
|
143
|
+
}
|
|
144
|
+
|
|
73
145
|
function renameKeyframes(root, pluginId) {
|
|
74
146
|
const prefix = `palette-${cssIdentifier(pluginId)}-`
|
|
75
147
|
const names = new Map()
|
|
@@ -97,7 +169,7 @@ function renameKeyframes(root, pluginId) {
|
|
|
97
169
|
|
|
98
170
|
function scopePluginCss(css, pluginId) {
|
|
99
171
|
if (!css || !String(css).trim()) return ""
|
|
100
|
-
const root = postcss.parse(css)
|
|
172
|
+
const root = flattenNesting(String(css), postcss.parse(css))
|
|
101
173
|
|
|
102
174
|
renameKeyframes(root, pluginId)
|
|
103
175
|
root.walkRules((rule) => {
|
package/lib/dev-simulator.js
CHANGED
|
@@ -222,6 +222,7 @@ DEV_STORAGE = None
|
|
|
222
222
|
DEV_LLM = None
|
|
223
223
|
DEV_WEB = None
|
|
224
224
|
DEV_MEDIA = None
|
|
225
|
+
DEV_EMAIL = None
|
|
225
226
|
if _service_enabled("llm"):
|
|
226
227
|
from palette_sdk.platform_services import LocalLLMService
|
|
227
228
|
DEV_LLM = LocalLLMService(DEV_SECRETS.get("OPENAI_API_KEY") or os.environ.get("OPENAI_API_KEY", ""))
|
|
@@ -229,6 +230,10 @@ if _service_enabled("llm"):
|
|
|
229
230
|
if _service_enabled("web"):
|
|
230
231
|
from palette_sdk.platform_services import LocalWebService
|
|
231
232
|
DEV_WEB = LocalWebService()
|
|
233
|
+
if _service_enabled("email"):
|
|
234
|
+
from palette_sdk.platform_services import LocalEmailService
|
|
235
|
+
DEV_EMAIL = LocalEmailService(ROOT / ".palette" / "dev-outbox", app_name=MANIFEST.get("name") or MANIFEST.get("id", ""))
|
|
236
|
+
print("[pltt] ctx.email: messages are saved to .palette/dev-outbox as .eml files, not sent")
|
|
232
237
|
if _service_enabled("redis"):
|
|
233
238
|
from palette_sdk.platform_services import LocalRedisService
|
|
234
239
|
DEV_REDIS = LocalRedisService()
|
|
@@ -542,6 +547,8 @@ def _local_job_context(session):
|
|
|
542
547
|
extra["talk"] = TalkClient(TALK, MANIFEST.get("permissions", []))
|
|
543
548
|
if "media" in getattr(PluginContext, "__dataclass_fields__", {}):
|
|
544
549
|
extra["media"] = DEV_MEDIA or UnavailablePlatformService("media")
|
|
550
|
+
if "email" in getattr(PluginContext, "__dataclass_fields__", {}):
|
|
551
|
+
extra["email"] = DEV_EMAIL or UnavailablePlatformService("email")
|
|
545
552
|
if "user_name" in getattr(PluginContext, "__dataclass_fields__", {}):
|
|
546
553
|
extra["user_name"] = "Palette Developer"
|
|
547
554
|
|
|
@@ -644,6 +651,7 @@ class DevPluginContextMiddleware(BaseHTTPMiddleware):
|
|
|
644
651
|
request.state.llm = DEV_LLM
|
|
645
652
|
request.state.web = DEV_WEB
|
|
646
653
|
request.state.media = DEV_MEDIA
|
|
654
|
+
request.state.email = DEV_EMAIL
|
|
647
655
|
request.state.plugin_local_connections = DEV_CONNECTIONS
|
|
648
656
|
request.state.plugin_apps = LocalAppInteropService()
|
|
649
657
|
request.state.plugin_events = LocalEventPublisher()
|
package/lib/manifest.js
CHANGED
|
@@ -291,10 +291,18 @@ const PLATFORM_SERVICES = [
|
|
|
291
291
|
{
|
|
292
292
|
name: "web",
|
|
293
293
|
accessor: "ctx.web",
|
|
294
|
-
summary: "Web search plus an SSRF-guarded page reader (HTML tables, PDFs)",
|
|
294
|
+
summary: "Web search plus an SSRF-guarded page reader (HTML tables, PDFs; render=True for pages built by scripts)",
|
|
295
295
|
python: 'hits = await ctx.web.search("fx rates", limit=5)',
|
|
296
296
|
instead_of: "TAVILY_API_KEY / SERPAPI_KEY",
|
|
297
297
|
},
|
|
298
|
+
{
|
|
299
|
+
name: "email",
|
|
300
|
+
accessor: "ctx.email",
|
|
301
|
+
summary: "Send email through the platform's provider — to/cc/bcc, html + text, reply_to, attachments and inline images, headers, tags",
|
|
302
|
+
python: 'await ctx.email.send("ann@acme.com", "Your invoice", html=body, attachments=[{"filename": "invoice.pdf", "content": pdf}])',
|
|
303
|
+
instead_of: "SENDGRID_API_KEY / SMTP credentials + a verified sender domain",
|
|
304
|
+
dev: "pltt dev: checked like hosted, saved to .palette/dev-outbox as .eml — nothing is sent",
|
|
305
|
+
},
|
|
298
306
|
]
|
|
299
307
|
|
|
300
308
|
function validatePlatformServices(value, errors) {
|
|
@@ -815,6 +823,8 @@ function validateManifest(m) {
|
|
|
815
823
|
errors.push("data_scope must be personal or organization")
|
|
816
824
|
}
|
|
817
825
|
requireString(m, "developer", "manifest", errors)
|
|
826
|
+
// Superadmins keep the store's categories on the platform (`pltt categories`), so
|
|
827
|
+
// the value is checked at publish: one that names none is filed under Other.
|
|
818
828
|
requireString(m, "category", "manifest", errors)
|
|
819
829
|
requireString(m, "tagline", "manifest", errors)
|
|
820
830
|
requireString(m, "description", "manifest", errors)
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""What an app migration may not do.
|
|
2
|
+
|
|
3
|
+
One file, two copies kept byte-identical: the platform's
|
|
4
|
+
(backend/app/plugins/migration_lint.py — install-time lint, App Store review,
|
|
5
|
+
App Builder guard) and the CLI's (sdk/cli-npm/lib/migration_lint.py, run with
|
|
6
|
+
the developer's python3), so `pltt check` and publish agree. Standard library
|
|
7
|
+
only; run as a script it prints {path: [[line, reason], ...]} as JSON.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import ast
|
|
13
|
+
import json
|
|
14
|
+
import re
|
|
15
|
+
import sys
|
|
16
|
+
|
|
17
|
+
GRANT_REASON = "GRANT is reserved for the platform"
|
|
18
|
+
|
|
19
|
+
BANNED_MIGRATION_PATTERNS = [
|
|
20
|
+
(re.compile(r"\bpublic\.", re.I), "plugin migrations must not reference public schema"),
|
|
21
|
+
(re.compile(r"\bDROP\s+POLICY\b", re.I), "DROP POLICY weakens RLS"),
|
|
22
|
+
(
|
|
23
|
+
re.compile(r"\bDISABLE\s+ROW\s+LEVEL\s+SECURITY\b", re.I),
|
|
24
|
+
"DISABLE ROW LEVEL SECURITY removes tenant isolation",
|
|
25
|
+
),
|
|
26
|
+
(
|
|
27
|
+
re.compile(r"\bNO\s+FORCE\s+ROW\s+LEVEL\s+SECURITY\b", re.I),
|
|
28
|
+
"NO FORCE ROW LEVEL SECURITY lets table owners bypass RLS",
|
|
29
|
+
),
|
|
30
|
+
(re.compile(r"\bSET\s+ROLE\b", re.I), "SET ROLE is reserved for the platform"),
|
|
31
|
+
(re.compile(r"\bALTER\s+ROLE\b", re.I), "ALTER ROLE is reserved for the platform"),
|
|
32
|
+
(re.compile(r"\bCREATE\s+EXTENSION\b", re.I), "CREATE EXTENSION is reserved for the platform"),
|
|
33
|
+
(re.compile(r"\bALTER\s+DATABASE\b", re.I), "ALTER DATABASE is not allowed"),
|
|
34
|
+
(re.compile(r"\bDROP\s+SCHEMA\b", re.I), "DROP SCHEMA is not allowed"),
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
# "grant" is everyday vocabulary — a leave grant, MONTHS_AFTER_GRANT, def
|
|
38
|
+
# grant(), "Grant of Copyright License" — so GRANT counts only as a SQL
|
|
39
|
+
# statement: in a Python string (docstrings skipped), after the string's SQL
|
|
40
|
+
# comments and quoted literals are blanked (RAISE messages, enum values; the
|
|
41
|
+
# dynamic SQL an EXECUTE runs stays code), at the start of a statement, and
|
|
42
|
+
# shaped like one: privileges ON objects TO roles, or roles TO roles, ending
|
|
43
|
+
# the statement.
|
|
44
|
+
_START = r"(?:^|;|\$\w*\$|\b(?:BEGIN|THEN|ELSE|LOOP|EXECUTE)\b(?:\s+format\s*\()?)\s*"
|
|
45
|
+
_ROLE = r'(?:"[^"]*"|[\w$%{}.]+)'
|
|
46
|
+
_ROLES = rf"{_ROLE}(?:\s*,\s*{_ROLE})*"
|
|
47
|
+
_PRIVILEGES = (
|
|
48
|
+
r"(?:ALL|SELECT|INSERT|UPDATE|DELETE|TRUNCATE|REFERENCES|TRIGGER|USAGE|CREATE|CONNECT"
|
|
49
|
+
r"|TEMP(?:ORARY)?|EXECUTE|SET|ALTER\s+SYSTEM|MAINTAIN)\b[^;]*?\bON\b[^;]*?"
|
|
50
|
+
)
|
|
51
|
+
GRANT_STATEMENT = re.compile(
|
|
52
|
+
rf"{_START}(GRANT\s+(?:{_PRIVILEGES}|{_ROLES})\s+TO\s+{_ROLES}"
|
|
53
|
+
rf"\s*(?:WITH\s+[\w\s,]+?)?(?:GRANTED\s+BY\s+{_ROLE}\s*)?(?:;|\)|$))"
|
|
54
|
+
r"|(\bALTER\s+DEFAULT\s+PRIVILEGES\b)",
|
|
55
|
+
re.I,
|
|
56
|
+
)
|
|
57
|
+
_DYNAMIC_SQL = re.compile(r"\bEXECUTE\b(?:'(?:[^']|'')*'|[^;'])*", re.I)
|
|
58
|
+
_SQL_PROSE = re.compile(r"--[^\n]*|/\*.*?\*/|'(?:[^']|'')*'", re.S)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _python_strings(tree: ast.AST):
|
|
62
|
+
"""(line, text) of each string expression, docstrings skipped; f-string and
|
|
63
|
+
`+` parts are joined, with x standing in for each expression."""
|
|
64
|
+
seen = {
|
|
65
|
+
id(node.body[0].value)
|
|
66
|
+
for node in ast.walk(tree)
|
|
67
|
+
if isinstance(node, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef))
|
|
68
|
+
and node.body
|
|
69
|
+
and isinstance(node.body[0], ast.Expr)
|
|
70
|
+
and isinstance(node.body[0].value, ast.Constant)
|
|
71
|
+
and isinstance(node.body[0].value.value, str)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
def text(node: ast.AST) -> str:
|
|
75
|
+
seen.add(id(node))
|
|
76
|
+
if isinstance(node, ast.Constant) and isinstance(node.value, str):
|
|
77
|
+
return node.value
|
|
78
|
+
if isinstance(node, ast.JoinedStr):
|
|
79
|
+
return "".join(text(part) for part in node.values)
|
|
80
|
+
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
|
|
81
|
+
return text(node.left) + text(node.right)
|
|
82
|
+
return " x "
|
|
83
|
+
|
|
84
|
+
for node in ast.walk(tree):
|
|
85
|
+
if id(node) not in seen and (
|
|
86
|
+
isinstance(node, ast.JoinedStr)
|
|
87
|
+
or (isinstance(node, ast.Constant) and isinstance(node.value, str))
|
|
88
|
+
or (isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add))
|
|
89
|
+
):
|
|
90
|
+
yield node.lineno, text(node)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _blank(match: re.Match) -> str:
|
|
94
|
+
return re.sub(r"[^\n]+", " ", match.group())
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _grant_line(source: str) -> int | None:
|
|
98
|
+
try:
|
|
99
|
+
strings = list(_python_strings(ast.parse(source)))
|
|
100
|
+
except (SyntaxError, ValueError): # unreadable as Python: every GRANT word counts
|
|
101
|
+
match = re.search(r"\bGRANT\b", source, re.I)
|
|
102
|
+
return source.count("\n", 0, match.start()) + 1 if match else None
|
|
103
|
+
for line, value in strings:
|
|
104
|
+
sql = _SQL_PROSE.sub(_blank, _DYNAMIC_SQL.sub(lambda m: m.group().replace("'", " "), value))
|
|
105
|
+
if match := GRANT_STATEMENT.search(sql):
|
|
106
|
+
# An escaped "\n" in a one-line string is a newline here, not in the file.
|
|
107
|
+
return min(line + sql.count("\n", 0, match.start(match.lastindex)), source.count("\n") + 1)
|
|
108
|
+
return None
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def migration_lint_hits(source: str) -> list[tuple[int, str]]:
|
|
112
|
+
"""(line, reason) for each operation one migration file must not run."""
|
|
113
|
+
hits = [
|
|
114
|
+
(source.count("\n", 0, match.start()) + 1, reason)
|
|
115
|
+
for pattern, reason in BANNED_MIGRATION_PATTERNS
|
|
116
|
+
if (match := pattern.search(source))
|
|
117
|
+
]
|
|
118
|
+
if (line := _grant_line(source)) is not None:
|
|
119
|
+
hits.append((line, GRANT_REASON))
|
|
120
|
+
return sorted(hits)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
if __name__ == "__main__":
|
|
124
|
+
report = {}
|
|
125
|
+
for path in sys.argv[1:]:
|
|
126
|
+
with open(path, encoding="utf-8", errors="ignore") as handle:
|
|
127
|
+
report[path] = migration_lint_hits(handle.read())
|
|
128
|
+
print(json.dumps(report))
|