@neon/config 0.0.0 → 0.9.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 (60) hide show
  1. package/LICENSE.md +178 -0
  2. package/README.md +148 -0
  3. package/dist/index.d.ts +11 -0
  4. package/dist/index.js +10 -0
  5. package/dist/lib/auth.d.ts +67 -0
  6. package/dist/lib/auth.d.ts.map +1 -0
  7. package/dist/lib/auth.js +107 -0
  8. package/dist/lib/auth.js.map +1 -0
  9. package/dist/lib/credentials.d.ts +37 -0
  10. package/dist/lib/credentials.d.ts.map +1 -0
  11. package/dist/lib/credentials.js +30 -0
  12. package/dist/lib/credentials.js.map +1 -0
  13. package/dist/lib/define-config.d.ts +123 -0
  14. package/dist/lib/define-config.d.ts.map +1 -0
  15. package/dist/lib/define-config.js +168 -0
  16. package/dist/lib/define-config.js.map +1 -0
  17. package/dist/lib/diff.d.ts +120 -0
  18. package/dist/lib/diff.d.ts.map +1 -0
  19. package/dist/lib/diff.js +284 -0
  20. package/dist/lib/diff.js.map +1 -0
  21. package/dist/lib/duration.d.ts +68 -0
  22. package/dist/lib/duration.d.ts.map +1 -0
  23. package/dist/lib/duration.js +111 -0
  24. package/dist/lib/duration.js.map +1 -0
  25. package/dist/lib/errors.d.ts +140 -0
  26. package/dist/lib/errors.d.ts.map +1 -0
  27. package/dist/lib/errors.js +185 -0
  28. package/dist/lib/errors.js.map +1 -0
  29. package/dist/lib/loader.d.ts +44 -0
  30. package/dist/lib/loader.d.ts.map +1 -0
  31. package/dist/lib/loader.js +120 -0
  32. package/dist/lib/loader.js.map +1 -0
  33. package/dist/lib/neon-api-real.d.ts +92 -0
  34. package/dist/lib/neon-api-real.d.ts.map +1 -0
  35. package/dist/lib/neon-api-real.js +957 -0
  36. package/dist/lib/neon-api-real.js.map +1 -0
  37. package/dist/lib/neon-api.d.ts +373 -0
  38. package/dist/lib/neon-api.d.ts.map +1 -0
  39. package/dist/lib/neon-api.js +1 -0
  40. package/dist/lib/patterns.d.ts +43 -0
  41. package/dist/lib/patterns.d.ts.map +1 -0
  42. package/dist/lib/patterns.js +76 -0
  43. package/dist/lib/patterns.js.map +1 -0
  44. package/dist/lib/schema.d.ts +215 -0
  45. package/dist/lib/schema.d.ts.map +1 -0
  46. package/dist/lib/schema.js +284 -0
  47. package/dist/lib/schema.js.map +1 -0
  48. package/dist/lib/types.d.ts +546 -0
  49. package/dist/lib/types.d.ts.map +1 -0
  50. package/dist/lib/types.js +18 -0
  51. package/dist/lib/types.js.map +1 -0
  52. package/dist/lib/wrap-neon-error.d.ts +30 -0
  53. package/dist/lib/wrap-neon-error.d.ts.map +1 -0
  54. package/dist/lib/wrap-neon-error.js +139 -0
  55. package/dist/lib/wrap-neon-error.js.map +1 -0
  56. package/dist/v1.d.ts +211 -0
  57. package/dist/v1.d.ts.map +1 -0
  58. package/dist/v1.js +82 -0
  59. package/dist/v1.js.map +1 -0
  60. package/package.json +57 -18
