Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions apps/cli/src/commands/skill/content/functions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
Use this topic for Edge Functions: creating, serving, deploying, and downloading them. Read the overview first (`supabase skill display`) for targeting, credentials, and the approval flow that this topic builds on.

## Where things run

- `functions new` and `functions serve` are local only. They never take `--remote` and never need approval.
- `functions deploy` and `functions download` are hosted only. They use the linked project, or the one named with `--remote=<ref|branch>`. Deploy changes the hosted project and needs approval (see Deploying). Download only reads the hosted project.
- Functions live in `supabase/functions/<name>/index.ts`. A name must start with a letter and contain only letters, digits, `_`, and `-`.

## Creating a function

- Run `supabase functions new <name>`. It writes `index.ts`, `deno.json`, and `.npmrc` in `supabase/functions/<name>/` and adds a `[functions.<name>]` entry to the config. If the entry exists already, it is left alone.
- `--auth` exists only on `functions new` and sets what the template checks: `apikey` (default, callers send an `apikey` header with the publishable key), `user` (also sets `verify_jwt = true`; callers send a user access token), or `none`. Pick it only when the user stated how callers authenticate. It cannot change an existing function.
- If it fails with "file already exists", the function exists: edit `index.ts` or choose another name. Do not delete the directory to make it succeed.
- If it rejects the name, fix the name to match the rule above and run the command again with it.

## Serving locally

`functions serve` runs in the foreground until it is stopped, so a plain tool call that waits for it never returns. Stop it with SIGINT or SIGTERM, including during startup: it then removes the runtime it created, or restores the settings of a Functions service that `supabase start` manages. If startup itself fails, see "When something fails".

