neon 9.3.2 → 9.5.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.
package/README.md CHANGED
@@ -1139,7 +1139,7 @@ Variables a template needs are declared on each function in `neon.ts` (`env: { A
1139
1139
 
1140
1140
  Nothing is written until every check passes: a file that already exists with different contents needs `--force`, and a slug `neon.ts` already declares needs `--slug`, `--force`, or `--no-add-to-config`. A `separate` template sets its own slugs, so `--slug` only changes its directory; remove the existing declarations from `neon.ts`, or use `--force` or `--no-add-to-config`.
1141
1141
 
1142
- The registry lives in [`registry/`](https://github.com/neondatabase/examples/tree/main/registry) in `neondatabase/examples`. The CLI reads the index from `https://neon.com/functions/registry/registry.json`, which serves `main` through a CDN cache, and falls back to raw GitHub when neon.com is unreachable. Template files are always read from raw GitHub. Index and template JSON are validated against the schemas at `https://neon.com/functions/registry/schemas/` (same GitHub fallback). Set `NEON_FUNCTION_REGISTRY_DIR` to a local checkout to try templates before they are merged, or `NEON_FUNCTION_REGISTRY_URL` to read an index from somewhere else.
1142
+ The registry is moving from [`registry/`](https://github.com/neondatabase/examples/tree/main/registry) in `neondatabase/examples` to the root of [`neondatabase/registry`](https://github.com/neondatabase/registry). The CLI reads both indexes and lists `neondatabase/registry` first; an examples template with the same `id` is dropped. A missing `neondatabase/registry` is skipped silently; one that fails to load for any other reason is skipped with a warning. `neondatabase/registry` must be public, because its index and per-file reads send no token. The examples index comes from `https://neon.com/functions/registry/registry.json`, which serves `main` through a CDN cache, with a raw GitHub fallback when neon.com is unreachable, and its template files are read file by file from raw GitHub. `neondatabase/registry` template files come from one tarball of the repo, so every file of a template is from the same commit (file by file from raw GitHub when the tarball cannot be downloaded; run with `DEBUG=1` to see why). An entry in `neondatabase/registry` can instead set `source.github` (`owner`, `repo`, optional `ref` — a branch, tag, or commit, defaulting to `HEAD`, the repo's default branch — and optional `dir`) to read its files one by one from another public GitHub repo. The examples index cannot: CLIs that predate `source` would list such an entry and fail to load it, so the CLI ignores examples entries that set `source`. Pin `ref` to a tag or commit so a push mid-download cannot mix files from two commits. `website` is display-only and is not a fetch source. `GITHUB_TOKEN` or `GH_TOKEN` raises GitHub's rate limit for the tarball; it is sent only to GitHub's own hosts and never with `source.github` reads, so those repos must be public. Index and template JSON are validated against the schemas at `https://neon.com/functions/registry/schemas/` (same GitHub fallback). Set `NEON_FUNCTION_REGISTRY_DIR` to a local checkout to try templates before they are merged, or `NEON_FUNCTION_REGISTRY_URL` to read an index from somewhere else.
1143
1143
 
1144
1144
  ## Function triggers (`triggers`)
1145
1145
 
@@ -63,9 +63,15 @@ const SUPPORTED_OAUTH_PROVIDERS = [
63
63
  NeonAuthOauthProviderId.Github,
64
64
  NeonAuthOauthProviderId.Vercel,
65
65
  NeonAuthOauthProviderId.Microsoft,
66
- NeonAuthOauthProviderId.Apple
66
+ NeonAuthOauthProviderId.Apple,
67
+ NeonAuthOauthProviderId.Discord
67
68
  ];
68
- const OWN_CREDENTIALS_NOTE = `${[NeonAuthOauthProviderId.Microsoft, NeonAuthOauthProviderId.Apple].join(" and ")} always need your own credentials`;
69
+ const PROVIDERS_WITHOUT_SHARED_APP = [
70
+ NeonAuthOauthProviderId.Microsoft,
71
+ NeonAuthOauthProviderId.Apple,
72
+ NeonAuthOauthProviderId.Discord
73
+ ];
74
+ const OWN_CREDENTIALS_NOTE = `${PROVIDERS_WITHOUT_SHARED_APP.slice(0, -1).join(", ")} and ${PROVIDERS_WITHOUT_SHARED_APP.at(-1)} always need your own credentials`;
69
75
  const OAUTH_CREDENTIAL_OPTIONS = {
70
76
  "oauth-client-id": {
71
77
  describe: `OAuth client ID from your provider app. For apple, the Services ID. Omit to use Neon's shared OAuth app, where one exists; ${OWN_CREDENTIALS_NOTE}.`,
@@ -746,6 +752,10 @@ const CALLBACK_INSTRUCTIONS = {
746
752
  lead: "Create a Services ID in the Apple Developer portal, enable Sign in with Apple for it, and add the following return URL (Apple requires HTTPS and does not accept localhost):",
747
753
  urlLabel: "callback/apple"
748
754
  },
755
+ discord: {
756
+ lead: "Create an application in the Discord Developer Portal, open OAuth2, and add the following redirect URL:",
757
+ urlLabel: "callback/discord"
758
+ },
749
759
  google: {
750
760
  lead: "Get Google credentials by creating an OAuth client in Google Cloud Console > Credentials, and add the following authorized redirect URL:",
751
761
  urlLabel: "callback/google"
@@ -1,5 +1,6 @@
1
1
  import { isInteractiveTerminal } from "../env.js";
2
2
  import { log } from "../log.js";
3
+ import { recordScaffoldedTemplate } from "../analytics.js";
3
4
  import { getCliName } from "../utils/cli_name.js";
4
5
  import { projectConfigPath, projectDir } from "../project.js";
5
6
  import { resolveEnvFilePath } from "../env_file.js";
@@ -11,7 +12,7 @@ import { displayPath } from "./env_output.js";
11
12
  import { _ as missingDependencies, d as ensureConfigPackages, g as installCommandFrom } from "../_chunks/config-DbUecUDS.js";
12
13
  import { recommendedOperations } from "../functions/registry.js";
13
14
  import { collidingFiles, operationsFromFlags, planConfigRegistration, planEnvExample, planScaffold, writeScaffold } from "../functions/scaffold.js";
14
- import { describeRegistrySource, openRegistry } from "../functions/source.js";
15
+ import { describeRegistrySources, openRegistry } from "../functions/source.js";
15
16
  import { writeFileSync } from "node:fs";
16
17
  import { dirname, join, resolve } from "node:path";
17
18
  import prompts from "prompts";
@@ -50,7 +51,7 @@ const writeTemplates = (props, entries) => writer(props).end(entries.map((entry)
50
51
  const listTemplates = async (props) => {
51
52
  writeTemplates(props, (await openRegistry()).entries);
52
53
  };
53
- const unknownTemplate = (id, registry) => /* @__PURE__ */ new Error(`Unknown function template "${id}" in ${describeRegistrySource(registry.source)}. Available templates: ${registry.entries.map((entry) => entry.id).join(", ")}.`);
54
+ const unknownTemplate = (id, registry) => /* @__PURE__ */ new Error(`Unknown function template "${id}" in ${describeRegistrySources(registry.sources)}. Available templates: ${registry.entries.map((entry) => entry.id).join(", ")}.`);
54
55
  const pickOperations = async (operations, provider) => {
55
56
  const answer = await prompts({
56
57
  type: "multiselect",
@@ -188,6 +189,7 @@ const scaffoldFromTemplate = async (options) => {
188
189
  next.push(`${cli} dev --source ${fn.source}`, `${cli} functions deploy ${fn.slug} --src ${fn.source}${envFlags}`);
189
190
  }
190
191
  }
192
+ if (registry.official) recordScaffoldedTemplate(template.id);
191
193
  return {
192
194
  cancelled: false,
193
195
  template: template.id,
@@ -30,7 +30,7 @@ import { a as init_exports } from "../_chunks/init-D2fClHtC.js";
30
30
  import { o as inspect_exports } from "../_chunks/inspect-yFAb61qo.js";
31
31
  import { a as ip_allow_exports } from "../_chunks/ip_allow-DBdxNEUa.js";
32
32
  import { l as logs_exports } from "../_chunks/logs-Zf8mcRVE.js";
33
- import { a as neon_auth_exports } from "../_chunks/neon_auth-C4AXiUR6.js";
33
+ import { a as neon_auth_exports } from "../_chunks/neon_auth-mfyjde2x.js";
34
34
  import { a as open_exports } from "../_chunks/open-T2nI89Oh.js";
35
35
  import { c as operations_exports } from "../_chunks/operations-D7qGkKo3.js";
36
36
  import { o as orgs_exports } from "../_chunks/orgs-BrvAWM8Z.js";
@@ -1 +1 @@
1
- export { t as builder, n as command, r as describe, i as handler } from "../_chunks/neon_auth-C4AXiUR6.js";
1
+ export { t as builder, n as command, r as describe, i as handler } from "../_chunks/neon_auth-mfyjde2x.js";
@@ -6,11 +6,18 @@ import YAML from "yaml";
6
6
  const builder = (argv) => argv.usage("$0 realtime subscribe \"<query>\" [options]").positional("query", {
7
7
  describe: "SELECT query to subscribe to",
8
8
  type: "string"
9
- }).options({ changes: {
10
- describe: "Show raw rows and changes events",
11
- type: "boolean",
12
- default: false
13
- } }).example("$0 realtime subscribe \"SELECT * FROM items\"", "Print the initial result followed by a readable transaction log").example("$0 realtime subscribe --changes \"SELECT * FROM items\"", "Print raw rows and changes events").epilogue("The subscription runs until interrupted. Terminal output is an append-only snapshot and transaction log; JSON output is newline-delimited; YAML output uses one document per event.").strict();
9
+ }).options({
10
+ changes: {
11
+ describe: "Show raw rows and changes events",
12
+ type: "boolean",
13
+ default: false
14
+ },
15
+ debug: {
16
+ describe: "Show full database error details, including SQLSTATE and PostgreSQL's message. Details can name schema objects and row values.",
17
+ type: "boolean",
18
+ default: false
19
+ }
20
+ }).example("$0 realtime subscribe \"SELECT * FROM items\"", "Print the initial result followed by a readable transaction log").example("$0 realtime subscribe --changes \"SELECT * FROM items\"", "Print raw rows and changes events").example("$0 realtime subscribe --debug \"SELECT * FROM items\"", "Show why a query is rejected or fails").epilogue("The subscription runs until interrupted. Terminal output is an append-only snapshot and transaction log; JSON output is newline-delimited; YAML output uses one document per event.").strict();
14
21
  const handler = async (args) => {
15
22
  const props = args;
16
23
  const controller = new AbortController();
@@ -55,7 +62,8 @@ const subscribe = async (props, dependencies = {}) => {
55
62
  const realtime = await connect({
56
63
  url,
57
64
  secret,
58
- database
65
+ database,
66
+ debugMode: props.debug ?? false
59
67
  });
60
68
  const render = createRenderer(props, {
61
69
  project: props.projectId,
@@ -85,7 +93,8 @@ const connectRealtime = async (options) => {
85
93
  const realtime = createRealtime({
86
94
  url: options.url,
87
95
  secret: options.secret,
88
- db: options.database
96
+ db: options.database,
97
+ debugMode: options.debugMode
89
98
  });
90
99
  return {
91
100
  subscribeMaterialized: (query) => realtime.subscribe(rawSql(query)),
@@ -284,9 +293,11 @@ const humanStatus = (state) => {
284
293
  case "live": return "Live — waiting for changes.";
285
294
  case "stale": return "Stale — showing the last known result.";
286
295
  case "closed": return "Subscription closed.";
287
- case "error": return `Subscription failed — ${state.error.message}`;
296
+ case "error": return `Subscription failed — ${errorText(state.error)}`;
288
297
  }
289
298
  };
299
+ /** The error's message, with the SQLSTATE that a debug subscription receives. */
300
+ const errorText = (error) => error.sqlState === void 0 ? error.message : `${error.message} (SQLSTATE ${error.sqlState})`;
290
301
  const branchDisplayName = (props, branchId) => {
291
302
  const branch = "branch" in props ? props.branch : props.id;
292
303
  return branch === branchId ? branchId : `${branch} (${branchId})`;
@@ -5,6 +5,20 @@ const MAX_TOTAL_BYTES = 2097152;
5
5
  const MAX_JSON_BYTES = 1048576;
6
6
  const WINDOWS_ABSOLUTE = /^[A-Za-z]:/;
7
7
  const isContainedRelativePath = (value) => value !== "" && value.length <= MAX_PATH_LENGTH && !value.includes("\0") && !value.includes("\\") && !value.startsWith("/") && !WINDOWS_ABSOLUTE.test(value) && !value.split("/").some((part) => part === "" || part === "." || part === "..");
8
+ const GITHUB_OWNER_PATTERN = "^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,37}[a-zA-Z0-9])?$";
9
+ const GITHUB_REPO_PATTERN = "^(?!\\.\\.?$)[A-Za-z0-9._-]{1,100}$";
10
+ const GITHUB_REF_PATTERN = "^[A-Za-z0-9._/+-]{1,255}$";
11
+ const DEFAULT_GITHUB_REF = "HEAD";
12
+ const remoteSourceJsonSchema = {
13
+ type: "object",
14
+ minProperties: 1
15
+ };
16
+ const allowGithubTemplateSources = (schema) => {
17
+ const clone = structuredClone(schema);
18
+ const properties = clone.properties?.templates?.items?.properties;
19
+ if (properties && properties.source === void 0) properties.source = remoteSourceJsonSchema;
20
+ return clone;
21
+ };
8
22
  function assertValid(validate, data, label) {
9
23
  if (!validate.check(data)) throw new Error(`${label}: ${validate.errorsText()}`);
10
24
  }
@@ -23,9 +37,42 @@ const parseRegistryIndex = (text, validate) => {
23
37
  if (seen.has(item.id)) throw new Error(`Invalid function registry: ${at} repeats an id.`);
24
38
  if (!isContainedRelativePath(item.path)) throw new Error(`Invalid function registry: ${at} has a missing or unsafe path.`);
25
39
  seen.add(item.id);
26
- return item;
40
+ const { source, ...entry } = item;
41
+ if (source === void 0) return entry;
42
+ if (!isRecord(source) || Object.keys(source).length === 0) throw new Error(`Invalid function registry: ${at} has an invalid source.`);
43
+ if (!isGithubSourceDocument(source)) return {
44
+ ...entry,
45
+ unsupportedSource: true
46
+ };
47
+ const invalid = invalidGithubField(source.github);
48
+ if (invalid) throw new Error(`Invalid function registry: ${at} has an invalid source.${invalid}.`);
49
+ const github = source.github;
50
+ return {
51
+ ...entry,
52
+ source: { github: {
53
+ ...github,
54
+ ref: github.ref ?? "HEAD"
55
+ } }
56
+ };
27
57
  });
28
58
  };
59
+ const GITHUB_SOURCE_KEYS = /* @__PURE__ */ new Set([
60
+ "owner",
61
+ "repo",
62
+ "ref",
63
+ "dir"
64
+ ]);
65
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
66
+ const isGithubSourceDocument = (source) => Object.keys(source).join() === "github" && (!isRecord(source.github) || Object.keys(source.github).every((key) => GITHUB_SOURCE_KEYS.has(key)));
67
+ const matches = (pattern, value) => typeof value === "string" && new RegExp(pattern).test(value);
68
+ const optionalPath = (value, pattern) => value === void 0 || typeof value === "string" && (pattern === void 0 || matches(pattern, value)) && isContainedRelativePath(value);
69
+ const invalidGithubField = (github) => {
70
+ if (!isRecord(github)) return "github";
71
+ if (!matches("^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,37}[a-zA-Z0-9])?$", github.owner)) return "github.owner";
72
+ if (!matches("^(?!\\.\\.?$)[A-Za-z0-9._-]{1,100}$", github.repo)) return "github.repo";
73
+ if (!optionalPath(github.ref, "^[A-Za-z0-9._/+-]{1,255}$")) return "github.ref";
74
+ if (!optionalPath(github.dir)) return "github.dir";
75
+ };
29
76
  const parseTemplateItem = (text, validate, expectedId) => {
30
77
  const data = JSON.parse(text);
31
78
  assertValid(validate, data, "Invalid template.json");
@@ -48,4 +95,4 @@ const parseTemplateItem = (text, validate, expectedId) => {
48
95
  ...operations ? { operations } : {}
49
96
  };
50
97
  };
51
- export { MAX_FILE_BYTES, MAX_JSON_BYTES, MAX_TOTAL_BYTES, isContainedRelativePath, parseRegistryIndex, parseTemplateItem, recommendedOperations, resolveOperationById };
98
+ export { DEFAULT_GITHUB_REF, GITHUB_OWNER_PATTERN, GITHUB_REF_PATTERN, GITHUB_REPO_PATTERN, MAX_FILE_BYTES, MAX_JSON_BYTES, MAX_TOTAL_BYTES, allowGithubTemplateSources, isContainedRelativePath, parseRegistryIndex, parseTemplateItem, recommendedOperations, remoteSourceJsonSchema, resolveOperationById };
@@ -1,17 +1,41 @@
1
- import { MAX_FILE_BYTES, MAX_JSON_BYTES, MAX_TOTAL_BYTES, isContainedRelativePath, parseRegistryIndex, parseTemplateItem } from "./registry.js";
1
+ import { log } from "../log.js";
2
+ import { MAX_FILE_BYTES, MAX_JSON_BYTES, MAX_TOTAL_BYTES, allowGithubTemplateSources, isContainedRelativePath, parseRegistryIndex, parseTemplateItem } from "./registry.js";
2
3
  import { readFileSync, realpathSync, statSync } from "node:fs";
3
4
  import { posix, resolve, sep } from "node:path";
4
5
  // src/functions/source.ts
6
+ const INDEX_FILE = "registry.json";
7
+ const DEFAULT_GITHUB_RAW_URL = "https://raw.githubusercontent.com";
8
+ const NEON_REGISTRY_GITHUB = {
9
+ owner: "neondatabase",
10
+ repo: "registry",
11
+ ref: "main"
12
+ };
13
+ const EXAMPLES_GITHUB = {
14
+ owner: "neondatabase",
15
+ repo: "examples",
16
+ ref: "main",
17
+ dir: "registry"
18
+ };
19
+ const rawIndexUrl = ({ owner, repo, ref, dir }) => [
20
+ DEFAULT_GITHUB_RAW_URL,
21
+ owner,
22
+ repo,
23
+ ref,
24
+ dir,
25
+ INDEX_FILE
26
+ ].filter((part) => part !== void 0).join("/");
5
27
  const DEFAULT_REGISTRY_URL = "https://neon.com/functions/registry/registry.json";
6
- const GITHUB_REGISTRY_URL = "https://raw.githubusercontent.com/neondatabase/examples/main/registry/registry.json";
28
+ const GITHUB_REGISTRY_URL = rawIndexUrl(EXAMPLES_GITHUB);
7
29
  const REGISTRY_DIR_ENV = "NEON_FUNCTION_REGISTRY_DIR";
8
30
  const REGISTRY_URL_ENV = "NEON_FUNCTION_REGISTRY_URL";
31
+ const GITHUB_RAW_ENV = "NEON_FUNCTION_REGISTRY_GITHUB";
9
32
  const REGISTRY_TIMEOUT_MS = 1e4;
10
33
  const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
11
34
  "localhost",
12
35
  "127.0.0.1",
13
36
  "[::1]"
14
37
  ]);
38
+ const DOT_SEGMENTS = /* @__PURE__ */ new Set([".", ".."]);
15
39
  var RegistryError = class extends Error {
16
40
  constructor(message, status) {
17
41
  super(message);
@@ -19,23 +43,71 @@ var RegistryError = class extends Error {
19
43
  if (status !== void 0) this.status = status;
20
44
  }
21
45
  };
46
+ const parseHttpsUrl = (raw, label) => {
47
+ if (!URL.canParse(raw)) throw new RegistryError(`${label} is not a URL: ${raw}`);
48
+ const url = new URL(raw);
49
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && LOOPBACK_HOSTS.has(url.hostname))) throw new RegistryError(`${label} must be an https:// URL, got ${raw}`);
50
+ return url;
51
+ };
22
52
  const resolveRegistrySource = (env = process.env, cwd = process.cwd(), defaultUrl = DEFAULT_REGISTRY_URL) => {
23
53
  const dir = env[REGISTRY_DIR_ENV];
24
54
  if (dir) return {
25
55
  kind: "dir",
26
56
  dir: resolve(cwd, dir)
27
57
  };
28
- const raw = env["NEON_FUNCTION_REGISTRY_URL"] || defaultUrl;
29
- if (!URL.canParse(raw)) throw new RegistryError(`${REGISTRY_URL_ENV} is not a URL: ${raw}`);
30
- const url = new URL(raw);
31
- if (url.protocol !== "https:" && !(url.protocol === "http:" && LOOPBACK_HOSTS.has(url.hostname))) throw new RegistryError(`${REGISTRY_URL_ENV} must be an https:// URL, got ${raw}`);
32
58
  return {
33
59
  kind: "url",
34
- url
60
+ url: parseHttpsUrl(env["NEON_FUNCTION_REGISTRY_URL"] || defaultUrl, REGISTRY_URL_ENV)
35
61
  };
36
62
  };
63
+ const resolveGithubRawBase = (env = process.env, override) => parseHttpsUrl(override || env["NEON_FUNCTION_REGISTRY_GITHUB"] || "https://raw.githubusercontent.com", GITHUB_RAW_ENV);
37
64
  const describeRegistrySource = (source) => source.kind === "dir" ? source.dir : source.url.href;
65
+ const describeRegistrySources = (sources) => sources.map(describeRegistrySource).join(" and ");
66
+ const describeGithub = (github) => `${github.owner}/${github.repo}@${github.ref}`;
67
+ const githubFileUrl = (raw, github, relativePath) => {
68
+ const repoPath = github.dir ? `${github.dir}/${relativePath}` : relativePath;
69
+ if (!isContainedRelativePath(repoPath) || !isContainedRelativePath(github.ref) || [github.owner, github.repo].some((part) => DOT_SEGMENTS.has(part))) throw new RegistryError(`Registry file ${relativePath} resolves outside ${describeGithub(github)}.`);
70
+ const url = new URL(raw);
71
+ url.pathname = [url.pathname.replace(/\/+$/, ""), ...[
72
+ github.owner,
73
+ github.repo,
74
+ github.ref,
75
+ repoPath
76
+ ].flatMap((part) => part.split("/")).map(encodeURIComponent)].join("/");
77
+ return url;
78
+ };
38
79
  const tooLarge = (path, limit) => new RegistryError(`Registry file ${path} is larger than the ${limit}-byte limit.`);
80
+ const LOCAL_COPY_HINT = `Check your connection, or set ${REGISTRY_DIR_ENV} to a local copy.`;
81
+ const REGISTRY_ORIGIN = {
82
+ name: "the Function Registry",
83
+ unreachableHint: LOCAL_COPY_HINT
84
+ };
85
+ const unreachable = (error, url, origin) => {
86
+ if (error instanceof Error && error.name === "TimeoutError") return new RegistryError(`${origin.name} did not answer ${url.href} within ${REGISTRY_TIMEOUT_MS / 1e3} seconds. ${origin.unreachableHint}`);
87
+ const cause = error instanceof Error && "cause" in error ? error.cause : void 0;
88
+ if (cause instanceof Error && /redirect/i.test(cause.message)) return new RegistryError(`${origin.name} redirected ${url.href}, and the CLI does not follow redirects.${origin.redirectHint ? ` ${origin.redirectHint}` : ""}`);
89
+ return new RegistryError(`Could not reach ${origin.name} at ${url.href}. ${origin.unreachableHint}`);
90
+ };
91
+ const fetchText = async (url, relativePath, limit, origin) => {
92
+ let response;
93
+ try {
94
+ response = await fetch(url, {
95
+ redirect: "error",
96
+ headers: { "User-Agent": "neon" },
97
+ signal: AbortSignal.timeout(REGISTRY_TIMEOUT_MS)
98
+ });
99
+ } catch (error) {
100
+ throw unreachable(error, url, origin);
101
+ }
102
+ if (!response.ok) {
103
+ const hint = (response.status === 403 || response.status === 429) && origin.rateLimitHint ? ` ${origin.rateLimitHint}` : "";
104
+ throw new RegistryError(`Could not read ${url.href}: ${origin.name} answered ${response.status}.${hint}`, response.status);
105
+ }
106
+ if (Number(response.headers.get("content-length")) > limit) throw tooLarge(relativePath, limit);
107
+ const text = await response.text();
108
+ if (Buffer.byteLength(text, "utf8") > limit) throw tooLarge(relativePath, limit);
109
+ return text;
110
+ };
39
111
  const dirReader = (dir) => {
40
112
  let root;
41
113
  return async (relativePath, limit) => {
@@ -60,24 +132,44 @@ const urlReader = (index) => {
60
132
  return async (relativePath, limit) => {
61
133
  const url = new URL(relativePath, base);
62
134
  if (url.origin !== base.origin || !url.pathname.startsWith(base.pathname)) throw new RegistryError(`Registry file ${relativePath} resolves outside ${base.href}.`);
63
- let response;
135
+ return fetchText(url, relativePath, limit, REGISTRY_ORIGIN);
136
+ };
137
+ };
138
+ const githubReader = (github, rawBase, unreachableHint = "Check your connection.") => {
139
+ const origin = {
140
+ name: `GitHub (${describeGithub(github)})`,
141
+ unreachableHint,
142
+ redirectHint: "The repo may have been renamed or moved; its registry entry needs updating.",
143
+ rateLimitHint: "GitHub is rate limiting this network; try again in a few minutes."
144
+ };
145
+ return async (relativePath, limit) => fetchText(githubFileUrl(rawBase(), github, relativePath), relativePath, limit, origin);
146
+ };
147
+ const archiveReader = (github, { env, rawBase }) => {
148
+ const { owner, repo, ref, dir = "" } = github;
149
+ const perFile = githubReader(github, rawBase, LOCAL_COPY_HINT);
150
+ let archive;
151
+ const download = async () => {
64
152
  try {
65
- response = await fetch(url, {
66
- redirect: "error",
67
- signal: AbortSignal.timeout(REGISTRY_TIMEOUT_MS)
68
- });
69
- } catch {
70
- throw new RegistryError(`Could not reach the Function Registry at ${url.href}. Check your connection, or set ${REGISTRY_DIR_ENV} to a local copy.`);
153
+ const { downloadGithubTarball, parseTar, selectTemplateFiles } = await import("../init/bootstrap.js");
154
+ const tar = await downloadGithubTarball(owner, repo, ref, env);
155
+ return new Map(selectTemplateFiles(parseTar(tar), dir).map((file) => [file.path, file]));
156
+ } catch (error) {
157
+ log.debug("Could not download the %s archive, reading files one by one: %s", describeGithub(github), error instanceof Error ? error.message : String(error));
158
+ return;
71
159
  }
72
- if (!response.ok) throw new RegistryError(`The Function Registry answered ${response.status} for ${url.href}.`, response.status);
73
- if (Number(response.headers.get("content-length")) > limit) throw tooLarge(relativePath, limit);
74
- const text = await response.text();
75
- if (Buffer.byteLength(text, "utf8") > limit) throw tooLarge(relativePath, limit);
76
- return text;
160
+ };
161
+ return async (relativePath, limit) => {
162
+ archive ??= download();
163
+ const files = await archive;
164
+ if (!files) return perFile(relativePath, limit);
165
+ const file = files.get(relativePath);
166
+ if (!file) throw new RegistryError(`Registry file ${relativePath} not found in ${describeGithub(github)}.`, 404);
167
+ if (file.kind !== "file") throw new RegistryError(`Registry file ${relativePath} is not a regular file.`);
168
+ if (file.bytes.length > limit) throw tooLarge(relativePath, limit);
169
+ return file.bytes.toString("utf8");
77
170
  };
78
171
  };
79
172
  const templateSourcePaths = (template) => template.operations?.map((operation) => operation.source) ?? ["functions/index.ts"];
80
- const INDEX_FILE = "registry.json";
81
173
  const REGISTRY_SCHEMA_FILE = "schemas/registry.schema.json";
82
174
  const TEMPLATE_SCHEMA_FILE = "schemas/template.schema.json";
83
175
  let publishedSchemas;
@@ -96,7 +188,7 @@ const compileSchemas = async (registrySchema, templateSchema) => {
96
188
  };
97
189
  };
98
190
  return {
99
- registry: wrap(registrySchema),
191
+ registry: wrap(allowGithubTemplateSources(registrySchema)),
100
192
  template: wrap(templateSchema)
101
193
  };
102
194
  };
@@ -117,20 +209,72 @@ const loadPublishedSchemas = () => {
117
209
  });
118
210
  return publishedSchemas;
119
211
  };
120
- const openRegistry = async (source, { primary = DEFAULT_REGISTRY_URL, fallback = GITHUB_REGISTRY_URL, env = process.env } = {}) => {
121
- if (source) return openRegistryAt(source);
122
- const resolved = resolveRegistrySource(env, process.cwd(), primary);
123
- if (resolved.kind !== "url" || resolved.url.href !== new URL(primary).href) return openRegistryAt(resolved);
212
+ const openRegistry = async (source, { primary = DEFAULT_REGISTRY_URL, fallback = GITHUB_REGISTRY_URL, neonRegistry = NEON_REGISTRY_GITHUB, env = process.env, githubRaw } = {}) => {
213
+ let base;
124
214
  const github = {
215
+ env,
216
+ rawBase: () => {
217
+ base ??= resolveGithubRawBase(env, githubRaw);
218
+ return base;
219
+ }
220
+ };
221
+ if (source) return openRegistryAt(source, github);
222
+ const resolved = resolveRegistrySource(env, process.cwd(), primary);
223
+ if (resolved.kind !== "url" || resolved.url.href !== new URL(primary).href) return openRegistryAt(resolved, github);
224
+ const mirror = {
125
225
  kind: "url",
126
226
  url: new URL(fallback)
127
227
  };
128
- try {
129
- return await openRegistryAt(resolved, github);
130
- } catch (error) {
131
- if (!(error instanceof RegistryError)) throw error;
132
- return openRegistryAt(github);
228
+ const openExamples = async () => {
229
+ try {
230
+ return await openRegistryAt(resolved, github, {
231
+ files: mirror,
232
+ remoteSources: false
233
+ });
234
+ } catch (error) {
235
+ if (!(error instanceof RegistryError)) throw error;
236
+ return openRegistryAt(mirror, github, { remoteSources: false });
237
+ }
238
+ };
239
+ const official = !(githubRaw || env["NEON_FUNCTION_REGISTRY_GITHUB"]);
240
+ if (neonRegistry === false) return {
241
+ ...await openExamples(),
242
+ official
243
+ };
244
+ const repoIndex = new URL(rawIndexUrl(neonRegistry));
245
+ const openNeonRegistry = () => openRegistryAt({
246
+ kind: "url",
247
+ url: repoIndex
248
+ }, github, {
249
+ read: githubReader(neonRegistry, github.rawBase, LOCAL_COPY_HINT),
250
+ readFiles: archiveReader(neonRegistry, github)
251
+ });
252
+ const results = await Promise.allSettled([openNeonRegistry(), openExamples()]);
253
+ for (const result of results) if (result.status === "rejected" && !(result.reason instanceof RegistryError)) throw result.reason;
254
+ const [neon, examples] = results;
255
+ if (neon.status === "rejected" && examples.status === "rejected") throw neon.reason.status === 404 ? examples.reason : neon.reason;
256
+ if (neon.status === "rejected" && neon.reason.status !== 404) log.warning("Skipping %s, listing only neondatabase/examples templates: %s", describeGithub(neonRegistry), neon.reason.message);
257
+ return mergeRegistries(results.flatMap((result) => result.status === "fulfilled" ? [result.value] : []), official);
258
+ };
259
+ const mergeRegistries = (registries, official) => {
260
+ const owners = /* @__PURE__ */ new Map();
261
+ const entries = [];
262
+ for (const registry of registries) for (const entry of registry.entries) {
263
+ if (owners.has(entry.id)) continue;
264
+ owners.set(entry.id, registry);
265
+ entries.push(entry);
133
266
  }
267
+ const sources = registries.flatMap((registry) => registry.sources);
268
+ return {
269
+ sources,
270
+ entries,
271
+ official,
272
+ load: async (entry) => {
273
+ const owner = owners.get(entry.id);
274
+ if (!owner) throw new RegistryError(`Template "${entry.id}" is not in ${describeRegistrySources(sources)}.`);
275
+ return owner.load(entry);
276
+ }
277
+ };
134
278
  };
135
279
  const readerFor = (source) => source.kind === "dir" ? dirReader(source.dir) : urlReader(source.url);
136
280
  const withStaleIndexHint = (read, index, files) => async (path, limit) => {
@@ -141,9 +285,8 @@ const withStaleIndexHint = (read, index, files) => async (path, limit) => {
141
285
  throw new RegistryError(`${error.message} The index from ${describeRegistrySource(index)} is cached and may still list a template that moved or was removed. Try again in a few minutes, or set ${REGISTRY_URL_ENV}=${describeRegistrySource(files)} to read the current index.`, 404);
142
286
  }
143
287
  };
144
- const openRegistryAt = async (source, files = source) => {
145
- const read = readerFor(source);
146
- const readFile = files === source ? read : withStaleIndexHint(readerFor(files), source, files);
288
+ const openRegistryAt = async (source, github, { files = source, read = readerFor(source), readFiles = readerFor(files), remoteSources = true } = {}) => {
289
+ const readFile = files === source ? readFiles : withStaleIndexHint(readFiles, source, files);
147
290
  const indexPath = source.kind === "dir" ? INDEX_FILE : posix.basename(source.url.pathname);
148
291
  const schemas = await loadPublishedSchemas();
149
292
  const parse = (path, text, fn) => {
@@ -153,28 +296,56 @@ const openRegistryAt = async (source, files = source) => {
153
296
  throw new RegistryError(`Invalid registry file ${path}: ${error instanceof Error ? error.message : String(error)}`);
154
297
  }
155
298
  };
156
- const entries = parse(indexPath, await read(indexPath, MAX_JSON_BYTES), (text) => parseRegistryIndex(text, schemas.registry));
299
+ const parsed = parse(indexPath, await read(indexPath, MAX_JSON_BYTES), (text) => parseRegistryIndex(text, schemas.registry));
300
+ const entries = remoteSources ? parsed : parsed.filter((entry) => {
301
+ const remote = entry.source || entry.unsupportedSource;
302
+ if (remote) log.debug("Ignoring template %s from %s: only neondatabase/registry can set source.", entry.id, describeRegistrySource(source));
303
+ return !remote;
304
+ });
157
305
  const load = async (entry) => {
306
+ if (entry.unsupportedSource) throw new RegistryError(`Template "${entry.id}" needs a newer version of the neon CLI. Update the CLI and retry.`);
158
307
  if (!entry.path || !isContainedRelativePath(entry.path)) throw new RegistryError(`Template "${entry.id}" has no valid path.`);
159
- const template = parse(entry.path, await readFile(entry.path, MAX_JSON_BYTES), (text) => parseTemplateItem(text, schemas.template, entry.id));
308
+ const readEntry = entry.source ? githubReader(entry.source.github, github.rawBase) : readFile;
309
+ const template = parse(entry.path, await readEntry(entry.path, MAX_JSON_BYTES), (text) => parseTemplateItem(text, schemas.template, entry.id));
310
+ const paths = templateSourcePaths(template);
311
+ const unsafe = paths.find((path) => !isContainedRelativePath(path));
312
+ if (unsafe !== void 0) throw new RegistryError(`Template "${entry.id}" references an unsafe path: ${unsafe}`);
160
313
  const dir = posix.dirname(entry.path);
161
- const sources = /* @__PURE__ */ new Map();
162
- let total = 0;
163
- for (const path of templateSourcePaths(template)) {
164
- if (!isContainedRelativePath(path)) throw new RegistryError(`Template "${entry.id}" references an unsafe path: ${path}`);
165
- const text = await readFile(dir === "." ? path : posix.join(dir, path), Math.min(MAX_FILE_BYTES, MAX_TOTAL_BYTES - total));
166
- total += Buffer.byteLength(text, "utf8");
167
- sources.set(path, text);
168
- }
314
+ const sources = await readSources(entry.id, [...new Set(paths)], (path) => readEntry(dir === "." ? path : posix.join(dir, path), MAX_FILE_BYTES));
169
315
  return {
170
316
  template,
171
- sources
317
+ sources: new Map(sources)
172
318
  };
173
319
  };
174
320
  return {
175
- source,
321
+ sources: [source],
176
322
  entries,
177
- load
323
+ load,
324
+ official: false
325
+ };
326
+ };
327
+ const MAX_PARALLEL_READS = 6;
328
+ const readSources = async (templateId, paths, read) => {
329
+ const results = new Array(paths.length);
330
+ let next = 0;
331
+ let total = 0;
332
+ let stopped = false;
333
+ const worker = async () => {
334
+ while (!stopped && next < paths.length) {
335
+ const index = next++;
336
+ const path = paths[index];
337
+ try {
338
+ const text = await read(path);
339
+ total += Buffer.byteLength(text, "utf8");
340
+ if (total > 2097152) throw new RegistryError(`Template "${templateId}" source files exceed the ${MAX_TOTAL_BYTES}-byte total limit.`);
341
+ results[index] = [path, text];
342
+ } catch (error) {
343
+ stopped = true;
344
+ throw error;
345
+ }
346
+ }
178
347
  };
348
+ await Promise.all(Array.from({ length: Math.min(MAX_PARALLEL_READS, paths.length) }, worker));
349
+ return results;
179
350
  };
180
- export { DEFAULT_REGISTRY_URL, GITHUB_REGISTRY_URL, REGISTRY_DIR_ENV, REGISTRY_URL_ENV, RegistryError, describeRegistrySource, openRegistry, resolveRegistrySource, templateSourcePaths };
351
+ export { DEFAULT_GITHUB_RAW_URL, DEFAULT_REGISTRY_URL, EXAMPLES_GITHUB, GITHUB_RAW_ENV, GITHUB_REGISTRY_URL, NEON_REGISTRY_GITHUB, REGISTRY_DIR_ENV, REGISTRY_URL_ENV, RegistryError, describeRegistrySource, describeRegistrySources, githubFileUrl, openRegistry, resolveGithubRawBase, resolveRegistrySource, templateSourcePaths };
@@ -1,3 +1,4 @@
1
+ import { githubRequestHeaders } from "../utils/github_headers.js";
1
2
  import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
2
3
  import { dirname, join } from "node:path";
3
4
  import YAML from "yaml";
@@ -75,12 +76,7 @@ const FALLBACK_TEMPLATES = [
75
76
  ];
76
77
  const templateIds = (templates) => templates.map((t) => t.id).join(", ");
77
78
  const findTemplate = (templates, id) => templates.find((t) => t.id === id);
78
- const githubToken = () => process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN ?? "";
79
- const downloadHeaders = () => ({
80
- "User-Agent": "neon",
81
- ...githubToken() ? { Authorization: `Bearer ${githubToken()}` } : {}
82
- });
83
- const codeloadBase = () => process.env.NEON_BOOTSTRAP_GITHUB_CODELOAD ?? "https://codeload.github.com";
79
+ const codeloadBase = (env = process.env) => env.NEON_BOOTSTRAP_GITHUB_CODELOAD ?? "https://codeload.github.com";
84
80
  const isRecord = (value) => typeof value === "object" && value !== null;
85
81
  /**
86
82
  * Normalize a manifest entry's string list (`tools` or `services`) into a clean
@@ -135,7 +131,7 @@ function parseManifest(text) {
135
131
  async function fetchTemplates() {
136
132
  for (const url of manifestUrls()) try {
137
133
  const res = await fetch(url, {
138
- headers: downloadHeaders(),
134
+ headers: githubRequestHeaders(url),
139
135
  signal: AbortSignal.timeout(1e4)
140
136
  });
141
137
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
@@ -243,7 +239,8 @@ const parseTar = (buf) => {
243
239
  * writing files re-creates their parent directories.
244
240
  */
245
241
  const selectTemplateFiles = (entries, subdir) => {
246
- const prefix = `${subdir.replace(/^\/+|\/+$/g, "")}/`;
242
+ const trimmed = subdir.replace(/^\/+|\/+$/g, "");
243
+ const prefix = trimmed ? `${trimmed}/` : "";
247
244
  const files = [];
248
245
  for (const entry of entries) {
249
246
  const slash = entry.name.indexOf("/");
@@ -266,27 +263,18 @@ const selectTemplateFiles = (entries, subdir) => {
266
263
  }
267
264
  return files;
268
265
  };
269
- const tarballUrl = (template) => {
270
- const { owner, repo, ref } = template.source;
271
- return `${codeloadBase()}/${owner}/${repo}/tar.gz/${ref}`;
272
- };
266
+ const githubTarballUrl = (owner, repo, ref, env = process.env) => `${codeloadBase(env)}/${owner}/${repo}/tar.gz/${ref}`;
273
267
  const friendlyGithubError = (status, url) => {
274
268
  if (status === 404) return /* @__PURE__ */ new Error(`GitHub returned 404 for ${url}. The template repo or ref may have moved.`);
275
269
  if (status === 403 || status === 429) return /* @__PURE__ */ new Error(`GitHub rate limited the template download (${url}). Set a GITHUB_TOKEN environment variable to raise the limit, then retry.`);
276
270
  return /* @__PURE__ */ new Error(`GitHub returned HTTP ${status} for ${url}.`);
277
271
  };
278
- /**
279
- * Download a template and resolve it to the exact set of files to write. The
280
- * entire subtree is captured in one tarball request, so the copy is atomically
281
- * consistent: a push to the template repo mid-download cannot produce a
282
- * mismatched checkout (unlike fetching a file list and then each blob).
283
- */
284
- const downloadTemplate = async (template) => {
285
- const url = tarballUrl(template);
272
+ const downloadGithubTarball = async (owner, repo, ref, env = process.env) => {
273
+ const url = githubTarballUrl(owner, repo, ref, env);
286
274
  let gzipped;
287
275
  try {
288
276
  const res = await fetch(url, {
289
- headers: downloadHeaders(),
277
+ headers: githubRequestHeaders(url, env),
290
278
  signal: AbortSignal.timeout(3e4)
291
279
  });
292
280
  if (!res.ok) throw friendlyGithubError(res.status, url);
@@ -294,13 +282,21 @@ const downloadTemplate = async (template) => {
294
282
  } catch (err) {
295
283
  throw err instanceof Error ? err : new Error(String(err));
296
284
  }
297
- let tar;
298
285
  try {
299
- tar = Buffer.from(gunzipSync(new Uint8Array(gzipped)));
286
+ return Buffer.from(gunzipSync(new Uint8Array(gzipped)));
300
287
  } catch (err) {
301
288
  throw new Error(`Failed to decompress the template archive from ${url}: ${err instanceof Error ? err.message : String(err)}`);
302
289
  }
290
+ };
291
+ /**
292
+ * Download a template and resolve it to the exact set of files to write. The
293
+ * entire subtree is captured in one tarball request, so the copy is atomically
294
+ * consistent: a push to the template repo mid-download cannot produce a
295
+ * mismatched checkout (unlike fetching a file list and then each blob).
296
+ */
297
+ const downloadTemplate = async (template) => {
303
298
  const { owner, repo, ref, subdir } = template.source;
299
+ const tar = await downloadGithubTarball(owner, repo, ref);
304
300
  const files = selectTemplateFiles(parseTar(tar), subdir);
305
301
  if (files.length === 0) throw new Error(`Template subdirectory "${subdir}" was not found in ${owner}/${repo}@${ref}.`);
306
302
  return files;
@@ -368,4 +364,4 @@ const scaffoldTemplate = async (template, targetDir, options = {}) => {
368
364
  }
369
365
  return files.length;
370
366
  };
371
- export { BootstrapInputError, FALLBACK_TEMPLATES, downloadTemplate, ensureTargetUsable, fetchTemplates, findTemplate, parseManifest, parseTar, scaffoldTemplate, selectTemplateFiles, templateIds };
367
+ export { BootstrapInputError, FALLBACK_TEMPLATES, downloadGithubTarball, downloadTemplate, ensureTargetUsable, fetchTemplates, findTemplate, githubTarballUrl, parseManifest, parseTar, scaffoldTemplate, selectTemplateFiles, templateIds };
@@ -1,6 +1,7 @@
1
1
  import { log } from "../log.js";
2
2
  import { writeJsonFile } from "../utils/json_file.js";
3
3
  import { showNotice } from "../notices.js";
4
+ import { githubRequestHeaders } from "../utils/github_headers.js";
4
5
  import { AGENT_SKILLS_SOURCE, PLATFORMS_SKILLS_SOURCE } from "./catalog.js";
5
6
  import { closeSync, constants, existsSync, fstatSync, openSync, readFileSync, statSync } from "node:fs";
6
7
  import { join } from "node:path";
@@ -180,17 +181,13 @@ const autocrlfCheckout = (bytes) => {
180
181
  };
181
182
  const gitBlobSha = (bytes) => createHash("sha1").update(`blob ${bytes.byteLength}\0`).update(bytes).digest("hex");
182
183
  const isTreeEntry = (value) => isRecord(value) && typeof value.path === "string" && typeof value.mode === "string" && typeof value.type === "string" && typeof value.sha === "string";
183
- const githubHeaders = (env) => {
184
- const token = env.GITHUB_TOKEN || env.GH_TOKEN;
185
- return {
186
- Accept: "application/vnd.github+json",
187
- "User-Agent": "neon-cli",
188
- ...token ? { Authorization: `Bearer ${token}` } : {}
189
- };
190
- };
191
184
  const fetchTree = async (source, env) => {
192
- const response = await fetch(`https://api.github.com/repos/${source}/git/trees/HEAD?recursive=1`, {
193
- headers: githubHeaders(env),
185
+ const url = `https://api.github.com/repos/${source}/git/trees/HEAD?recursive=1`;
186
+ const response = await fetch(url, {
187
+ headers: {
188
+ Accept: "application/vnd.github+json",
189
+ ...githubRequestHeaders(url, env)
190
+ },
194
191
  signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
195
192
  });
196
193
  if (!response.ok) {
@@ -0,0 +1,16 @@
1
+ // src/utils/github_headers.ts
2
+ const GITHUB_HOSTS = /* @__PURE__ */ new Set([
3
+ "api.github.com",
4
+ "codeload.github.com",
5
+ "github.com",
6
+ "raw.githubusercontent.com"
7
+ ]);
8
+ const githubRequestHeaders = (url, env = process.env) => {
9
+ const token = env.GITHUB_TOKEN || env.GH_TOKEN;
10
+ const { protocol, hostname } = new URL(url);
11
+ return {
12
+ "User-Agent": "neon",
13
+ ...token && protocol === "https:" && GITHUB_HOSTS.has(hostname) ? { Authorization: `Bearer ${token}` } : {}
14
+ };
15
+ };
16
+ export { githubRequestHeaders };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neon",
3
- "version": "9.3.2",
3
+ "version": "9.5.0",
4
4
  "description": "CLI tool for Neon, the cloud backend primitives built around Lakebase Postgres",
5
5
  "keywords": [
6
6
  "neon",
@@ -114,9 +114,9 @@
114
114
  "vitest": "^3.0.9",
115
115
  "@neon-internals/cli-core": "0.0.0",
116
116
  "@neon-internals/env-core": "0.0.51",
117
+ "@neon/e2e-harness": "0.0.0",
117
118
  "@neon/env": "2.1.3",
118
- "@neon/functions": "0.11.0",
119
- "@neon/e2e-harness": "0.0.0"
119
+ "@neon/functions": "0.11.0"
120
120
  },
121
121
  "publishConfig": {
122
122
  "access": "public",