@neon/config-runtime 1.8.1 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/lib/operations.d.ts +2 -2
  2. package/dist/lib/operations.d.ts.map +1 -1
  3. package/dist/lib/operations.js +2 -1
  4. package/dist/lib/operations.js.map +1 -1
  5. package/dist/lib/pull-config.d.ts +7 -2
  6. package/dist/lib/pull-config.d.ts.map +1 -1
  7. package/dist/lib/pull-config.js +16 -8
  8. package/dist/lib/pull-config.js.map +1 -1
  9. package/dist/lib/push-config.d.ts.map +1 -1
  10. package/dist/lib/push-config.js +45 -1
  11. package/dist/lib/push-config.js.map +1 -1
  12. package/dist/node_modules/.pnpm/@vitest_pretty-format@3.0.9/node_modules/@vitest/pretty-format/dist/index.js.map +1 -1
  13. package/dist/node_modules/.pnpm/@vitest_runner@3.0.9/node_modules/@vitest/runner/dist/chunk-tasks.js.map +1 -1
  14. package/dist/node_modules/.pnpm/@vitest_runner@3.0.9/node_modules/@vitest/runner/dist/index.js.map +1 -1
  15. package/dist/node_modules/.pnpm/@vitest_utils@3.0.9/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.js.map +1 -1
  16. package/dist/node_modules/.pnpm/@vitest_utils@3.0.9/node_modules/@vitest/utils/dist/helpers.js.map +1 -1
  17. package/dist/node_modules/.pnpm/@vitest_utils@3.0.9/node_modules/@vitest/utils/dist/index.js.map +1 -1
  18. package/dist/node_modules/.pnpm/@vitest_utils@3.0.9/node_modules/@vitest/utils/dist/source-map.js.map +1 -1
  19. package/dist/node_modules/.pnpm/chai@5.2.0/node_modules/chai/chai.js.map +1 -1
  20. package/dist/node_modules/.pnpm/expect-type@1.2.1/node_modules/expect-type/dist/branding.js.map +1 -1
  21. package/dist/node_modules/.pnpm/expect-type@1.2.1/node_modules/expect-type/dist/index.js.map +1 -1
  22. package/dist/node_modules/.pnpm/expect-type@1.2.1/node_modules/expect-type/dist/messages.js.map +1 -1
  23. package/dist/node_modules/.pnpm/expect-type@1.2.1/node_modules/expect-type/dist/overloads.js.map +1 -1
  24. package/dist/node_modules/.pnpm/expect-type@1.2.1/node_modules/expect-type/dist/utils.js.map +1 -1
  25. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/arguments.js.map +1 -1
  26. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/array.js.map +1 -1
  27. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/bigint.js.map +1 -1
  28. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/class.js.map +1 -1
  29. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/date.js.map +1 -1
  30. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/error.js.map +1 -1
  31. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/function.js.map +1 -1
  32. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/helpers.js.map +1 -1
  33. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/html.js.map +1 -1
  34. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/index.js.map +1 -1
  35. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/map.js.map +1 -1
  36. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/number.js.map +1 -1
  37. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/object.js.map +1 -1
  38. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/promise.js.map +1 -1
  39. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/regexp.js.map +1 -1
  40. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/set.js.map +1 -1
  41. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/string.js.map +1 -1
  42. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/symbol.js.map +1 -1
  43. package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/typedarray.js.map +1 -1
  44. package/dist/node_modules/.pnpm/tinyrainbow@2.0.0/node_modules/tinyrainbow/dist/chunk-BVHSVHOK.js.map +1 -1
  45. package/dist/node_modules/.pnpm/tinyrainbow@2.0.0/node_modules/tinyrainbow/dist/node.js.map +1 -1
  46. package/dist/node_modules/.pnpm/vitest@3.0.9_@types_debug@4.1.13_@types_node@20.19.17_jiti@2.7.0_jsdom@29.1.1_@noble_ha_0258998ed4eee0dc3e7b1b8446e9e9d6/node_modules/vitest/dist/index.js.map +1 -1
  47. package/package.json +4 -4
@@ -1,5 +1,5 @@
1
1
  import { FunctionBundler } from "./function-bundle.js";
2
- import { PulledBranchConfig } from "./pull-config.js";
2
+ import { PullConfigOptions, PulledBranchConfig } from "./pull-config.js";
3
3
  import { PushConfigOptions } from "./push-config.js";
4
4
  import { Config, NeonApi, PushResult } from "@neon/config";
5
5
 
