ref0-git 0.26.0 → 0.29.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 (49) hide show
  1. package/app/apps/github/README.md +1 -5
  2. package/app/apps/github/package.json +0 -1
  3. package/app/apps/github/src/signin/auth.ts +17 -89
  4. package/app/apps/github/src/signin/credentials.ts +10 -14
  5. package/app/apps/github/src/signin/guarded-write.ts +19 -0
  6. package/app/apps/github/src/signin/owner-names.ts +11 -41
  7. package/app/apps/github/src/signin/unborn.ts +20 -30
  8. package/app/apps/github/tsconfig.json +0 -2
  9. package/app/pnpm-workspace.yaml +14 -34
  10. package/dist/cli/documents.mjs +39 -25
  11. package/dist/cli/keys.mjs +9 -3
  12. package/dist/cli/node.mjs +1 -2
  13. package/dist/cli/runtime.mjs +3 -4
  14. package/dist/cli/setup.mjs +216 -468
  15. package/dist/cli/tools-node.mjs +8 -7
  16. package/dist/cli/tools.mjs +3 -3
  17. package/dist/cli/vercel-stores.mjs +287 -0
  18. package/dist/init/app.mjs +4 -37
  19. package/dist/init/choices.mjs +62 -209
  20. package/dist/init/cloudflare.mjs +1 -2
  21. package/dist/init/detect.mjs +77 -167
  22. package/dist/init/files.mjs +2 -12
  23. package/dist/init/frameworks.mjs +50 -174
  24. package/dist/init/git-module.mjs +5 -1
  25. package/dist/init/metadata.mjs +4 -22
  26. package/dist/init/next.mjs +13 -66
  27. package/dist/init/output.mjs +3 -6
  28. package/dist/init/plan.mjs +1 -29
  29. package/dist/init/routes.mjs +1 -78
  30. package/dist/init/stores.mjs +6 -35
  31. package/dist/init/template.mjs +14 -49
  32. package/dist/init/templates.mjs +30 -115
  33. package/dist/init/vercel-regions.mjs +87 -0
  34. package/dist/init/vercel.mjs +313 -212
  35. package/dist/init/versions.mjs +3 -3
  36. package/package.json +5 -11
  37. package/app/apps/github/migrations/postgres/0001_auth.sql +0 -53
  38. package/app/apps/github/src/camo/lookup.ts +0 -23
  39. package/app/apps/github/src/camo/node.ts +0 -50
  40. package/app/apps/github/src/signin/person-lock.ts +0 -104
  41. package/dist/cli/sqlite.mjs +0 -28
  42. package/dist/init/astro.mjs +0 -49
  43. package/dist/init/create.mjs +0 -152
  44. package/dist/init/mounts.mjs +0 -104
  45. package/dist/init/node-app.mjs +0 -196
  46. package/dist/init/node.mjs +0 -446
  47. package/dist/init/nuxt.mjs +0 -240
  48. package/dist/init/react-router.mjs +0 -59
  49. package/dist/init/sveltekit.mjs +0 -141
