@valbuild/server 0.134.1 → 0.136.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,151 @@
1
1
  # @valbuild/server
2
2
 
3
+ ## 0.136.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#713](https://github.com/valbuild/val/pull/713) [`f3a4bb7`](https://github.com/valbuild/val/commit/f3a4bb7aea604943b92545c122243798c759715c) Thanks [@freekh](https://github.com/freekh)! - The Studio can load a bundler, and it stops telling a managed project that its
8
+ publish is on its way out.
9
+
10
+ **A managed project is one with no repository and no host watching one.** There
11
+ is nothing outside the browser to pick a commit up, so the Studio has been
12
+ showing it a story that belongs to a project with a repository: a `Building`
13
+ spinner, waiting for an event that can never arrive. It does not resolve on a
14
+ reload, on a retry, or tomorrow, and there is no way to tell it from a deploy
15
+ that is merely slow.
16
+
17
+ The content service now reports which kind of project this is, as `sourceMode`
18
+ on `/stat`, and the Studio narrates accordingly:
19
+
20
+ - a **connected** project keeps the deploy feed and keeps `Building`, because
21
+ there a host genuinely does pick the commit up;
22
+ - a **managed** one says `Saved, not yet live` instead — a durable condition,
23
+ not a phase, because nothing else will ever resolve it.
24
+
25
+ A server that reports no source mode keeps the behaviour it has today. Absence
26
+ means "not reported", never "managed": `fs` mode has no project to have a mode,
27
+ and neither does a content service that predates the field.
28
+
29
+ **The Studio also loads `@valbuild/tanstack-build` in the tab**, at mount and at
30
+ idle, for the managed projects that will need it — a browser that is the
31
+ deployer needs a bundler. This is the groundwork for browser-side publishing;
32
+ the publish path itself is unchanged in this release.
33
+
34
+ That bundler is `@rolldown/browser`, whose WebAssembly binary is 10.9 MB and is
35
+ **not** in the npm package. It is served from `static.val.build`, addressed by
36
+ the SHA-256 of its own bytes, so the build and the binary it needs cannot drift
37
+ apart. A deployment that must not reach that host — an air-gapped install, a
38
+ mirror — sets `globalThis.__VAL_ROLLDOWN_WASM_URL__` before the Studio loads and
39
+ needs no rebuild.
40
+
41
+ **Building in the browser requires a cross-origin isolated page.** Rolldown runs
42
+ WebAssembly on worker threads that share memory, and a browser will not hand a
43
+ `SharedArrayBuffer` to a worker otherwise. Without
44
+ `Cross-Origin-Opener-Policy: same-origin` and
45
+ `Cross-Origin-Embedder-Policy: require-corp` on the document Val is mounted in,
46
+ loading the bundler now fails with a message that says exactly that, instead of
47
+ a `DataCloneError` thrown from inside a worker. Nothing else in this release is
48
+ affected: a Studio that never builds in the browser never asks.
49
+
50
+ ### Patch Changes
51
+
52
+ - [#699](https://github.com/valbuild/val/pull/699) [`1d72d00`](https://github.com/valbuild/val/commit/1d72d00a1b036959ae0f1540121701cbb2694dcb) Thanks [@freekh](https://github.com/freekh)! - A `*.val.ts` with no default export is no longer reported as a missing module
53
+
54
+ `*.val.ts` is a naming convention, not a promise: plenty of files under it hold
55
+ only the schemas and helpers the modules beside them import. Every one of those
56
+ was getting two errors in the editor — `Module '…' was not found in
57
+ val.modules` and `… is not registered in val.modules, so Val will not serve it`
58
+ — both on line 1, telling their author to register a file that has nothing to
59
+ register. `val validate` has never reported them; only the editor did.
60
+
61
+ The default export is what makes a `*.val.ts` a module, so that is what the
62
+ diagnostic now asks about:
63
+
64
+ - **No default export → nothing is reported.** The file is not a module, so it
65
+ is not a module Val is failing to serve.
66
+ - **A default export → one diagnostic, on the `export default` itself** rather
67
+ than on line 1, so it is next to the thing that has to change, and the
68
+ duplicate fatal beside it is gone. The message now gives both remedies: add
69
+ the file to `val.modules`, or export what it holds by name instead. The "Val:
70
+ register … in val.modules" quick fix is offered there.
71
+
72
+ The rule is `findDefaultExport` in `@valbuild/server`, which `val validate`
73
+ already used to decide the same question — so the editor and the CLI now agree
74
+ about which files are modules, including the cases that are easy to get wrong
75
+ (`export * from …` carries no default; `export type { T as default }` and
76
+ `export default interface T {}` are both gone after transpilation).
77
+
78
+ Because the diagnostic now replaces a module's own findings rather than adding
79
+ to them, the editor also stops guessing about registration it cannot read: a
80
+ `val.modules` that registers modules through a tsconfig path alias
81
+ (`import("_/content/page.val")`), or that builds its list in another file, is no
82
+ longer taken to register nothing.
83
+
84
+ - Updated dependencies [[`f3a4bb7`](https://github.com/valbuild/val/commit/f3a4bb7aea604943b92545c122243798c759715c)]:
85
+ - @valbuild/ui@0.136.0
86
+ - @valbuild/core@0.136.0
87
+ - @valbuild/shared@0.136.0
88
+
89
+ ## 0.135.0
90
+
91
+ ### Patch Changes
92
+
93
+ - [#707](https://github.com/valbuild/val/pull/707) [`c9affec`](https://github.com/valbuild/val/commit/c9affece6ae6ba62bd6c1113ed1fdab6317fa112) Thanks [@freekh](https://github.com/freekh)! - `val validate --fix` now formats with your prettier config instead of prettier's defaults
94
+
95
+ `--fix` formatted the files it repaired by calling `prettier.format(code, { filepath })`, which never reads `.prettierrc`: `filepath` picks the parser and nothing else — only `resolveConfig`, `getFileInfo` and prettier's own CLI consult the config. On a project whose style is not prettier's default, a two-line content fix therefore arrived as a whole-file rewrite, and in a repo with a format check in CI it turned a content fix into a red build.
96
+
97
+ There is now one implementation of "format a written file the way this project does", `createPrettierFormatter`, exported from `@valbuild/server` and re-exported by `@valbuild/next/server` and `@valbuild/tanstack/server`. It resolves `.prettierrc` for each file (including any `overrides` that match it), leaves anything in `.prettierignore` untouched, and falls back to prettier's defaults when the project has no config. `val validate --fix` uses it, so the CLI and the Studio can no longer disagree about formatting.
98
+
99
+ Use it for your app's `formatter` too — this is the recommended setup, and it replaces reading `.prettierrc.json` by hand:
100
+
101
+ ```ts
102
+ import prettier from "prettier";
103
+ import {
104
+ initValServer,
105
+ createPrettierFormatter,
106
+ } from "@valbuild/next/server";
107
+
108
+ const { valNextAppRouter } = initValServer(
109
+ valModules,
110
+ { ...config },
111
+ {
112
+ draftMode,
113
+ formatter: createPrettierFormatter(prettier, {
114
+ projectRoot: process.cwd(),
115
+ }),
116
+ },
117
+ );
118
+ ```
119
+
120
+ Existing `formatter` callbacks keep working unchanged.
121
+
122
+ - [#706](https://github.com/valbuild/val/pull/706) [`72a7ca7`](https://github.com/valbuild/val/commit/72a7ca78354fff00e37a51359b17fba9334dc5e6) Thanks [@freekh](https://github.com/freekh)! - An endpoint that throws now answers Val's own 500 instead of the framework's.
123
+
124
+ Nothing caught a throw from an endpoint implementation, so it left the Val
125
+ router entirely and became whatever the host does with an unhandled error. On
126
+ TanStack Start that is h3, which replaces the message with the literal string
127
+ `"HTTPError"` and drops the stack — the same five words for a missing project,
128
+ a bad cookie and a module that failed to link — and keeps the real cause on the
129
+ server console. Where that console cannot be read (a Cloudflare Worker, for
130
+ one), a Val server had no way to say what broke inside it.
131
+
132
+ Such a request now answers Val's usual error envelope, naming the route, the
133
+ method and the cause:
134
+
135
+ ```json
136
+ {
137
+ "message": "Val: GET /authorize failed: Project is not set",
138
+ "details": {
139
+ "route": "/authorize",
140
+ "method": "GET",
141
+ "error": "Project is not set"
142
+ }
143
+ }
144
+ ```
145
+
146
+ The stack is logged rather than returned: `/authorize` and `/enable` are
147
+ reachable without a session, and the message is the part a caller can act on.
148
+
3
149
  ## 0.134.1
4
150
 
5
151
  ### Patch Changes
@@ -417,6 +417,22 @@ export declare abstract class ValOps {
417
417
  * project requires.
418
418
  */
419
419
  publishRefusal(): PublishRefusal | null;
420
+ /**
421
+ * How this project's SOURCE is kept, or `null` when it is nobody's question.
422
+ *
423
+ * `"managed"` -- the content service is the store of record, there is no
424
+ * repository, and nothing outside the browser will ever pick a commit up.
425
+ * `"connected"` -- commits are mirrored into a repository a host watches.
426
+ *
427
+ * `null` is the honest answer for `fs` and memory mode, where publishing is
428
+ * writing to disk and there is no project to have a mode, and for an `http`
429
+ * project whose content service predates the field. The Studio treats it as
430
+ * "the story I have always told", which is the connected one -- the feed, and
431
+ * a `building` state that something outside resolves. Guessing `managed`
432
+ * instead would take the deploy feed away from every project running against
433
+ * an older service.
434
+ */
435
+ sourceMode(): "managed" | "connected" | null;
420
436
  /**
421
437
  * Whether a commit here produces `.val.ts` TEXT as well as data.
422
438
  *
@@ -126,6 +126,21 @@ export declare class ValOpsHttp extends ValOps {
126
126
  * checking.
127
127
  */
128
128
  publishRefusal(): PublishRefusal | null;
129
+ /**
130
+ * What the content service last said this project's source mode is.
131
+ *
132
+ * Read off the same remembered expectation {@link publishRefusal} uses. It is
133
+ * CURRENT wherever it matters rather than a poll behind, and by construction
134
+ * rather than by luck: the only caller is `/stat`, which awaits `getStat`
135
+ * first, and that fetches the patches -- which is the response the expectation
136
+ * is recorded from.
137
+ *
138
+ * `null` before anything has fetched patches, which is the same "not
139
+ * reported" the wire field means, and reads as connected. The alternative
140
+ * would be to ask for it separately, which is a round trip for a field that
141
+ * has just arrived.
142
+ */
143
+ sourceMode(): "managed" | "connected" | null;
129
144
  onInit(): Promise<void>;
130
145
  getPresignedAuthNonce(profileId: string, corsOrigin: string): Promise<{
131
146
  status: "success";
@@ -0,0 +1,87 @@
1
+ /**
2
+ * What Val calls to format a file it has just written.
3
+ *
4
+ * The same shape `initValServer`, `initValMcp` and `ValOps` take as their
5
+ * `formatter` option. The path is the file's path INSIDE the project — a
6
+ * `ModuleFilePath` such as `/content/page.val.ts`, or a `*.val.json` entry
7
+ * beside it — never an absolute path on disk, because the writers that call it
8
+ * (`ValOps.prepare`, the CLI's `--fix`) only ever know a module by that path.
9
+ */
10
+ export type ValFormatter = (code: string, filePath: string) => Promise<string> | string;
11
+ /**
12
+ * Prettier's options, as far as this file is concerned.
13
+ *
14
+ * Deliberately opaque: this file never reads an option, it only carries the
15
+ * bag from `resolveConfig` to `format`. Naming the real `Options` here would
16
+ * make it a compile error to build `@valbuild/server` in a project that has no
17
+ * prettier installed, which is most of them — prettier is a dependency the app
18
+ * opts into, so it is passed IN rather than imported.
19
+ */
20
+ export type PrettierLikeConfig = object;
21
+ /**
22
+ * `prettier`, as this file wants it.
23
+ *
24
+ * Structural for the same reason `SharpLike` in `@valbuild/mcp` is: a type-only
25
+ * import of a package that is not installed is still a compile error, and this
26
+ * package has to typecheck without prettier. `createPrettierFormatter.test.ts`
27
+ * asserts the real library against this type so the structural description
28
+ * cannot drift away from it unnoticed.
29
+ *
30
+ * Every result is `T | Promise<T>` so that `@prettier/sync` — the same API with
31
+ * the awaits taken out — satisfies it too. Everything here is awaited either
32
+ * way, and a formatter is allowed to be synchronous: `ValFormatter` says so.
33
+ */
34
+ export type PrettierLike = {
35
+ format(source: string, options: PrettierLikeConfig & {
36
+ filepath: string;
37
+ }): Promise<string> | string;
38
+ resolveConfig(filePath: string): Promise<PrettierLikeConfig | null> | PrettierLikeConfig | null;
39
+ getFileInfo(filePath: string, options: {
40
+ ignorePath: string[];
41
+ }): Promise<{
42
+ ignored: boolean;
43
+ }> | {
44
+ ignored: boolean;
45
+ };
46
+ };
47
+ /**
48
+ * A {@link ValFormatter} that formats the way the project itself does.
49
+ *
50
+ * ONE implementation, for every writer of source files Val has: the Studio and
51
+ * the dev server (`initValServer`), an agent (`initValMcp`) and
52
+ * `val validate --fix`. They used to disagree — the CLI called
53
+ * `prettier.format(code, { filepath })` on its own behalf, and `format` does
54
+ * not read `.prettierrc`; only `resolveConfig`, `getFileInfo` and the prettier
55
+ * CLI do. `filepath` there selects the PARSER and nothing else, so the output
56
+ * was valid TypeScript in prettier's default style rather than the project's:
57
+ * a two-line content fix arriving as a whole-file rewrite, and a red `format`
58
+ * job in any repo that checks formatting in CI.
59
+ *
60
+ * ```ts
61
+ * import prettier from "prettier";
62
+ * import { createPrettierFormatter } from "@valbuild/next/server";
63
+ *
64
+ * initValServer(valModules, config, {
65
+ * draftMode,
66
+ * formatter: createPrettierFormatter(prettier, { projectRoot: process.cwd() }),
67
+ * });
68
+ * ```
69
+ *
70
+ * `projectRoot` is what a project-relative path is resolved against, and is
71
+ * therefore also where `.prettierignore` is looked for. Prettier's own config
72
+ * search walks UP from the resolved file, so a monorepo package with its own
73
+ * `.prettierrc` is found without being named here.
74
+ *
75
+ * Two decisions worth knowing:
76
+ *
77
+ * - **`.prettierignore` is honoured; `.gitignore` is not.** The prettier CLI
78
+ * consults both, but only one of them is a statement about formatting — a
79
+ * file is gitignored for reasons that have nothing to do with style, and the
80
+ * only files reaching this function are ones Val itself just wrote.
81
+ * - **No config found is not an error.** `resolveConfig` returns `null` and
82
+ * the file is formatted with prettier's defaults, which is what a project
83
+ * without a config has asked for.
84
+ */
85
+ export declare function createPrettierFormatter(prettier: PrettierLike, options: {
86
+ projectRoot: string;
87
+ }): ValFormatter;
@@ -29,6 +29,8 @@ export { getValidationErrorFileRef } from "./getValidationErrorFileRef.js";
29
29
  export { checkRemoteRef, downloadFileFromRemote, getCachedRemoteFileDir, getCachedRemoteFilePath, } from "./checkRemoteRef.js";
30
30
  export { hasRemoteFileSchema } from "@valbuild/core";
31
31
  export { getFileExt } from "./getFileExt.js";
32
+ export { createPrettierFormatter } from "./createPrettierFormatter.js";
33
+ export type { PrettierLike, PrettierLikeConfig, ValFormatter, } from "./createPrettierFormatter.js";
32
34
  export { evalValConfigFile, findAndEvalValConfigFile, } from "./evalValConfigFile.js";
33
35
  export { startValLogin, awaitValLoginConfirmation, persistPersonalAccessToken, ValLoginError, DEFAULT_LOGIN_HOST, DEFAULT_LOGIN_EXPIRES_IN_SECONDS, DEFAULT_LOGIN_POLL_INTERVAL_SECONDS, } from "./login.js";
34
36
  export type { ValLoginErrorCode, ValLoginResult, ValDeviceAuthorization, } from "./login.js";
@@ -42,7 +44,7 @@ export type { ModulePathMap } from "./modulePathMap.js";
42
44
  export { ValOpsFS } from "./ValOpsFS.js";
43
45
  export { ValOpsHttp } from "./ValOpsHttp.js";
44
46
  export { ValOpsMemory, InMemoryPatchStore, type ValPatchStore, type StoredPatch, type ValOpsMemoryOptions, } from "./ValOpsMemory.js";
45
- export { loadValModules, createValModuleFileInspector } from "./loadValModules.js";
47
+ export { loadValModules, createValModuleFileInspector, findDefaultExport, } from "./loadValModules.js";
46
48
  export type { ValModuleFileInspection } from "./loadValModules.js";
47
49
  export { formatPatchSourceError } from "./ValOps.js";
48
50
  export { compareWithCapturedReport, readCapturedReport, replaySnapshot, } from "./debug/replaySnapshot.js";
@@ -71,3 +71,26 @@ export type ValModuleFileInspection =
71
71
  * project's own first-party files.
72
72
  */
73
73
  export declare function createValModuleFileInspector(projectRoot: string, host?: ValModulesHost): (absPath: string) => ValModuleFileInspection;
74
+ /**
75
+ * The statement that exports a RUNTIME value as `default`, without evaluating
76
+ * it — or `undefined` when the file has no such export.
77
+ *
78
+ * This is the one rule that separates a Val module from a `*.val.ts` that
79
+ * merely wears the naming convention: a shared schema or helper is exported by
80
+ * name, a module is exported by default. Every caller that needs to tell those
81
+ * apart goes through this — `val validate` to decide whether an unregistered
82
+ * file is worth reporting, and the language server to decide the same thing and
83
+ * to put its diagnostic on the export rather than on line 1.
84
+ *
85
+ * Two things deliberately do not count, because neither exists once the file is
86
+ * transpiled — and treating either as a default export would send a pure helper
87
+ * off to be evaluated and reported:
88
+ *
89
+ * - `export * from "./x"`, since a star re-export never carries the default;
90
+ * - a type-only export, in any of its three spellings
91
+ * (`export type { T as default }`, `export { type T as default }` and
92
+ * `export default interface T {}` — the last one parses as a declaration
93
+ * carrying a `default` modifier, exactly like `export default class`, and is
94
+ * the one that looks like a runtime export and is not).
95
+ */
96
+ export declare function findDefaultExport(sourceFile: ts.SourceFile): ts.Statement | undefined;
@@ -1007,18 +1007,29 @@ function createValModuleFileInspector(projectRoot, host = ts__default["default"]
1007
1007
  }
1008
1008
 
1009
1009
  /**
1010
- * Whether the file exports a RUNTIME value as `default`, without evaluating it.
1010
+ * The statement that exports a RUNTIME value as `default`, without evaluating
1011
+ * it — or `undefined` when the file has no such export.
1012
+ *
1013
+ * This is the one rule that separates a Val module from a `*.val.ts` that
1014
+ * merely wears the naming convention: a shared schema or helper is exported by
1015
+ * name, a module is exported by default. Every caller that needs to tell those
1016
+ * apart goes through this — `val validate` to decide whether an unregistered
1017
+ * file is worth reporting, and the language server to decide the same thing and
1018
+ * to put its diagnostic on the export rather than on line 1.
1011
1019
  *
1012
1020
  * Two things deliberately do not count, because neither exists once the file is
1013
1021
  * transpiled — and treating either as a default export would send a pure helper
1014
1022
  * off to be evaluated and reported:
1015
1023
  *
1016
1024
  * - `export * from "./x"`, since a star re-export never carries the default;
1017
- * - a type-only export, in either of its spellings
1018
- * (`export type { T as default }` and `export { type T as default }`).
1025
+ * - a type-only export, in any of its three spellings
1026
+ * (`export type { T as default }`, `export { type T as default }` and
1027
+ * `export default interface T {}` — the last one parses as a declaration
1028
+ * carrying a `default` modifier, exactly like `export default class`, and is
1029
+ * the one that looks like a runtime export and is not).
1019
1030
  */
1020
- function hasDefaultExport(sourceFile) {
1021
- return sourceFile.statements.some(statement => {
1031
+ function findDefaultExport(sourceFile) {
1032
+ return sourceFile.statements.find(statement => {
1022
1033
  // `export default <expr>` — but not `export = x`, which shares this node.
1023
1034
  if (ts__default["default"].isExportAssignment(statement)) {
1024
1035
  return !statement.isExportEquals;
@@ -1029,10 +1040,17 @@ function hasDefaultExport(sourceFile) {
1029
1040
  }
1030
1041
  // `export default function f() {}` / `export default class C {}`, which are
1031
1042
  // declarations carrying a `default` modifier rather than export assignments.
1032
- return ts__default["default"].canHaveModifiers(statement) && (ts__default["default"].getModifiers(statement) ?? []).some(modifier => modifier.kind === ts__default["default"].SyntaxKind.DefaultKeyword);
1043
+ // `export default interface T {}` is spelled the same way and is a type, so
1044
+ // it is excluded here rather than by the `isTypeOnly` checks above.
1045
+ return !ts__default["default"].isInterfaceDeclaration(statement) && ts__default["default"].canHaveModifiers(statement) && (ts__default["default"].getModifiers(statement) ?? []).some(modifier => modifier.kind === ts__default["default"].SyntaxKind.DefaultKeyword);
1033
1046
  });
1034
1047
  }
1035
1048
 
1049
+ /** Whether the file exports a runtime value as `default`. */
1050
+ function hasDefaultExport(sourceFile) {
1051
+ return findDefaultExport(sourceFile) !== undefined;
1052
+ }
1053
+
1036
1054
  /** A short, human-readable "what you exported instead" for the error message. */
1037
1055
  function describeDefaultExport(value) {
1038
1056
  if (value === null) {
@@ -4558,6 +4576,25 @@ class ValOps {
4558
4576
  return null;
4559
4577
  }
4560
4578
 
4579
+ /**
4580
+ * How this project's SOURCE is kept, or `null` when it is nobody's question.
4581
+ *
4582
+ * `"managed"` -- the content service is the store of record, there is no
4583
+ * repository, and nothing outside the browser will ever pick a commit up.
4584
+ * `"connected"` -- commits are mirrored into a repository a host watches.
4585
+ *
4586
+ * `null` is the honest answer for `fs` and memory mode, where publishing is
4587
+ * writing to disk and there is no project to have a mode, and for an `http`
4588
+ * project whose content service predates the field. The Studio treats it as
4589
+ * "the story I have always told", which is the connected one -- the feed, and
4590
+ * a `building` state that something outside resolves. Guessing `managed`
4591
+ * instead would take the deploy feed away from every project running against
4592
+ * an older service.
4593
+ */
4594
+ sourceMode() {
4595
+ return null;
4596
+ }
4597
+
4561
4598
  /**
4562
4599
  * Whether a commit here produces `.val.ts` TEXT as well as data.
4563
4600
  *
@@ -7917,6 +7954,25 @@ class ValOpsHttp extends ValOps {
7917
7954
  message: `This project mirrors its content into a git repository (branch ` + `'${this.projectExpectation.branch}'), but this deployment was not ` + "built from one, so it does not know which commit to write that " + "mirror against. Publishing would save the content and silently " + "leave the repository behind. Deploy this project again from its " + "repository, and publishing will work from that build on."
7918
7955
  };
7919
7956
  }
7957
+
7958
+ /**
7959
+ * What the content service last said this project's source mode is.
7960
+ *
7961
+ * Read off the same remembered expectation {@link publishRefusal} uses. It is
7962
+ * CURRENT wherever it matters rather than a poll behind, and by construction
7963
+ * rather than by luck: the only caller is `/stat`, which awaits `getStat`
7964
+ * first, and that fetches the patches -- which is the response the expectation
7965
+ * is recorded from.
7966
+ *
7967
+ * `null` before anything has fetched patches, which is the same "not
7968
+ * reported" the wire field means, and reads as connected. The alternative
7969
+ * would be to ask for it separately, which is a round trip for a field that
7970
+ * has just arrived.
7971
+ */
7972
+ sourceMode() {
7973
+ var _this$projectExpectat2;
7974
+ return ((_this$projectExpectat2 = this.projectExpectation) === null || _this$projectExpectat2 === void 0 ? void 0 : _this$projectExpectat2.sourceMode) ?? null;
7975
+ }
7920
7976
  async onInit() {
7921
7977
  // TODO: unused for now. Implement or remove
7922
7978
  }
@@ -11898,6 +11954,16 @@ const ValServer = (valModules, options, callbacks) => {
11898
11954
  * it failed to compute.
11899
11955
  */
11900
11956
  const publishRefusal = serverOps.publishRefusal();
11957
+ /*
11958
+ * How this project's source is kept, when the store knows.
11959
+ *
11960
+ * Spread for the same reason `publishRefusal` is: absent has to keep
11961
+ * meaning "not reported" rather than becoming a mode. The Studio
11962
+ * narrates a publish differently for a managed project -- there is
11963
+ * nothing outside the browser to finish it -- so a wrong default here
11964
+ * shows one story to a project that lives by the other.
11965
+ */
11966
+ const sourceMode = serverOps.sourceMode();
11901
11967
  return {
11902
11968
  status: 200,
11903
11969
  json: {
@@ -11907,6 +11973,9 @@ const ValServer = (valModules, options, callbacks) => {
11907
11973
  ...(publishRefusal ? {
11908
11974
  publishRefusal
11909
11975
  } : {}),
11976
+ ...(sourceMode ? {
11977
+ sourceMode
11978
+ } : {}),
11910
11979
  config: options.config
11911
11980
  }
11912
11981
  };
@@ -15311,12 +15380,62 @@ function createValApiRouter(route, valServerPromise, convert) {
15311
15380
  }
15312
15381
  query = queryRes.data;
15313
15382
  }
15314
- const res = await endpointImpl({
15315
- body: bodyRes.data,
15316
- cookies: cookiesRes.data,
15317
- query,
15318
- path
15319
- });
15383
+
15384
+ /*
15385
+ * A throw from an endpoint is Val's to report, not the framework's.
15386
+ *
15387
+ * Nothing here used to catch, so an endpoint that threw left the router
15388
+ * entirely and became whatever the host does with an unhandled error --
15389
+ * and on TanStack Start that is h3, which replaces the message with the
15390
+ * literal string "HTTPError" and drops the stack. Its `debug` and
15391
+ * `silent` options are not reachable from out here: `requestHandler`
15392
+ * calls `toResponse(value, event)` with no config, and the default is
15393
+ * `{}`. So the body a caller got was
15394
+ * `{"status":500,"unhandled":true,"message":"HTTPError"}` -- the same
15395
+ * five words for a missing project, a bad cookie secret and a module
15396
+ * that failed to link -- with the real cause only on the server's
15397
+ * console.
15398
+ *
15399
+ * That is survivable where the console is readable. It is not in a
15400
+ * Cloudflare Dynamic Worker, whose `console` reaches no tail stream: a
15401
+ * link error in a lazily imported chunk (`does not provide an export
15402
+ * named 'getSerovalPlugins'`) showed up as an unreadable 500 on
15403
+ * `/authorize` and nowhere else at all.
15404
+ *
15405
+ * So every endpoint's throw becomes Val's own 500 envelope, which the
15406
+ * Studio already renders and `curl` already prints. The route and method
15407
+ * are named because a message rarely says which endpoint it came from.
15408
+ *
15409
+ * The MESSAGE travels and the STACK does not. The message is the whole
15410
+ * diagnostic value -- the line above names the package, the chunk and
15411
+ * the export -- while a stack is a walk through somebody's bundle, and
15412
+ * `/authorize` and `/enable` are reachable without a session. So the
15413
+ * stack goes to the console, where a host that can read one will find
15414
+ * it, and the body carries what a caller can act on.
15415
+ */
15416
+ let res;
15417
+ try {
15418
+ res = await endpointImpl({
15419
+ body: bodyRes.data,
15420
+ cookies: cookiesRes.data,
15421
+ query,
15422
+ path
15423
+ });
15424
+ } catch (err) {
15425
+ const error = err instanceof Error ? err : new Error(String(err));
15426
+ console.error(`Val: ${method} ${route} threw: ${error.message}`, error.stack);
15427
+ return {
15428
+ status: 500,
15429
+ json: {
15430
+ message: `Val: ${method} ${route} failed: ${error.message}`,
15431
+ details: {
15432
+ route,
15433
+ method,
15434
+ error: error.message
15435
+ }
15436
+ }
15437
+ };
15438
+ }
15320
15439
  if (res.status === 500) {
15321
15440
  var _res$json;
15322
15441
  return {
@@ -17246,6 +17365,123 @@ function validateMetadata(actualMetadata, expectedMetadata) {
17246
17365
  };
17247
17366
  }
17248
17367
 
17368
+ /**
17369
+ * What Val calls to format a file it has just written.
17370
+ *
17371
+ * The same shape `initValServer`, `initValMcp` and `ValOps` take as their
17372
+ * `formatter` option. The path is the file's path INSIDE the project — a
17373
+ * `ModuleFilePath` such as `/content/page.val.ts`, or a `*.val.json` entry
17374
+ * beside it — never an absolute path on disk, because the writers that call it
17375
+ * (`ValOps.prepare`, the CLI's `--fix`) only ever know a module by that path.
17376
+ */
17377
+
17378
+ /**
17379
+ * Prettier's options, as far as this file is concerned.
17380
+ *
17381
+ * Deliberately opaque: this file never reads an option, it only carries the
17382
+ * bag from `resolveConfig` to `format`. Naming the real `Options` here would
17383
+ * make it a compile error to build `@valbuild/server` in a project that has no
17384
+ * prettier installed, which is most of them — prettier is a dependency the app
17385
+ * opts into, so it is passed IN rather than imported.
17386
+ */
17387
+
17388
+ /**
17389
+ * `prettier`, as this file wants it.
17390
+ *
17391
+ * Structural for the same reason `SharpLike` in `@valbuild/mcp` is: a type-only
17392
+ * import of a package that is not installed is still a compile error, and this
17393
+ * package has to typecheck without prettier. `createPrettierFormatter.test.ts`
17394
+ * asserts the real library against this type so the structural description
17395
+ * cannot drift away from it unnoticed.
17396
+ *
17397
+ * Every result is `T | Promise<T>` so that `@prettier/sync` — the same API with
17398
+ * the awaits taken out — satisfies it too. Everything here is awaited either
17399
+ * way, and a formatter is allowed to be synchronous: `ValFormatter` says so.
17400
+ */
17401
+
17402
+ /**
17403
+ * Resolve a path Val handed us against the project.
17404
+ *
17405
+ * Val's writers pass a project-relative path (`/content/page.val.ts`), and
17406
+ * prettier needs a real one — both to find the `.prettierrc` that governs the
17407
+ * file and to match it against `.prettierignore`. An absolute path that is
17408
+ * already inside the project is taken as it comes, so a caller that happens to
17409
+ * hold a real path is not mangled into `<root>/<root>/...`.
17410
+ */
17411
+ function resolveAgainstProject(projectRoot, filePath) {
17412
+ if (path__namespace["default"].isAbsolute(filePath)) {
17413
+ const relative = path__namespace["default"].relative(projectRoot, filePath);
17414
+ if (relative && !relative.startsWith("..") && !path__namespace["default"].isAbsolute(relative)) {
17415
+ return filePath;
17416
+ }
17417
+ }
17418
+ return path__namespace["default"].join(projectRoot, filePath);
17419
+ }
17420
+
17421
+ /**
17422
+ * A {@link ValFormatter} that formats the way the project itself does.
17423
+ *
17424
+ * ONE implementation, for every writer of source files Val has: the Studio and
17425
+ * the dev server (`initValServer`), an agent (`initValMcp`) and
17426
+ * `val validate --fix`. They used to disagree — the CLI called
17427
+ * `prettier.format(code, { filepath })` on its own behalf, and `format` does
17428
+ * not read `.prettierrc`; only `resolveConfig`, `getFileInfo` and the prettier
17429
+ * CLI do. `filepath` there selects the PARSER and nothing else, so the output
17430
+ * was valid TypeScript in prettier's default style rather than the project's:
17431
+ * a two-line content fix arriving as a whole-file rewrite, and a red `format`
17432
+ * job in any repo that checks formatting in CI.
17433
+ *
17434
+ * ```ts
17435
+ * import prettier from "prettier";
17436
+ * import { createPrettierFormatter } from "@valbuild/next/server";
17437
+ *
17438
+ * initValServer(valModules, config, {
17439
+ * draftMode,
17440
+ * formatter: createPrettierFormatter(prettier, { projectRoot: process.cwd() }),
17441
+ * });
17442
+ * ```
17443
+ *
17444
+ * `projectRoot` is what a project-relative path is resolved against, and is
17445
+ * therefore also where `.prettierignore` is looked for. Prettier's own config
17446
+ * search walks UP from the resolved file, so a monorepo package with its own
17447
+ * `.prettierrc` is found without being named here.
17448
+ *
17449
+ * Two decisions worth knowing:
17450
+ *
17451
+ * - **`.prettierignore` is honoured; `.gitignore` is not.** The prettier CLI
17452
+ * consults both, but only one of them is a statement about formatting — a
17453
+ * file is gitignored for reasons that have nothing to do with style, and the
17454
+ * only files reaching this function are ones Val itself just wrote.
17455
+ * - **No config found is not an error.** `resolveConfig` returns `null` and
17456
+ * the file is formatted with prettier's defaults, which is what a project
17457
+ * without a config has asked for.
17458
+ */
17459
+ function createPrettierFormatter(prettier, options) {
17460
+ const projectRoot = path__namespace["default"].resolve(options.projectRoot);
17461
+ // One array, built once: prettier reads and caches the ignore file itself, so
17462
+ // this is only here to avoid rebuilding the path per file.
17463
+ const ignorePath = [path__namespace["default"].join(projectRoot, ".prettierignore")];
17464
+ return async (code, filePath) => {
17465
+ const absoluteFilePath = resolveAgainstProject(projectRoot, filePath);
17466
+ const {
17467
+ ignored
17468
+ } = await prettier.getFileInfo(absoluteFilePath, {
17469
+ ignorePath
17470
+ });
17471
+ if (ignored) {
17472
+ return code;
17473
+ }
17474
+ // `resolveConfig` applies the `overrides` that match this file and caches
17475
+ // per directory, so calling it per file is cheap even on a project-wide
17476
+ // `--fix`. `filepath` is still required: it is what picks the parser.
17477
+ const config = await prettier.resolveConfig(absoluteFilePath);
17478
+ return prettier.format(code, {
17479
+ ...config,
17480
+ filepath: absoluteFilePath
17481
+ });
17482
+ };
17483
+ }
17484
+
17249
17485
  /**
17250
17486
  * NOTE: this is intentionally NOT `SharedValConfig` from `@valbuild/shared`.
17251
17487
  * That schema requires `files.directory` to be exactly `/public/val`, whereas
@@ -17854,6 +18090,7 @@ exports.createDefaultValFSHost = createDefaultValFSHost;
17854
18090
  exports.createFixPatch = createFixPatch;
17855
18091
  exports.createJsonEntryPathMap = createJsonEntryPathMap;
17856
18092
  exports.createModulePathMap = createModulePathMap;
18093
+ exports.createPrettierFormatter = createPrettierFormatter;
17857
18094
  exports.createService = createService;
17858
18095
  exports.createValApiRouter = createValApiRouter;
17859
18096
  exports.createValModuleFileInspector = createValModuleFileInspector;
@@ -17871,6 +18108,7 @@ exports.extractFileMetadata = extractFileMetadata;
17871
18108
  exports.extractImageMetadata = extractImageMetadata;
17872
18109
  exports.extractJsonValuesEntry = extractJsonValuesEntry;
17873
18110
  exports.findAndEvalValConfigFile = findAndEvalValConfigFile;
18111
+ exports.findDefaultExport = findDefaultExport;
17874
18112
  exports.findJsonEntryFilePath = findJsonEntryFilePath;
17875
18113
  exports.fixHandlers = fixHandlers;
17876
18114
  exports.formatPatchSourceError = formatPatchSourceError;