@@ -52,7 +52,7 @@ interface ApplyOptions extends ConfigOperationOptions {
52
52
  *
53
53
  * `projectId` and `branchId` are **required** (both in `options`).
54
54
  */
55
- declare function inspect(options: ConfigOperationOptions): Promise<PulledBranchConfig>;
55
+ declare function inspect(options: ConfigOperationOptions & Pick<PullConfigOptions, "realtime">): Promise<PulledBranchConfig>;
56
56
  /**
57
57
  * Compute what {@link apply} would do for the given branch without mutating anything
58
58
  * (dry-run plan). Returns the full {@link PushResult} with the planned changes in
@@ -1 +1 @@
1
- {"version":3,"file":"operations.d.ts","names":["Config","NeonApi","PushResult","FunctionBundler","PulledBranchConfig","PushConfigOptions","ConfigOperationOptions","ApplyOptions","inspect","Promise","plan","apply","CreateBranchOptions","CreateBranchResult","createBranch","FunctionBundler","PulledBranchConfig","PushConfigOptions","Config","NeonApi","PushResult","ConfigOperationOptions","projectId","branchId","apiKey","apiHost","api","ApplyOptions","updateExisting","allowProtectedBranch","confirm","beforeMutations","bundleFunction","inspect","options","Promise","plan","config","apply","CreateBranchOptions","branchName","CreateBranchResult","result","createBranch"],"sources":["../../src/lib/operations.ts"],"mappings":";;;;;;;;;AAsBA;AAsBA;AAA8B;AASnBK,UA/BMC,sBAAAA,CA+BND;EAEQA;AAEDF;AAboBG;AAAsB;EAsBtCE,SAAAA,EAAO,MAAA;EAAA;AACnBF;AACCF;AAARK;EAAOc,QAAA,EAAA,MAAA;EAkBYb;EAAIc,MAAA,CAAA,EAAA,MAAA;EACjBxB;EACCM,OAAAA,CAAAA,EAAAA,MAAAA;EACCJ;EAARO,GAAAA,CAAAA,EAnDIJ,iBAmDJI,CAAAA,KAAAA,CAAAA;AAAO;AAwBV;AAA2B;AAClBT;AACCO,UAvEOA,YAAAA,SAAqBD,sBAuE5BC,CAAAA;EACCL;AAARO;AAAO;AAuBV;EAAoCmB,cAAA,CAAA,EAAA,OAAA;EAQ7B3B;EAEWE,oBAAAA,CAAAA,EAAAA,OAAAA;EAAe;EAOhBU,OAAAA,CAAAA,EAvGNR,iBAuGwB,CAAA,SAI1BH,CAAAA;EA+BaY;EAAYiB,eAAA,CAAA,EAxIf1B,iBAwIe,CAAA,iBAAA,CAAA;EACzBL;EACCY,cAAAA,CAAAA,EAxIQT,eAwIRS;AACCC;AAARJ;AAAO;;;;;iBAhIYD,OAAAA,UACZF,yBACPG,QAAQL;;;;;;;;;iBAkBWM,IAAAA,SACbV,iBACCM,yBACPG,QAAQP;;;;;;;;;;;;iBAwBWS,KAAAA,SACbX,iBACCO,eACPE,QAAQP;;;;;UAuBMU,mBAAAA;;;;;;;;QAQVX;;mBAEWE;;;;;;UAODU,kBAAAA;;;;UAIRX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+BaY,YAAAA,SACbd,iBACCY,sBACPH,QAAQI"}
1
+ {"version":3,"file":"operations.d.ts","names":["Config","NeonApi","PushResult","FunctionBundler","PullConfigOptions","PulledBranchConfig","PushConfigOptions","ConfigOperationOptions","ApplyOptions","inspect","Pick","Promise","plan","apply","CreateBranchOptions","CreateBranchResult","createBranch","FunctionBundler","PullConfigOptions","PulledBranchConfig","PushConfigOptions","Config","NeonApi","PushResult","ConfigOperationOptions","projectId","branchId","apiKey","apiHost","api","ApplyOptions","updateExisting","allowProtectedBranch","confirm","beforeMutations","bundleFunction","inspect","options","Pick","Promise","plan","config","apply","CreateBranchOptions","branchName","CreateBranchResult","result","createBranch"],"sources":["../../src/lib/operations.ts"],"mappings":";;;;;;;;;AA0BA;AAsBA;AAA8B;AASnBM,UA/BMC,sBAAAA,CA+BND;EAEQA;AAEDH;AAboBI;AAAsB;EAsBtCE,SAAAA,EAAO,MAAA;EAAA;AACnBF;AAA8BH;AAALM;EACxBL,QAAAA,EAAAA,MAAAA;EAARM;EAAOgB,MAAA,CAAA,EAAA,MAAA;EAmBYf;EAAIgB,OAAA,CAAA,EAAA,MAAA;EACjB5B;EACCO,GAAAA,CAAAA,EAnDHD,iBAmDGC,CAAAA,KAAAA,CAAAA;AACCL;AAARS;AAAO;AAwBV;AAA2B,UAtEVH,YAAAA,SAAqBD,sBAsEX,CAAA;EAClBP;AACCQ;AACCN;AAARS;EAAOoB,cAAA,CAAA,EAAA,OAAA;EAuBOjB;EAAmBkB,oBAAA,CAAA,EAAA,OAAA;EAQ7B/B;EAEWE,OAAAA,CAAAA,EAjGPG,iBAiGOH,CAAAA,SAAAA,CAAAA;EAAe;EAOhBY,eAAAA,CAAAA,EAtGET,iBA0GVJ,CAAAA,iBAAU,CAAA;EA+BGc;EAAYmB,cAAA,CAAA,EAvIhBhC,eAuIgB;AACzBH;AACCc;AACCC;AAARJ;AAAO;;;iBAjIYF,OAAAA,UACZF,yBAAyBG,KAAKN,iCACrCO,QAAQN;;;;;;;;;iBAmBWO,IAAAA,SACbZ,iBACCO,yBACPI,QAAQT;;;;;;;;;;;;iBAwBWW,KAAAA,SACbb,iBACCQ,eACPG,QAAQT;;;;;UAuBMY,mBAAAA;;;;;;;;QAQVb;;mBAEWE;;;;;;UAODY,kBAAAA;;;;UAIRb;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+Bac,YAAAA,SACbhB,iBACCc,sBACPH,QAAQI"}
@@ -14,7 +14,8 @@ async function inspect(options) {
14
14
  branchId: options.branchId,
15
15
  ...options.api ? { api: options.api } : {},
16
16
  ...options.apiKey ? { apiKey: options.apiKey } : {},
17
- ...options.apiHost ? { apiHost: options.apiHost } : {}
17
+ ...options.apiHost ? { apiHost: options.apiHost } : {},
18
+ ...options.realtime === false ? { realtime: false } : {}
18
19
  });
19
20
  }
20
21
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"operations.js","names":[],"sources":["../../src/lib/operations.ts"],"sourcesContent":["import {\n\ttype AppliedChange,\n\ttype ComputeSettings,\n\ttype Config,\n\tcreateNeonApiFromOptions,\n\tErrorCode,\n\ttype NeonApi,\n\ttype NeonBranchSnapshot,\n\tPartialBranchCreateError,\n\tPlatformError,\n\ttype PushResult,\n\tresolveConfig,\n} from \"@neon/config\";\nimport type { FunctionBundler } from \"./function-bundle.js\";\nimport { type PulledBranchConfig, pullConfig } from \"./pull-config.js\";\nimport { type PushConfigOptions, pushConfig } from \"./push-config.js\";\n\n/**\n * Where to run the operation and how to authenticate. Filesystem- and env-agnostic: the\n * `projectId` and `branchId` are always passed explicitly by the caller (e.g. neonctl\n * resolves them from `.neon` / `NEON_*` and forwards them here).\n */\nexport interface ConfigOperationOptions {\n\t/**\n\t * Neon project id. **Required** — the management API addresses branches through their\n\t * project, so operations cannot run without it.\n\t */\n\tprojectId: string;\n\t/**\n\t * Neon branch id (`br-…`). **Required.** Must already exist on the project; resolve\n\t * branch names to ids before calling.\n\t */\n\tbranchId: string;\n\t/** Neon API key. Falls back to `NEON_API_KEY` / neonctl credentials. */\n\tapiKey?: string;\n\t/** Neon API base URL. Falls back to `NEON_API_HOST`, then production. */\n\tapiHost?: string;\n\t/** Inject a custom NeonApi adapter (primarily for tests). */\n\tapi?: PushConfigOptions[\"api\"];\n}\n\n/**\n * Options accepted by {@link apply} on top of {@link ConfigOperationOptions}.\n */\nexport interface ApplyOptions extends ConfigOperationOptions {\n\t/**\n\t * Auto-confirm overriding existing remote settings (TTL, `protected`, compute\n\t * settings) on the selected branch. Without it, drift is reported as a conflict.\n\t */\n\tupdateExisting?: boolean;\n\t/** Auto-confirm applying to a branch marked `protected` on Neon. */\n\tallowProtectedBranch?: boolean;\n\t/** Asked before a protected-branch push or an override. See {@link PushConfigOptions.confirm}. */\n\tconfirm?: PushConfigOptions[\"confirm\"];\n\t/** Runs after confirmation, before any change. See {@link PushConfigOptions.beforeMutations}. */\n\tbeforeMutations?: PushConfigOptions[\"beforeMutations\"];\n\t/** Inject to deploy without this package loading esbuild. */\n\tbundleFunction?: FunctionBundler;\n}\n\n/**\n * Read a branch's live Neon state as a plain object (project + branch metadata and the\n * reverse-engineered `BranchConfig`). Network read only — never mutates.\n *\n * `projectId` and `branchId` are **required** (both in `options`).\n */\nexport async function inspect(\n\toptions: ConfigOperationOptions,\n): Promise<PulledBranchConfig> {\n\treturn pullConfig({\n\t\tprojectId: options.projectId,\n\t\tbranchId: options.branchId,\n\t\t...(options.api ? { api: options.api } : {}),\n\t\t...(options.apiKey ? { apiKey: options.apiKey } : {}),\n\t\t...(options.apiHost ? { apiHost: options.apiHost } : {}),\n\t});\n}\n\n/**\n * Compute what {@link apply} would do for the given branch without mutating anything\n * (dry-run plan). Returns the full {@link PushResult} with the planned changes in\n * `applied` and any blocking drift in `conflicts` — the Neon equivalent of\n * `terraform plan`.\n *\n * `projectId` and `branchId` are **required** (both in `options`).\n */\nexport async function plan(\n\tconfig: Config,\n\toptions: ConfigOperationOptions,\n): Promise<PushResult> {\n\treturn pushConfig(config, {\n\t\tprojectId: options.projectId,\n\t\tbranchId: options.branchId,\n\t\tdryRun: true,\n\t\t// Surface the full would-apply list as plan steps without mutating anything.\n\t\tupdateExisting: true,\n\t\t...(options.api ? { api: options.api } : {}),\n\t\t...(options.apiKey ? { apiKey: options.apiKey } : {}),\n\t\t...(options.apiHost ? { apiHost: options.apiHost } : {}),\n\t});\n}\n\n/**\n * Apply a `neon.ts` policy to the given Neon branch and return the {@link PushResult}\n * describing what changed — the Neon equivalent of `terraform apply`.\n *\n * `projectId` and `branchId` are **required** (both in `options`). Pass `updateExisting`\n * to auto-confirm overriding existing remote settings and `allowProtectedBranch` to\n * auto-confirm applying to a protected branch; otherwise drift is reported as a\n * `PushConflictError`.\n *\n * Never creates projects or branches — both must already exist.\n */\nexport async function apply(\n\tconfig: Config,\n\toptions: ApplyOptions,\n): Promise<PushResult> {\n\treturn pushConfig(config, {\n\t\tprojectId: options.projectId,\n\t\tbranchId: options.branchId,\n\t\t...(options.api ? { api: options.api } : {}),\n\t\t...(options.apiKey ? { apiKey: options.apiKey } : {}),\n\t\t...(options.apiHost ? { apiHost: options.apiHost } : {}),\n\t\t...(options.updateExisting ? { updateExisting: true } : {}),\n\t\t...(options.allowProtectedBranch ? { allowProtectedBranch: true } : {}),\n\t\t...(options.confirm ? { confirm: options.confirm } : {}),\n\t\t...(options.beforeMutations\n\t\t\t? { beforeMutations: options.beforeMutations }\n\t\t\t: {}),\n\t\t...(options.bundleFunction\n\t\t\t? { bundleFunction: options.bundleFunction }\n\t\t\t: {}),\n\t});\n}\n\n/**\n * Options accepted by {@link createBranch}. Unlike {@link ConfigOperationOptions} this takes a\n * branch **name** (the branch does not exist yet) rather than an id.\n */\nexport interface CreateBranchOptions {\n\t/** Neon project id to create the branch in. **Required.** */\n\tprojectId: string;\n\t/** Name of the branch to create. **Required.** Must not already exist on the project. */\n\tbranchName: string;\n\t/** Neon API key. Falls back to `NEON_API_KEY` / neonctl credentials. Ignored when `api` is set. */\n\tapiKey?: string;\n\t/** Inject a custom NeonApi adapter (primarily for tests). */\n\tapi?: NeonApi;\n\t/** Inject to deploy without this package loading esbuild. */\n\tbundleFunction?: FunctionBundler;\n}\n\n/**\n * Result of {@link createBranch}: the created branch's id/name plus the {@link PushResult}\n * describing the policy that was applied to it.\n */\nexport interface CreateBranchResult {\n\tbranchId: string;\n\tbranchName: string;\n\t/** What applying the policy to the freshly created branch changed. */\n\tresult: PushResult;\n}\n\n/**\n * Create a Neon branch **from a `neon.ts` policy** and bring it up with its declared\n * settings/infra in one step — the operation `neonctl checkout <new-name>` needs.\n *\n * The flow is the one a creation actually wants:\n * 1. Evaluate the policy for the new branch with `exists: false` (so creation-time tuning —\n * `parent`, `ttl`, compute settings, `protected` — resolves instead of the\n * \"existing branch, leave as-is\" path most policies guard with `if (branch.exists)`).\n * 2. Create the branch **with** that tuning: `parent`, `expires_at`, `protected`, and the\n * compute settings all ride along on the single create call, which Neon validates as a\n * whole. A setting it rejects therefore fails the creation outright, leaving nothing\n * behind, rather than producing a branch that doesn't match the policy.\n * 3. {@link pushConfig} the rest onto it with `branchExists: false` — the services (Neon\n * Auth, Data API, buckets, functions), which have no create-time equivalent because they\n * are provisioned against an existing branch id.\n *\n * This is why `apply` alone couldn't do it: `apply` operates on an *existing* branch\n * (`exists: true`), so a policy keyed on `!branch.exists` never returns the creation tuning.\n *\n * `result.applied` covers both steps — the settings the create call carried are reported\n * exactly like the ones a push applies (see {@link settingsAppliedAtCreate}), so folding them\n * into the creation doesn't make them vanish from the summary.\n *\n * Throws {@link PlatformError} (`Conflict`) if a branch with `branchName` already exists, or\n * (`BranchNotFound`) if the policy names a `parent` that isn't on the project — both before\n * anything is created, as is a setting Neon rejects in step 2. Only step 3 can fail with a\n * branch already created; that throws {@link PartialBranchCreateError} carrying its id/name.\n */\nexport async function createBranch(\n\tconfig: Config,\n\toptions: CreateBranchOptions,\n): Promise<CreateBranchResult> {\n\tconst api =\n\t\toptions.api ??\n\t\tcreateNeonApiFromOptions(\n\t\t\t\"createBranch\",\n\t\t\toptions.apiKey ? { apiKey: options.apiKey } : {},\n\t\t);\n\tconst { projectId, branchName } = options;\n\n\tconst branches = await api.listBranches(projectId);\n\tif (branches.some((b) => b.name === branchName)) {\n\t\tthrow new PlatformError(\n\t\t\tErrorCode.Conflict,\n\t\t\t`createBranch: a branch named \"${branchName}\" already exists on project ${projectId}. Pick a different name or check it out instead of creating it.`,\n\t\t\t{ details: { projectId, branchName } },\n\t\t);\n\t}\n\n\t// Evaluate the policy as a creation so `parent` (only settable at create time) resolves.\n\tconst resolved = resolveConfig(config, {\n\t\tname: branchName,\n\t\texists: false,\n\t});\n\tconst parentId = resolveParentBranchId(\n\t\tresolved.parent,\n\t\tbranches,\n\t\tbranchName,\n\t);\n\n\t// Everything the policy can express *in the create call itself* goes into it. Neon\n\t// validates the whole request, so a value it rejects (a plan-gated suspend timeout, an\n\t// out-of-range autoscaling limit) fails with **no branch created** instead of leaving one\n\t// behind that silently diverges from the policy. Only the services below genuinely need an\n\t// existing branch id, which is what keeps them a second step.\n\tconst expiresAt =\n\t\tresolved.ttlSeconds !== undefined\n\t\t\t? new Date(Date.now() + resolved.ttlSeconds * 1000).toISOString()\n\t\t\t: undefined;\n\tconst computeSettings = resolved.postgres?.computeSettings;\n\n\tconst { branch } = await api.createBranch(projectId, {\n\t\tname: branchName,\n\t\t...(parentId ? { parentId } : {}),\n\t\t...(expiresAt ? { expiresAt } : {}),\n\t\t...(resolved.protected !== undefined\n\t\t\t? { protected: resolved.protected }\n\t\t\t: {}),\n\t\t...(computeSettings ? { computeSettings } : {}),\n\t});\n\n\tconst appliedAtCreate = settingsAppliedAtCreate({\n\t\tbranchName: branch.name,\n\t\t...(resolved.parent !== undefined\n\t\t\t? { parentName: resolved.parent }\n\t\t\t: {}),\n\t\t...(expiresAt !== undefined ? { expiresAt } : {}),\n\t\t...(resolved.protected !== undefined\n\t\t\t? { isProtected: resolved.protected }\n\t\t\t: {}),\n\t\t...(computeSettings ? { computeSettings } : {}),\n\t});\n\n\t// Reconcile what the create call could not express as a new branch (`branchExists: false`):\n\t// the services/functions the policy declares. The settings above are already in place, so\n\t// push sees them satisfied and applies nothing for them.\n\t// `updateExisting`/`allowProtectedBranch` are safe here — there is no pre-existing state a\n\t// user would be surprised to see overridden.\n\t//\n\t// The branch is already created at this point, so a failure here (a service that can't be\n\t// provisioned, a function that fails to deploy, a transient API error) cannot be undone by\n\t// throwing: the branch would linger without its declared services, invisible to the caller.\n\t// Re-throw as PartialBranchCreateError so the id/name survive and the caller can keep the\n\t// branch usable while reporting that it diverges from the policy.\n\tlet result: PushResult;\n\ttry {\n\t\tresult = await pushConfig(config, {\n\t\t\tprojectId,\n\t\t\tbranchId: branch.id,\n\t\t\tapi,\n\t\t\tbranchExists: false,\n\t\t\tupdateExisting: true,\n\t\t\tallowProtectedBranch: true,\n\t\t\t...(options.bundleFunction\n\t\t\t\t? { bundleFunction: options.bundleFunction }\n\t\t\t\t: {}),\n\t\t});\n\t} catch (cause) {\n\t\tthrow new PartialBranchCreateError(branch.id, branch.name, cause);\n\t}\n\n\treturn {\n\t\tbranchId: branch.id,\n\t\tbranchName: branch.name,\n\t\tresult: {\n\t\t\t...result,\n\t\t\tapplied: mergeCreateSettings(appliedAtCreate, result.applied),\n\t\t},\n\t};\n}\n\n/**\n * Describe the policy settings the create call itself carried as {@link AppliedChange}s, keyed\n * by field.\n *\n * Applying a setting *at creation* rather than in a follow-up call must not make it disappear\n * from the report, so these are shaped exactly like the changes `pushConfig` returns for the\n * same fields — same `kind`/`identifier`/`details`, so every renderer already knows how to\n * print them and no caller needs to special-case a creation.\n */\nconst settingsAppliedAtCreate = (args: {\n\tbranchName: string;\n\t/** The parent the *policy* named, omitted when the branch fell back to the project default. */\n\tparentName?: string;\n\texpiresAt?: string;\n\tisProtected?: boolean;\n\tcomputeSettings?: ComputeSettings;\n}): Map<string, AppliedChange> => {\n\tconst changes = new Map<string, AppliedChange>();\n\tconst add = (field: string, details: Record<string, unknown>): void => {\n\t\tchanges.set(field, {\n\t\t\tkind: \"branch\",\n\t\t\taction: \"create\",\n\t\t\tidentifier: args.branchName,\n\t\t\tdetails: { field, ...details },\n\t\t});\n\t};\n\tif (args.parentName !== undefined) {\n\t\tadd(\"parent\", { parent: args.parentName });\n\t}\n\tif (args.expiresAt !== undefined) add(\"ttl\", { expiresAt: args.expiresAt });\n\tif (args.isProtected !== undefined) {\n\t\tadd(\"protected\", { protected: args.isProtected });\n\t}\n\tif (args.computeSettings) {\n\t\tadd(\"computeSettings\", { settings: args.computeSettings });\n\t}\n\treturn changes;\n};\n\n/**\n * Fold the create-time settings into what the push applied, reporting each field once.\n *\n * A field the create call already satisfied is a noop for the push, so the two normally don't\n * overlap. They do when the create didn't take (an API that ignores a create-time field, or\n * drift in the moments between the two calls) and the push applied it for real — the push\n * change is the one that describes what actually happened, so it wins.\n */\nconst mergeCreateSettings = (\n\tatCreate: Map<string, AppliedChange>,\n\tpushed: AppliedChange[],\n): AppliedChange[] => {\n\tconst pushedFields = new Set(\n\t\tpushed\n\t\t\t.filter((c) => c.kind === \"branch\" && c.action !== \"noop\")\n\t\t\t.map((c) => c.details?.field)\n\t\t\t.filter((field): field is string => typeof field === \"string\"),\n\t);\n\tconst fromCreate = [...atCreate]\n\t\t.filter(([field]) => !pushedFields.has(field))\n\t\t.map(([, change]) => change);\n\treturn [...fromCreate, ...pushed];\n};\n\n/**\n * Resolve the parent branch id for a new branch. A policy-declared `parent` (a branch name) is\n * looked up by name; an unknown name is a hard error. With no `parent`, fall back to the\n * project's default branch, or `undefined` (let the API pick the project default) when none is\n * marked default.\n */\nfunction resolveParentBranchId(\n\tparentName: string | undefined,\n\tbranches: NeonBranchSnapshot[],\n\tbranchName: string,\n): string | undefined {\n\tif (parentName !== undefined) {\n\t\tconst match = branches.find((b) => b.name === parentName);\n\t\tif (!match) {\n\t\t\tthrow new PlatformError(\n\t\t\t\tErrorCode.BranchNotFound,\n\t\t\t\t`createBranch: the policy for \"${branchName}\" sets parent \"${parentName}\", but no branch with that name exists. Existing branches: ${\n\t\t\t\t\tbranches.map((b) => b.name).join(\", \") || \"(none)\"\n\t\t\t\t}.`,\n\t\t\t\t{\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tbranchName,\n\t\t\t\t\t\tparent: parentName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,OACE,QAAQ,MAAM,EAAE,SAAS,YAAY,EAAE,WAAW,MAAM,CAAC,CACzD,KAAK,MAAM,EAAE,SAAS,KAAK,CAAC,CAC5B,QAAQ,UAA2B,OAAO,UAAU,QAAQ,CAC/D;CAIA,OAAO,CAAC,GAHW,CAAC,GAAG,QAAQ,CAAC,CAC9B,QAAQ,CAAC,WAAW,CAAC,aAAa,IAAI,KAAK,CAAC,CAAC,CAC7C,KAAK,GAAG,YAAY,MACF,GAAG,GAAG,MAAM;AACjC;;;;;;;AAQA,SAAS,sBACR,YACA,UACA,YACqB;CACrB,IAAI,eAAe,KAAA,GAAW;EAC7B,MAAM,QAAQ,SAAS,MAAM,MAAM,EAAE,SAAS,UAAU;EACxD,IAAI,CAAC,OACJ,MAAM,IAAI,cACT,UAAU,gBACV,iCAAiC,WAAW,iBAAiB,WAAW,6DACvE,SAAS,KAAK,MAAM,EAAE,IAAI,CAAC,CAAC,KAAK,IAAI,KAAK,SAC1C,IACD,EACC,SAAS;GACR;GACA,QAAQ;GACR,WAAW,SAAS,KAAK,MAAM,EAAE,IAAI;EACtC,EACD,CACD;EAED,OAAO,MAAM;CACd;CACA,OAAO,SAAS,MAAM,MAAM,EAAE,SAAS,CAAC,EAAE;AAC3C"}
1
+ {"version":3,"file":"operations.js","names":[],"sources":["../../src/lib/operations.ts"],"sourcesContent":["import {\n\ttype AppliedChange,\n\ttype ComputeSettings,\n\ttype Config,\n\tcreateNeonApiFromOptions,\n\tErrorCode,\n\ttype NeonApi,\n\ttype NeonBranchSnapshot,\n\tPartialBranchCreateError,\n\tPlatformError,\n\ttype PushResult,\n\tresolveConfig,\n} from \"@neon/config\";\nimport type { FunctionBundler } from \"./function-bundle.js\";\nimport {\n\ttype PullConfigOptions,\n\ttype PulledBranchConfig,\n\tpullConfig,\n} from \"./pull-config.js\";\nimport { type PushConfigOptions, pushConfig } from \"./push-config.js\";\n\n/**\n * Where to run the operation and how to authenticate. Filesystem- and env-agnostic: the\n * `projectId` and `branchId` are always passed explicitly by the caller (e.g. neonctl\n * resolves them from `.neon` / `NEON_*` and forwards them here).\n */\nexport interface ConfigOperationOptions {\n\t/**\n\t * Neon project id. **Required** — the management API addresses branches through their\n\t * project, so operations cannot run without it.\n\t */\n\tprojectId: string;\n\t/**\n\t * Neon branch id (`br-…`). **Required.** Must already exist on the project; resolve\n\t * branch names to ids before calling.\n\t */\n\tbranchId: string;\n\t/** Neon API key. Falls back to `NEON_API_KEY` / neonctl credentials. */\n\tapiKey?: string;\n\t/** Neon API base URL. Falls back to `NEON_API_HOST`, then production. */\n\tapiHost?: string;\n\t/** Inject a custom NeonApi adapter (primarily for tests). */\n\tapi?: PushConfigOptions[\"api\"];\n}\n\n/**\n * Options accepted by {@link apply} on top of {@link ConfigOperationOptions}.\n */\nexport interface ApplyOptions extends ConfigOperationOptions {\n\t/**\n\t * Auto-confirm overriding existing remote settings (TTL, `protected`, compute\n\t * settings) on the selected branch. Without it, drift is reported as a conflict.\n\t */\n\tupdateExisting?: boolean;\n\t/** Auto-confirm applying to a branch marked `protected` on Neon. */\n\tallowProtectedBranch?: boolean;\n\t/** Asked before a protected-branch push or an override. See {@link PushConfigOptions.confirm}. */\n\tconfirm?: PushConfigOptions[\"confirm\"];\n\t/** Runs after confirmation, before any change. See {@link PushConfigOptions.beforeMutations}. */\n\tbeforeMutations?: PushConfigOptions[\"beforeMutations\"];\n\t/** Inject to deploy without this package loading esbuild. */\n\tbundleFunction?: FunctionBundler;\n}\n\n/**\n * Read a branch's live Neon state as a plain object (project + branch metadata and the\n * reverse-engineered `BranchConfig`). Network read only — never mutates.\n *\n * `projectId` and `branchId` are **required** (both in `options`).\n */\nexport async function inspect(\n\toptions: ConfigOperationOptions & Pick<PullConfigOptions, \"realtime\">,\n): Promise<PulledBranchConfig> {\n\treturn pullConfig({\n\t\tprojectId: options.projectId,\n\t\tbranchId: options.branchId,\n\t\t...(options.api ? { api: options.api } : {}),\n\t\t...(options.apiKey ? { apiKey: options.apiKey } : {}),\n\t\t...(options.apiHost ? { apiHost: options.apiHost } : {}),\n\t\t...(options.realtime === false ? { realtime: false } : {}),\n\t});\n}\n\n/**\n * Compute what {@link apply} would do for the given branch without mutating anything\n * (dry-run plan). Returns the full {@link PushResult} with the planned changes in\n * `applied` and any blocking drift in `conflicts` — the Neon equivalent of\n * `terraform plan`.\n *\n * `projectId` and `branchId` are **required** (both in `options`).\n */\nexport async function plan(\n\tconfig: Config,\n\toptions: ConfigOperationOptions,\n): Promise<PushResult> {\n\treturn pushConfig(config, {\n\t\tprojectId: options.projectId,\n\t\tbranchId: options.branchId,\n\t\tdryRun: true,\n\t\t// Surface the full would-apply list as plan steps without mutating anything.\n\t\tupdateExisting: true,\n\t\t...(options.api ? { api: options.api } : {}),\n\t\t...(options.apiKey ? { apiKey: options.apiKey } : {}),\n\t\t...(options.apiHost ? { apiHost: options.apiHost } : {}),\n\t});\n}\n\n/**\n * Apply a `neon.ts` policy to the given Neon branch and return the {@link PushResult}\n * describing what changed — the Neon equivalent of `terraform apply`.\n *\n * `projectId` and `branchId` are **required** (both in `options`). Pass `updateExisting`\n * to auto-confirm overriding existing remote settings and `allowProtectedBranch` to\n * auto-confirm applying to a protected branch; otherwise drift is reported as a\n * `PushConflictError`.\n *\n * Never creates projects or branches — both must already exist.\n */\nexport async function apply(\n\tconfig: Config,\n\toptions: ApplyOptions,\n): Promise<PushResult> {\n\treturn pushConfig(config, {\n\t\tprojectId: options.projectId,\n\t\tbranchId: options.branchId,\n\t\t...(options.api ? { api: options.api } : {}),\n\t\t...(options.apiKey ? { apiKey: options.apiKey } : {}),\n\t\t...(options.apiHost ? { apiHost: options.apiHost } : {}),\n\t\t...(options.updateExisting ? { updateExisting: true } : {}),\n\t\t...(options.allowProtectedBranch ? { allowProtectedBranch: true } : {}),\n\t\t...(options.confirm ? { confirm: options.confirm } : {}),\n\t\t...(options.beforeMutations\n\t\t\t? { beforeMutations: options.beforeMutations }\n\t\t\t: {}),\n\t\t...(options.bundleFunction\n\t\t\t? { bundleFunction: options.bundleFunction }\n\t\t\t: {}),\n\t});\n}\n\n/**\n * Options accepted by {@link createBranch}. Unlike {@link ConfigOperationOptions} this takes a\n * branch **name** (the branch does not exist yet) rather than an id.\n */\nexport interface CreateBranchOptions {\n\t/** Neon project id to create the branch in. **Required.** */\n\tprojectId: string;\n\t/** Name of the branch to create. **Required.** Must not already exist on the project. */\n\tbranchName: string;\n\t/** Neon API key. Falls back to `NEON_API_KEY` / neonctl credentials. Ignored when `api` is set. */\n\tapiKey?: string;\n\t/** Inject a custom NeonApi adapter (primarily for tests). */\n\tapi?: NeonApi;\n\t/** Inject to deploy without this package loading esbuild. */\n\tbundleFunction?: FunctionBundler;\n}\n\n/**\n * Result of {@link createBranch}: the created branch's id/name plus the {@link PushResult}\n * describing the policy that was applied to it.\n */\nexport interface CreateBranchResult {\n\tbranchId: string;\n\tbranchName: string;\n\t/** What applying the policy to the freshly created branch changed. */\n\tresult: PushResult;\n}\n\n/**\n * Create a Neon branch **from a `neon.ts` policy** and bring it up with its declared\n * settings/infra in one step — the operation `neonctl checkout <new-name>` needs.\n *\n * The flow is the one a creation actually wants:\n * 1. Evaluate the policy for the new branch with `exists: false` (so creation-time tuning —\n * `parent`, `ttl`, compute settings, `protected` — resolves instead of the\n * \"existing branch, leave as-is\" path most policies guard with `if (branch.exists)`).\n * 2. Create the branch **with** that tuning: `parent`, `expires_at`, `protected`, and the\n * compute settings all ride along on the single create call, which Neon validates as a\n * whole. A setting it rejects therefore fails the creation outright, leaving nothing\n * behind, rather than producing a branch that doesn't match the policy.\n * 3. {@link pushConfig} the rest onto it with `branchExists: false` — the services (Neon\n * Auth, Data API, buckets, functions), which have no create-time equivalent because they\n * are provisioned against an existing branch id.\n *\n * This is why `apply` alone couldn't do it: `apply` operates on an *existing* branch\n * (`exists: true`), so a policy keyed on `!branch.exists` never returns the creation tuning.\n *\n * `result.applied` covers both steps — the settings the create call carried are reported\n * exactly like the ones a push applies (see {@link settingsAppliedAtCreate}), so folding them\n * into the creation doesn't make them vanish from the summary.\n *\n * Throws {@link PlatformError} (`Conflict`) if a branch with `branchName` already exists, or\n * (`BranchNotFound`) if the policy names a `parent` that isn't on the project — both before\n * anything is created, as is a setting Neon rejects in step 2. Only step 3 can fail with a\n * branch already created; that throws {@link PartialBranchCreateError} carrying its id/name.\n */\nexport async function createBranch(\n\tconfig: Config,\n\toptions: CreateBranchOptions,\n): Promise<CreateBranchResult> {\n\tconst api =\n\t\toptions.api ??\n\t\tcreateNeonApiFromOptions(\n\t\t\t\"createBranch\",\n\t\t\toptions.apiKey ? { apiKey: options.apiKey } : {},\n\t\t);\n\tconst { projectId, branchName } = options;\n\n\tconst branches = await api.listBranches(projectId);\n\tif (branches.some((b) => b.name === branchName)) {\n\t\tthrow new PlatformError(\n\t\t\tErrorCode.Conflict,\n\t\t\t`createBranch: a branch named \"${branchName}\" already exists on project ${projectId}. Pick a different name or check it out instead of creating it.`,\n\t\t\t{ details: { projectId, branchName } },\n\t\t);\n\t}\n\n\t// Evaluate the policy as a creation so `parent` (only settable at create time) resolves.\n\tconst resolved = resolveConfig(config, {\n\t\tname: branchName,\n\t\texists: false,\n\t});\n\tconst parentId = resolveParentBranchId(\n\t\tresolved.parent,\n\t\tbranches,\n\t\tbranchName,\n\t);\n\n\t// Everything the policy can express *in the create call itself* goes into it. Neon\n\t// validates the whole request, so a value it rejects (a plan-gated suspend timeout, an\n\t// out-of-range autoscaling limit) fails with **no branch created** instead of leaving one\n\t// behind that silently diverges from the policy. Only the services below genuinely need an\n\t// existing branch id, which is what keeps them a second step.\n\tconst expiresAt =\n\t\tresolved.ttlSeconds !== undefined\n\t\t\t? new Date(Date.now() + resolved.ttlSeconds * 1000).toISOString()\n\t\t\t: undefined;\n\tconst computeSettings = resolved.postgres?.computeSettings;\n\n\tconst { branch } = await api.createBranch(projectId, {\n\t\tname: branchName,\n\t\t...(parentId ? { parentId } : {}),\n\t\t...(expiresAt ? { expiresAt } : {}),\n\t\t...(resolved.protected !== undefined\n\t\t\t? { protected: resolved.protected }\n\t\t\t: {}),\n\t\t...(computeSettings ? { computeSettings } : {}),\n\t});\n\n\tconst appliedAtCreate = settingsAppliedAtCreate({\n\t\tbranchName: branch.name,\n\t\t...(resolved.parent !== undefined\n\t\t\t? { parentName: resolved.parent }\n\t\t\t: {}),\n\t\t...(expiresAt !== undefined ? { expiresAt } : {}),\n\t\t...(resolved.protected !== undefined\n\t\t\t? { isProtected: resolved.protected }\n\t\t\t: {}),\n\t\t...(computeSettings ? { computeSettings } : {}),\n\t});\n\n\t// Reconcile what the create call could not express as a new branch (`branchExists: false`):\n\t// the services/functions the policy declares. The settings above are already in place, so\n\t// push sees them satisfied and applies nothing for them.\n\t// `updateExisting`/`allowProtectedBranch` are safe here — there is no pre-existing state a\n\t// user would be surprised to see overridden.\n\t//\n\t// The branch is already created at this point, so a failure here (a service that can't be\n\t// provisioned, a function that fails to deploy, a transient API error) cannot be undone by\n\t// throwing: the branch would linger without its declared services, invisible to the caller.\n\t// Re-throw as PartialBranchCreateError so the id/name survive and the caller can keep the\n\t// branch usable while reporting that it diverges from the policy.\n\tlet result: PushResult;\n\ttry {\n\t\tresult = await pushConfig(config, {\n\t\t\tprojectId,\n\t\t\tbranchId: branch.id,\n\t\t\tapi,\n\t\t\tbranchExists: false,\n\t\t\tupdateExisting: true,\n\t\t\tallowProtectedBranch: true,\n\t\t\t...(options.bundleFunction\n\t\t\t\t? { bundleFunction: options.bundleFunction }\n\t\t\t\t: {}),\n\t\t});\n\t} catch (cause) {\n\t\tthrow new PartialBranchCreateError(branch.id, branch.name, cause);\n\t}\n\n\treturn {\n\t\tbranchId: branch.id,\n\t\tbranchName: branch.name,\n\t\tresult: {\n\t\t\t...result,\n\t\t\tapplied: mergeCreateSettings(appliedAtCreate, result.applied),\n\t\t},\n\t};\n}\n\n/**\n * Describe the policy settings the create call itself carried as {@link AppliedChange}s, keyed\n * by field.\n *\n * Applying a setting *at creation* rather than in a follow-up call must not make it disappear\n * from the report, so these are shaped exactly like the changes `pushConfig` returns for the\n * same fields — same `kind`/`identifier`/`details`, so every renderer already knows how to\n * print them and no caller needs to special-case a creation.\n */\nconst settingsAppliedAtCreate = (args: {\n\tbranchName: string;\n\t/** The parent the *policy* named, omitted when the branch fell back to the project default. */\n\tparentName?: string;\n\texpiresAt?: string;\n\tisProtected?: boolean;\n\tcomputeSettings?: ComputeSettings;\n}): Map<string, AppliedChange> => {\n\tconst changes = new Map<string, AppliedChange>();\n\tconst add = (field: string, details: Record<string, unknown>): void => {\n\t\tchanges.set(field, {\n\t\t\tkind: \"branch\",\n\t\t\taction: \"create\",\n\t\t\tidentifier: args.branchName,\n\t\t\tdetails: { field, ...details },\n\t\t});\n\t};\n\tif (args.parentName !== undefined) {\n\t\tadd(\"parent\", { parent: args.parentName });\n\t}\n\tif (args.expiresAt !== undefined) add(\"ttl\", { expiresAt: args.expiresAt });\n\tif (args.isProtected !== undefined) {\n\t\tadd(\"protected\", { protected: args.isProtected });\n\t}\n\tif (args.computeSettings) {\n\t\tadd(\"computeSettings\", { settings: args.computeSettings });\n\t}\n\treturn changes;\n};\n\n/**\n * Fold the create-time settings into what the push applied, reporting each field once.\n *\n * A field the create call already satisfied is a noop for the push, so the two normally don't\n * overlap. They do when the create didn't take (an API that ignores a create-time field, or\n * drift in the moments between the two calls) and the push applied it for real — the push\n * change is the one that describes what actually happened, so it wins.\n */\nconst mergeCreateSettings = (\n\tatCreate: Map<string, AppliedChange>,\n\tpushed: AppliedChange[],\n): AppliedChange[] => {\n\tconst pushedFields = new Set(\n\t\tpushed\n\t\t\t.filter((c) => c.kind === \"branch\" && c.action !== \"noop\")\n\t\t\t.map((c) => c.details?.field)\n\t\t\t.filter((field): field is string => typeof field === \"string\"),\n\t);\n\tconst fromCreate = [...atCreate]\n\t\t.filter(([field]) => !pushedFields.has(field))\n\t\t.map(([, change]) => change);\n\treturn [...fromCreate, ...pushed];\n};\n\n/**\n * Resolve the parent branch id for a new branch. A policy-declared `parent` (a branch name) is\n * looked up by name; an unknown name is a hard error. With no `parent`, fall back to the\n * project's default branch, or `undefined` (let the API pick the project default) when none is\n * marked default.\n */\nfunction resolveParentBranchId(\n\tparentName: string | undefined,\n\tbranches: NeonBranchSnapshot[],\n\tbranchName: string,\n): string | undefined {\n\tif (parentName !== undefined) {\n\t\tconst match = branches.find((b) => b.name === parentName);\n\t\tif (!match) {\n\t\t\tthrow new PlatformError(\n\t\t\t\tErrorCode.BranchNotFound,\n\t\t\t\t`createBranch: the policy for \"${branchName}\" sets parent \"${parentName}\", but no branch with that name exists. Existing branches: ${\n\t\t\t\t\tbranches.map((b) => b.name).join(\", \") || \"(none)\"\n\t\t\t\t}.`,\n\t\t\t\t{\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tbranchName,\n\t\t\t\t\t\tparent: parentName,\n\t\t\t\t\t\tavailable: branches.map((b) => b.name),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t\treturn match.id;\n\t}\n\treturn branches.find((b) => b.isDefault)?.id;\n}\n"],"mappings":";;;;;;;;;;AAsEA,eAAsB,QACrB,SAC8B;CAC9B,OAAO,WAAW;EACjB,WAAW,QAAQ;EACnB,UAAU,QAAQ;EAClB,GAAI,QAAQ,MAAM,EAAE,KAAK,QAAQ,IAAI,IAAI,CAAC;EAC1C,GAAI,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC;EACnD,GAAI,QAAQ,UAAU,EAAE,SAAS,QAAQ,QAAQ,IAAI,CAAC;EACtD,GAAI,QAAQ,aAAa,QAAQ,EAAE,UAAU,MAAM,IAAI,CAAC;CACzD,CAAC;AACF;;;;;;;;;AAUA,eAAsB,KACrB,QACA,SACsB;CACtB,OAAO,WAAW,QAAQ;EACzB,WAAW,QAAQ;EACnB,UAAU,QAAQ;EAClB,QAAQ;EAER,gBAAgB;EAChB,GAAI,QAAQ,MAAM,EAAE,KAAK,QAAQ,IAAI,IAAI,CAAC;EAC1C,GAAI,QAAQ,SAAS,EAAE,Q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ACD,CACD;EAED,OAAO,MAAM;CACd;CACA,OAAO,SAAS,MAAM,MAAM,EAAE,SAAS,CAAC,EAAE;AAC3C"}
@@ -1,4 +1,4 @@
1
- import { BucketAccessLevel, Config, NeonApi, NeonBranchSnapshot, NeonBucketSnapshot, NeonCredentialMeta, NeonEndpointSnapshot, NeonFunctionSnapshot, NeonProjectSnapshot } from "@neon/config";
1
+ import { BucketAccessLevel, Config, NeonApi, NeonBranchSnapshot, NeonBucketSnapshot, NeonCredentialMeta, NeonEndpointSnapshot, NeonFunctionSnapshot, NeonProjectSnapshot, NeonRealtimeSnapshot } from "@neon/config";
2
2
 
3
3
  //#region src/lib/pull-config.d.ts
4
4
  interface PullConfigOptions {
@@ -12,6 +12,8 @@ interface PullConfigOptions {
12
12
  apiHost?: string;
13
13
  /** Inject a custom NeonApi adapter (primarily for tests). */
14
14
  api?: NeonApi;
15
+ /** Read the branch's Realtime state. Defaults to `true`. */
16
+ realtime?: boolean;
15
17
  }
16
18
  /**
17
19
  * Live Preview-feature state read back from a branch. Surfaced alongside `config` rather
@@ -54,7 +56,8 @@ interface PulledBranchConfig {
54
56
  };
55
57
  /**
56
58
  * The branch's live state expressed as a {@link Config}: static `auth` / `dataApi`
57
- * toggles, any object-storage `preview.buckets`, plus a `branch` closure carrying the
59
+ * toggles, Realtime under `preview.realtime`, any object-storage `preview.buckets`, plus
60
+ * a `branch` closure carrying the
58
61
  * branch's lifecycle/compute tuning. Buckets are included here (not just in
59
62
  * {@link PulledBranchConfig.preview}) because they round-trip cleanly — name + access
60
63
  * level is all a {@link Config} needs — so the no-policy env path (`neon dev` /
@@ -82,6 +85,8 @@ declare function buildPulledBranchConfig(project: NeonProjectSnapshot, branch: N
82
85
  authEnabled?: boolean;
83
86
  /** Whether a Neon Data API integration is enabled on the branch. */
84
87
  dataApiEnabled?: boolean;
88
+ /** Realtime state when the adapter supports the branch endpoint. */
89
+ realtime?: NeonRealtimeSnapshot | null;
85
90
  }): PulledBranchConfig;
86
91
  //#endregion
87
92
  export { PullConfigOptions, PulledBranchConfig, PulledPreview, buildPulledBranchConfig, pullConfig };
@@ -1 +1 @@
1
- {"version":3,"file":"pull-config.d.ts","names":["BucketAccessLevel","Config","NeonApi","NeonBranchSnapshot","NeonBucketSnapshot","NeonCredentialMeta","NeonEndpointSnapshot","NeonFunctionSnapshot","NeonProjectSnapshot","PullConfigOptions","PulledPreview","Array","PulledBranchConfig","pullConfig","Promise","buildPulledBranchConfig","BucketAccessLevel","Config","NeonApi","NeonBranchSnapshot","NeonBucketSnapshot","NeonCredentialMeta","NeonEndpointSnapshot","NeonFunctionSnapshot","NeonProjectSnapshot","PullConfigOptions","projectId","branchId","apiKey","apiHost","api","PulledPreview","buckets","Array","name","access","functions","slug","credentials","PulledBranchConfig","project","id","region","pgVersion","orgId","branch","parent","isDefault","protected","expiresAt","config","preview","pullConfig","options","Promise","buildPulledBranchConfig","branches","endpoint","previewState","authEnabled","dataApiEnabled"],"sources":["../../src/lib/pull-config.ts"],"mappings":";;;UAkBiBS,iBAAAA;;EAAAA,SAAAA,EAAAA,MAAAA;EAmBAC;EAAaiB,QAAA,EAAA,MAAA;EACU3B;EAA9BW,MAAAA,CAAAA,EAAAA,MAAAA;EACEA;EAOEN,OAAAA,CAAAA,EAAAA,MAAAA;EAAkB;EAGfO,GAAAA,CAAAA,EArBVV,OAqBUU;AAAkB;AA6B1BX;AAMES;AAAa;AAGxB;AAAgC;AACtBD;AACCG,UApDMF,aAAAA,CAoDNE;EAARE,OAAAA,EAnDOH,KAmDPG,CAAAA;IAAOoB,IAAA,EAAA,MAAA;IAoIMnB,MAAAA,EAvLwBf,iBAuLD;EAAA,CAAA,CAAA;EAC7BQ,SAAAA,EAvLEG,KAuLFH,CAAAA;IACDL,IAAAA,EAAAA,MAAAA;IACEA,IAAAA,EAAAA,MAAAA;EACAG,CAAAA,CAAAA;EAEAF;AACEG;AACGF;AAMbO;AAAkB;;eA7LPP;;UAGGO,kBAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA6BRX;;;;;;YAMES;;iBAGWG,UAAAA,UACZJ,oBACPK,QAAQF;iBAoIKG,uBAAAA,UACNP,6BACDL,8BACEA,gCACAG;WAEAF;aACEG;gBACGF;;;;;IAMbO"}
1
+ {"version":3,"file":"pull-config.d.ts","names":["BucketAccessLevel","Config","NeonApi","NeonBranchSnapshot","NeonBucketSnapshot","NeonCredentialMeta","NeonEndpointSnapshot","NeonFunctionSnapshot","NeonProjectSnapshot","NeonRealtimeSnapshot","PullConfigOptions","PulledPreview","Array","PulledBranchConfig","pullConfig","Promise","buildPulledBranchConfig","BucketAccessLevel","Config","NeonApi","NeonBranchSnapshot","NeonBucketSnapshot","NeonCredentialMeta","NeonEndpointSnapshot","NeonFunctionSnapshot","NeonProjectSnapshot","NeonRealtimeSnapshot","PullConfigOptions","projectId","branchId","apiKey","apiHost","api","realtime","PulledPreview","buckets","Array","name","access","functions","slug","credentials","PulledBranchConfig","project","id","region","pgVersion","orgId","branch","parent","isDefault","protected","expiresAt","config","preview","pullConfig","options","Promise","buildPulledBranchConfig","branches","endpoint","previewState","authEnabled","dataApiEnabled"],"sources":["../../src/lib/pull-config.ts"],"mappings":";;;UAmBiBU,iBAAAA;;EAAAA,SAAAA,EAAAA,MAAAA;EAqBAC;EAAakB,QAAA,EAAA,MAAA;EACU7B;EAA9BY,MAAAA,CAAAA,EAAAA,MAAAA;EACEA;EAOEP,OAAAA,CAAAA,EAAAA,MAAAA;EAAkB;EAGfQ,GAAAA,CAAAA,EAvBVX,OAuBUW;EAAkB;EA8B1BZ,QAAAA,CAAAA,EAAAA,OAAAA;AAMEU;AAAa;AAGxB;AAAgC;AACtBD;AACCG;AAARE;AAAO,UArDOJ,aAAAA,CAqDP;EAqJMK,OAAAA,EAzMNJ,KAyMMI,CAAAA;IAAuBqB,IAAA,EAAA,MAAA;IAC7B7B,MAAAA,EA1M8BR,iBA0M9BQ;EACDL,CAAAA,CAAAA;EACEA,SAAAA,EA3MCS,KA2MDT,CAAAA;IACAG,IAAAA,EAAAA,MAAAA;IAEAF,IAAAA,EAAAA,MAAAA;EACEG,CAAAA,CAAAA;EACGF;AAMHI;AAEVI;AAAkB;;;eAjNPR;;UAGGQ,kBAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA8BRZ;;;;;;YAMEU;;iBAGWG,UAAAA,UACZJ,oBACPK,QAAQF;iBAqJKG,uBAAAA,UACNR,6BACDL,8BACEA,gCACAG;WAEAF;aACEG;gBACGF;;;;;;aAMHI;IAEVI"}
@@ -4,6 +4,7 @@ async function pullConfig(options) {
4
4
  const api = options.api ?? createApiFromOptions(options);
5
5
  const projectId = options.projectId;
6
6
  const branchId = options.branchId;
7
+ const getRealtime = options.realtime === false ? void 0 : api.getProjectBranchRealtime?.bind(api);
7
8
  const projectRead = started(() => api.getProject(projectId));
8
9
  const listsRead = started(() => Promise.all([started(() => api.listBranches(projectId)), started(() => api.listEndpoints(projectId))]));
9
10
  const databasesRead = started(() => api.listBranchDatabases(projectId, branchId));
@@ -14,7 +15,8 @@ async function pullConfig(options) {
14
15
  started(() => degradeUnavailable(() => api.listBranchFunctions(projectId, branchId), [])),
15
16
  started(() => degradeUnavailable(() => api.listCredentials(projectId, branchId), [])),
16
17
  started(() => api.getNeonAuth(projectId, branchId)),
17
- started(() => probeDatabase ? api.getNeonDataApi(projectId, branchId, probeDatabase) : Promise.resolve(null))
18
+ started(() => probeDatabase ? api.getNeonDataApi(projectId, branchId, probeDatabase) : Promise.resolve(null)),
19
+ started(() => getRealtime ? degradeUnavailable(() => getRealtime(projectId, branchId), null) : Promise.resolve(null))
18
20
  ]);
19
21
  }));