@@ -1,240 +0,0 @@
1
- import { lines } from "./files.mjs";
2
- import { pathMatchers, routeImports } from "./routes.mjs";
3
- // src/init/nuxt.ts
4
- /**
5
- * What `init` writes in a Nuxt project on Node, under Nitro's Node preset: one server middleware
6
- * that answers Git's URLs, and with `--serve github` the drop-in's, and a Nitro plugin that starts
7
- * the jobs. The middleware loads the server module on Git's first request, as every framework's
8
- * routes do.
9
- */
10
- /** `to`'s import specifier from the file at `from`: relative, with its `.ts`, as Nitro resolves it. */
11
- const importOf = (from, to) => {
12
- const folders = from.split("/").slice(0, -1);
13
- const target = to.split("/");
14
- const shared = folders.findIndex((folder, at) => target[at] !== folder || at === target.length - 1);
15
- const common = shared === -1 ? folders.length : shared;
16
- const ups = folders.length - common;
17
- return `${ups === 0 ? "./" : "../".repeat(ups)}${target.slice(common).join("/")}`;
18
- };
19
- /** The Nitro plugin that starts Git's jobs once in each server process, and stops them on close. */
20
- const nuxtJobsPlugin = "server/plugins/git-jobs.ts";
21
- /** The plugin's lines, which a step in the person's own file at that path names too. */
22
- const pluginLines = (framework) => [
23
- "export default defineNitroPlugin(async (nitroApp) => {",
24
- ` const { runtime } = await import('${importOf(nuxtJobsPlugin, framework.serverModule)}');`,
25
- " const Node = await import('@ref0/infra/node');",
26
- "",
27
- " const stop = Node.toJobRunner(runtime);",
28
- " nitroApp.hooks.hook('close', () => void stop());",
29
- "});"
30
- ];
31
- /** The middleware that answers Git's URLs, and the drop-in's, in front of the app's own. */
32
- const nuxtGitMiddleware = "server/middleware/git.ts";
33
- /**
34
- * Git's URLs under the base path, and with `--serve github` the drop-in's at the root and `gh`'s
35
- * root Git URLs, answered in place at the path the matcher gives, the query kept; every other path
36
- * falls through to the app, its body unread. The matcher reads the URL Git is handed, with its dot
37
- * segments resolved, never the raw path Nitro routes by.
38
- */
39
- const middlewareLines = (choices, framework) => {
40
- const matcher = pathMatchers[choices.serve];
41
- return [
42
- ...routeImports(choices),
43
- "",
44
- "export default defineEventHandler(async (event) => {",
45
- " // The URL Git is handed, dot segments resolved, under the Host's origin: an absolute target",
46
- " // keeps only its path and query. Then the path Git answers it at. h3's toWebRequest is",
47
- " // called only for Git's, since its body starts reading the app's request.",
48
- " const named = getRequestURL(event);",
49
- " const url = new URL(`${getRequestProtocol(event)}://${getRequestHost(event)}`);",
50
- " url.pathname = named.pathname;",
51
- " url.search = named.search;",
52
- ` const path = ${matcher.name}(url, '${choices.basePath.replace(/\/$/, "")}');`,
53
- " if (path === undefined) return;",
54
- "",
55
- " // Loaded on Git's first request. toWebRequest reads a body without backpressure, so a fast",
56
- " // push waits in memory while Git reads it.",
57
- ` const { runtime } = await import('${importOf(nuxtGitMiddleware, framework.serverModule)}');`,
58
- " url.pathname = path;",
59
- "",
60
- " return Git.toFetch(runtime)(new Request(url, toWebRequest(event)));",
61
- "});"
62
- ];
63
- };
64
- /**
65
- * Nitro's build target, as a `nuxt.config`'s member holds it, indented by two. Nitro 2 builds the
66
- * server for es2019, which refuses `server/git.ts`'s top-level `await xdiff()`.
67
- */
68
- const nitroTargetLines = [
69
- " // Nitro builds the server for es2019 otherwise, which refuses server/git.ts's top-level await.",
70
- " // Written by `ref0-git init`.",
71
- " nitro: { esbuild: { options: { target: 'es2022' } } },"
72
- ];
73
- /**
74
- * Nitro's target as a data `nuxt.config` holds it, by its extension: c12 parses these as JSON, YAML
75
- * or TOML, with no `defineNuxtConfig` and no JavaScript.
76
- */
77
- const dataTargetLines = {
78
- json: [" \"nitro\": { \"esbuild\": { \"options\": { \"target\": \"es2022\" } } }"],
79
- yaml: [
80
- "nitro:",
81
- " esbuild:",
82
- " options:",
83
- " target: es2022"
84
- ],
85
- toml: ["[nitro.esbuild.options]", "target = \"es2022\""]
86
- };
87
- /** The data format a `nuxt.config`'s extension names, or `undefined` for JavaScript and TypeScript. */
88
- const dataFormatOf = (path) => {
89
- const extension = path.slice(path.lastIndexOf(".") + 1);
90
- if (extension.startsWith("json")) return "json";
91
- if (extension === "yaml" || extension === "yml") return "yaml";
92
- if (extension === "toml") return "toml";
93
- };
94
- /** A `nuxt.config`'s tokens: strings, names, comments and the punctuation an object's shape is. */
95
- const configTokens = /(["'`])(?:\\.|(?!\1)[^\\])*\1|[A-Za-z_$][\w$]*|\/\/[^\n]*|\/\*[\s\S]*?\*\/|[{}:,]/g;
96
- /** A target with top-level `await`: es2022 or later, or esnext, quoted. */
97
- const modernTarget = /^["'`](?:es202[2-9]|es20[3-9]\d|esnext)["'`]$/;
98
- /**
99
- * Whether a `nuxt.config`'s text sets Nitro's own target, `nitro.esbuild.options.target`, to one
100
- * with top-level `await`, read by the keys around each `target`, so siblings in any order, nested
101
- * or not, read the same. Nitro spreads only those options over its es2019, so Vite's
102
- * `build.target` or `esbuild.target` sets nothing for it. A target from a variable reads as unset.
103
- */
104
- const targetsTopLevelAwait = (text) => {
105
- const tokens = (text.match(configTokens) ?? []).filter((token) => !token.startsWith("/"));
106
- const keys = [];
107
- let key;
108
- for (let at = 0; at < tokens.length; at += 1) {
109
- const token = tokens[at] ?? "";
110
- if (token === "{") keys.push(key ?? "");
111
- if (token === "{" || token === "}" || token === ",") key = void 0;
112
- if (token === "}") keys.pop();
113
- if (tokens[at + 1] !== ":" || /^[{}:,]$/.test(token)) continue;
114
- key = token.replace(/^["'`]|["'`]$/g, "");
115
- at += 1;
116
- const inOptions = keys.slice(-3).join(".") === "nitro.esbuild.options";
117
- if (key === "target" && inOptions && modernTarget.test(tokens[at + 1] ?? "")) return true;
118
- }
119
- return false;
120
- };
121
- /** `init`'s own `nuxt.config.ts`, with the target in it: what it writes where there's none. */
122
- const nuxtConfigText = lines("export default defineNuxtConfig({", ...nitroTargetLines, "});", "");
123
- /**
124
- * The line of `create-nuxt`'s `nuxt.config.ts` the target goes after: `init` edits the file the
125
- * create command actually wrote there, when the line is in it exactly once.
126
- */
127
- const nuxtConfigAnchor = "export default defineNuxtConfig({\n";
128
- /** The target after `path`'s one anchor line, as an edit of `text`, or `undefined` where it isn't once. */
129
- const withTarget = (path, text) => {
130
- const at = text.indexOf(nuxtConfigAnchor);
131
- if (at === -1 || text.includes("export default defineNuxtConfig({\n", at + 1)) return void 0;
132
- const after = at + 34;
133
- return {
134
- path,
135
- kind: "edit",
136
- from: text,
137
- text: `${text.slice(0, after)}${nitroTargetLines.join("\n")}\n${text.slice(after)}`,
138
- edit: {
139
- anchor: nuxtConfigAnchor.trimEnd(),
140
- adds: nitroTargetLines,
141
- swaps: []
142
- }
143
- };
144
- };
145
- /**
146
- * Nitro's target: a `nuxt.config.ts` where the project has none, or, in the one a create command
147
- * wrote in this same run, after its anchor line; else, in the person's own `nuxt.config`, or one
148
- * whose anchor isn't there exactly once, a printed step.
149
- */
150
- const nuxtConfigOutput = (framework, created) => {
151
- const { config } = framework;
152
- if (config !== void 0 && targetsTopLevelAwait(config.text)) return {
153
- files: [],
154
- manual: []
155
- };
156
- if (config === void 0) return {
157
- files: [{
158
- path: "nuxt.config.ts",
159
- kind: "whole",
160
- text: nuxtConfigText
161
- }],
162
- manual: []
163
- };
164
- const edited = created ? withTarget(config.path, config.text) : void 0;
165
- if (edited !== void 0) return {
166
- files: [edited],
167
- manual: []
168
- };
169
- const format = dataFormatOf(config.path);
170
- return {
171
- files: [],
172
- manual: [{
173
- path: config.path,
174
- says: format === void 0 ? "Build Nitro's server for es2022, which has top-level await, in defineNuxtConfig" : "Build Nitro's server for es2022, which has top-level await: set nitro.esbuild.options.target",
175
- why: created ? "template_changed" : "yours",
176
- lines: format === void 0 ? nitroTargetLines : dataTargetLines[format]
177
- }]
178
- };
179
- };
180
- /** The first line of the middleware `init` writes, which marks the file as init's to rewrite. */
181
- const middlewareHeader = "// Git's URLs to Git, in front of the app's own. Written by `ref0-git init`.";
182
- /** Whether a file at the middleware's path answers Git: `init`'s, or one with its lines. */
183
- const answersGit = (text) => /\bgit(?:hub)?PathOf\(/.test(text);
184
- /** What `doctor` finds in a Nuxt app on Node: Git's middleware, and h3's reading of a push. */
185
- const nuxtFindings = (framework) => {
186
- const middleware = framework.nitro?.middleware;
187
- const answered = middleware !== void 0 && answersGit(middleware.text);
188
- return [{
189
- check: "Git's URLs",
190
- ok: answered,
191
- says: answered ? `${middleware.path} answers Git's URLs, and with the drop-in gh's root ones` : `${middleware?.path ?? `No server/middleware/git.ts`} answers no Git URL, so every clone gets Nuxt's 404: add the middleware init printed`,
192
- blocks: "clone, fetch and push"
193
- }, {
194
- check: "Push memory",
195
- ok: true,
196
- says: "h3's toWebRequest reads a push with no backpressure, so a push that arrives faster than Git reads it waits in memory"
197
- }];
198
- };
199
- /**
200
- * Nuxt's files and steps beside the server module: the jobs plugin, Git's middleware and Nitro's
201
- * target in `nuxt.config`. The middleware is init's to rewrite where it answers Git, so a rerun at
202
- * a new base path moves it; a person's own file at its path gets a step.
203
- */
204
- const nuxtOutput = (choices, framework, created) => {
205
- const config = nuxtConfigOutput(framework, created);
206
- const plugin = framework.nitro?.plugin;
207
- const middleware = framework.nitro?.middleware;
208
- const ours = middleware === void 0 || middleware.text.startsWith(middlewareHeader);
209
- return {
210
- files: [
211
- ...plugin === void 0 ? [{
212
- path: nuxtJobsPlugin,
213
- kind: "whole",
214
- text: lines("// Starts Git's jobs once in each Nitro server process, and stops them as it closes.", "// Written by `ref0-git init`.", ...pluginLines(framework), "")
215
- }] : [],
216
- ...ours ? [{
217
- path: nuxtGitMiddleware,
218
- kind: "whole",
219
- text: lines(middlewareHeader, ...middlewareLines(choices, framework), "")
220
- }] : [],
221
- ...config.files
222
- ],
223
- manual: [
224
- ...config.manual,
225
- ...plugin === void 0 || /\btoJobRunner\(/.test(plugin.text) ? [] : [{
226
- path: plugin.path,
227
- why: "yours",
228
- says: "Start Git's jobs in a Nitro plugin, once in each server process",
229
- lines: pluginLines(framework)
230
- }],
231
- ...middleware === void 0 || answersGit(middleware.text) ? [] : [{
232
- path: middleware.path,
233
- why: "yours",
234
- says: "Answer Git's URLs with Git, and let every other path through",
235
- lines: middlewareLines(choices, framework)
236
- }]
237
- ]
238
- };
239
- };
240
- export { nuxtConfigAnchor, nuxtFindings, nuxtGitMiddleware, nuxtJobsPlugin, nuxtOutput };
@@ -1,59 +0,0 @@
1
- import { lines } from "./files.mjs";
2
- import { fileRoutes, routeHandler, routeImports } from "./routes.mjs";
3
- // src/init/react-router.ts
4
- /**
5
- * What `init` writes in a React Router project on Node: a resource route for each route, whose
6
- * `loader` and `action` hand the request to Git, and, where `app/routes.ts` lists its routes
7
- * rather than reading them by `flatRoutes()`, the lines that list these.
8
- */
9
- /**
10
- * A route's file under `app/routes/`, by `flatRoutes()`'s names, and its line in `app/routes.ts`:
11
- * a parameter such as `:repo` is `$repo`, and the text that follows it in the segment is escaped.
12
- */
13
- const placeOf = (route) => {
14
- const file = `${route.at.split("/").map((segment) => segment.replace(/^:(\w+)(.+)?$/, (_, name, rest) => rest === void 0 ? `$${name}` : `$${name}[${rest}]`)).join(".")}${{
15
- rest: ".$",
16
- optional: ".$",
17
- segment: ".$id",
18
- none: ""
19
- }[route.tail]}.ts`;
20
- const url = `${route.at}${{
21
- rest: "/*",
22
- optional: "/*",
23
- segment: "/:id",
24
- none: ""
25
- }[route.tail]}`;
26
- return {
27
- file,
28
- path: `app/routes/${file}`,
29
- line: `route('${url}', 'routes/${file}'),`
30
- };
31
- };
32
- /** One resource route, typed by `react-router typegen`'s `./+types/<file>`. */
33
- const resourceRoute = (choices, route, module) => {
34
- const { file, path } = placeOf(route);
35
- return {
36
- path,
37
- kind: "whole",
38
- text: lines(`// ${route.says} Written by \`ref0-git init\`.`, `import type { Route } from './+types/${file.replace(/\.ts$/, "")}';`, "", ...routeImports(choices), "", "// Loaded on the first request, so `react-router build` opens no database and needs no secret.", ...routeHandler(choices, path, module), "", "export const loader = ({ request }: Route.LoaderArgs) => git(request);", "", "export const action = ({ request }: Route.ActionArgs) => git(request);", "")
39
- };
40
- };
41
- /** React Router's resource routes for `choices`, over `framework`'s server module. */
42
- const reactRouterRouteFiles = (choices, framework) => fileRoutes(choices).map((route) => resourceRoute(choices, route, framework.serverModule));
43
- /** `app/routes.ts`'s lines for the routes, where it lists its routes and doesn't list these yet. */
44
- const reactRouterSteps = (choices, framework) => {
45
- const routes = framework.config?.text ?? "";
46
- const missing = fileRoutes(choices).map(placeOf).filter((place) => ["\"", "'"].every((quote) => !routes.includes(`${quote}routes/${place.file}${quote}`)));
47
- if (framework.flatRoutes === true || missing.length === 0) return [];
48
- return [{
49
- path: "app/routes.ts",
50
- why: "yours",
51
- says: "List Git's routes in app/routes.ts, which routes only the files it names, before any route of the app's that takes every path",
52
- lines: [
53
- "import { route } from '@react-router/dev/routes';",
54
- "",
55
- ...missing.map((place) => place.line)
56
- ]
57
- }];
58
- };
59
- export { reactRouterRouteFiles, reactRouterSteps };
@@ -1,141 +0,0 @@
1
- import { lines } from "./files.mjs";
2
- import { parseJsonc, stringAt, withEntries } from "./jsonc.mjs";
3
- import { gitRoutes, rootGitPattern } from "./routes.mjs";
4
- // src/init/sveltekit.ts
5
- /**
6
- * What `init` writes in a SvelteKit project on Node, under adapter-node: a `+server.ts` for Git's
7
- * URLs under the base path and one for each of the drop-in's paths at the root, `hooks.server.ts`
8
- * to start the jobs, and `hooks.ts`'s `reroute` for `gh`'s root Git URLs. Each route loads the
9
- * server module on its first request: `vite build` loads every route to read its options.
10
- */
11
- /** `to`'s import specifier from the file at `from`: relative, as Vite resolves it with its `.ts`. */
12
- const importOf = (from, to) => {
13
- const ups = from.split("/").length - 2;
14
- return `${ups === 0 ? "./" : "../".repeat(ups)}${to.replace(/^src\//, "")}`;
15
- };
16
- /** SvelteKit's folders for each parameter a route ends with: a rest parameter matches no segment too. */
17
- const svelteTails = {
18
- rest: "[...path]/",
19
- optional: "[...path]/",
20
- segment: "[id]/",
21
- none: ""
22
- };
23
- /** SvelteKit's route files for `choices`, over `framework`'s server module. */
24
- const svelteRouteFiles = (choices, framework) => gitRoutes(choices).map((route) => {
25
- const path = `src/routes/${route.at}/${svelteTails[route.tail]}+server.ts`;
26
- return {
27
- path,
28
- kind: "whole",
29
- text: lines(`// ${route.says} Written by \`ref0-git init\`.`, "import { Git } from '@ref0/git';", "", "import type { RequestHandler } from './$types';", "", "// Loaded on the first request, so `vite build`, which loads each route to read its options, opens", "// no database and needs no secret.", "const git: RequestHandler = async ({ request }) => {", ` const { runtime } = await import('${importOf(path, framework.serverModule)}');`, "", " return Git.toFetch(runtime)(request);", "};", "", `export { ${route.methods.map((method) => `git as ${method}`).join(", ")} };`, "")
30
- };
31
- });
32
- /** What the `init` hook names: Kit's type and `building`, which keeps it out of a build. */
33
- const initImports = ["import type { ServerInit } from '@sveltejs/kit/hooks';", "import { building } from '$app/env';"];
34
- /** The `init` hook's body, which starts Git's jobs once in each server process, never in a build. */
35
- const initLines = (framework) => [
36
- "export const init: ServerInit = async () => {",
37
- " if (building) return;",
38
- "",
39
- ` const { runtime } = await import('${importOf("src/hooks.server.ts", framework.serverModule)}');`,
40
- " const Node = await import('@ref0/infra/node');",
41
- "",
42
- " Node.toJobRunner(runtime);",
43
- "};"
44
- ];
45
- /** `src/hooks.server.ts`, where the project has none. */
46
- const svelteServerHooks = (framework) => lines("// Starts Git's jobs once in each SvelteKit server process. Written by `ref0-git init`.", ...initImports, "", ...initLines(framework), "");
47
- /** The `init` hook as a step in the person's own `hooks.server.*`: its imports, then the hook. */
48
- const svelteInitLines = (framework) => [
49
- ...initImports,
50
- "",
51
- ...initLines(framework)
52
- ];
53
- const rerouteImports = ["import type { Reroute } from '@sveltejs/kit/hooks';"];
54
- /**
55
- * `gh`'s root Git URLs, `/<owner>/<repo>.git/` then Smart HTTP's or LFS's ending, as
56
- * `@ref0/github`'s `urls.ts` matches them, rerouted to Git's route under the base path. `reroute`
57
- * changes only the path SvelteKit routes by: the route gets the request as it came, query kept, and
58
- * the drop-in answers its root URL with a 308 under the base path, or, for an LFS POST, in place.
59
- */
60
- const rerouteLines = (choices) => [
61
- "const gitRoot =",
62
- ` /^\\/[^/]+\\/[^/]+\\.git\\/(${rootGitPattern({
63
- slash: "\\/",
64
- more: ".+"
65
- })})$/;`,
66
- "",
67
- "export const reroute: Reroute = ({ url }) =>",
68
- ` gitRoot.test(url.pathname) ? \`${choices.basePath.replace(/\/$/, "")}\${url.pathname}\` : undefined;`
69
- ];
70
- /** The reroute as a step in the person's own `hooks.*`: its import, then `reroute`. */
71
- const svelteRerouteLines = (choices) => [
72
- ...rerouteImports,
73
- "",
74
- ...rerouteLines(choices)
75
- ];
76
- /** `src/hooks.ts`, where the project has none. */
77
- const svelteHooks = (choices) => lines("// gh's Git URLs at the root, `/<owner>/<repo>.git/…`, to Git's route. Written by `ref0-git init`.", ...rerouteImports, "", ...rerouteLines(choices), "");
78
- /**
79
- * The adapter `sv create` imports in its `vite.config.ts`: `init` swaps it for adapter-node, whose
80
- * server runs Git's jobs between requests, in the file the create command actually wrote, when the
81
- * import is in it exactly once.
82
- */
83
- const svelteAdapterAnchor = "'@sveltejs/adapter-auto'";
84
- /** What the anchor becomes: adapter-node's import. */
85
- const svelteNodeAdapter = "'@sveltejs/adapter-node'";
86
- /** `text` on adapter-node, or `undefined` where its adapter-auto import isn't there exactly once. */
87
- const onAdapterNode = (text) => {
88
- const at = text.indexOf(svelteAdapterAnchor);
89
- if (at === -1 || text.includes("'@sveltejs/adapter-auto'", at + 1)) return void 0;
90
- return `${text.slice(0, at)}${svelteNodeAdapter}${text.slice(at + 24)}`;
91
- };
92
- /** adapter-node's limit, 512 KB by default for every route, lifted so a push of any size gets in. */
93
- const bodySizeLimit = "BODY_SIZE_LIMIT=Infinity";
94
- /**
95
- * SvelteKit's `start`, the one framework start `init` writes. adapter-node reads `BODY_SIZE_LIMIT`
96
- * as its handler loads, before `server.init` runs the hook that imports the server module, which
97
- * loads `.env`: only Node's own `--env-file` reaches it in time.
98
- */
99
- const svelteStart = "node --env-file-if-exists=.env build";
100
- /** `package.json`'s `start`, or `undefined`. */
101
- const startOf = (packageJson) => packageJson === void 0 ? void 0 : stringAt(parseJsonc(packageJson), ["scripts", "start"]);
102
- /** `package.json` with SvelteKit's `start`, where it has none. */
103
- const withSvelteStart = (text) => withEntries(text, ["scripts"], { start: svelteStart });
104
- /** The step for the person's own `start`, where it neither loads `.env` nor sets the limit. */
105
- const svelteStartStep = (packageJson) => {
106
- const start = startOf(packageJson);
107
- if (start === void 0 || /--env-file|\bBODY_SIZE_LIMIT=/.test(start)) return [];
108
- return [{
109
- path: "package.json",
110
- why: "yours",
111
- says: "Load .env in your start script: adapter-node reads BODY_SIZE_LIMIT before Git's module loads .env",
112
- lines: [`"start": "${svelteStart}"`]
113
- }];
114
- };
115
- /**
116
- * Where `node build`, as `npm start` runs it, gets `BODY_SIZE_LIMIT=Infinity`, or `undefined` where
117
- * it keeps a limit. The value it reads is the first of the `start` script's own assignment, the
118
- * environment, which `--env-file` never overrides, and the env file the script loads. `.env`
119
- * alone counts for nothing: the server module loads it too late.
120
- */
121
- const svelteBodyLimit = (read, env) => {
122
- const start = startOf(read("package.json")) ?? "";
123
- const file = /--env-file(?:-if-exists)?[= ](\S+)/.exec(start)?.[1];
124
- const inFile = file === void 0 ? void 0 : /^BODY_SIZE_LIMIT=(.*)$/m.exec(read(file) ?? "")?.[1];
125
- const seen = [
126
- {
127
- from: "package.json's start script",
128
- value: /\bBODY_SIZE_LIMIT=(\S+)/.exec(start)?.[1]
129
- },
130
- {
131
- from: "The environment",
132
- value: env["BODY_SIZE_LIMIT"]
133
- },
134
- {
135
- from: `${file ?? ""}, which the start script loads,`,
136
- value: inFile
137
- }
138
- ].find((each) => each.value !== void 0);
139
- return seen?.value === "Infinity" ? seen.from : void 0;
140
- };
141
- export { bodySizeLimit, onAdapterNode, svelteAdapterAnchor, svelteBodyLimit, svelteHooks, svelteInitLines, svelteNodeAdapter, svelteRerouteLines, svelteRouteFiles, svelteServerHooks, svelteStart, svelteStartStep, withSvelteStart };