package/LICENSE.md ADDED
@@ -0,0 +1,178 @@
1
+ # Apache License 2.0
2
+
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work
134
+ by You to the Licensor shall be under the terms and conditions of
135
+ this License, without any additional terms or conditions.
136
+ Notwithstanding the above, nothing herein shall supersede or modify
137
+ the terms of any separate license agreement you may have executed
138
+ with Licensor regarding such Contributions.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for reasonable and customary use in describing the
143
+ origin of the Work and reproducing the content of the NOTICE file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this License.
154
+
155
+ 8. Limitation of Liability. In no event and under no legal theory,
156
+ whether in tort (including negligence), contract, or otherwise,
157
+ unless required by applicable law (such as deliberate and grossly
158
+ negligent acts) or agreed to in writing, shall any Contributor be
159
+ liable to You for damages, including any direct, indirect, special,
160
+ incidental, or consequential damages of any character arising as a
161
+ result of this License or out of the use or inability to use the
162
+ Work (including but not limited to damages for loss of goodwill,
163
+ work stoppage, computer failure or malfunction, or any and all
164
+ other commercial damages or losses), even if such Contributor
165
+ has been advised of the possibility of such damages.
166
+
167
+ 9. Accepting Warranty or Additional Liability. While redistributing
168
+ the Work or Derivative Works thereof, You may choose to offer,
169
+ and charge a fee for, acceptance of support, warranty, indemnity,
170
+ or other liability obligations and/or rights consistent with this
171
+ License. However, in accepting such obligations, You may act only
172
+ on Your own behalf and on Your sole responsibility, not on behalf
173
+ of any other Contributor, and only if You agree to indemnify,
174
+ defend, and hold each Contributor harmless for any liability
175
+ incurred by, or claims asserted against, such Contributor by reason
176
+ of your accepting any such warranty or additional liability.
177
+
178
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,148 @@
1
+ # @neon/config
2
+
3
+ Config-as-Code for the Neon Platform. A repo-local `neon.ts` exports a TypeScript policy function describing a branch's desired state. This package exposes **functions** to inspect, diff, and deploy that policy against the Neon API.
4
+
5
+ > No CLI commands ship here, and the package is **filesystem- and env-agnostic**: it never reads `.neon` files or `NEON_*` environment variables. You pass `projectId` and the target branch explicitly (resolve them in your CLI, e.g. neonctl). This package is functions only.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @neon/config
11
+ ```
12
+
13
+ > **Requirements:** Node.js >= 20.19.
14
+
15
+ ## Define a policy
16
+
17
+ ```ts
18
+ // neon.ts
19
+ import { defineConfig } from "@neon/config/v1";
20
+
21
+ export default defineConfig({
22
+ // Static: what *exists* on every branch. GA service toggles drive the typed env.
23
+ auth: true,
24
+ dataApi: false,
25
+ // Beta (Preview) features, keyed by slug / name.
26
+ preview: {
27
+ functions: {
28
+ hello: { name: "Hello", source: "./functions/hello.ts", dev: { port: 8787 } },
29
+ },
30
+ },
31
+ // Dynamic: per-branch tuning only. Cannot add/remove services or functions.
32
+ branch: (branch) => ({
33
+ protected: branch.name === "main",
34
+ ...(branch.name === "main" ? {} : { parent: "main", ttl: "7d" }),
35
+ }),
36
+ });
37
+ ```
38
+
39
+ A policy is split into a **static** existential set and a **dynamic** `branch` closure:
40
+
41
+ - **Static top-level** — `auth` / `dataApi` (GA service toggles) and the beta `preview` block (`aiGateway`, `functions` keyed by slug, `buckets` keyed by name). Because this is static, the secret set is known at the type level, so `parseEnv` / `fetchEnv` from `@neon/env` return an exact `NeonEnv`.
42
+ - **`branch` closure** — receives a **read-only descriptor** (`BranchTarget`) of the branch being evaluated (`name`, `id`, `exists`, `isDefault`, `isProtected`, `parentId`, `expiresAt`) and returns per-branch *tuning*: `parent`, `ttl`, `protected`, `postgres.computeSettings`, and per-function `runtime`. Function memory is fixed at `2048` MiB for now and is not user-configurable. It runs both against existing branches and during pre-create evaluation (`exists: false`). It **cannot** change which services or functions exist — that is what keeps the static secret set sound.
43
+
44
+ Service toggles accept `true` / `{}` / `{ enabled: true }` (enabled) and `false` / `{ enabled: false }` (disabled). Function slugs (record keys) must match `^[a-z0-9]{1,20}$`.
45
+
46
+ ### Data API
47
+
48
+ `dataApi` accepts the same boolean/toggle forms **or** an object that selects the auth provider and reusable runtime `settings`:
49
+
50
+ ```ts
51
+ export default defineConfig({
52
+ auth: true, // required when the Data API verifies Neon Auth tokens
53
+ dataApi: {
54
+ // "neon" (default) verifies Neon Auth tokens; "external" verifies a third-party IdP.
55
+ authProvider: "neon",
56
+ settings: {
57
+ dbSchemas: ["public", "api"],
58
+ dbMaxRows: 1000,
59
+ // dbAnonRole, dbExtraSearchPath, jwtRoleClaimKey, jwtCacheMaxLifetime,
60
+ // openapiMode ("ignore-privileges" | "disabled"), serverCorsAllowedOrigins,
61
+ // serverTimingEnabled — all optional, camelCase mirrors of the Neon API.
62
+ },
63
+ },
64
+ });
65
+ ```
66
+
67
+ ```ts
68
+ // External IdP (Clerk / Stytch / Auth0 / …): you provide the JWKS wiring, and no Neon Auth is required.
69
+ export default defineConfig({
70
+ dataApi: {
71
+ authProvider: "external",
72
+ jwksUrl: "https://your-idp.example.com/.well-known/jwks.json",
73
+ providerName: "Clerk", // optional label
74
+ jwtAudience: "my-api", // optional; only *rejects* tokens with a different `aud`
75
+ settings: { dbSchemas: ["public"] },
76
+ },
77
+ });
78
+ ```
79
+
80
+ Two invariants are enforced **both** at author time (TypeScript) and at runtime (zod):
81
+
82
+ - **`authProvider: "neon"` requires Neon Auth.** A Neon-verified Data API needs `auth` enabled on the same branch (so the tokens it verifies exist). `jwksUrl` / `providerName` / `jwtAudience` are forbidden on this variant — Neon supplies them.
83
+ - **`authProvider: "external"`** is where `jwksUrl` / `providerName` / `jwtAudience` live, and it does **not** require Neon Auth.
84
+
85
+ The auth wiring (`authProvider`, `jwksUrl`, …) is set when the Data API is first **enabled** and is immutable afterwards. The runtime `settings` are reconcilable: changing them is treated as an **update** and requires `updateExisting: true` (`apply`) / `--update-existing` (CLI), like compute/TTL/`protected` drift.
86
+
87
+ ## Functions
88
+
89
+ The three operations mirror the Terraform mental model: **`inspect`** (read live state), **`plan`** (dry-run diff), **`apply`** (reconcile).
90
+
91
+ `projectId` and `branchId` are **required** — there is no `.neon`/env fallback. (`projectId` is required because the Neon management API addresses every branch through its project; deriving it from a branch id would need an extra discovery round-trip.)
92
+
93
+ ```ts
94
+ import config from "../neon";
95
+ import { inspect, plan, apply } from "@neon/config/v1";
96
+
97
+ const target = { projectId: "patient-art-12345", branchId: "main" };
98
+
99
+ // Dry-run: what would apply do for this branch? No mutations.
100
+ const diff = await plan(config, target);
101
+
102
+ // Apply the policy to a branch. Never creates projects/branches.
103
+ await apply(config, { ...target, updateExisting: true });
104
+
105
+ // Read a branch's live Neon state as a plain object.
106
+ const live = await inspect(target);
107
+ ```
108
+
109
+ | Function | Description |
110
+ | --- | --- |
111
+ | `inspect(options)` | Returns the branch's live Neon state (project + branch metadata and a reverse-engineered `BranchConfig`). Read-only. |
112
+ | `plan(config, options)` | Returns the dry-run diff — what `apply` would do for the branch, with no mutations. Returns a `PushResult` whose `applied` holds the plan and `conflicts` holds blocking drift. |
113
+ | `apply(config, options)` | Reconciles your local `neon.ts` policy onto the branch. Pass `updateExisting` to auto-confirm overriding existing remote settings and `allowProtectedBranch` to auto-confirm applying to a protected branch. |
114
+
115
+ `options` requires both `projectId` and `branchId` (a Neon branch id, `br-…`). Resolve branch names to ids before calling. The Neon API key resolves via the `apiKey` option → `NEON_API_KEY` → `~/.config/neonctl/credentials.json`.
116
+
117
+ ## Lower-level engine
118
+
119
+ `inspect` / `plan` / `apply` are thin wrappers over `pullConfig(options)` / `pushConfig(config, options)` (both require `projectId` + `branchId`), which are also exported for advanced/programmatic use along with `defineConfig`, `loadConfigFromFile` (optional `neon.ts` loader), `createRealNeonApi`, the `PlatformError` base class + `ErrorCode` enum, the `errors` and `schemas` namespaces, and the supporting types.
120
+
121
+ ```ts
122
+ import {
123
+ defineConfig,
124
+ inspect,
125
+ plan,
126
+ apply,
127
+ pushConfig,
128
+ pullConfig,
129
+ loadConfigFromFile,
130
+ createRealNeonApi,
131
+ resolveApiKey,
132
+ PlatformError,
133
+ ErrorCode,
134
+ errors,
135
+ schemas,
136
+ } from "@neon/config/v1";
137
+ ```
138
+
139
+ ## Safety Rules
140
+
141
+ - `apply` / `pushConfig` never creates projects or branches.
142
+ - `auth: {}` and `dataApi: {}` enable those integrations with Neon defaults. `auth.enabled: false`, `dataApi.enabled: false`, or absence leaves existing integrations alone. Disabling is destructive and remains explicit/manual.
143
+ - Mutable branch drift (`protected`, `ttl`, `postgres.computeSettings`) is reported as a conflict unless `updateExisting` is passed (or a `confirm` callback is supplied to `pushConfig`).
144
+ - Applying to a branch with the `protected` flag set on Neon requires `allowProtectedBranch` (or a `confirm` callback).
145
+
146
+ ## Env vars
147
+
148
+ Connection-string resolution/injection lives in the companion package [`@neon/env`](../env), which depends on this package for the `Config` type and the Neon API client.
@@ -0,0 +1,11 @@
1
+ import { AppliedChange, BranchTarget, BranchTuning, BranchTuningFn, BucketAccessLevel, BucketDef, ComputeSettings, ComputeUnit, Config, ConflictReport, CredentialPrincipalType, CredentialScope, DATA_API_AUTH_PROVIDERS, DataApiAuthProvider, DataApiConfig, DataApiExternalAuthConfig, DataApiInput, DataApiNeonAuthConfig, DataApiSettings, DurationString, DurationUnit, FunctionDef, FunctionDevConfig, FunctionRuntime, FunctionTuning, PostgresConfig, PreviewInput, PreviewTuning, PushResult, ResolvedBranchConfig, ResolvedBucketConfig, ResolvedDataApiConfig, ResolvedFunctionConfig, ResolvedPreviewConfig, ServiceEnabled, ServiceToggle, ServiceToggleInput } from "./lib/types.js";
2
+ import { ConfigLoadError, ConfigValidationError, ErrorCode, MissingContextError, PlatformError, PushAbortedError, PushConflictError, isPlatformError } from "./lib/errors.js";
3
+ import { CreateBranchInput, CreateBucketInput, CreateCredentialInput, CreateProjectInput, DeployFunctionInput, EnableDataApiInput, GetConnectionUriInput, NeonApi, NeonAuthSnapshot, NeonBranchSnapshot, NeonBranchStorageSnapshot, NeonBucketSnapshot, NeonCredentialMeta, NeonCredentialSecret, NeonDataApiSnapshot, NeonDatabaseSnapshot, NeonEndpointSnapshot, NeonFunctionDeploymentSnapshot, NeonFunctionSnapshot, NeonProjectSnapshot, NeonRoleSnapshot, UpdateBranchInput } from "./lib/neon-api.js";
4
+ import { createNeonApiFromOptions, resolveApiKey } from "./lib/auth.js";
5
+ import { CredentialFeatureFlags, credentialScopesSatisfied, deriveCredentialScopes } from "./lib/credentials.js";
6
+ import { defineConfig, resolveConfig } from "./lib/define-config.js";
7
+ import { DiffOptions, DiffResult, PlanStep, RemotePreviewState, RemoteServiceState, RemoteState, diffConfig } from "./lib/diff.js";
8
+ import { LoadConfigOptions, loadConfigFromFile } from "./lib/loader.js";
9
+ import { createRealNeonApi } from "./lib/neon-api-real.js";
10
+ import { errors, schemas } from "./v1.js";
11
+ export { AppliedChange, BranchTarget, BranchTuning, BranchTuningFn, BucketAccessLevel, BucketDef, ComputeSettings, ComputeUnit, Config, ConfigLoadError, ConfigValidationError, ConflictReport, CreateBranchInput, CreateBucketInput, CreateCredentialInput, CreateProjectInput, CredentialFeatureFlags, CredentialPrincipalType, CredentialScope, DATA_API_AUTH_PROVIDERS, DataApiAuthProvider, DataApiConfig, DataApiExternalAuthConfig, DataApiInput, DataApiNeonAuthConfig, DataApiSettings, DeployFunctionInput, DiffOptions, DiffResult, DurationString, DurationUnit, EnableDataApiInput, ErrorCode, FunctionDef, FunctionDevConfig, FunctionRuntime, FunctionTuning, GetConnectionUriInput, LoadConfigOptions, MissingContextError, NeonApi, NeonAuthSnapshot, NeonBranchSnapshot, NeonBranchStorageSnapshot, NeonBucketSnapshot, NeonCredentialMeta, NeonCredentialSecret, NeonDataApiSnapshot, NeonDatabaseSnapshot, NeonEndpointSnapshot, NeonFunctionDeploymentSnapshot, NeonFunctionSnapshot, NeonProjectSnapshot, NeonRoleSnapshot, PlanStep, PlatformError, PostgresConfig, PreviewInput, PreviewTuning, PushAbortedError, PushConflictError, PushResult, RemotePreviewState, RemoteServiceState, RemoteState, ResolvedBranchConfig, ResolvedBucketConfig, ResolvedDataApiConfig, ResolvedFunctionConfig, ResolvedPreviewConfig, ServiceEnabled, ServiceToggle, ServiceToggleInput, UpdateBranchInput, createNeonApiFromOptions, createRealNeonApi, credentialScopesSatisfied, defineConfig, deriveCredentialScopes, diffConfig, errors, isPlatformError, loadConfigFromFile, resolveApiKey, resolveConfig, schemas };
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ import { ConfigLoadError, ConfigValidationError, ErrorCode, MissingContextError, PlatformError, PushAbortedError, PushConflictError, isPlatformError } from "./lib/errors.js";
2
+ import { createRealNeonApi } from "./lib/neon-api-real.js";
3
+ import { createNeonApiFromOptions, resolveApiKey } from "./lib/auth.js";
4
+ import { credentialScopesSatisfied, deriveCredentialScopes } from "./lib/credentials.js";
5
+ import { defineConfig, resolveConfig } from "./lib/define-config.js";
6
+ import { diffConfig } from "./lib/diff.js";
7
+ import { loadConfigFromFile } from "./lib/loader.js";
8
+ import { DATA_API_AUTH_PROVIDERS } from "./lib/types.js";
9
+ import { errors, schemas } from "./v1.js";
10
+ export { ConfigLoadError, ConfigValidationError, DATA_API_AUTH_PROVIDERS, ErrorCode, MissingContextError, PlatformError, PushAbortedError, PushConflictError, createNeonApiFromOptions, createRealNeonApi, credentialScopesSatisfied, defineConfig, deriveCredentialScopes, diffConfig, errors, isPlatformError, loadConfigFromFile, resolveApiKey, resolveConfig, schemas };
@@ -0,0 +1,67 @@
1
+ import { NeonApi } from "./neon-api.js";
2
+
3
+ //#region src/lib/auth.d.ts
4
+
5
+ /**
6
+ * Minimal shape of `~/.config/neonctl/credentials.json` we read. `neonctl` writes more
7
+ * fields (refresh_token, expires_at, …) but only `access_token` is what we need — it's a
8
+ * Bearer token the Neon API accepts on the same endpoints `napi_*` API keys do.
9
+ */
10
+ interface NeonctlCredentials {
11
+ access_token: string;
12
+ [key: string]: unknown;
13
+ }
14
+ /**
15
+ * Locate and read the OAuth credentials neonctl writes after `neon auth`.
16
+ *
17
+ * Resolution:
18
+ * 1. `options.configDir` (explicit override — mirrors neonctl's `--config-dir` flag).
19
+ * 2. `NEONCTL_CONFIG_DIR` environment variable.
20
+ * 3. `<home>/.config/neonctl/credentials.json` (the neonctl default; `home` reads
21
+ * `HOME`, falling back to `USERPROFILE` for Windows parity).
22
+ *
23
+ * Returns `null` (never throws) when the file is missing, unreadable, malformed, or has
24
+ * no `access_token` — so callers can use this as a quiet fallback in a resolution chain
25
+ * without try/catch noise.
26
+ */
27
+ declare function readNeonctlCredentials(options?: {
28
+ configDir?: string;
29
+ }): NeonctlCredentials | null;
30
+ /**
31
+ * Resolution chain for the Bearer token sent to the Neon API. Each entry wins over the
32
+ * next:
33
+ *
34
+ * 1. `options.apiKey` (explicit).
35
+ * 2. `NEON_API_KEY` environment variable.
36
+ * 3. `access_token` from `~/.config/neonctl/credentials.json` (or `NEONCTL_CONFIG_DIR`).
37
+ *
38
+ * Returns `null` when no source provides one. Callers wrap the null case in a
39
+ * `PLATFORM_MISSING_API_KEY` error with a message tailored to the operation.
40
+ */
41
+ declare function resolveApiKey(options?: {
42
+ apiKey?: string;
43
+ configDir?: string;
44
+ }): {
45
+ token: string;
46
+ source: "option" | "env" | "neonctl";
47
+ } | null;
48
+ /**
49
+ * Resolve the Neon API key via the standard chain (option → `NEON_API_KEY` env →
50
+ * `~/.config/neonctl/credentials.json`) and construct a real {@link NeonApi} adapter from
51
+ * it, or throw a uniform `PLATFORM_MISSING_API_KEY` error if no key can be found.
52
+ *
53
+ * The API host is resolved via: `options.apiHost` → `NEON_API_HOST` env → production
54
+ * default (`https://console.neon.tech/api/v2`).
55
+ *
56
+ * Used by `pullConfig`, `pushConfig`, `fetchEnv`, and `branch` to build their default
57
+ * `NeonApi` when the caller doesn't inject one. `operation` is the calling function's
58
+ * name (e.g. `"pushConfig"`, `"branch"`) — it's prepended to the error message so users
59
+ * can tell which call surfaced the missing key.
60
+ */
61
+ declare function createNeonApiFromOptions(operation: string, options?: {
62
+ apiKey?: string;
63
+ apiHost?: string;
64
+ }): NeonApi;
65
+ //#endregion
66
+ export { NeonctlCredentials, createNeonApiFromOptions, readNeonctlCredentials, resolveApiKey };
67
+ //# sourceMappingURL=auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.d.ts","names":[],"sources":["../../src/lib/auth.ts"],"mappings":";;;;;;AAWA;AAkBA;AA8CA;AAsCgB,UAtGC,kBAAA,CAsGuB;;;;;;;;;;;;;;;;;iBApFxB,sBAAA;;IAEb;;;;;;;;;;;;iBA4Ca,aAAA;;;;;;;;;;;;;;;;;;;;iBAsCA,wBAAA;;;IAMb"}
@@ -0,0 +1,107 @@
1
+ import { ErrorCode, PlatformError } from "./errors.js";
2
+ import { createRealNeonApi } from "./neon-api-real.js";
3
+ import { existsSync, readFileSync } from "node:fs";
4
+ import { resolve } from "node:path";
5
+ //#region src/lib/auth.ts
6
+ /**
7
+ * Locate and read the OAuth credentials neonctl writes after `neon auth`.
8
+ *
9
+ * Resolution:
10
+ * 1. `options.configDir` (explicit override — mirrors neonctl's `--config-dir` flag).
11
+ * 2. `NEONCTL_CONFIG_DIR` environment variable.
12
+ * 3. `<home>/.config/neonctl/credentials.json` (the neonctl default; `home` reads
13
+ * `HOME`, falling back to `USERPROFILE` for Windows parity).
14
+ *
15
+ * Returns `null` (never throws) when the file is missing, unreadable, malformed, or has
16
+ * no `access_token` — so callers can use this as a quiet fallback in a resolution chain
17
+ * without try/catch noise.
18
+ */
19
+ function readNeonctlCredentials(options = {}) {
20
+ const home = process.env.HOME ?? process.env.USERPROFILE;
21
+ const configDir = options.configDir ?? process.env.NEONCTL_CONFIG_DIR ?? (home ? resolve(home, ".config", "neonctl") : void 0);
22
+ if (!configDir) return null;
23
+ const credentialsPath = resolve(configDir, "credentials.json");
24
+ if (!existsSync(credentialsPath)) return null;
25
+ let raw;
26
+ try {
27
+ raw = readFileSync(credentialsPath, "utf-8");
28
+ } catch {
29
+ return null;
30
+ }
31
+ let parsed;
32
+ try {
33
+ parsed = JSON.parse(raw);
34
+ } catch {
35
+ return null;
36
+ }
37
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
38
+ const obj = parsed;
39
+ if (typeof obj.access_token !== "string" || obj.access_token === "") return null;
40
+ return obj;
41
+ }
42
+ /**
43
+ * Resolution chain for the Bearer token sent to the Neon API. Each entry wins over the
44
+ * next:
45
+ *
46
+ * 1. `options.apiKey` (explicit).
47
+ * 2. `NEON_API_KEY` environment variable.
48
+ * 3. `access_token` from `~/.config/neonctl/credentials.json` (or `NEONCTL_CONFIG_DIR`).
49
+ *
50
+ * Returns `null` when no source provides one. Callers wrap the null case in a
51
+ * `PLATFORM_MISSING_API_KEY` error with a message tailored to the operation.
52
+ */
53
+ function resolveApiKey(options = {}) {
54
+ if (options.apiKey && options.apiKey.trim() !== "") return {
55
+ token: options.apiKey.trim(),
56
+ source: "option"
57
+ };
58
+ const envKey = process.env.NEON_API_KEY;
59
+ if (typeof envKey === "string" && envKey.trim() !== "") return {
60
+ token: envKey.trim(),
61
+ source: "env"
62
+ };
63
+ const creds = readNeonctlCredentials(options.configDir ? { configDir: options.configDir } : {});
64
+ if (creds) return {
65
+ token: creds.access_token,
66
+ source: "neonctl"
67
+ };
68
+ return null;
69
+ }
70
+ /** Trim trailing slashes and surrounding whitespace; treat empty as unset. */
71
+ function normalizeApiHost(url) {
72
+ const trimmed = url?.trim().replace(/\/+$/, "");
73
+ return trimmed ? trimmed : void 0;
74
+ }
75
+ /**
76
+ * Resolve the Neon API key via the standard chain (option → `NEON_API_KEY` env →
77
+ * `~/.config/neonctl/credentials.json`) and construct a real {@link NeonApi} adapter from
78
+ * it, or throw a uniform `PLATFORM_MISSING_API_KEY` error if no key can be found.
79
+ *
80
+ * The API host is resolved via: `options.apiHost` → `NEON_API_HOST` env → production
81
+ * default (`https://console.neon.tech/api/v2`).
82
+ *
83
+ * Used by `pullConfig`, `pushConfig`, `fetchEnv`, and `branch` to build their default
84
+ * `NeonApi` when the caller doesn't inject one. `operation` is the calling function's
85
+ * name (e.g. `"pushConfig"`, `"branch"`) — it's prepended to the error message so users
86
+ * can tell which call surfaced the missing key.
87
+ */
88
+ function createNeonApiFromOptions(operation, options = {}) {
89
+ const resolved = resolveApiKey(options.apiKey ? { apiKey: options.apiKey } : {});
90
+ if (resolved) {
91
+ const baseUrl = normalizeApiHost(options.apiHost) ?? normalizeApiHost(process.env.NEON_API_HOST);
92
+ return createRealNeonApi({
93
+ apiKey: resolved.token,
94
+ ...baseUrl ? { baseUrl } : {}
95
+ });
96
+ }
97
+ throw new PlatformError(ErrorCode.MissingApiKey, [
98
+ `${operation} has no Neon API key to work with.`,
99
+ "Tried (in order): `apiKey` option, NEON_API_KEY env, and `~/.config/neonctl/credentials.json`.",
100
+ "Either pass `apiKey` directly, set NEON_API_KEY, run `npx neonctl auth` to populate the credentials file, or pass a custom `api` adapter (e.g. an in-memory fake for tests).",
101
+ "Generate a key at https://console.neon.tech/app/settings/api-keys."
102
+ ].join(" "));
103
+ }
104
+ //#endregion
105
+ export { createNeonApiFromOptions, readNeonctlCredentials, resolveApiKey };
106
+
107
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","names":[],"sources":["../../src/lib/auth.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { ErrorCode, PlatformError } from \"./errors.js\";\nimport type { NeonApi } from \"./neon-api.js\";\nimport { createRealNeonApi } from \"./neon-api-real.js\";\n\n/**\n * Minimal shape of `~/.config/neonctl/credentials.json` we read. `neonctl` writes more\n * fields (refresh_token, expires_at, …) but only `access_token` is what we need — it's a\n * Bearer token the Neon API accepts on the same endpoints `napi_*` API keys do.\n */\nexport interface NeonctlCredentials {\n\taccess_token: string;\n\t[key: string]: unknown;\n}\n\n/**\n * Locate and read the OAuth credentials neonctl writes after `neon auth`.\n *\n * Resolution:\n * 1. `options.configDir` (explicit override — mirrors neonctl's `--config-dir` flag).\n * 2. `NEONCTL_CONFIG_DIR` environment variable.\n * 3. `<home>/.config/neonctl/credentials.json` (the neonctl default; `home` reads\n * `HOME`, falling back to `USERPROFILE` for Windows parity).\n *\n * Returns `null` (never throws) when the file is missing, unreadable, malformed, or has\n * no `access_token` — so callers can use this as a quiet fallback in a resolution chain\n * without try/catch noise.\n */\nexport function readNeonctlCredentials(\n\toptions: { configDir?: string } = {},\n): NeonctlCredentials | null {\n\tconst home = process.env.HOME ?? process.env.USERPROFILE;\n\tconst configDir =\n\t\toptions.configDir ??\n\t\tprocess.env.NEONCTL_CONFIG_DIR ??\n\t\t(home ? resolve(home, \".config\", \"neonctl\") : undefined);\n\tif (!configDir) return null;\n\n\tconst credentialsPath = resolve(configDir, \"credentials.json\");\n\tif (!existsSync(credentialsPath)) return null;\n\n\tlet raw: string;\n\ttry {\n\t\traw = readFileSync(credentialsPath, \"utf-8\");\n\t} catch {\n\t\treturn null;\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch {\n\t\treturn null;\n\t}\n\n\tif (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed))\n\t\treturn null;\n\tconst obj = parsed as Record<string, unknown>;\n\tif (typeof obj.access_token !== \"string\" || obj.access_token === \"\")\n\t\treturn null;\n\treturn obj as NeonctlCredentials;\n}\n\n/**\n * Resolution chain for the Bearer token sent to the Neon API. Each entry wins over the\n * next:\n *\n * 1. `options.apiKey` (explicit).\n * 2. `NEON_API_KEY` environment variable.\n * 3. `access_token` from `~/.config/neonctl/credentials.json` (or `NEONCTL_CONFIG_DIR`).\n *\n * Returns `null` when no source provides one. Callers wrap the null case in a\n * `PLATFORM_MISSING_API_KEY` error with a message tailored to the operation.\n */\nexport function resolveApiKey(\n\toptions: { apiKey?: string; configDir?: string } = {},\n): { token: string; source: \"option\" | \"env\" | \"neonctl\" } | null {\n\tif (options.apiKey && options.apiKey.trim() !== \"\") {\n\t\treturn { token: options.apiKey.trim(), source: \"option\" };\n\t}\n\tconst envKey = process.env.NEON_API_KEY;\n\tif (typeof envKey === \"string\" && envKey.trim() !== \"\") {\n\t\treturn { token: envKey.trim(), source: \"env\" };\n\t}\n\tconst creds = readNeonctlCredentials(\n\t\toptions.configDir ? { configDir: options.configDir } : {},\n\t);\n\tif (creds) {\n\t\treturn { token: creds.access_token, source: \"neonctl\" };\n\t}\n\treturn null;\n}\n\n/** Trim trailing slashes and surrounding whitespace; treat empty as unset. */\nfunction normalizeApiHost(url: string | undefined): string | undefined {\n\tconst trimmed = url?.trim().replace(/\\/+$/, \"\");\n\treturn trimmed ? trimmed : undefined;\n}\n\n/**\n * Resolve the Neon API key via the standard chain (option → `NEON_API_KEY` env →\n * `~/.config/neonctl/credentials.json`) and construct a real {@link NeonApi} adapter from\n * it, or throw a uniform `PLATFORM_MISSING_API_KEY` error if no key can be found.\n *\n * The API host is resolved via: `options.apiHost` → `NEON_API_HOST` env → production\n * default (`https://console.neon.tech/api/v2`).\n *\n * Used by `pullConfig`, `pushConfig`, `fetchEnv`, and `branch` to build their default\n * `NeonApi` when the caller doesn't inject one. `operation` is the calling function's\n * name (e.g. `\"pushConfig\"`, `\"branch\"`) — it's prepended to the error message so users\n * can tell which call surfaced the missing key.\n */\nexport function createNeonApiFromOptions(\n\toperation: string,\n\toptions: {\n\t\tapiKey?: string;\n\t\tapiHost?: string;\n\t} = {},\n): NeonApi {\n\tconst resolved = resolveApiKey(\n\t\toptions.apiKey ? { apiKey: options.apiKey } : {},\n\t);\n\tif (resolved) {\n\t\tconst baseUrl =\n\t\t\tnormalizeApiHost(options.apiHost) ??\n\t\t\tnormalizeApiHost(process.env.NEON_API_HOST);\n\t\treturn createRealNeonApi({\n\t\t\tapiKey: resolved.token,\n\t\t\t...(baseUrl ? { baseUrl } : {}),\n\t\t});\n\t}\n\tthrow new PlatformError(\n\t\tErrorCode.MissingApiKey,\n\t\t[\n\t\t\t`${operation} has no Neon API key to work with.`,\n\t\t\t\"Tried (in order): `apiKey` option, NEON_API_KEY env, and `~/.config/neonctl/credentials.json`.\",\n\t\t\t\"Either pass `apiKey` directly, set NEON_API_KEY, run `npx neonctl auth` to populate the credentials file, or pass a custom `api` adapter (e.g. an in-memory fake for tests).\",\n\t\t\t\"Generate a key at https://console.neon.tech/app/settings/api-keys.\",\n\t\t].join(\" \"),\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA6BA,SAAgB,uBACf,UAAkC,CAAC,GACP;CAC5B,MAAM,OAAO,QAAQ,IAAI,QAAQ,QAAQ,IAAI;CAC7C,MAAM,YACL,QAAQ,aACR,QAAQ,IAAI,uBACX,OAAO,QAAQ,MAAM,WAAW,SAAS,IAAI,KAAA;CAC/C,IAAI,CAAC,WAAW,OAAO;CAEvB,MAAM,kBAAkB,QAAQ,WAAW,kBAAkB;CAC7D,IAAI,CAAC,WAAW,eAAe,GAAG,OAAO;CAEzC,IAAI;CACJ,IAAI;EACH,MAAM,aAAa,iBAAiB,OAAO;CAC5C,QAAQ;EACP,OAAO;CACR;CAEA,IAAI;CACJ,IAAI;EACH,SAAS,KAAK,MAAM,GAAG;CACxB,QAAQ;EACP,OAAO;CACR;CAEA,IAAI,WAAW,QAAQ,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,GACxE,OAAO;CACR,MAAM,MAAM;CACZ,IAAI,OAAO,IAAI,iBAAiB,YAAY,IAAI,iBAAiB,IAChE,OAAO;CACR,OAAO;AACR;;;;;;;;;;;;AAaA,SAAgB,cACf,UAAmD,CAAC,GACa;CACjE,IAAI,QAAQ,UAAU,QAAQ,OAAO,KAAK,MAAM,IAC/C,OAAO;EAAE,OAAO,QAAQ,OAAO,KAAK;EAAG,QAAQ;CAAS;CAEzD,MAAM,SAAS,QAAQ,IAAI;CAC3B,IAAI,OAAO,WAAW,YAAY,OAAO,KAAK,MAAM,IACnD,OAAO;EAAE,OAAO,OAAO,KAAK;EAAG,QAAQ;CAAM;CAE9C,MAAM,QAAQ,uBACb,QAAQ,YAAY,EAAE,WAAW,QAAQ,UAAU,IAAI,CAAC,CACzD;CACA,IAAI,OACH,OAAO;EAAE,OAAO,MAAM;EAAc,QAAQ;CAAU;CAEvD,OAAO;AACR;;AAGA,SAAS,iBAAiB,KAA6C;CACtE,MAAM,UAAU,KAAK,KAAK,CAAC,CAAC,QAAQ,QAAQ,EAAE;CAC9C,OAAO,UAAU,UAAU,KAAA;AAC5B;;;;;;;;;;;;;;AAeA,SAAgB,yBACf,WACA,UAGI,CAAC,GACK;CACV,MAAM,WAAW,cAChB,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC,CAChD;CACA,IAAI,UAAU;EACb,MAAM,UACL,iBAAiB,QAAQ,OAAO,KAChC,iBAAiB,QAAQ,IAAI,aAAa;EAC3C,OAAO,kBAAkB;GACxB,QAAQ,SAAS;GACjB,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC;EAC9B,CAAC;CACF;CACA,MAAM,IAAI,cACT,UAAU,eACV;EACC,GAAG,UAAU;EACb;EACA;EACA;CACD,CAAC,CAAC,KAAK,GAAG,CACX;AACD"}
@@ -0,0 +1,37 @@
1
+ import { CredentialScope } from "./types.js";
2
+
3
+ //#region src/lib/credentials.d.ts
4
+
5
+ /**
6
+ * Which branch-scoped Preview features a policy enables, reduced to the booleans that drive
7
+ * credential scopes. Decoupled from the full `Config` / `ResolvedPreviewConfig` shapes so it
8
+ * can be computed from either the static policy (`parseEnv`) or the resolved branch config
9
+ * (`fetchEnv`).
10
+ */
11
+ interface CredentialFeatureFlags {
12
+ /** At least one object-storage bucket is declared (grants `storage:read` + `storage:write`). */
13
+ storage: boolean;
14
+ /** The AI Gateway is enabled (grants `ai_gateway:invoke`). */
15
+ aiGateway: boolean;
16
+ /** At least one Neon Function is declared (grants `functions:invoke`). */
17
+ functions: boolean;
18
+ }
19
+ /**
20
+ * Derive the set of {@link CredentialScope}s a branch credential needs from the policy's
21
+ * enabled Preview features. Deterministic and order-stable (handy for diffing / round-trip
22
+ * comparisons). Returns an empty array when no credential-bearing feature is enabled — the
23
+ * signal that **no credential should be minted** (and the credentials endpoint never
24
+ * touched), which is what keeps the non-Preview path byte-for-byte unchanged.
25
+ */
26
+ declare function deriveCredentialScopes(flags: CredentialFeatureFlags): CredentialScope[];
27
+ /**
28
+ * Whether a credential granted `granted` scopes can satisfy a policy that needs `desired`
29
+ * scopes — i.e. `desired ⊆ granted`. Used to decide whether an already-persisted credential
30
+ * can be **reused** as-is, or must be re-minted because the policy now needs a scope the old
31
+ * credential lacks (e.g. the user added the AI Gateway after first pulling a storage-only
32
+ * credential).
33
+ */
34
+ declare function credentialScopesSatisfied(granted: readonly CredentialScope[], desired: readonly CredentialScope[]): boolean;
35
+ //#endregion
36
+ export { CredentialFeatureFlags, credentialScopesSatisfied, deriveCredentialScopes };
37
+ //# sourceMappingURL=credentials.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credentials.d.ts","names":[],"sources":["../../src/lib/credentials.ts"],"mappings":";;;;;;AAQA;AAgBA;;;AAEG,UAlBc,sBAAA,CAkBd;EAAe;EAqBF,OAAA,EAAA,OAAA;EAAyB;WACtB,EAAA,OAAA;;EACe,SAAA,EAAA,OAAA;;;;;;;;;iBAzBlB,sBAAA,QACR,yBACL;;;;;;;;iBAqBa,yBAAA,mBACG,qCACA"}
@@ -0,0 +1,30 @@
1
+ //#region src/lib/credentials.ts
2
+ /**
3
+ * Derive the set of {@link CredentialScope}s a branch credential needs from the policy's
4
+ * enabled Preview features. Deterministic and order-stable (handy for diffing / round-trip
5
+ * comparisons). Returns an empty array when no credential-bearing feature is enabled — the
6
+ * signal that **no credential should be minted** (and the credentials endpoint never
7
+ * touched), which is what keeps the non-Preview path byte-for-byte unchanged.
8
+ */
9
+ function deriveCredentialScopes(flags) {
10
+ const scopes = [];
11
+ if (flags.storage) scopes.push("storage:read", "storage:write");
12
+ if (flags.aiGateway) scopes.push("ai_gateway:invoke");
13
+ if (flags.functions) scopes.push("functions:invoke");
14
+ return scopes;
15
+ }
16
+ /**
17
+ * Whether a credential granted `granted` scopes can satisfy a policy that needs `desired`
18
+ * scopes — i.e. `desired ⊆ granted`. Used to decide whether an already-persisted credential
19
+ * can be **reused** as-is, or must be re-minted because the policy now needs a scope the old
20
+ * credential lacks (e.g. the user added the AI Gateway after first pulling a storage-only
21
+ * credential).
22
+ */
23
+ function credentialScopesSatisfied(granted, desired) {
24
+ const grantedSet = new Set(granted);
25
+ return desired.every((scope) => grantedSet.has(scope));
26
+ }
27
+ //#endregion
28
+ export { credentialScopesSatisfied, deriveCredentialScopes };
29
+
30
+ //# sourceMappingURL=credentials.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credentials.js","names":[],"sources":["../../src/lib/credentials.ts"],"sourcesContent":["import type { CredentialScope } from \"./types.js\";\n\n/**\n * Which branch-scoped Preview features a policy enables, reduced to the booleans that drive\n * credential scopes. Decoupled from the full `Config` / `ResolvedPreviewConfig` shapes so it\n * can be computed from either the static policy (`parseEnv`) or the resolved branch config\n * (`fetchEnv`).\n */\nexport interface CredentialFeatureFlags {\n\t/** At least one object-storage bucket is declared (grants `storage:read` + `storage:write`). */\n\tstorage: boolean;\n\t/** The AI Gateway is enabled (grants `ai_gateway:invoke`). */\n\taiGateway: boolean;\n\t/** At least one Neon Function is declared (grants `functions:invoke`). */\n\tfunctions: boolean;\n}\n\n/**\n * Derive the set of {@link CredentialScope}s a branch credential needs from the policy's\n * enabled Preview features. Deterministic and order-stable (handy for diffing / round-trip\n * comparisons). Returns an empty array when no credential-bearing feature is enabled — the\n * signal that **no credential should be minted** (and the credentials endpoint never\n * touched), which is what keeps the non-Preview path byte-for-byte unchanged.\n */\nexport function deriveCredentialScopes(\n\tflags: CredentialFeatureFlags,\n): CredentialScope[] {\n\tconst scopes: CredentialScope[] = [];\n\tif (flags.storage) {\n\t\tscopes.push(\"storage:read\", \"storage:write\");\n\t}\n\tif (flags.aiGateway) {\n\t\tscopes.push(\"ai_gateway:invoke\");\n\t}\n\tif (flags.functions) {\n\t\tscopes.push(\"functions:invoke\");\n\t}\n\treturn scopes;\n}\n\n/**\n * Whether a credential granted `granted` scopes can satisfy a policy that needs `desired`\n * scopes — i.e. `desired ⊆ granted`. Used to decide whether an already-persisted credential\n * can be **reused** as-is, or must be re-minted because the policy now needs a scope the old\n * credential lacks (e.g. the user added the AI Gateway after first pulling a storage-only\n * credential).\n */\nexport function credentialScopesSatisfied(\n\tgranted: readonly CredentialScope[],\n\tdesired: readonly CredentialScope[],\n): boolean {\n\tconst grantedSet = new Set(granted);\n\treturn desired.every((scope) => grantedSet.has(scope));\n}\n"],"mappings":";;;;;;;;AAwBA,SAAgB,uBACf,OACoB;CACpB,MAAM,SAA4B,CAAC;CACnC,IAAI,MAAM,SACT,OAAO,KAAK,gBAAgB,eAAe;CAE5C,IAAI,MAAM,WACT,OAAO,KAAK,mBAAmB;CAEhC,IAAI,MAAM,WACT,OAAO,KAAK,kBAAkB;CAE/B,OAAO;AACR;;;;;;;;AASA,SAAgB,0BACf,SACA,SACU;CACV,MAAM,aAAa,IAAI,IAAI,OAAO;CAClC,OAAO,QAAQ,OAAO,UAAU,WAAW,IAAI,KAAK,CAAC;AACtD"}