20
22
  const project = await projectRead;
@@ -22,13 +24,14 @@ async function pullConfig(options) {
22
24
  const branch = resolveBranch(branchId, branches);
23
25
  const endpoint = endpoints.find((ep) => ep.type === "read_write" && ep.branchId === branch.id);
24
26
  await databasesRead;
25
- const [buckets, functions, credentials, auth, dataApi] = await previewRead;
27
+ const [buckets, functions, credentials, auth, dataApi, realtime] = await previewRead;
26
28
  return buildPulledBranchConfig(project, branch, branches, endpoint, {
27
29
  buckets,
28
30
  functions,
29
31
  credentials,
30
32
  authEnabled: auth !== null,
31
- dataApiEnabled: dataApi !== null
33
+ dataApiEnabled: dataApi !== null,
34
+ realtime
32
35
  });
33
36
  }
34
37
  /**
@@ -55,15 +58,17 @@ function pickProbeDatabase(databases) {
55
58
  }
56
59
  /**
57
60
  * Run a Preview-feature read, returning `fallback` if the feature is unavailable for the
58
- * project/region (a {@link ErrorCode.FeatureUnavailable} from the adapter). Other errors
59
- * propagate. Used by `pullConfig` so a branch without a Preview feature still mirrors
60
- * cleanly for env resolution / `inspect`, rather than aborting on an unrelated capability.
61
+ * project/region. Most adapters report {@link ErrorCode.FeatureUnavailable}; API hosts where
62
+ * a route is not deployed can instead return a generic 404. The project and branch are
63
+ * validated independently by `pullConfig`, so that route-level 404 is also safe to degrade.
64
+ * Other errors propagate. This lets a branch without a Preview feature still mirror cleanly
65
+ * for env resolution / `inspect`, rather than aborting on an unrelated capability.
61
66
  */
