@neon/config-runtime 0.0.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +178 -0
- package/README.md +24 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/lib/function-bundle.d.ts +40 -0
- package/dist/lib/function-bundle.d.ts.map +1 -0
- package/dist/lib/function-bundle.js +78 -0
- package/dist/lib/function-bundle.js.map +1 -0
- package/dist/lib/operations.d.ts +125 -0
- package/dist/lib/operations.d.ts.map +1 -0
- package/dist/lib/operations.js +133 -0
- package/dist/lib/operations.js.map +1 -0
- package/dist/lib/pull-config.d.ts +81 -0
- package/dist/lib/pull-config.d.ts.map +1 -0
- package/dist/lib/pull-config.js +132 -0
- package/dist/lib/pull-config.js.map +1 -0
- package/dist/lib/push-config.d.ts +124 -0
- package/dist/lib/push-config.d.ts.map +1 -0
- package/dist/lib/push-config.js +405 -0
- package/dist/lib/push-config.js.map +1 -0
- package/dist/v1.d.ts +6 -0
- package/dist/v1.js +6 -0
- package/package.json +58 -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,24 @@
|
|
|
1
|
+
# @neon/config-runtime
|
|
2
|
+
|
|
3
|
+
Imperative runtime for [`@neon/config`](../config): run a `neon.ts` policy against the Neon API — `inspect`, `plan`, `apply` (push/pull) — and bundle + deploy Neon Functions.
|
|
4
|
+
|
|
5
|
+
> This package pulls in `esbuild`, so import it from your CLI or CI — **not** from a `neon.ts` policy. Keep policies side-effect-free; that's what `@neon/config` is for. New code should import from `@neon/config-runtime/v1` to pin a major.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @neon/config-runtime
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## API
|
|
14
|
+
|
|
15
|
+
- `inspect` / `plan` / `apply` — read the current branch state, diff a policy against it, and apply the changes.
|
|
16
|
+
- `pullConfig` / `pushConfig` — lower-level pull/push primitives.
|
|
17
|
+
- `createBranch` — create a branch to target.
|
|
18
|
+
- `buildFunctionBundle` — bundle Neon Functions for deploy.
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import { inspect, plan, apply } from "@neon/config-runtime/v1";
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
See [`@neon/config`](../config) for authoring the `neon.ts` policy these operate on.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { FunctionBundler, buildFunctionBundle } from "./lib/function-bundle.js";
|
|
2
|
+
import { PullConfigOptions, PulledBranchConfig, PulledPreview, pullConfig } from "./lib/pull-config.js";
|
|
3
|
+
import { PushConfigOptions, PushConfirmContext, pushConfig } from "./lib/push-config.js";
|
|
4
|
+
import { ApplyOptions, ConfigOperationOptions, CreateBranchOptions, CreateBranchResult, apply, createBranch, inspect, plan } from "./lib/operations.js";
|
|
5
|
+
import { AppliedChange, Config, ConfigLoadError, ConfigValidationError, ConflictReport, ErrorCode, LoadConfigOptions, MissingContextError, NeonApi, PlatformError, PushAbortedError, PushConflictError, PushResult, createNeonApiFromOptions, createRealNeonApi, defineConfig, isPlatformError, loadConfigFromFile } from "./v1.js";
|
|
6
|
+
export { AppliedChange, ApplyOptions, Config, ConfigLoadError, ConfigOperationOptions, ConfigValidationError, ConflictReport, CreateBranchOptions, CreateBranchResult, ErrorCode, FunctionBundler, LoadConfigOptions, MissingContextError, NeonApi, PlatformError, PullConfigOptions, PulledBranchConfig, PulledPreview, PushAbortedError, PushConfigOptions, PushConfirmContext, PushConflictError, PushResult, apply, buildFunctionBundle, createBranch, createNeonApiFromOptions, createRealNeonApi, defineConfig, inspect, isPlatformError, loadConfigFromFile, plan, pullConfig, pushConfig };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { buildFunctionBundle } from "./lib/function-bundle.js";
|
|
2
|
+
import { pullConfig } from "./lib/pull-config.js";
|
|
3
|
+
import { pushConfig } from "./lib/push-config.js";
|
|
4
|
+
import { apply, createBranch, inspect, plan } from "./lib/operations.js";
|
|
5
|
+
import { ConfigLoadError, ConfigValidationError, ErrorCode, MissingContextError, PlatformError, PushAbortedError, PushConflictError, createNeonApiFromOptions, createRealNeonApi, defineConfig, isPlatformError, loadConfigFromFile } from "./v1.js";
|
|
6
|
+
export { ConfigLoadError, ConfigValidationError, ErrorCode, MissingContextError, PlatformError, PushAbortedError, PushConflictError, apply, buildFunctionBundle, createBranch, createNeonApiFromOptions, createRealNeonApi, defineConfig, inspect, isPlatformError, loadConfigFromFile, plan, pullConfig, pushConfig };
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { ResolvedFunctionConfig } from "@neon/config";
|
|
2
|
+
|
|
3
|
+
//#region src/lib/function-bundle.d.ts
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Builds the deployable ZIP bundle for a single function. The default
|
|
7
|
+
* implementation ({@link buildFunctionBundle}) shells out to esbuild, but
|
|
8
|
+
* `pushConfig` / `apply` accept a custom bundler so a consumer that can't ship
|
|
9
|
+
* esbuild's native binary (e.g. a single-file CLI) can supply its own — a WASM
|
|
10
|
+
* build, an esbuild binary on PATH, etc. — without this package dragging esbuild
|
|
11
|
+
* into their bundle.
|
|
12
|
+
*/
|
|
13
|
+
type FunctionBundler = (fn: ResolvedFunctionConfig) => Promise<Uint8Array>;
|
|
14
|
+
/**
|
|
15
|
+
* Build the deployable bundle (a ZIP archive of the esbuild-bundled source) for a function.
|
|
16
|
+
*
|
|
17
|
+
* This is the **imperative shell** step of function deploys, and the reason it lives in
|
|
18
|
+
* `@neon/config-runtime` rather than `@neon/config`: it pulls in `esbuild`
|
|
19
|
+
* (a native binary) and `fflate`. Keeping it out of `@neon/config` means a `neon.ts`
|
|
20
|
+
* that only imports `defineConfig` never drags esbuild into the user's dependency tree or
|
|
21
|
+
* bundle. Deploy-side consumers (the neonctl CLI, CI) import this package and get esbuild as
|
|
22
|
+
* a normal, auto-installed dependency.
|
|
23
|
+
*
|
|
24
|
+
* esbuild and fflate are loaded with a dynamic `import()` (not a static top-level import) so
|
|
25
|
+
* that nothing in this package's static graph names esbuild until a deploy actually runs —
|
|
26
|
+
* a second layer of protection on top of the package split.
|
|
27
|
+
*
|
|
28
|
+
* Mirrors: `esbuild <source> --bundle --outfile=index.mjs --minify --format=esm
|
|
29
|
+
* --platform=node --banner:js=<createRequire shim>`, then zips the emitted files into the
|
|
30
|
+
* archive the Functions deploy endpoint expects. Dependencies are bundled into the entry
|
|
31
|
+
* (Node built-ins stay external); see {@link ESM_CJS_INTEROP_BANNER} for why the banner.
|
|
32
|
+
*
|
|
33
|
+
* No source map is emitted: the Functions runtime does not run Node with source-map support,
|
|
34
|
+
* so an uploaded `index.mjs.map` is never consumed (a thrown error's stack still points into
|
|
35
|
+
* the minified bundle). Generating it only inflated the deployed archive, so it is omitted.
|
|
36
|
+
*/
|
|
37
|
+
declare function buildFunctionBundle(fn: ResolvedFunctionConfig): Promise<Uint8Array>;
|
|
38
|
+
//#endregion
|
|
39
|
+
export { FunctionBundler, buildFunctionBundle };
|
|
40
|
+
//# sourceMappingURL=function-bundle.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"function-bundle.d.ts","names":[],"sources":["../../src/lib/function-bundle.ts"],"mappings":";;;;;;AAeA;;;;;AAEY;AAmCU,KArCV,eAAA,GAqC6B,CAAA,EAAA,EApCpC,sBAoCoC,EAAA,GAnCpC,OAmCoC,CAnC5B,UAmC4B,CAAA;;;;;AAE/B;;;;;;;;;;;;;;;;;;;iBAFY,mBAAA,KACjB,yBACF,QAAQ"}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { ErrorCode, PlatformError } from "@neon/config";
|
|
2
|
+
import { basename } from "node:path";
|
|
3
|
+
//#region src/lib/function-bundle.ts
|
|
4
|
+
/**
|
|
5
|
+
* Prepended to the ESM bundle. Bundled dependencies are frequently CommonJS, but an ESM
|
|
6
|
+
* output (`format: "esm"`) has no `require` / `__filename` / `__dirname` in scope — so any
|
|
7
|
+
* bundled CJS code that calls `require(...)` would fail at load with
|
|
8
|
+
* `Dynamic require of "x" is not supported`. Re-create those globals via `createRequire`
|
|
9
|
+
* so CJS and ESM dependencies coexist in the single `index.mjs`.
|
|
10
|
+
*/
|
|
11
|
+
const ESM_CJS_INTEROP_BANNER = "import{createRequire as ___cr}from'module';import{fileURLToPath as ___f}from'url';import{dirname as ___d}from'path';const require=___cr(import.meta.url);const __filename=___f(import.meta.url);const __dirname=___d(__filename);";
|
|
12
|
+
/**
|
|
13
|
+
* Build the deployable bundle (a ZIP archive of the esbuild-bundled source) for a function.
|
|
14
|
+
*
|
|
15
|
+
* This is the **imperative shell** step of function deploys, and the reason it lives in
|
|
16
|
+
* `@neon/config-runtime` rather than `@neon/config`: it pulls in `esbuild`
|
|
17
|
+
* (a native binary) and `fflate`. Keeping it out of `@neon/config` means a `neon.ts`
|
|
18
|
+
* that only imports `defineConfig` never drags esbuild into the user's dependency tree or
|
|
19
|
+
* bundle. Deploy-side consumers (the neonctl CLI, CI) import this package and get esbuild as
|
|
20
|
+
* a normal, auto-installed dependency.
|
|
21
|
+
*
|
|
22
|
+
* esbuild and fflate are loaded with a dynamic `import()` (not a static top-level import) so
|
|
23
|
+
* that nothing in this package's static graph names esbuild until a deploy actually runs —
|
|
24
|
+
* a second layer of protection on top of the package split.
|
|
25
|
+
*
|
|
26
|
+
* Mirrors: `esbuild <source> --bundle --outfile=index.mjs --minify --format=esm
|
|
27
|
+
* --platform=node --banner:js=<createRequire shim>`, then zips the emitted files into the
|
|
28
|
+
* archive the Functions deploy endpoint expects. Dependencies are bundled into the entry
|
|
29
|
+
* (Node built-ins stay external); see {@link ESM_CJS_INTEROP_BANNER} for why the banner.
|
|
30
|
+
*
|
|
31
|
+
* No source map is emitted: the Functions runtime does not run Node with source-map support,
|
|
32
|
+
* so an uploaded `index.mjs.map` is never consumed (a thrown error's stack still points into
|
|
33
|
+
* the minified bundle). Generating it only inflated the deployed archive, so it is omitted.
|
|
34
|
+
*/
|
|
35
|
+
async function buildFunctionBundle(fn) {
|
|
36
|
+
const esbuild = await loadEsbuild();
|
|
37
|
+
let result;
|
|
38
|
+
try {
|
|
39
|
+
result = await esbuild.build({
|
|
40
|
+
entryPoints: [fn.source],
|
|
41
|
+
bundle: true,
|
|
42
|
+
write: false,
|
|
43
|
+
outfile: "index.mjs",
|
|
44
|
+
minify: true,
|
|
45
|
+
format: "esm",
|
|
46
|
+
platform: "node",
|
|
47
|
+
banner: { js: ESM_CJS_INTEROP_BANNER },
|
|
48
|
+
logLevel: "silent"
|
|
49
|
+
});
|
|
50
|
+
} catch (cause) {
|
|
51
|
+
throw new PlatformError(ErrorCode.InvalidConfig, [`Failed to bundle function "${fn.slug}" from ${fn.source}.`, cause?.message ?? String(cause)].join(" "), { cause });
|
|
52
|
+
}
|
|
53
|
+
const entries = {};
|
|
54
|
+
for (const file of result.outputFiles ?? []) entries[basename(file.path)] = file.contents;
|
|
55
|
+
return zipBundle(entries);
|
|
56
|
+
}
|
|
57
|
+
async function zipBundle(entries) {
|
|
58
|
+
const { zipSync } = await loadFflate();
|
|
59
|
+
return zipSync(entries, { level: 6 });
|
|
60
|
+
}
|
|
61
|
+
async function loadEsbuild() {
|
|
62
|
+
try {
|
|
63
|
+
return await import("esbuild");
|
|
64
|
+
} catch (cause) {
|
|
65
|
+
throw new PlatformError(ErrorCode.InvalidConfig, ["Deploying Neon Functions requires `esbuild`, which could not be loaded.", "It is a dependency of @neon/config-runtime — reinstall your dependencies (`pnpm install` / `npm install`)."].join(" "), { cause });
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
async function loadFflate() {
|
|
69
|
+
try {
|
|
70
|
+
return await import("fflate");
|
|
71
|
+
} catch (cause) {
|
|
72
|
+
throw new PlatformError(ErrorCode.InvalidConfig, ["Deploying Neon Functions requires `fflate`, which could not be loaded.", "It is a dependency of @neon/config-runtime — reinstall your dependencies (`pnpm install` / `npm install`)."].join(" "), { cause });
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
//#endregion
|
|
76
|
+
export { buildFunctionBundle };
|
|
77
|
+
|
|
78
|
+
//# sourceMappingURL=function-bundle.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"function-bundle.js","names":[],"sources":["../../src/lib/function-bundle.ts"],"sourcesContent":["import { basename } from \"node:path\";\nimport {\n\tErrorCode,\n\tPlatformError,\n\ttype ResolvedFunctionConfig,\n} from \"@neon/config\";\n\n/**\n * Builds the deployable ZIP bundle for a single function. The default\n * implementation ({@link buildFunctionBundle}) shells out to esbuild, but\n * `pushConfig` / `apply` accept a custom bundler so a consumer that can't ship\n * esbuild's native binary (e.g. a single-file CLI) can supply its own — a WASM\n * build, an esbuild binary on PATH, etc. — without this package dragging esbuild\n * into their bundle.\n */\nexport type FunctionBundler = (\n\tfn: ResolvedFunctionConfig,\n) => Promise<Uint8Array>;\n\n/**\n * Prepended to the ESM bundle. Bundled dependencies are frequently CommonJS, but an ESM\n * output (`format: \"esm\"`) has no `require` / `__filename` / `__dirname` in scope — so any\n * bundled CJS code that calls `require(...)` would fail at load with\n * `Dynamic require of \"x\" is not supported`. Re-create those globals via `createRequire`\n * so CJS and ESM dependencies coexist in the single `index.mjs`.\n */\nconst ESM_CJS_INTEROP_BANNER =\n\t\"import{createRequire as ___cr}from'module';import{fileURLToPath as ___f}from'url';import{dirname as ___d}from'path';const require=___cr(import.meta.url);const __filename=___f(import.meta.url);const __dirname=___d(__filename);\";\n\n/**\n * Build the deployable bundle (a ZIP archive of the esbuild-bundled source) for a function.\n *\n * This is the **imperative shell** step of function deploys, and the reason it lives in\n * `@neon/config-runtime` rather than `@neon/config`: it pulls in `esbuild`\n * (a native binary) and `fflate`. Keeping it out of `@neon/config` means a `neon.ts`\n * that only imports `defineConfig` never drags esbuild into the user's dependency tree or\n * bundle. Deploy-side consumers (the neonctl CLI, CI) import this package and get esbuild as\n * a normal, auto-installed dependency.\n *\n * esbuild and fflate are loaded with a dynamic `import()` (not a static top-level import) so\n * that nothing in this package's static graph names esbuild until a deploy actually runs —\n * a second layer of protection on top of the package split.\n *\n * Mirrors: `esbuild <source> --bundle --outfile=index.mjs --minify --format=esm\n * --platform=node --banner:js=<createRequire shim>`, then zips the emitted files into the\n * archive the Functions deploy endpoint expects. Dependencies are bundled into the entry\n * (Node built-ins stay external); see {@link ESM_CJS_INTEROP_BANNER} for why the banner.\n *\n * No source map is emitted: the Functions runtime does not run Node with source-map support,\n * so an uploaded `index.mjs.map` is never consumed (a thrown error's stack still points into\n * the minified bundle). Generating it only inflated the deployed archive, so it is omitted.\n */\nexport async function buildFunctionBundle(\n\tfn: ResolvedFunctionConfig,\n): Promise<Uint8Array> {\n\tconst esbuild = await loadEsbuild();\n\n\tlet result: Awaited<ReturnType<typeof esbuild.build>>;\n\ttry {\n\t\tresult = await esbuild.build({\n\t\t\tentryPoints: [fn.source],\n\t\t\tbundle: true,\n\t\t\twrite: false,\n\t\t\t// Emit `index.mjs`: the Functions runtime imports the archive's entry by the\n\t\t\t// conventional `index.{js,mjs}` name, and `.mjs` makes Node load the ESM output\n\t\t\t// directly. (With `write: false` and no outfile, esbuild would label the buffer\n\t\t\t// `<stdout>`.) No `sourcemap` — see the doc comment above for why.\n\t\t\toutfile: \"index.mjs\",\n\t\t\tminify: true,\n\t\t\tformat: \"esm\",\n\t\t\tplatform: \"node\",\n\t\t\t// Bundle dependencies into the entry so the deployed archive is self-contained\n\t\t\t// (the Functions runtime has no node_modules). Node built-ins stay external on\n\t\t\t// `platform: \"node\"`. The banner re-creates require/__filename/__dirname so\n\t\t\t// bundled CommonJS deps work inside the ESM output.\n\t\t\tbanner: { js: ESM_CJS_INTEROP_BANNER },\n\t\t\tlogLevel: \"silent\",\n\t\t});\n\t} catch (cause) {\n\t\tthrow new PlatformError(\n\t\t\tErrorCode.InvalidConfig,\n\t\t\t[\n\t\t\t\t`Failed to bundle function \"${fn.slug}\" from ${fn.source}.`,\n\t\t\t\t(cause as Error)?.message ?? String(cause),\n\t\t\t].join(\" \"),\n\t\t\t{ cause },\n\t\t);\n\t}\n\n\tconst entries: Record<string, Uint8Array> = {};\n\t// `write: false` guarantees `outputFiles`, but the type is optional — guard for safety.\n\tfor (const file of result.outputFiles ?? []) {\n\t\t// esbuild returns absolute output paths; archive them under their basename\n\t\t// (`index.mjs`) so the bundle layout is stable regardless of cwd.\n\t\tentries[basename(file.path)] = file.contents;\n\t}\n\n\treturn zipBundle(entries);\n}\n\nasync function zipBundle(\n\tentries: Record<string, Uint8Array>,\n): Promise<Uint8Array> {\n\tconst { zipSync } = await loadFflate();\n\treturn zipSync(entries, { level: 6 });\n}\n\nasync function loadEsbuild(): Promise<typeof import(\"esbuild\")> {\n\ttry {\n\t\treturn await import(\"esbuild\");\n\t} catch (cause) {\n\t\tthrow new PlatformError(\n\t\t\tErrorCode.InvalidConfig,\n\t\t\t[\n\t\t\t\t\"Deploying Neon Functions requires `esbuild`, which could not be loaded.\",\n\t\t\t\t\"It is a dependency of @neon/config-runtime — reinstall your dependencies (`pnpm install` / `npm install`).\",\n\t\t\t].join(\" \"),\n\t\t\t{ cause },\n\t\t);\n\t}\n}\n\nasync function loadFflate(): Promise<typeof import(\"fflate\")> {\n\ttry {\n\t\treturn await import(\"fflate\");\n\t} catch (cause) {\n\t\tthrow new PlatformError(\n\t\t\tErrorCode.InvalidConfig,\n\t\t\t[\n\t\t\t\t\"Deploying Neon Functions requires `fflate`, which could not be loaded.\",\n\t\t\t\t\"It is a dependency of @neon/config-runtime — reinstall your dependencies (`pnpm install` / `npm install`).\",\n\t\t\t].join(\" \"),\n\t\t\t{ cause },\n\t\t);\n\t}\n}\n"],"mappings":";;;;;;;;;;AA0BA,MAAM,yBACL;;;;;;;;;;;;;;;;;;;;;;;;AAyBD,eAAsB,oBACrB,IACsB;CACtB,MAAM,UAAU,MAAM,YAAY;CAElC,IAAI;CACJ,IAAI;EACH,SAAS,MAAM,QAAQ,MAAM;GAC5B,aAAa,CAAC,GAAG,MAAM;GACvB,QAAQ;GACR,OAAO;GAKP,SAAS;GACT,QAAQ;GACR,QAAQ;GACR,UAAU;GAKV,QAAQ,EAAE,IAAI,uBAAuB;GACrC,UAAU;EACX,CAAC;CACF,SAAS,OAAO;EACf,MAAM,IAAI,cACT,UAAU,eACV,CACC,8BAA8B,GAAG,KAAK,SAAS,GAAG,OAAO,IACxD,OAAiB,WAAW,OAAO,KAAK,CAC1C,CAAC,CAAC,KAAK,GAAG,GACV,EAAE,MAAM,CACT;CACD;CAEA,MAAM,UAAsC,CAAC;CAE7C,KAAK,MAAM,QAAQ,OAAO,eAAe,CAAC,GAGzC,QAAQ,SAAS,KAAK,IAAI,KAAK,KAAK;CAGrC,OAAO,UAAU,OAAO;AACzB;AAEA,eAAe,UACd,SACsB;CACtB,MAAM,EAAE,YAAY,MAAM,WAAW;CACrC,OAAO,QAAQ,SAAS,EAAE,OAAO,EAAE,CAAC;AACrC;AAEA,eAAe,cAAiD;CAC/D,IAAI;EACH,OAAO,MAAM,OAAO;CACrB,SAAS,OAAO;EACf,MAAM,IAAI,cACT,UAAU,eACV,CACC,2EACA,4GACD,CAAC,CAAC,KAAK,GAAG,GACV,EAAE,MAAM,CACT;CACD;AACD;AAEA,eAAe,aAA+C;CAC7D,IAAI;EACH,OAAO,MAAM,OAAO;CACrB,SAAS,OAAO;EACf,MAAM,IAAI,cACT,UAAU,eACV,CACC,0EACA,4GACD,CAAC,CAAC,KAAK,GAAG,GACV,EAAE,MAAM,CACT;CACD;AACD"}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { FunctionBundler } from "./function-bundle.js";
|
|
2
|
+
import { PulledBranchConfig } from "./pull-config.js";
|
|
3
|
+
import { PushConfigOptions } from "./push-config.js";
|
|
4
|
+
import { Config, NeonApi, PushResult } from "@neon/config";
|
|
5
|
+
|
|
6
|
+
//#region src/lib/operations.d.ts
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Where to run the operation and how to authenticate. Filesystem- and env-agnostic: the
|
|
10
|
+
* `projectId` and `branchId` are always passed explicitly by the caller (e.g. neonctl
|
|
11
|
+
* resolves them from `.neon` / `NEON_*` and forwards them here).
|
|
12
|
+
*/
|
|
13
|
+
interface ConfigOperationOptions {
|
|
14
|
+
/**
|
|
15
|
+
* Neon project id. **Required** — the management API addresses branches through their
|
|
16
|
+
* project, so operations cannot run without it.
|
|
17
|
+
*/
|
|
18
|
+
projectId: string;
|
|
19
|
+
/**
|
|
20
|
+
* Neon branch id (`br-…`). **Required.** Must already exist on the project; resolve
|
|
21
|
+
* branch names to ids before calling.
|
|
22
|
+
*/
|
|
23
|
+
branchId: string;
|
|
24
|
+
/** Neon API key. Falls back to `NEON_API_KEY` / neonctl credentials. */
|
|
25
|
+
apiKey?: string;
|
|
26
|
+
/** Neon API base URL. Falls back to `NEON_API_HOST`, then production. */
|
|
27
|
+
apiHost?: string;
|
|
28
|
+
/** Inject a custom NeonApi adapter (primarily for tests). */
|
|
29
|
+
api?: PushConfigOptions["api"];
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Options accepted by {@link apply} on top of {@link ConfigOperationOptions}.
|
|
33
|
+
*/
|
|
34
|
+
interface ApplyOptions extends ConfigOperationOptions {
|
|
35
|
+
/**
|
|
36
|
+
* Auto-confirm overriding existing remote settings (TTL, `protected`, compute
|
|
37
|
+
* settings) on the selected branch. Without it, drift is reported as a conflict.
|
|
38
|
+
*/
|
|
39
|
+
updateExisting?: boolean;
|
|
40
|
+
/** Auto-confirm applying to a branch marked `protected` on Neon. */
|
|
41
|
+
allowProtectedBranch?: boolean;
|
|
42
|
+
/**
|
|
43
|
+
* Custom function bundler. Defaults to esbuild (`buildFunctionBundle`); inject
|
|
44
|
+
* your own to deploy functions without pulling esbuild's native binary into
|
|
45
|
+
* your build. See {@link FunctionBundler}.
|
|
46
|
+
*/
|
|
47
|
+
bundleFunction?: FunctionBundler;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Read a branch's live Neon state as a plain object (project + branch metadata and the
|
|
51
|
+
* reverse-engineered `BranchConfig`). Network read only — never mutates.
|
|
52
|
+
*
|
|
53
|
+
* `projectId` and `branchId` are **required** (both in `options`).
|
|
54
|
+
*/
|
|
55
|
+
declare function inspect(options: ConfigOperationOptions): Promise<PulledBranchConfig>;
|
|
56
|
+
/**
|
|
57
|
+
* Compute what {@link apply} would do for the given branch without mutating anything
|
|
58
|
+
* (dry-run plan). Returns the full {@link PushResult} with the planned changes in
|
|
59
|
+
* `applied` and any blocking drift in `conflicts` — the Neon equivalent of
|
|
60
|
+
* `terraform plan`.
|
|
61
|
+
*
|
|
62
|
+
* `projectId` and `branchId` are **required** (both in `options`).
|
|
63
|
+
*/
|
|
64
|
+
declare function plan(config: Config, options: ConfigOperationOptions): Promise<PushResult>;
|
|
65
|
+
/**
|
|
66
|
+
* Apply a `neon.ts` policy to the given Neon branch and return the {@link PushResult}
|
|
67
|
+
* describing what changed — the Neon equivalent of `terraform apply`.
|
|
68
|
+
*
|
|
69
|
+
* `projectId` and `branchId` are **required** (both in `options`). Pass `updateExisting`
|
|
70
|
+
* to auto-confirm overriding existing remote settings and `allowProtectedBranch` to
|
|
71
|
+
* auto-confirm applying to a protected branch; otherwise drift is reported as a
|
|
72
|
+
* `PushConflictError`.
|
|
73
|
+
*
|
|
74
|
+
* Never creates projects or branches — both must already exist.
|
|
75
|
+
*/
|
|
76
|
+
declare function apply(config: Config, options: ApplyOptions): Promise<PushResult>;
|
|
77
|
+
/**
|
|
78
|
+
* Options accepted by {@link createBranch}. Unlike {@link ConfigOperationOptions} this takes a
|
|
79
|
+
* branch **name** (the branch does not exist yet) rather than an id.
|
|
80
|
+
*/
|
|
81
|
+
interface CreateBranchOptions {
|
|
82
|
+
/** Neon project id to create the branch in. **Required.** */
|
|
83
|
+
projectId: string;
|
|
84
|
+
/** Name of the branch to create. **Required.** Must not already exist on the project. */
|
|
85
|
+
branchName: string;
|
|
86
|
+
/** Neon API key. Falls back to `NEON_API_KEY` / neonctl credentials. Ignored when `api` is set. */
|
|
87
|
+
apiKey?: string;
|
|
88
|
+
/** Inject a custom NeonApi adapter (primarily for tests). */
|
|
89
|
+
api?: NeonApi;
|
|
90
|
+
/** Custom function bundler (defaults to esbuild). See {@link FunctionBundler}. */
|
|
91
|
+
bundleFunction?: FunctionBundler;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Result of {@link createBranch}: the created branch's id/name plus the {@link PushResult}
|
|
95
|
+
* describing the policy that was applied to it.
|
|
96
|
+
*/
|
|
97
|
+
interface CreateBranchResult {
|
|
98
|
+
branchId: string;
|
|
99
|
+
branchName: string;
|
|
100
|
+
/** What applying the policy to the freshly created branch changed. */
|
|
101
|
+
result: PushResult;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Create a Neon branch **from a `neon.ts` policy** and bring it up with its declared
|
|
105
|
+
* settings/infra in one step — the operation `neonctl checkout <new-name>` needs.
|
|
106
|
+
*
|
|
107
|
+
* The flow is the one a creation actually wants:
|
|
108
|
+
* 1. Evaluate the policy for the new branch with `exists: false` (so creation-time tuning —
|
|
109
|
+
* `parent`, `ttl`, compute settings, `protected` — resolves instead of the
|
|
110
|
+
* "existing branch, leave as-is" path most policies guard with `if (branch.exists)`).
|
|
111
|
+
* 2. Create the branch, branched from the policy's `parent` (falling back to the project's
|
|
112
|
+
* default branch).
|
|
113
|
+
* 3. {@link pushConfig} the policy onto it with `branchExists: false`, so TTL / compute /
|
|
114
|
+
* `protected` and the services (Neon Auth, Data API, functions) are applied.
|
|
115
|
+
*
|
|
116
|
+
* This is why `apply` alone couldn't do it: `apply` operates on an *existing* branch
|
|
117
|
+
* (`exists: true`), so a policy keyed on `!branch.exists` never returns the creation tuning.
|
|
118
|
+
*
|
|
119
|
+
* Throws {@link PlatformError} (`Conflict`) if a branch with `branchName` already exists, or
|
|
120
|
+
* (`BranchNotFound`) if the policy names a `parent` that isn't on the project.
|
|
121
|
+
*/
|
|
122
|
+
declare function createBranch(config: Config, options: CreateBranchOptions): Promise<CreateBranchResult>;
|
|
123
|
+
//#endregion
|
|
124
|
+
export { ApplyOptions, ConfigOperationOptions, CreateBranchOptions, CreateBranchResult, apply, createBranch, inspect, plan };
|
|
125
|
+
//# sourceMappingURL=operations.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"operations.d.ts","names":[],"sources":["../../src/lib/operations.ts"],"mappings":";;;;;;;;;AAmBA;AAsBA;;AAakB,UAnCD,sBAAA,CAmCC;;AAb0C;AAsB5D;;WACU,EAAA,MAAA;;;AACA;AAkBV;EAA0B,QAAA,EAAA,MAAA;;QAEhB,CAAA,EAAA,MAAA;;SACP,CAAA,EAAA,MAAA;EAAO;EAwBY,GAAA,CAAA,EA3Ef,iBA2EoB,CAAA,KAAA,CAAA;;;;;AAGxB,UAxEc,YAAA,SAAqB,sBAwEnC,CAAA;EAAO;AAmBV;;;gBAUkB,CAAA,EAAA,OAAA;EAAe;EAOhB,oBAAA,CAAkB,EAAA,OAAA;EA0Bb;;;;;gBAGnB,CAAA,EA5He,eA4Hf;AAAO;;;;;;;iBAnHY,OAAA,UACZ,yBACP,QAAQ;;;;;;;;;iBAkBW,IAAA,SACb,iBACC,yBACP,QAAQ;;;;;;;;;;;;iBAwBW,KAAA,SACb,iBACC,eACP,QAAQ;;;;;UAmBM,mBAAA;;;;;;;;QAQV;;mBAEW;;;;;;UAOD,kBAAA;;;;UAIR;;;;;;;;;;;;;;;;;;;;;iBAsBa,YAAA,SACb,iBACC,sBACP,QAAQ"}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { pullConfig } from "./pull-config.js";
|
|
2
|
+
import { pushConfig } from "./push-config.js";
|
|
3
|
+
import { ErrorCode, PlatformError, createNeonApiFromOptions, resolveConfig } from "@neon/config";
|
|
4
|
+
//#region src/lib/operations.ts
|
|
5
|
+
/**
|
|
6
|
+
* Read a branch's live Neon state as a plain object (project + branch metadata and the
|
|
7
|
+
* reverse-engineered `BranchConfig`). Network read only — never mutates.
|
|
8
|
+
*
|
|
9
|
+
* `projectId` and `branchId` are **required** (both in `options`).
|
|
10
|
+
*/
|
|
11
|
+
async function inspect(options) {
|
|
12
|
+
return pullConfig({
|
|
13
|
+
projectId: options.projectId,
|
|
14
|
+
branchId: options.branchId,
|
|
15
|
+
...options.api ? { api: options.api } : {},
|
|
16
|
+
...options.apiKey ? { apiKey: options.apiKey } : {},
|
|
17
|
+
...options.apiHost ? { apiHost: options.apiHost } : {}
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Compute what {@link apply} would do for the given branch without mutating anything
|
|
22
|
+
* (dry-run plan). Returns the full {@link PushResult} with the planned changes in
|
|
23
|
+
* `applied` and any blocking drift in `conflicts` — the Neon equivalent of
|
|
24
|
+
* `terraform plan`.
|
|
25
|
+
*
|
|
26
|
+
* `projectId` and `branchId` are **required** (both in `options`).
|
|
27
|
+
*/
|
|
28
|
+
async function plan(config, options) {
|
|
29
|
+
return pushConfig(config, {
|
|
30
|
+
projectId: options.projectId,
|
|
31
|
+
branchId: options.branchId,
|
|
32
|
+
dryRun: true,
|
|
33
|
+
updateExisting: true,
|
|
34
|
+
...options.api ? { api: options.api } : {},
|
|
35
|
+
...options.apiKey ? { apiKey: options.apiKey } : {},
|
|
36
|
+
...options.apiHost ? { apiHost: options.apiHost } : {}
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Apply a `neon.ts` policy to the given Neon branch and return the {@link PushResult}
|
|
41
|
+
* describing what changed — the Neon equivalent of `terraform apply`.
|
|
42
|
+
*
|
|
43
|
+
* `projectId` and `branchId` are **required** (both in `options`). Pass `updateExisting`
|
|
44
|
+
* to auto-confirm overriding existing remote settings and `allowProtectedBranch` to
|
|
45
|
+
* auto-confirm applying to a protected branch; otherwise drift is reported as a
|
|
46
|
+
* `PushConflictError`.
|
|
47
|
+
*
|
|
48
|
+
* Never creates projects or branches — both must already exist.
|
|
49
|
+
*/
|
|
50
|
+
async function apply(config, options) {
|
|
51
|
+
return pushConfig(config, {
|
|
52
|
+
projectId: options.projectId,
|
|
53
|
+
branchId: options.branchId,
|
|
54
|
+
...options.api ? { api: options.api } : {},
|
|
55
|
+
...options.apiKey ? { apiKey: options.apiKey } : {},
|
|
56
|
+
...options.apiHost ? { apiHost: options.apiHost } : {},
|
|
57
|
+
...options.updateExisting ? { updateExisting: true } : {},
|
|
58
|
+
...options.allowProtectedBranch ? { allowProtectedBranch: true } : {},
|
|
59
|
+
...options.bundleFunction ? { bundleFunction: options.bundleFunction } : {}
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Create a Neon branch **from a `neon.ts` policy** and bring it up with its declared
|
|
64
|
+
* settings/infra in one step — the operation `neonctl checkout <new-name>` needs.
|
|
65
|
+
*
|
|
66
|
+
* The flow is the one a creation actually wants:
|
|
67
|
+
* 1. Evaluate the policy for the new branch with `exists: false` (so creation-time tuning —
|
|
68
|
+
* `parent`, `ttl`, compute settings, `protected` — resolves instead of the
|
|
69
|
+
* "existing branch, leave as-is" path most policies guard with `if (branch.exists)`).
|
|
70
|
+
* 2. Create the branch, branched from the policy's `parent` (falling back to the project's
|
|
71
|
+
* default branch).
|
|
72
|
+
* 3. {@link pushConfig} the policy onto it with `branchExists: false`, so TTL / compute /
|
|
73
|
+
* `protected` and the services (Neon Auth, Data API, functions) are applied.
|
|
74
|
+
*
|
|
75
|
+
* This is why `apply` alone couldn't do it: `apply` operates on an *existing* branch
|
|
76
|
+
* (`exists: true`), so a policy keyed on `!branch.exists` never returns the creation tuning.
|
|
77
|
+
*
|
|
78
|
+
* Throws {@link PlatformError} (`Conflict`) if a branch with `branchName` already exists, or
|
|
79
|
+
* (`BranchNotFound`) if the policy names a `parent` that isn't on the project.
|
|
80
|
+
*/
|
|
81
|
+
async function createBranch(config, options) {
|
|
82
|
+
const api = options.api ?? createNeonApiFromOptions("createBranch", options.apiKey ? { apiKey: options.apiKey } : {});
|
|
83
|
+
const { projectId, branchName } = options;
|
|
84
|
+
const branches = await api.listBranches(projectId);
|
|
85
|
+
if (branches.some((b) => b.name === branchName)) throw new PlatformError(ErrorCode.Conflict, `createBranch: a branch named "${branchName}" already exists on project ${projectId}. Pick a different name or check it out instead of creating it.`, { details: {
|
|
86
|
+
projectId,
|
|
87
|
+
branchName
|
|
88
|
+
} });
|
|
89
|
+
const parentId = resolveParentBranchId(resolveConfig(config, {
|
|
90
|
+
name: branchName,
|
|
91
|
+
exists: false
|
|
92
|
+
}).parent, branches, branchName);
|
|
93
|
+
const { branch } = await api.createBranch(projectId, {
|
|
94
|
+
name: branchName,
|
|
95
|
+
...parentId ? { parentId } : {}
|
|
96
|
+
});
|
|
97
|
+
const result = await pushConfig(config, {
|
|
98
|
+
projectId,
|
|
99
|
+
branchId: branch.id,
|
|
100
|
+
api,
|
|
101
|
+
branchExists: false,
|
|
102
|
+
updateExisting: true,
|
|
103
|
+
allowProtectedBranch: true,
|
|
104
|
+
...options.bundleFunction ? { bundleFunction: options.bundleFunction } : {}
|
|
105
|
+
});
|
|
106
|
+
return {
|
|
107
|
+
branchId: branch.id,
|
|
108
|
+
branchName: branch.name,
|
|
109
|
+
result
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Resolve the parent branch id for a new branch. A policy-declared `parent` (a branch name) is
|
|
114
|
+
* looked up by name; an unknown name is a hard error. With no `parent`, fall back to the
|
|
115
|
+
* project's default branch, or `undefined` (let the API pick the project default) when none is
|
|
116
|
+
* marked default.
|
|
117
|
+
*/
|
|
118
|
+
function resolveParentBranchId(parentName, branches, branchName) {
|
|
119
|
+
if (parentName !== void 0) {
|
|
120
|
+
const match = branches.find((b) => b.name === parentName);
|
|
121
|
+
if (!match) throw new PlatformError(ErrorCode.BranchNotFound, `createBranch: the policy for "${branchName}" sets parent "${parentName}", but no branch with that name exists. Existing branches: ${branches.map((b) => b.name).join(", ") || "(none)"}.`, { details: {
|
|
122
|
+
branchName,
|
|
123
|
+
parent: parentName,
|
|
124
|
+
available: branches.map((b) => b.name)
|
|
125
|
+
} });
|
|
126
|
+
return match.id;
|
|
127
|
+
}
|
|
128
|
+
return branches.find((b) => b.isDefault)?.id;
|
|
129
|
+
}
|
|
130
|
+
//#endregion
|
|
131
|
+
export { apply, createBranch, inspect, plan };
|
|
132
|
+
|
|
133
|
+
//# sourceMappingURL=operations.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"operations.js","names":[],"sources":["../../src/lib/operations.ts"],"sourcesContent":["import {\n\ttype Config,\n\tcreateNeonApiFromOptions,\n\tErrorCode,\n\ttype NeonApi,\n\ttype NeonBranchSnapshot,\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/**\n\t * Custom function bundler. Defaults to esbuild (`buildFunctionBundle`); inject\n\t * your own to deploy functions without pulling esbuild's native binary into\n\t * your build. See {@link FunctionBundler}.\n\t */\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.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/** Custom function bundler (defaults to esbuild). See {@link FunctionBundler}. */\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, branched from the policy's `parent` (falling back to the project's\n * default branch).\n * 3. {@link pushConfig} the policy onto it with `branchExists: false`, so TTL / compute /\n * `protected` and the services (Neon Auth, Data API, functions) are applied.\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 * 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.\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\tconst { branch } = await api.createBranch(projectId, {\n\t\tname: branchName,\n\t\t...(parentId ? { parentId } : {}),\n\t});\n\n\t// Reconcile the rest as a new branch (`branchExists: false`): TTL, compute settings,\n\t// `protected`, and the services/functions the policy declares are applied onto the\n\t// freshly created branch. `updateExisting`/`allowProtectedBranch` are safe here — there is\n\t// no pre-existing state a user would be surprised to see overridden.\n\tconst result = await pushConfig(config, {\n\t\tprojectId,\n\t\tbranchId: branch.id,\n\t\tapi,\n\t\tbranchExists: false,\n\t\tupdateExisting: true,\n\t\tallowProtectedBranch: true,\n\t\t...(options.bundleFunction\n\t\t\t? { bundleFunction: options.bundleFunction }\n\t\t\t: {}),\n\t});\n\n\treturn { branchId: branch.id, branchName: branch.name, result };\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":";;;;;;;;;;AA+DA,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;CACvD,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,QAAQ,QAAQ,OAAO,IAAI,CAAC;EACnD,GAAI,QAAQ,UAAU,EAAE,SAAS,QAAQ,QAAQ,IAAI,CAAC;CACvD,CAAC;AACF;;;;;;;;;;;;AAaA,eAAsB,MACrB,QACA,SACsB;CACtB,OAAO,WAAW,QAAQ;EACzB,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,iBAAiB,EAAE,gBAAgB,KAAK,IAAI,CAAC;EACzD,GAAI,QAAQ,uBAAuB,EAAE,sBAAsB,KAAK,IAAI,CAAC;EACrE,GAAI,QAAQ,iBACT,EAAE,gBAAgB,QAAQ,eAAe,IACzC,CAAC;CACL,CAAC;AACF;;;;;;;;;;;;;;;;;;;;AAiDA,eAAsB,aACrB,QACA,SAC8B;CAC9B,MAAM,MACL,QAAQ,OACR,yBACC,gBACA,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC,CAChD;CACD,MAAM,EAAE,WAAW,eAAe;CAElC,MAAM,WAAW,MAAM,IAAI,aAAa,SAAS;CACjD,IAAI,SAAS,MAAM,MAAM,EAAE,SAAS,UAAU,GAC7C,MAAM,IAAI,cACT,UAAU,UACV,iCAAiC,WAAW,8BAA8B,UAAU,kEACpF,EAAE,SAAS;EAAE;EAAW;CAAW,EAAE,CACtC;CAQD,MAAM,WAAW,sBAJA,cAAc,QAAQ;EACtC,MAAM;EACN,QAAQ;CACT,CAEQ,CAAC,CAAC,QACT,UACA,UACD;CAEA,MAAM,EAAE,WAAW,MAAM,IAAI,aAAa,WAAW;EACpD,MAAM;EACN,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;CAChC,CAAC;CAMD,MAAM,SAAS,MAAM,WAAW,QAAQ;EACvC;EACA,UAAU,OAAO;EACjB;EACA,cAAc;EACd,gBAAgB;EAChB,sBAAsB;EACtB,GAAI,QAAQ,iBACT,EAAE,gBAAgB,QAAQ,eAAe,IACzC,CAAC;CACL,CAAC;CAED,OAAO;EAAE,UAAU,OAAO;EAAI,YAAY,OAAO;EAAM;CAAO;AAC/D;;;;;;;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"}
|