- Start it as a background process in your shell tool, or with `nohup supabase functions serve > "$LOG" 2>&1 & echo $!` where `LOG` is a log file outside the repository; keep the printed PID to stop it later. Do not run it in the foreground and interrupt it after a timeout.
- Make sure the local stack is running first: run `supabase status`, and `supabase start` if it is stopped.
- Do not treat the first output as readiness. The legacy Docker backend prints "Setting up Edge Functions runtime..." on stderr and then streams the runtime logs. When using the experimental stack backend (`SUPABASE_EXPERIMENTAL_STACK=1`), it prints `Serving Functions at <url>`; with the `stream-json` format it emits a result event holding `instance_id` and `url`. Agents get `stream-json` by default there; JSON output is rejected.
- Confirm readiness by calling the function you intend to use: `curl -i "<api-url>/functions/v1/<name>"` where the API URL comes from `supabase status`, with the credentials that function requires (for the default template, the header `apikey: <publishable key>` from `supabase status`; for `--auth user`, a signed-in user's access token). Check for the response the function is expected to give. A connection error or a 5xx from the runtime means it is not ready; a 401 means the call lacks valid credentials, not that the function works.
- It serves every function in `supabase/functions`. Positional function names are accepted but all functions are still served.
- The legacy backend watches the files and restarts the runtime after edits. The stack backend has no watcher: after editing a function, stop `serve` and start it again.
- To stop it, run `kill <pid>` (SIGTERM) on the serve process, not the shell that started it. The legacy backend prints `Stopped serving supabase/functions` and removes its container; the stack backend prints nothing on stop. Never use `kill -9`: it can bypass cleanup and leave the runtime or changed settings behind. `supabase stop` also stops the runtime.
- Under the experimental stack backend, `--import-map`, `--inspect`, `--inspect-mode`, and `--inspect-main` are rejected with a flags error. Remove them.

## Secrets and environment

- Local serve reads `supabase/functions/.env` and `supabase/functions/<name>/.env`. `--env-file <path>` replaces both. After changing an env file, stop `serve` and start it again.
- Never put secrets in `index.ts`, the config, or a committed file. Use `Deno.env.get("NAME")` in the function.
- Hosted functions do not read local `.env` files. Set their secrets with `supabase secrets set NAME=<value>` or `supabase secrets set --env-file <path>`, which changes the hosted project and needs approval in the same way as deploy. It also sends any `[edge_runtime.secrets]` from the config. Show the user the project ref and the secret names, including those from the config, with literal values redacted from any command you display. `supabase secrets list` shows names.
- Deploy does not send secrets. If a deployed function reports a missing variable, show the user which names the code reads and ask before setting them. Never print secret values in your replies.

## Deploying to a hosted project

- Deploy is a hosted change. Unless approval is already present, the first run fails with "Confirmation required: Deploy N Function(s)". The error shows the action, the counts, and usually the target, but not function names or flags. Nothing was deployed.
- Name the functions to deploy explicitly: the ones the user asked for, or, for a full deploy, the directories in `supabase/functions` that the config does not disable. Show the user the exact command, the project ref, and that list of function names, then ask. If the user named no project, ask which one.
- After the user approves, re-run the same command with `--yes` added and with `--remote=<ref>` instead of bare `--remote`. Keep the same function names and flags. Leave the function files, `deno.json`, import map, and config unchanged until it finishes; if the list or any of them changed, ask again. If the run succeeds, it is done; never deploy twice.
- Add `--no-verify-jwt` only when the user asks for a function that is public. It turns off the JWT check for what is deployed.
- `--prune` deletes every hosted function that is not part of this deploy. With named functions, that is every other hosted function, even one that still exists locally. Use it only when the user asked for it. The error gives only a count ("delete M Functions with --prune"), so before asking, compare `supabase functions list --remote=<ref>` with the functions you are deploying and show the user which hosted functions would be deleted. Before adding `--yes`, check both lists again and ask again if either changed.
- Deploy bundles with Docker when it is available and falls back to server-side bundling when it is not. `--use-api` skips Docker. `--jobs` (parallel deploys) needs `--use-api` when above 1.
- `--import-map` points at an import map file. Without it, the function's `import_map` entry in the config is used, then its own `deno.json`. `functions new` writes that entry, so edit both when you change imports.
- If a deploy fails after approval, read the error before anything else. If it is a bundling error, fix the code or the import and ask the user again before re-deploying. For credential errors, follow the overview. Never re-run unchanged.

## Downloading a function

- `supabase functions download <name>` writes the hosted source into `supabase/functions/<name>/`. Without a name it downloads all functions. It overwrites matching local files, so check `git status` first and commit or back up local edits.
- If unbundling with Docker fails, run `supabase functions download --use-api <name>`, which unbundles on the server.

## When something fails

- **A stack-backend startup error.** Read the message:
- "The local stack is not running." Run `supabase status`, then `supabase start`, then start `serve` again in the background.
- "Standalone Functions instance ... is already active." Another standalone Functions session holds it. The CLI suggests stopping the stack before starting another session: ask the user, run `supabase stop`, then start `serve` again.
- A Docker inspect error. Ask the user to start Docker.
- "Enable edge_runtime in <config> before serving Functions." Ask the user before enabling `edge_runtime` in the config, then start `serve` again.
- **"supabase start is not running." (legacy backend only).** Run `supabase start`, then start `serve` again.
- **A Docker error from `serve`.** Serve needs Docker: ask the user to start it. Deploy and download print "WARNING: Docker is not running" and fall back to server-side bundling on their own; if a Docker step fails while Docker is running, retry with `--use-api`.
- **`serve` exits right after starting.** Read its log file for the runtime error, usually a syntax error or a failed import in a function. Fix it, then start again.
- **A function returns 401.** Two checks can cause it: the runtime's JWT verification (on when `verify_jwt = true`, as in the `user` template) and the handler's own auth check. Read the response body and the serve log to see which one, then check the `withSupabase` auth option in `index.ts` for what the function expects: an `apikey` header with the publishable key, or a signed-in user's access token. Fix the caller. To make the function public, ask the user first, then change the check in `index.ts`, the `verify_jwt` setting in the config, or run `serve` with `--no-verify-jwt` for a local-only fix. On a hosted deploy, `--no-verify-jwt` changes the deployed config. `functions new --auth` cannot change an existing function.
- **"Confirmation required".** See Deploying. This is the approval step, not a bug.
- **"Access token not provided" or a project-not-linked error.** Follow "Linking and credentials for `--remote`" in the overview; for bare `--remote` ask the user which project to use and pass `--remote=<ref>`.

## Examples

```bash
# Alternatives: pick one.
supabase functions new hello-world
supabase functions new hello-world --auth user
supabase functions serve --env-file supabase/functions/.env.local
supabase functions list --remote="$PROJECT_REF"
supabase functions deploy hello-world --remote="$PROJECT_REF"
supabase functions deploy hello-world --use-api --remote="$PROJECT_REF"
supabase functions download hello-world --remote="$PROJECT_REF"
supabase secrets set --env-file supabase/functions/.env.production --remote="$PROJECT_REF"
```

Set `PROJECT_REF` to the real project ref before running the hosted examples. The deploy and secrets commands need the approval flow above first.
1 change: 1 addition & 0 deletions apps/cli/src/commands/skill/content/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ supabase db query --remote --read-only "select 1"
## Topics

- Before running `supabase db query`, run `supabase skill display db-query`.
- Before running `supabase functions serve` or `supabase functions deploy`, run `supabase skill display functions`.
- Before any schema change or migration command, run `supabase skill display migrations`.

```bash
Expand Down
20 changes: 19 additions & 1 deletion apps/cli/src/commands/skill/content/topics.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
import { Option } from "effect";
import dbQueryBody from "./db-query.md" with { type: "text" };
import functionsBody from "./functions.md" with { type: "text" };
import migrationsBody from "./migrations.md" with { type: "text" };
import overviewBody from "./overview.md" with { type: "text" };

interface TopicDefinition {
readonly slug: string;
readonly title: string;
readonly summary: string;
readonly body: string;
/** Slugs of topics an agent is likely to need next, in display order. */
readonly related?: ReadonlyArray<string>;
}

export const topics = [
{
slug: "overview",
Expand All @@ -15,14 +25,22 @@ export const topics = [
title: "Running SQL with db query",
summary: "Run SQL safely against local and hosted databases.",
body: dbQueryBody,
related: ["migrations"],
},
{
slug: "functions",
title: "Edge Functions: new, serve, deploy, download",
summary: "Create, serve, deploy, and download Edge Functions.",
body: functionsBody,
},
{
slug: "migrations",
title: "Schema changes and migrations",
summary: "Create, diff, apply, push, and repair migrations.",
body: migrationsBody,
related: ["db-query"],
},
] as const;
] as const satisfies ReadonlyArray<TopicDefinition>;

export type SkillTopic = (typeof topics)[number];
export type SkillTopicSlug = SkillTopic["slug"];
Expand Down
17 changes: 17 additions & 0 deletions apps/cli/src/commands/skill/content/topics.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ const TOPIC_BYTE_CAP = 12 * 1024;

const byteLength = (text: string) => new TextEncoder().encode(text).length;

const relatedOf = (topic: { readonly slug: string; readonly related?: ReadonlyArray<string> }) =>
topic.related ?? [];

interface PublishedCommand {
readonly path: ReadonlyArray<string>;
readonly flags: ReadonlySet<string>;
Expand Down Expand Up @@ -116,6 +119,13 @@ describe("skill topic registry", () => {
}).pipe(Effect.provide(BunFileSystem.layer)),
);

it("lists every other topic in the overview", () => {
const overview = topics.find((topic) => topic.slug === "overview");
for (const slug of topicSlugs.filter((candidate) => candidate !== "overview")) {
expect(overview?.body, slug).toContain(`supabase skill display ${slug}`);
}
});

it("resolves a topic ignoring whitespace and case", () => {
expect(Option.map(resolveTopic(" Overview "), (topic) => topic.slug)).toEqual(
Option.some("overview"),
Expand Down Expand Up @@ -180,6 +190,13 @@ describe.each(topics)("skill topic $slug content", (topic) => {
}
});

it("lists only other registered topics as related", () => {
const related = relatedOf(topic);
for (const slug of related) expect(topicSlugs).toContain(slug);
expect(related).not.toContain(topic.slug);
expect(new Set(related).size).toBe(related.length);
});

it("renders within its size cap", () => {
const cap = topic.slug === "overview" ? OVERVIEW_BYTE_CAP : TOPIC_BYTE_CAP;
expect(byteLength(renderTopic(topic, "9.9.9"))).toBeLessThanOrEqual(cap);
Expand Down
27 changes: 12 additions & 15 deletions apps/cli/src/commands/skill/display/display.render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ interface RenderableTopic {
readonly title: string;
readonly summary: string;
readonly body: string;
readonly related?: ReadonlyArray<string>;
}

const STABLE_OR_PRERELEASE = /^[1-9]\d*\.\d+\.\d+(-(beta|next)\.\d+)?$/;
Expand All @@ -16,21 +17,17 @@ export const releaseNotesUrl = (version: string): string =>
STABLE_OR_PRERELEASE.test(version) ? `${RELEASES_URL}/tag/v${version}` : RELEASES_URL;

/** Renders a topic as markdown ending in a single newline. */
export const renderTopic = (
topic: RenderableTopic,
version: string,
registry: ReadonlyArray<RenderableTopic> = topics,
): string => {
const others = registry.filter((other) => other.slug !== topic.slug);
const moreTopics =
others.length === 0
export const renderTopic = (topic: RenderableTopic, version: string): string => {
const related = (topic.related ?? []).flatMap((slug) => {
const found = topics.find((candidate) => candidate.slug === slug);
return found === undefined ? [] : [`- \`supabase skill display ${slug}\`: ${found.summary}`];
});
const relatedTopics = [
...(related.length === 0 ? [] : ["## Related topics", "", ...related, ""]),
...(topic.slug === "overview"
? []
: [
"## More topics",
"",
...others.map((other) => `- \`supabase skill display ${other.slug}\`: ${other.summary}`),
"",
];
: ["Run `supabase skill display` for the overview and the full topic list.", ""]),
Comment thread
Prashansa-K marked this conversation as resolved.
Resolved
];
return [
`# ${topic.title}`,
"",
Expand All @@ -40,7 +37,7 @@ export const renderTopic = (
"",
"---",
"",
...moreTopics,
...relatedTopics,
"## Links",
"",
`- ${STABLE_OR_PRERELEASE.test(version) ? "Release notes for this version" : "CLI releases"}: ${releaseNotesUrl(version)}`,
Expand Down
49 changes: 26 additions & 23 deletions apps/cli/src/commands/skill/display/display.render.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,15 @@ import { describe, expect, it } from "@effect/vitest";
import { topics } from "../content/topics.ts";
import { releaseNotesUrl, renderTopic } from "./display.render.ts";

const [overview] = topics;

const secondTopic = {
slug: "second",
title: "Second",
summary: "Second summary.",
body: "Second body\n",
const topicBySlug = (slug: string) => {
const topic = topics.find((candidate) => candidate.slug === slug);
if (topic === undefined) throw new Error(`No topic registered with slug "${slug}"`);
return topic;
};

const thirdTopic = {
slug: "third",
title: "Third",
summary: "Third summary.",
body: "Third body\n",
};
const overview = topicBySlug("overview");
const dbQuery = topicBySlug("db-query");
const migrations = topicBySlug("migrations");

describe("releaseNotesUrl", () => {
it.each([
Expand Down Expand Up @@ -56,19 +50,28 @@ describe("renderTopic", () => {
expect(text).not.toContain("Release notes for this version");
});

it("omits the more-topics section when the topic is the only one", () => {
expect(renderTopic(overview, "3.4.5", [overview])).not.toContain("## More topics");
it("lists related topics with their summaries, in the order given", () => {
const text = renderTopic({ ...dbQuery, related: ["migrations", "overview"] }, "3.4.5");
expect(text).toContain(
"## Related topics\n\n" +
`- \`supabase skill display migrations\`: ${migrations.summary}\n` +
`- \`supabase skill display overview\`: ${overview.summary}\n\n` +
"Run `supabase skill display` for the overview and the full topic list.\n",
);
expect(text).not.toContain("## More topics");
});
});

describe("renderTopic with several topics", () => {
it("lists every other topic in registry order and not the current one", () => {
const text = renderTopic(overview, "3.4.5", [overview, secondTopic, thirdTopic]);
it("leaves out the related list when the topic has none, keeping the overview pointer", () => {
const text = renderTopic({ ...dbQuery, related: [] }, "3.4.5");
expect(text).not.toContain("## Related topics");
expect(text).toContain(
"## More topics\n\n" +
"- `supabase skill display second`: Second summary.\n" +
"- `supabase skill display third`: Third summary.\n",
"Run `supabase skill display` for the overview and the full topic list.",
);
expect(text).not.toContain(`supabase skill display ${overview.slug}\``);
});

it("renders nothing between the body and the links for the overview", () => {
const text = renderTopic(overview, "3.4.5");
expect(text).not.toContain("## Related topics");
expect(text).not.toContain("for the overview and the full topic list");
});
});
Loading