62
67
  async function degradeUnavailable(read, fallback) {
63
68
  try {
64
69
  return await read();
65
70
  } catch (err) {
66
- if (err instanceof PlatformError && err.code === ErrorCode.FeatureUnavailable) return fallback;
71
+ if (err instanceof PlatformError && (err.code === ErrorCode.FeatureUnavailable || err.code === ErrorCode.NotFound && err.details.status === 404)) return fallback;
67
72
  throw err;
68
73
  }
69
74
  }
@@ -84,10 +89,13 @@ function buildPulledBranchConfig(project, branch, branches, endpoint, previewSta
84
89
  }
85
90
  const bucketDefs = {};
86
91
  for (const b of previewState?.buckets ?? []) bucketDefs[b.name] = { access: b.accessLevel };
92
+ const policyPreview = {};
93
+ if (previewState?.realtime?.enabled) policyPreview.realtime = true;
94
+ if (Object.keys(bucketDefs).length > 0) policyPreview.buckets = bucketDefs;
87
95
  const config = {
88
96
  ...previewState?.authEnabled ? { auth: true } : {},
89
97
  ...previewState?.dataApiEnabled ? { dataApi: true } : {},
90
- ...Object.keys(bucketDefs).length > 0 ? { preview: { buckets: bucketDefs } } : {},
98
+ ...Object.keys(policyPreview).length > 0 ? { preview: policyPreview } : {},
91
99
  ...Object.keys(tuning).length > 0 ? { branch: () => tuning } : {}
92
100
  };
93
101
  const result = {
@@ -1 +1 @@
1
- {"version":3,"file":"pull-config.js","names":[],"sources":["../../src/lib/pull-config.ts"],"sourcesContent":["import {\n\ttype BranchTuning,\n\ttype BucketAccessLevel,\n\ttype ComputeSettings,\n\ttype Config,\n\tcreateNeonApiFromOptions,\n\tErrorCode,\n\ttype NeonApi,\n\ttype NeonBranchSnapshot,\n\ttype NeonBucketSnapshot,\n\ttype NeonCredentialMeta,\n\ttype NeonDatabaseSnapshot,\n\ttype NeonEndpointSnapshot,\n\ttype NeonFunctionSnapshot,\n\ttype NeonProjectSnapshot,\n\tPlatformError,\n} from \"@neon/config\";\n\nexport interface PullConfigOptions {\n\t/** Neon project id (`<project>`). Required — the API addresses branches by project. */\n\tprojectId: string;\n\t/** Neon branch id (`br-…`). Required. Resolve names to ids before calling. */\n\tbranchId: string;\n\t/** Neon API key. Falls back to `NEON_API_KEY` / neonctl credentials. */\n\tapiKey?: string;\n\t/** Neon API base URL. Falls back to `NEON_API_HOST`, then production. */\n\tapiHost?: string;\n\t/** Inject a custom NeonApi adapter (primarily for tests). */\n\tapi?: NeonApi;\n}\n\n/**\n * Live Preview-feature state read back from a branch. Surfaced alongside `config` rather\n * than inside it because functions cannot round-trip: the remote only knows the deployed\n * bundle, not the local `source` path a {@link FunctionConfig} requires, so a pulled\n * function is reported as `{ slug, name }` (no `source`).\n */\nexport interface PulledPreview {\n\tbuckets: Array<{ name: string; access: BucketAccessLevel }>;\n\tfunctions: Array<{ slug: string; name: string }>;\n\t/**\n\t * Secret-free metadata for the credentials issued on the branch (Preview). Surfaced so\n\t * `config status` can show issued credentials (id, scopes, last used) without ever\n\t * exposing the one-time `api_token` / `s3_secret_access_key`. Empty when none / the\n\t * credentials endpoint is unavailable for the project.\n\t */\n\tcredentials: NeonCredentialMeta[];\n}\n\nexport interface PulledBranchConfig {\n\tproject: {\n\t\tid: string;\n\t\tname: string;\n\t\tregion: string;\n\t\tpgVersion: number;\n\t\torgId?: string;\n\t};\n\tbranch: {\n\t\tid: string;\n\t\tname: string;\n\t\tparent?: string;\n\t\tisDefault: boolean;\n\t\tprotected: boolean;\n\t\texpiresAt?: string;\n\t};\n\t/**\n\t * The branch's live state expressed as a {@link Config}: static `auth` / `dataApi`\n\t * toggles, any object-storage `preview.buckets`, plus a `branch` closure carrying the\n\t * branch's lifecycle/compute tuning. Buckets are included here (not just in\n\t * {@link PulledBranchConfig.preview}) because they round-trip cleanly — name + access\n\t * level is all a {@link Config} needs — so the no-policy env path (`neon dev` /\n\t * `neon env pull`) can resolve the branch's storage credentials without a local\n\t * `neon.ts`. Preview **functions** are reported only in\n\t * {@link PulledBranchConfig.preview}: they cannot round-trip (the remote has no local\n\t * `source` path). The AI Gateway is omitted from both — it has no branch-level \"enabled\"\n\t * state to read back (it is always available, credential-gated), so `pullConfig` cannot\n\t * tell whether a policy would enable it.\n\t */\n\tconfig: Config;\n\t/**\n\t * Live Preview-feature state, when the branch has any buckets/functions or issued\n\t * credentials. Omitted entirely when there is nothing to report. The AI Gateway is not\n\t * included: it is always available (credential-gated), not per-branch state.\n\t */\n\tpreview?: PulledPreview;\n}\n\nexport async function pullConfig(\n\toptions: PullConfigOptions,\n): Promise<PulledBranchConfig> {\n\tconst api = options.api ?? createApiFromOptions(options);\n\tconst projectId = options.projectId;\n\tconst branchId = options.branchId;\n\n\t// The first three stages need only the project and branch ids, so they start together.\n\t// They are awaited in the order they used to run, so the first error reported is the same\n\t// one as before (project, then branches/endpoints, then the branch lookup, then databases).\n\tconst projectRead = started(() => api.getProject(projectId));\n\tconst listsRead = started(() =>\n\t\tPromise.all([\n\t\t\tstarted(() => api.listBranches(projectId)),\n\t\t\tstarted(() => api.listEndpoints(projectId)),\n\t\t]),\n\t);\n\t// Data API is enabled per branch + database, so resolve a database to probe.\n\tconst databasesRead = started(() =>\n\t\tapi.listBranchDatabases(projectId, branchId),\n\t);\n\t// Preview reads degrade to \"none / disabled\" when the feature isn't available for the\n\t// project/region. `pullConfig` mirrors the branch for env resolution (`neon dev`,\n\t// `neon env pull`) and `inspect` — an unavailable Preview feature should not break those\n\t// (env comes from auth/dataApi/postgres). `pushConfig` is the place that fails on an\n\t// unavailable feature, and only when the policy declares it.\n\t// The group starts together once databases resolve (the Data API probe needs one), as\n\t// before, so which member's error comes first is unchanged.\n\tconst previewRead = started(() =>\n\t\tdatabasesRead.then((databases) => {\n\t\t\tconst probeDatabase = pickProbeDatabase(databases);\n\t\t\treturn Promise.all([\n\t\t\t\tstarted(() =>\n\t\t\t\t\tdegradeUnavailable(\n\t\t\t\t\t\t() => api.listBranchBuckets(projectId, branchId),\n\t\t\t\t\t\t[],\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\tstarted(() =>\n\t\t\t\t\tdegradeUnavailable(\n\t\t\t\t\t\t() => api.listBranchFunctions(projectId, branchId),\n\t\t\t\t\t\t[],\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\tstarted(() =>\n\t\t\t\t\tdegradeUnavailable(\n\t\t\t\t\t\t() => api.listCredentials(projectId, branchId),\n\t\t\t\t\t\t[],\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\tstarted(() => api.getNeonAuth(projectId, branchId)),\n\t\t\t\tstarted(() =>\n\t\t\t\t\tprobeDatabase\n\t\t\t\t\t\t? api.getNeonDataApi(projectId, branchId, probeDatabase)\n\t\t\t\t\t\t: Promise.resolve(null),\n\t\t\t\t),\n\t\t\t]);\n\t\t}),\n\t);\n\n\tconst project = await projectRead;\n\tconst [branches, endpoints] = await listsRead;\n\tconst branch = resolveBranch(branchId, branches);\n\tconst endpoint = endpoints.find(\n\t\t(ep) => ep.type === \"read_write\" && ep.branchId === branch.id,\n\t);\n\tawait databasesRead;\n\tconst [buckets, functions, credentials, auth, dataApi] = await previewRead;\n\n\treturn buildPulledBranchConfig(project, branch, branches, endpoint, {\n\t\tbuckets,\n\t\tfunctions,\n\t\tcredentials,\n\t\tauthEnabled: auth !== null,\n\t\tdataApiEnabled: dataApi !== null,\n\t});\n}\n\n/**\n * Starts a read now and keeps an unread rejection from crashing the process; the caller\n * awaits it (and sees the error) when its turn comes. Also turns a synchronous throw from\n * a custom adapter into a rejection.\n */\nfunction started<T>(read: () => Promise<T>): Promise<T> {\n\tconst promise = Promise.resolve().then(read);\n\tpromise.catch(() => undefined);\n\treturn promise;\n}\n\n/**\n * Pick the database to probe for a Data API integration. Data API is enabled per\n * branch + database; for read-back we only need to know whether *any* database has it\n * on, so prefer the conventional default (`neondb`) and otherwise fall back to the first\n * database. Returns `undefined` when the branch has no databases.\n */\nfunction pickProbeDatabase(\n\tdatabases: NeonDatabaseSnapshot[],\n): string | undefined {\n\tif (databases.length === 0) return undefined;\n\tconst byName = databases.find((d) => d.name === \"neondb\");\n\tif (byName) return byName.name;\n\treturn databases[0].name;\n}\n\n/**\n * Run a Preview-feature read, returning `fallback` if the feature is unavailable for the\n * project/region (a {@link ErrorCode.FeatureUnavailable} from the adapter). Other errors\n * propagate. Used by `pullConfig` so a branch without a Preview feature still mirrors\n * cleanly for env resolution / `inspect`, rather than aborting on an unrelated capability.\n */\nasync function degradeUnavailable<T>(\n\tread: () => Promise<T>,\n\tfallback: T,\n): Promise<T> {\n\ttry {\n\t\treturn await read();\n\t} catch (err) {\n\t\tif (\n\t\t\terr instanceof PlatformError &&\n\t\t\terr.code === ErrorCode.FeatureUnavailable\n\t\t) {\n\t\t\treturn fallback;\n\t\t}\n\t\tthrow err;\n\t}\n}\n\nfunction createApiFromOptions(options: PullConfigOptions): NeonApi {\n\treturn createNeonApiFromOptions(\"pullConfig\", {\n\t\t...(options.apiKey ? { apiKey: options.apiKey } : {}),\n\t\t...(options.apiHost ? { apiHost: options.apiHost } : {}),\n\t});\n}\n\nexport function buildPulledBranchConfig(\n\tproject: NeonProjectSnapshot,\n\tbranch: NeonBranchSnapshot,\n\tbranches: NeonBranchSnapshot[],\n\tendpoint: NeonEndpointSnapshot | undefined,\n\tpreviewState?: {\n\t\tbuckets: NeonBucketSnapshot[];\n\t\tfunctions: NeonFunctionSnapshot[];\n\t\tcredentials?: NeonCredentialMeta[];\n\t\t/** Whether a Neon Auth integration is enabled on the branch. */\n\t\tauthEnabled?: boolean;\n\t\t/** Whether a Neon Data API integration is enabled on the branch. */\n\t\tdataApiEnabled?: boolean;\n\t},\n): PulledBranchConfig {\n\tconst parent = branch.parentId\n\t\t? branches.find((b) => b.id === branch.parentId)\n\t\t: undefined;\n\t// Auth/Data API are static top-level toggles, so a config pulled from a branch with\n\t// them enabled round-trips through `resolveConfig` / `fetchEnv` and the matching\n\t// secrets get injected. Branch lifecycle/compute is per-branch tuning, so it goes in\n\t// the `branch` closure.\n\tconst tuning: BranchTuning = {};\n\tif (parent) tuning.parent = parent.name;\n\t// Deliberately NOT emitting `ttl` from `branch.expiresAt`: policy `ttl` is a\n\t// creation-time *duration*, while `expiresAt` is an absolute timestamp. Feeding the\n\t// timestamp through `parseDuration` (in `resolveConfig`) would throw, breaking\n\t// `fetchEnv` / `neon dev` / `neon env pull` for any branch that has a TTL. The expiry\n\t// is reported faithfully on `branch.expiresAt` above.\n\tif (branch.protected) tuning.protected = true;\n\tif (endpoint) {\n\t\tconst compute = endpointToComputeSettings(endpoint, project);\n\t\tif (compute) tuning.postgres = { computeSettings: compute };\n\t}\n\t// Buckets round-trip cleanly (name + access level), so they belong in the config the\n\t// env path resolves from — this is what lets `neon dev` / `neon env pull` inject the\n\t// branch's object-storage credentials (AWS_*) with no local neon.ts. Functions are\n\t// deliberately NOT emitted here (they can't round-trip: the remote has no `source`\n\t// path) and neither is the AI Gateway (no branch-level enabled state to detect, only a\n\t// credential) — both would otherwise turn a read-back into a bogus policy declaration.\n\tconst bucketDefs: Record<string, { access: BucketAccessLevel }> = {};\n\tfor (const b of previewState?.buckets ?? []) {\n\t\tbucketDefs[b.name] = { access: b.accessLevel };\n\t}\n\tconst config: Config = {\n\t\t...(previewState?.authEnabled ? { auth: true } : {}),\n\t\t...(previewState?.dataApiEnabled ? { dataApi: true } : {}),\n\t\t...(Object.keys(bucketDefs).length > 0\n\t\t\t? { preview: { buckets: bucketDefs } }\n\t\t\t: {}),\n\t\t...(Object.keys(tuning).length > 0 ? { branch: () => tuning } : {}),\n\t};\n\tconst result: PulledBranchConfig = {\n\t\tproject: {\n\t\t\tid: project.id,\n\t\t\tname: project.name,\n\t\t\tregion: project.regionId,\n\t\t\tpgVersion: project.pgVersion,\n\t\t\t...(project.orgId ? { orgId: project.orgId } : {}),\n\t\t},\n\t\tbranch: {\n\t\t\tid: branch.id,\n\t\t\tname: branch.name,\n\t\t\t...(parent ? { parent: parent.name } : {}),\n\t\t\tisDefault: branch.isDefault,\n\t\t\tprotected: branch.protected,\n\t\t\t...(branch.expiresAt ? { expiresAt: branch.expiresAt } : {}),\n\t\t},\n\t\tconfig,\n\t};\n\tconst preview = previewState ? buildPulledPreview(previewState) : undefined;\n\tif (preview) result.preview = preview;\n\treturn result;\n}\n\n/**\n * Reverse-engineer the {@link PulledPreview} from remote snapshots. Returns `undefined` when\n * the branch has no Preview features so the field can be omitted entirely.\n */\nfunction buildPulledPreview(state: {\n\tbuckets: NeonBucketSnapshot[];\n\tfunctions: NeonFunctionSnapshot[];\n\tcredentials?: NeonCredentialMeta[];\n}): PulledPreview | undefined {\n\tconst credentials = state.credentials ?? [];\n\tif (\n\t\tstate.buckets.length === 0 &&\n\t\tstate.functions.length === 0 &&\n\t\tcredentials.length === 0\n\t) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\tbuckets: state.buckets.map((b) => ({\n\t\t\tname: b.name,\n\t\t\taccess: b.accessLevel,\n\t\t})),\n\t\tfunctions: state.functions.map((f) => ({\n\t\t\tslug: f.slug,\n\t\t\tname: f.name,\n\t\t})),\n\t\tcredentials,\n\t};\n}\n\nfunction resolveBranch(\n\tbranchId: string,\n\tbranches: NeonBranchSnapshot[],\n): NeonBranchSnapshot {\n\tconst match = branches.find((b) => b.id === branchId);\n\tif (match) return match;\n\tthrow new PlatformError(\n\t\tErrorCode.BranchNotFound,\n\t\t[\n\t\t\t`pullConfig: branch id ${JSON.stringify(branchId)} not found on project.`,\n\t\t\t`Available branches: ${branches.map((b) => `${b.name} (${b.id})`).join(\", \") || \"(none)\"}.`,\n\t\t].join(\" \"),\n\t\t{\n\t\t\tdetails: {\n\t\t\t\tbranchId,\n\t\t\t\tavailable: branches.map((b) => b.id),\n\t\t\t},\n\t\t},\n\t);\n}\n\nfunction endpointToComputeSettings(\n\tendpoint: NeonEndpointSnapshot,\n\tproject: NeonProjectSnapshot,\n): ComputeSettings | undefined {\n\tconst defaults = project.defaultEndpointSettings;\n\tconst out: ComputeSettings = {};\n\tif (\n\t\tendpoint.autoscalingLimitMinCu !== undefined &&\n\t\tendpoint.autoscalingLimitMinCu !== defaults?.autoscalingLimitMinCu\n\t) {\n\t\tout.autoscalingLimitMinCu = endpoint.autoscalingLimitMinCu;\n\t}\n\tif (\n\t\tendpoint.autoscalingLimitMaxCu !== undefined &&\n\t\tendpoint.autoscalingLimitMaxCu !== defaults?.autoscalingLimitMaxCu\n\t) {\n\t\tout.autoscalingLimitMaxCu = endpoint.autoscalingLimitMaxCu;\n\t}\n\tif (\n\t\tendpoint.suspendTimeout !== undefined &&\n\t\tendpoint.suspendTimeout !== defaults?.suspendTimeout\n\t) {\n\t\tout.suspendTimeout = endpoint.suspendTimeout;\n\t}\n\treturn Object.keys(out).length > 0 ? out : undefined;\n}\n"],"mappings":";;AAuFA,eAAsB,WACrB,SAC8B;CAC9B,MAAM,MAAM,QAAQ,OAAO,qBAAqB,OAAO;CACvD,MAAM,YAAY,QAAQ;CAC1B,MAAM,WAAW,QAAQ;CAKzB,MAAM,cAAc,cAAc,IAAI,WAAW,SAAS,CAAC;CAC3D,MAAM,YAAY,cACjB,QAAQ,IAAI,CACX,cAAc,IAAI,aAAa,SAAS,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AW,QAAQ;CACzB,MAAM,MAAuB,CAAC;CAC9B,IACC,SAAS,0BAA0B,KAAA,KACnC,SAAS,0BAA0B,UAAU,uBAE7C,IAAI,wBAAwB,SAAS;CAEtC,IACC,SAAS,0BAA0B,KAAA,KACnC,SAAS,0BAA0B,UAAU,uBAE7C,IAAI,wBAAwB,SAAS;CAEtC,IACC,SAAS,mBAAmB,KAAA,KAC5B,SAAS,mBAAmB,UAAU,gBAEtC,IAAI,iBAAiB,SAAS;CAE/B,OAAO,OAAO,KAAK,GAAG,CAAC,CAAC,SAAS,IAAI,MAAM,KAAA;AAC5C"}
1
+ {"version":3,"file":"pull-config.js","names":[],"sources":["../../src/lib/pull-config.ts"],"sourcesContent":["import {\n\ttype BranchTuning,\n\ttype BucketAccessLevel,\n\ttype ComputeSettings,\n\ttype Config,\n\tcreateNeonApiFromOptions,\n\tErrorCode,\n\ttype NeonApi,\n\ttype NeonBranchSnapshot,\n\ttype NeonBucketSnapshot,\n\ttype NeonCredentialMeta,\n\ttype NeonDatabaseSnapshot,\n\ttype NeonEndpointSnapshot,\n\ttype NeonFunctionSnapshot,\n\ttype NeonProjectSnapshot,\n\ttype NeonRealtimeSnapshot,\n\tPlatformError,\n} from \"@neon/config\";\n\nexport interface PullConfigOptions {\n\t/** Neon project id (`<project>`). Required — the API addresses branches by project. */\n\tprojectId: string;\n\t/** Neon branch id (`br-…`). Required. Resolve names to ids before calling. */\n\tbranchId: string;\n\t/** Neon API key. Falls back to `NEON_API_KEY` / neonctl credentials. */\n\tapiKey?: string;\n\t/** Neon API base URL. Falls back to `NEON_API_HOST`, then production. */\n\tapiHost?: string;\n\t/** Inject a custom NeonApi adapter (primarily for tests). */\n\tapi?: NeonApi;\n\t/** Read the branch's Realtime state. Defaults to `true`. */\n\trealtime?: boolean;\n}\n\n/**\n * Live Preview-feature state read back from a branch. Surfaced alongside `config` rather\n * than inside it because functions cannot round-trip: the remote only knows the deployed\n * bundle, not the local `source` path a {@link FunctionConfig} requires, so a pulled\n * function is reported as `{ slug, name }` (no `source`).\n */\nexport interface PulledPreview {\n\tbuckets: Array<{ name: string; access: BucketAccessLevel }>;\n\tfunctions: Array<{ slug: string; name: string }>;\n\t/**\n\t * Secret-free metadata for the credentials issued on the branch (Preview). Surfaced so\n\t * `config status` can show issued credentials (id, scopes, last used) without ever\n\t * exposing the one-time `api_token` / `s3_secret_access_key`. Empty when none / the\n\t * credentials endpoint is unavailable for the project.\n\t */\n\tcredentials: NeonCredentialMeta[];\n}\n\nexport interface PulledBranchConfig {\n\tproject: {\n\t\tid: string;\n\t\tname: string;\n\t\tregion: string;\n\t\tpgVersion: number;\n\t\torgId?: string;\n\t};\n\tbranch: {\n\t\tid: string;\n\t\tname: string;\n\t\tparent?: string;\n\t\tisDefault: boolean;\n\t\tprotected: boolean;\n\t\texpiresAt?: string;\n\t};\n\t/**\n\t * The branch's live state expressed as a {@link Config}: static `auth` / `dataApi`\n\t * toggles, Realtime under `preview.realtime`, any object-storage `preview.buckets`, plus\n\t * a `branch` closure carrying the\n\t * branch's lifecycle/compute tuning. Buckets are included here (not just in\n\t * {@link PulledBranchConfig.preview}) because they round-trip cleanly — name + access\n\t * level is all a {@link Config} needs — so the no-policy env path (`neon dev` /\n\t * `neon env pull`) can resolve the branch's storage credentials without a local\n\t * `neon.ts`. Preview **functions** are reported only in\n\t * {@link PulledBranchConfig.preview}: they cannot round-trip (the remote has no local\n\t * `source` path). The AI Gateway is omitted from both — it has no branch-level \"enabled\"\n\t * state to read back (it is always available, credential-gated), so `pullConfig` cannot\n\t * tell whether a policy would enable it.\n\t */\n\tconfig: Config;\n\t/**\n\t * Live Preview-feature state, when the branch has any buckets/functions or issued\n\t * credentials. Omitted entirely when there is nothing to report. The AI Gateway is not\n\t * included: it is always available (credential-gated), not per-branch state.\n\t */\n\tpreview?: PulledPreview;\n}\n\nexport async function pullConfig(\n\toptions: PullConfigOptions,\n): Promise<PulledBranchConfig> {\n\tconst api = options.api ?? createApiFromOptions(options);\n\tconst projectId = options.projectId;\n\tconst branchId = options.branchId;\n\tconst getRealtime =\n\t\toptions.realtime === false\n\t\t\t? undefined\n\t\t\t: api.getProjectBranchRealtime?.bind(api);\n\n\t// The first three stages need only the project and branch ids, so they start together.\n\t// They are awaited in the order they used to run, so the first error reported is the same\n\t// one as before (project, then branches/endpoints, then the branch lookup, then databases).\n\tconst projectRead = started(() => api.getProject(projectId));\n\tconst listsRead = started(() =>\n\t\tPromise.all([\n\t\t\tstarted(() => api.listBranches(projectId)),\n\t\t\tstarted(() => api.listEndpoints(projectId)),\n\t\t]),\n\t);\n\t// Data API is enabled per branch + database, so resolve a database to probe.\n\tconst databasesRead = started(() =>\n\t\tapi.listBranchDatabases(projectId, branchId),\n\t);\n\t// Preview reads degrade to \"none / disabled\" when the feature isn't available for the\n\t// project/region. `pullConfig` mirrors the branch for env resolution (`neon dev`,\n\t// `neon env pull`) and `inspect` — an unavailable Preview feature should not break those\n\t// (env comes from auth/dataApi/postgres). `pushConfig` is the place that fails on an\n\t// unavailable feature, and only when the policy declares it.\n\t// The group starts together once databases resolve (the Data API probe needs one), as\n\t// before, so which member's error comes first is unchanged.\n\tconst previewRead = started(() =>\n\t\tdatabasesRead.then((databases) => {\n\t\t\tconst probeDatabase = pickProbeDatabase(databases);\n\t\t\treturn Promise.all([\n\t\t\t\tstarted(() =>\n\t\t\t\t\tdegradeUnavailable(\n\t\t\t\t\t\t() => api.listBranchBuckets(projectId, branchId),\n\t\t\t\t\t\t[],\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\tstarted(() =>\n\t\t\t\t\tdegradeUnavailable(\n\t\t\t\t\t\t() => api.listBranchFunctions(projectId, branchId),\n\t\t\t\t\t\t[],\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\tstarted(() =>\n\t\t\t\t\tdegradeUnavailable(\n\t\t\t\t\t\t() => api.listCredentials(projectId, branchId),\n\t\t\t\t\t\t[],\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\tstarted(() => api.getNeonAuth(projectId, branchId)),\n\t\t\t\tstarted(() =>\n\t\t\t\t\tprobeDatabase\n\t\t\t\t\t\t? api.getNeonDataApi(projectId, branchId, probeDatabase)\n\t\t\t\t\t\t: Promise.resolve(null),\n\t\t\t\t),\n\t\t\t\tstarted(() =>\n\t\t\t\t\tgetRealtime\n\t\t\t\t\t\t? degradeUnavailable(\n\t\t\t\t\t\t\t\t() => getRealtime(projectId, branchId),\n\t\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: Promise.resolve(null),\n\t\t\t\t),\n\t\t\t]);\n\t\t}),\n\t);\n\n\tconst project = await projectRead;\n\tconst [branches, endpoints] = await listsRead;\n\tconst branch = resolveBranch(branchId, branches);\n\tconst endpoint = endpoints.find(\n\t\t(ep) => ep.type === \"read_write\" && ep.branchId === branch.id,\n\t);\n\tawait databasesRead;\n\tconst [buckets, functions, credentials, auth, dataApi, realtime] =\n\t\tawait previewRead;\n\n\treturn buildPulledBranchConfig(project, branch, branches, endpoint, {\n\t\tbuckets,\n\t\tfunctions,\n\t\tcredentials,\n\t\tauthEnabled: auth !== null,\n\t\tdataApiEnabled: dataApi !== null,\n\t\trealtime,\n\t});\n}\n\n/**\n * Starts a read now and keeps an unread rejection from crashing the process; the caller\n * awaits it (and sees the error) when its turn comes. Also turns a synchronous throw from\n * a custom adapter into a rejection.\n */\nfunction started<T>(read: () => Promise<T>): Promise<T> {\n\tconst promise = Promise.resolve().then(read);\n\tpromise.catch(() => undefined);\n\treturn promise;\n}\n\n/**\n * Pick the database to probe for a Data API integration. Data API is enabled per\n * branch + database; for read-back we only need to know whether *any* database has it\n * on, so prefer the conventional default (`neondb`) and otherwise fall back to the first\n * database. Returns `undefined` when the branch has no databases.\n */\nfunction pickProbeDatabase(\n\tdatabases: NeonDatabaseSnapshot[],\n): string | undefined {\n\tif (databases.length === 0) return undefined;\n\tconst byName = databases.find((d) => d.name === \"neondb\");\n\tif (byName) return byName.name;\n\treturn databases[0].name;\n}\n\n/**\n * Run a Preview-feature read, returning `fallback` if the feature is unavailable for the\n * project/region. Most adapters report {@link ErrorCode.FeatureUnavailable}; API hosts where\n * a route is not deployed can instead return a generic 404. The project and branch are\n * validated independently by `pullConfig`, so that route-level 404 is also safe to degrade.\n * Other errors propagate. This lets a branch without a Preview feature still mirror cleanly\n * for env resolution / `inspect`, rather than aborting on an unrelated capability.\n */\nasync function degradeUnavailable<T>(\n\tread: () => Promise<T>,\n\tfallback: T,\n): Promise<T> {\n\ttry {\n\t\treturn await read();\n\t} catch (err) {\n\t\tif (\n\t\t\terr instanceof PlatformError &&\n\t\t\t(err.code === ErrorCode.FeatureUnavailable ||\n\t\t\t\t(err.code === ErrorCode.NotFound && err.details.status === 404))\n\t\t) {\n\t\t\treturn fallback;\n\t\t}\n\t\tthrow err;\n\t}\n}\n\nfunction createApiFromOptions(options: PullConfigOptions): NeonApi {\n\treturn createNeonApiFromOptions(\"pullConfig\", {\n\t\t...(options.apiKey ? { apiKey: options.apiKey } : {}),\n\t\t...(options.apiHost ? { apiHost: options.apiHost } : {}),\n\t});\n}\n\nexport function buildPulledBranchConfig(\n\tproject: NeonProjectSnapshot,\n\tbranch: NeonBranchSnapshot,\n\tbranches: NeonBranchSnapshot[],\n\tendpoint: NeonEndpointSnapshot | undefined,\n\tpreviewState?: {\n\t\tbuckets: NeonBucketSnapshot[];\n\t\tfunctions: NeonFunctionSnapshot[];\n\t\tcredentials?: NeonCredentialMeta[];\n\t\t/** Whether a Neon Auth integration is enabled on the branch. */\n\t\tauthEnabled?: boolean;\n\t\t/** Whether a Neon Data API integration is enabled on the branch. */\n\t\tdataApiEnabled?: boolean;\n\t\t/** Realtime state when the adapter supports the branch endpoint. */\n\t\trealtime?: NeonRealtimeSnapshot | null;\n\t},\n): PulledBranchConfig {\n\tconst parent = branch.parentId\n\t\t? branches.find((b) => b.id === branch.parentId)\n\t\t: undefined;\n\t// Auth and Data API are static top-level toggles, while Realtime is static under\n\t// `preview.realtime`. A config pulled from a branch with them enabled round-trips through\n\t// `resolveConfig` / `fetchEnv` and the matching secrets get injected. Branch\n\t// lifecycle/compute is per-branch tuning, so it goes in the `branch` closure.\n\tconst tuning: BranchTuning = {};\n\tif (parent) tuning.parent = parent.name;\n\t// Deliberately NOT emitting `ttl` from `branch.expiresAt`: policy `ttl` is a\n\t// creation-time *duration*, while `expiresAt` is an absolute timestamp. Feeding the\n\t// timestamp through `parseDuration` (in `resolveConfig`) would throw, breaking\n\t// `fetchEnv` / `neon dev` / `neon env pull` for any branch that has a TTL. The expiry\n\t// is reported faithfully on `branch.expiresAt` above.\n\tif (branch.protected) tuning.protected = true;\n\tif (endpoint) {\n\t\tconst compute = endpointToComputeSettings(endpoint, project);\n\t\tif (compute) tuning.postgres = { computeSettings: compute };\n\t}\n\t// Buckets round-trip cleanly (name + access level), so they belong in the config the\n\t// env path resolves from — this is what lets `neon dev` / `neon env pull` inject the\n\t// branch's object-storage credentials (AWS_*) with no local neon.ts. Functions are\n\t// deliberately NOT emitted here (they can't round-trip: the remote has no `source`\n\t// path) and neither is the AI Gateway (no branch-level enabled state to detect, only a\n\t// credential) — both would otherwise turn a read-back into a bogus policy declaration.\n\tconst bucketDefs: Record<string, { access: BucketAccessLevel }> = {};\n\tfor (const b of previewState?.buckets ?? []) {\n\t\tbucketDefs[b.name] = { access: b.accessLevel };\n\t}\n\tconst policyPreview: NonNullable<Config[\"preview\"]> = {};\n\tif (previewState?.realtime?.enabled) policyPreview.realtime = true;\n\tif (Object.keys(bucketDefs).length > 0) policyPreview.buckets = bucketDefs;\n\tconst config: Config = {\n\t\t...(previewState?.authEnabled ? { auth: true } : {}),\n\t\t...(previewState?.dataApiEnabled ? { dataApi: true } : {}),\n\t\t...(Object.keys(policyPreview).length > 0\n\t\t\t? { preview: policyPreview }\n\t\t\t: {}),\n\t\t...(Object.keys(tuning).length > 0 ? { branch: () => tuning } : {}),\n\t};\n\tconst result: PulledBranchConfig = {\n\t\tproject: {\n\t\t\tid: project.id,\n\t\t\tname: project.name,\n\t\t\tregion: project.regionId,\n\t\t\tpgVersion: project.pgVersion,\n\t\t\t...(project.orgId ? { orgId: project.orgId } : {}),\n\t\t},\n\t\tbranch: {\n\t\t\tid: branch.id,\n\t\t\tname: branch.name,\n\t\t\t...(parent ? { parent: parent.name } : {}),\n\t\t\tisDefault: branch.isDefault,\n\t\t\tprotected: branch.protected,\n\t\t\t...(branch.expiresAt ? { expiresAt: branch.expiresAt } : {}),\n\t\t},\n\t\tconfig,\n\t};\n\tconst preview = previewState ? buildPulledPreview(previewState) : undefined;\n\tif (preview) result.preview = preview;\n\treturn result;\n}\n\n/**\n * Reverse-engineer the {@link PulledPreview} from remote snapshots. Returns `undefined` when\n * the branch has no Preview features so the field can be omitted entirely.\n */\nfunction buildPulledPreview(state: {\n\tbuckets: NeonBucketSnapshot[];\n\tfunctions: NeonFunctionSnapshot[];\n\tcredentials?: NeonCredentialMeta[];\n}): PulledPreview | undefined {\n\tconst credentials = state.credentials ?? [];\n\tif (\n\t\tstate.buckets.length === 0 &&\n\t\tstate.functions.length === 0 &&\n\t\tcredentials.length === 0\n\t) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\tbuckets: state.buckets.map((b) => ({\n\t\t\tname: b.name,\n\t\t\taccess: b.accessLevel,\n\t\t})),\n\t\tfunctions: state.functions.map((f) => ({\n\t\t\tslug: f.slug,\n\t\t\tname: f.name,\n\t\t})),\n\t\tcredentials,\n\t};\n}\n\nfunction resolveBranch(\n\tbranchId: string,\n\tbranches: NeonBranchSnapshot[],\n): NeonBranchSnapshot {\n\tconst match = branches.find((b) => b.id === branchId);\n\tif (match) return match;\n\tthrow new PlatformError(\n\t\tErrorCode.BranchNotFound,\n\t\t[\n\t\t\t`pullConfig: branch id ${JSON.stringify(branchId)} not found on project.`,\n\t\t\t`Available branches: ${branches.map((b) => `${b.name} (${b.id})`).join(\", \") || \"(none)\"}.`,\n\t\t].join(\" \"),\n\t\t{\n\t\t\tdetails: {\n\t\t\t\tbranchId,\n\t\t\t\tavailable: branches.map((b) => b.id),\n\t\t\t},\n\t\t},\n\t);\n}\n\nfunction endpointToComputeSettings(\n\tendpoint: NeonEndpointSnapshot,\n\tproject: NeonProjectSnapshot,\n): ComputeSettings | undefined {\n\tconst defaults = project.defaultEndpointSettings;\n\tconst out: ComputeSettings = {};\n\tif (\n\t\tendpoint.autoscalingLimitMinCu !== undefined &&\n\t\tendpoint.autoscalingLimitMinCu !== defaults?.autoscalingLimitMinCu\n\t) {\n\t\tout.autoscalingLimitMinCu = endpoint.autoscalingLimitMinCu;\n\t}\n\tif (\n\t\tendpoint.autoscalingLimitMaxCu !== undefined &&\n\t\tendpoint.autoscalingLimitMaxCu !== defaults?.autoscalingLimitMaxCu\n\t) {\n\t\tout.autoscalingLimitMaxCu = endpoint.autoscalingLimitMaxCu;\n\t}\n\tif (\n\t\tendpoint.suspendTimeout !== undefined &&\n\t\tendpoint.suspendTimeout !== defaults?.suspendTimeout\n\t) {\n\t\tout.suspendTimeout = endpoint.suspendTimeout;\n\t}\n\treturn Object.keys(out).length > 0 ? out : undefined;\n}\n"],"mappings":";;AA2FA,eAAsB,WACrB,SAC8B;CAC9B,MAAM,MAAM,QAAQ,OAAO,qBAAqB,OAAO;CACvD,MAAM,YAAY,QAAQ;CAC1B,MAAM,WAAW,QAAQ;CACzB,MAAM,cACL,QAAQ,aAAa,QAClB,KAAA,IACA,IAAI,0BAA0B,KAAK,GAAG;CAK1C,MAAM,cAAc,cAAc,IAAI,WAAW,SAAS,CAAC;CAC3D,MAAM,YAAY,cACjB,QAAQ,IAAI,CACX,cAAc,IAAI,aAAa,SAAS,CAAC,GACzC,cAAc,IAAI,cAAc,SAAS,CAAC,CAC3C,CAAC,CACF;CAEA,MAAM,gBAAgB,cACrB,IAAI,oBAAoB,WAAW,QAAQ,CAC5C;CAQA,MAAM,cAAc,cACnB,cAAc,MAAM,cAAc;EACjC,MAAM,gBAAgB,kBAAkB,SAAS;EACjD,OAAO,QAAQ,IAAI;GAClB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0BACR,UACA,SAC8B;CAC9B,MAAM,WAAW,QAAQ;CACzB,MAAM,MAAuB,CAAC;CAC9B,IACC,SAAS,0BAA0B,KAAA,KACnC,SAAS,0BAA0B,UAAU,uBAE7C,IAAI,wBAAwB,SAAS;CAEtC,IACC,SAAS,0BAA0B,KAAA,KACnC,SAAS,0BAA0B,UAAU,uBAE7C,IAAI,wBAAwB,SAAS;CAEtC,IACC,SAAS,mBAAmB,KAAA,KAC5B,SAAS,mBAAmB,UAAU,gBAEtC,IAAI,iBAAiB,SAAS;CAE/B,OAAO,OAAO,KAAK,GAAG,CAAC,CAAC,SAAS,IAAI,MAAM,KAAA;AAC5C"}
@@ -1 +1 @@
1
- {"version":3,"file":"push-config.d.ts","names":["Config","ConflictReport","NeonApi","PushResult","FunctionBundler","PushConfigOptions","PushConfirmContext","Promise","pushConfig","FunctionBundler","Config","ConflictReport","NeonApi","PushResult","PushConfigOptions","projectId","branchId","apiKey","apiHost","api","branchExists","updateExisting","allowProtectedBranch","confirm","context","PushConfirmContext","Promise","beforeMutations","bundleFunction","dryRun","branchName","protectedBranch","overrideUpdates","overrides","pushConfig","config","options"],"sources":["../../src/lib/push-config.ts"],"mappings":";;;;UAmCiBK,iBAAAA;;AAAjB;AAAkC;AAoB3BH;AA8CcI;EAAiCC,SAAAA,EAAAA,MAAAA;EAMtBA;AAEdH;AAAe;AAmBjC;EAgCsBI,QAAAA,EAAAA,MAAU;EAAA;EACvBR,MAAAA,CAAAA,EAAAA,MAAAA;EACCK;EACCF,OAAAA,CAAAA,EAAAA,MAAAA;EAARI;AAAO;;;QA5GHL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;sBA8CcI,iCAAiCC;;;;;;iCAMtBA;;mBAEdH;;;;;;;;;;;;;;;;;;UAmBDE,kBAAAA;;;;;;;;;;;;;;;;;;;;sBAoBIL;;;;;;;;;;;iBAYCO,UAAAA,SACbR,iBACCK,oBACPE,QAAQJ"}
1
+ {"version":3,"file":"push-config.d.ts","names":["Config","ConflictReport","NeonApi","PushResult","FunctionBundler","PushConfigOptions","PushConfirmContext","Promise","pushConfig","FunctionBundler","Config","ConflictReport","NeonApi","PushResult","PushConfigOptions","projectId","branchId","apiKey","apiHost","api","branchExists","updateExisting","allowProtectedBranch","confirm","context","PushConfirmContext","Promise","beforeMutations","bundleFunction","dryRun","branchName","protectedBranch","overrideUpdates","overrides","pushConfig","config","options"],"sources":["../../src/lib/push-config.ts"],"mappings":";;;;UAoCiBK,iBAAAA;;AAAjB;AAAkC;AAoB3BH;AA8CcI;EAAiCC,SAAAA,EAAAA,MAAAA;EAMtBA;AAEdH;AAAe;AAmBjC;EAgCsBI,QAAAA,EAAAA,MAAU;EAAA;EACvBR,MAAAA,CAAAA,EAAAA,MAAAA;EACCK;EACCF,OAAAA,CAAAA,EAAAA,MAAAA;EAARI;AAAO;;;QA5GHL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;sBA8CcI,iCAAiCC;;;;;;iCAMtBA;;mBAEdH;;;;;;;;;;;;;;;;;;UAmBDE,kBAAAA;;;;;;;;;;;;;;;;;;;;sBAoBIL;;;;;;;;;;;iBAYCO,UAAAA,SACbR,iBACCK,oBACPE,QAAQJ"}
@@ -34,6 +34,8 @@ async function pushConfig(config, options) {
34
34
  isProtected: branch.protected,
35
35
  ...branch.expiresAt ? { expiresAt: branch.expiresAt } : {}
36
36
  });
37
+ const realtimeApi = hasRealtimePolicy(resolved) ? requireRealtimeApi(api) : void 0;
38
+ const realtimeRead = realtimeApi ? started(() => realtimeApi.getProjectBranchRealtime(remoteProject.id, branch.id)) : void 0;
37
39
  const servicesRead = started(() => resolveServiceState({
38
40
  api,
39
41
  projectId: remoteProject.id,
@@ -56,6 +58,7 @@ async function pushConfig(config, options) {
56
58
  endpoint: endpoints.find((ep) => ep.type === "read_write" && ep.branchId === branch.id),
57
59
  services
58
60
  };
61
+ if (realtimeRead) remote.realtime = await realtimeRead;
59
62
  if (previewRead) remote.preview = await previewRead;
60
63
  const diff = diffConfig(resolved, remote, { updateExisting: true });
61
64
  const needsOverrideConfirm = diff.plan.filter(isOverrideStep).length > 0 && !updateExisting;
@@ -130,7 +133,7 @@ async function pushConfig(config, options) {
130
133
  return result;
131
134
  }
132
135
  function isOverrideStep(step) {
133
- return step.kind === "update-branch-ttl" || step.kind === "update-branch-protected" || step.kind === "update-endpoint" || step.kind === "update-data-api" || step.kind === "disable-data-api" || step.kind === "retarget-custom-domain";
136
+ return step.kind === "update-branch-ttl" || step.kind === "update-branch-protected" || step.kind === "update-endpoint" || step.kind === "update-realtime" || step.kind === "disable-realtime" || step.kind === "update-data-api" || step.kind === "disable-data-api" || step.kind === "retarget-custom-domain";
134
137
  }
135
138
  /**
136
139
  * Build an {@link AppliedChange} from a {@link PlanStep} without calling the Neon API.
@@ -140,6 +143,26 @@ function isOverrideStep(step) {
140
143
  */
141
144
  function synthesizeAppliedChange(step) {
142
145
  switch (step.kind) {
146
+ case "enable-realtime": return {
147
+ kind: "service",
148
+ action: "create",
149
+ identifier: "realtime",
150
+ ...step.input?.allowedOrigins !== void 0 ? { details: { allowedOrigins: step.input.allowedOrigins } } : {}
151
+ };
152
+ case "update-realtime": return {
153
+ kind: "service",
154
+ action: "update",
155
+ identifier: "realtime",
156
+ details: {
157
+ field: "allowedOrigins",
158
+ allowedOrigins: step.input.allowedOrigins
159
+ }
160
+ };
161
+ case "disable-realtime": return {
162
+ kind: "service",
163
+ action: "delete",
164
+ identifier: "realtime"
165
+ };
143
166
  case "update-branch-ttl": return {
144
167
  kind: "branch",
145
168
  action: "update",
@@ -347,6 +370,13 @@ async function pickServiceDatabaseName(api, projectId, branchId) {
347
370
  }
348
371
  async function applyStep(step, ctx) {
349
372
  switch (step.kind) {
373
+ case "enable-realtime":
374
+ case "update-realtime":
375
+ await requireRealtimeApi(ctx.api).enableProjectBranchRealtime(ctx.remoteProjectId, step.branchId, step.input);
376
+ return synthesizeAppliedChange(step);
377
+ case "disable-realtime":
378
+ await requireRealtimeApi(ctx.api).disableProjectBranchRealtime(ctx.remoteProjectId, step.branchId);
379
+ return synthesizeAppliedChange(step);
350
380
  case "update-branch-ttl": {
351
381
  const updated = await ctx.api.updateBranch(ctx.remoteProjectId, step.branchId, { expiresAt: step.expiresAt ?? null });
352
382
  ctx.branchById.set(updated.id, updated);
@@ -537,6 +567,20 @@ async function applyStep(step, ctx) {
537
567
  }
538
568
  }
539
569
  }
570
+ function hasRealtimePolicy(resolved) {
571
+ return resolved.realtimePolicy !== void 0 && resolved.realtimePolicy !== "omitted";
572
+ }
573
+ function requireRealtimeApi(api) {
574
+ const get = api.getProjectBranchRealtime;
575
+ const enable = api.enableProjectBranchRealtime;
576
+ const disable = api.disableProjectBranchRealtime;
577
+ if (!get || !enable || !disable) throw new PlatformError(ErrorCode.FeatureUnavailable, "This NeonApi adapter does not implement Realtime. Implement getProjectBranchRealtime, enableProjectBranchRealtime, and disableProjectBranchRealtime, or remove preview.realtime from neon.ts.");
578
+ return {
579
+ getProjectBranchRealtime: get.bind(api),
580
+ enableProjectBranchRealtime: enable.bind(api),
581
+ disableProjectBranchRealtime: disable.bind(api)
582
+ };
583
+ }
540
584
  /**
541
585
  * Add each deployed function's invocation URL to its applied-change `details` so callers
542
586
  * (e.g. neonctl) can show users where to call the function right after a push.