@valbuild/server 0.150.23 → 0.152.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 (66) hide show
  1. package/CHANGELOG.md +341 -0
  2. package/browser/dist/valbuild-server-browser.cjs.dev.js +5 -137
  3. package/browser/dist/valbuild-server-browser.cjs.prod.js +5 -137
  4. package/browser/dist/valbuild-server-browser.esm.js +4 -140
  5. package/dist/ValRouter-05fcb0da.esm.js +14663 -0
  6. package/dist/ValRouter-afcba447.cjs.dev.js +14759 -0
  7. package/dist/ValRouter-b4e5b412.cjs.prod.js +14759 -0
  8. package/dist/{ValRouterCore-0c7ae881.cjs.prod.js → ValRouterCore-a0ea46bf.cjs.prod.js} +3324 -1883
  9. package/dist/{ValRouterCore-5b6cccd4.esm.js → ValRouterCore-b5d70504.esm.js} +3316 -1879
  10. package/dist/{ValRouterCore-cfa7b001.cjs.dev.js → ValRouterCore-d16c3327.cjs.dev.js} +3324 -1883
  11. package/dist/declarations/src/ValOps.d.ts +334 -70
  12. package/dist/declarations/src/ValOpsFS.d.ts +32 -0
  13. package/dist/declarations/src/ValOpsHttp.d.ts +93 -3
  14. package/dist/declarations/src/ValOpsMemory.d.ts +22 -47
  15. package/dist/declarations/src/ValRouter.d.ts +10 -0
  16. package/dist/declarations/src/ValServer.d.ts +0 -10
  17. package/dist/declarations/src/browser/inTabFetch.d.ts +19 -2
  18. package/dist/declarations/src/draftOverlay.d.ts +51 -0
  19. package/dist/declarations/src/draftReads.d.ts +103 -0
  20. package/dist/declarations/src/head.d.ts +312 -0
  21. package/dist/declarations/src/history/getJsonEntryAtCommit.d.ts +52 -0
  22. package/dist/declarations/src/index.d.ts +1 -0
  23. package/dist/declarations/src/internal/browser/index.d.ts +11 -0
  24. package/dist/declarations/src/internal/index.d.ts +15 -0
  25. package/dist/declarations/src/patch/jsonValuesPatch.d.ts +2 -165
  26. package/dist/declarations/src/patch/ts/jsonValuesModule.d.ts +38 -0
  27. package/dist/declarations/src/patch/ts/loadTypeScriptKit.d.ts +14 -0
  28. package/dist/declarations/src/patch/ts/ops.d.ts +45 -0
  29. package/dist/declarations/src/patch/ts/publishKit.d.ts +26 -0
  30. package/dist/declarations/src/platform.d.ts +14 -0
  31. package/dist/declarations/src/proposal.d.ts +54 -3
  32. package/dist/declarations/src/valRuntime.d.ts +35 -0
  33. package/dist/draftReads-05415ff6.cjs.dev.js +366 -0
  34. package/dist/draftReads-5f99edd3.esm.js +361 -0
  35. package/dist/draftReads-ea3946e0.cjs.prod.js +366 -0
  36. package/dist/inTabFetch-095bb2be.cjs.prod.js +179 -0
  37. package/dist/inTabFetch-2cbbfaa4.cjs.dev.js +179 -0
  38. package/dist/inTabFetch-91c3e85e.esm.js +176 -0
  39. package/dist/{getJsonEntryAtCommit-d9b5f753.cjs.dev.js → publishKit-4e2b0014.cjs.dev.js} +55 -6
  40. package/dist/{getJsonEntryAtCommit-acf8c269.cjs.prod.js → publishKit-6e52ffa6.cjs.prod.js} +55 -6
  41. package/dist/{getJsonEntryAtCommit-8ff81ef5.esm.js → publishKit-af14cd7a.esm.js} +48 -5
  42. package/dist/valbuild-server.cjs.dev.js +160 -13319
  43. package/dist/valbuild-server.cjs.prod.js +160 -13319
  44. package/dist/valbuild-server.esm.js +34 -13174
  45. package/internal/browser/dist/valbuild-server-internal-browser.cjs.d.ts +2 -0
  46. package/internal/browser/dist/valbuild-server-internal-browser.cjs.dev.js +19 -0
  47. package/internal/browser/dist/valbuild-server-internal-browser.cjs.js +7 -0
  48. package/internal/browser/dist/valbuild-server-internal-browser.cjs.prod.js +19 -0
  49. package/internal/browser/dist/valbuild-server-internal-browser.esm.js +10 -0
  50. package/internal/browser/package.json +4 -0
  51. package/internal/dist/valbuild-server-internal.cjs.d.ts +2 -0
  52. package/internal/dist/valbuild-server-internal.cjs.dev.js +43 -0
  53. package/internal/dist/valbuild-server-internal.cjs.js +7 -0
  54. package/internal/dist/valbuild-server-internal.cjs.prod.js +43 -0
  55. package/internal/dist/valbuild-server-internal.esm.js +24 -0
  56. package/internal/package.json +4 -0
  57. package/package.json +17 -6
  58. package/dist/jsonValuesModule-235bd751.cjs.dev.js +0 -326
  59. package/dist/jsonValuesModule-23eb6f53.esm.js +0 -310
  60. package/dist/jsonValuesModule-625ebae8.cjs.prod.js +0 -326
  61. package/dist/ops-0e54b388.cjs.prod.js +0 -361
  62. package/dist/ops-9ca2ef2a.cjs.dev.js +0 -361
  63. package/dist/ops-b904007e.esm.js +0 -353
  64. package/dist/publishKit-34f71e50.cjs.dev.js +0 -42
  65. package/dist/publishKit-65e9e564.cjs.prod.js +0 -42
  66. package/dist/publishKit-7441c0fd.esm.js +0 -31
@@ -0,0 +1,45 @@
1
+ import ts from "typescript";
2
+ import { result, array } from "@valbuild/core/fp";
3
+ import { ValSyntaxErrorTree } from "./syntax.js";
4
+ import { Ops, PatchError, JSONValue } from "@valbuild/core/patch";
5
+ type TSOpsResult<T> = result.Result<T, PatchError | ValSyntaxErrorTree>;
6
+ declare module "typescript" {
7
+ interface PrinterOptions {
8
+ /**
9
+ * Internal option that stops printing unnecessary ASCII escape sequences
10
+ * in strings, though it might have unintended effects. Might be useful?
11
+ */
12
+ neverAsciiEscape?: boolean;
13
+ }
14
+ }
15
+ /**
16
+ * Builds the expression `c.json(() => import("<importPath>"))` used to reference
17
+ * a lazily-loaded `*.val.json` entry of a `.jsonValues()` record.
18
+ */
19
+ export declare function createValJsonReference(importPath: string): ts.Expression;
20
+ /**
21
+ * Inserts a new `.jsonValues()` entry `"<key>": c.json(() => import("<importPath>"))`
22
+ * into the record's object literal in a `.val.ts` module. `recordPath` is the
23
+ * path from the module source to the record (empty for a root record/router).
24
+ * Fails if the entry key already exists.
25
+ */
26
+ export declare function insertValJsonEntry(document: ts.SourceFile, recordPath: string[], key: string, importPath: string): TSOpsResult<ts.SourceFile>;
27
+ /**
28
+ * Removes the `.jsonValues()` entry `"<key>"` from the record's object literal
29
+ * in a `.val.ts` module. `recordPath` is the path from the module source to the
30
+ * record (empty for a root record/router). Fails if the entry key is missing.
31
+ */
32
+ export declare function removeValJsonEntry(document: ts.SourceFile, recordPath: string[], key: string): TSOpsResult<ts.SourceFile>;
33
+ export declare function getFromNode(node: ts.Expression, key: string): TSOpsResult<ts.Expression | undefined>;
34
+ export declare class TSOps implements Ops<ts.SourceFile, ValSyntaxErrorTree> {
35
+ private findRoot;
36
+ constructor(findRoot: (document: ts.SourceFile) => result.Result<ts.Expression, ValSyntaxErrorTree>);
37
+ get(document: ts.SourceFile, path: string[]): TSOpsResult<JSONValue>;
38
+ add(document: ts.SourceFile, path: string[], value: JSONValue): TSOpsResult<ts.SourceFile>;
39
+ remove(document: ts.SourceFile, path: array.NonEmptyArray<string>): TSOpsResult<ts.SourceFile>;
40
+ replace(document: ts.SourceFile, path: string[], value: JSONValue): TSOpsResult<ts.SourceFile>;
41
+ move(document: ts.SourceFile, from: array.NonEmptyArray<string>, path: string[]): TSOpsResult<ts.SourceFile>;
42
+ copy(document: ts.SourceFile, from: string[], path: string[]): TSOpsResult<ts.SourceFile>;
43
+ test(document: ts.SourceFile, path: string[], value: JSONValue): TSOpsResult<boolean>;
44
+ }
45
+ export {};
@@ -0,0 +1,26 @@
1
+ import ts from "typescript";
2
+ import { TSOps, insertValJsonEntry, removeValJsonEntry } from "./ops.js";
3
+ import { analyzeValModule } from "./valModule.js";
4
+ import { analyzeJsonValuesEntries, evaluateModuleSource, jsonValuesRecordKeys } from "./jsonValuesModule.js";
5
+ import { getJsonEntryAtCommit } from "../../history/getJsonEntryAtCommit.js";
6
+ /**
7
+ * Everything Val's server needs from the TypeScript compiler, in one module:
8
+ * what a publish needs (`ValOps.prepare`) and what the history reader needs
9
+ * (`/history/json`, which reads a `.val.ts` at a commit to find an entry's
10
+ * file).
11
+ *
12
+ * The compiler is 10.8 MB of source -- 84% of Val's server as a Worker
13
+ * bundles it -- and a server in a browser tab or a memory-mode Worker never
14
+ * publishes from it. So it is not imported by the request handlers at all,
15
+ * not even dynamically: a bundler that does not split chunks (wrangler,
16
+ * esbuild with one output file) inlines a dynamic `import()` and ships the
17
+ * compiler anyway. It reaches the server through `ValServerPlatform`'s
18
+ * `typescript` (the platform) and `ValOpsOptions.typescript` (the data layer),
19
+ * both of which `nodePlatform` fills with `loadTypeScriptKit`, and the browser
20
+ * platform leaves empty. `noNodeFromBrowser.test.ts` fails, naming the chain,
21
+ * if TypeScript becomes reachable from `@valbuild/server/browser` again.
22
+ */
23
+ declare const tsOps: TSOps;
24
+ /** A `.val.ts` file's text, parsed. */
25
+ declare function parseValFile(text: string): ts.SourceFile;
26
+ export { tsOps, parseValFile, analyzeValModule, evaluateModuleSource, analyzeJsonValuesEntries, jsonValuesRecordKeys, insertValJsonEntry, removeValJsonEntry, getJsonEntryAtCommit, };
@@ -7,6 +7,7 @@ import type { ResolveRemoteFileAuthResult } from "./valServerConfig.js";
7
7
  import type { JwtResult } from "./jwt.js";
8
8
  import type { ProbeResult } from "./linkCheck/probeUrl.js";
9
9
  import type { checkModuleForStudio, fixForStudio } from "./studioValidation.js";
10
+ import type { TypeScriptKit } from "./patch/ts/loadTypeScriptKit.js";
10
11
  /**
11
12
  * What `ValServer` needs from the machine it runs on.
12
13
  *
@@ -43,6 +44,19 @@ export type ValServerPlatform = {
43
44
  readValLoginToken: (options: ValServerConfig) => Promise<string | null>;
44
45
  /** Which credential talks to the content host. See `resolveRemoteFileAuth`. */
45
46
  resolveRemoteFileAuth: (options: ValServerConfig) => Promise<ResolveRemoteFileAuthResult>;
47
+ /**
48
+ * The TypeScript compiler, for the one route that parses a `.val.ts` itself:
49
+ * `/history/json`, which reads a module's text at a commit to find a
50
+ * `.jsonValues()` entry's file. (A publish needs it too, and gets it from
51
+ * `createOps`: see `ValOpsOptions.typescript`.)
52
+ *
53
+ * A platform, because it is 10.8 MB of a 12.9 MB Worker bundle, and a
54
+ * bundler that does not split chunks inlines a dynamic `import()` -- so the
55
+ * only way to keep it out of a server that never uses it is for that server
56
+ * never to name it. `loadTypeScriptKit` on Node; absent in a browser, which
57
+ * has no history to read (memory mode has none), and the route says so.
58
+ */
59
+ typescript?: () => Promise<TypeScriptKit>;
46
60
  /**
47
61
  * The Studio's full check (`/validate`, `/validate/fix`). It reads files'
48
62
  * bytes and asks remote hosts, so it needs Node; absent in a browser, where
@@ -1,5 +1,6 @@
1
1
  import type { Json, ModuleFilePath } from "@valbuild/core";
2
2
  import type { JSONValue } from "@valbuild/core/patch";
3
+ import { STAGED_SCHEMA_PREFIX } from "@valbuild/shared/internal";
3
4
  /**
4
5
  * A proposal this server runs at the address of: an editor-managed branch of
5
6
  * the project's content, served from its own copy of the content the
@@ -47,23 +48,64 @@ export type ValProposal = {
47
48
  /**
48
49
  * Saved `.val.ts` text, by path with no leading slash, laid over the
49
50
  * build's `projectSource`: the next save patches the text the last one
50
- * wrote, not the text the base build was made from.
51
+ * wrote, not the text the base build was made from. A staged module file's
52
+ * text is here too: what the assistant staged, with every save since.
51
53
  */
52
54
  files: Record<string, string>;
55
+ /**
56
+ * The module files whose CODE the proposal has staged, by module file path,
57
+ * each with the schema version content records for it: `staged:<inputs>`,
58
+ * `inputs` being the proposal's staged inputs (valbuild/home
59
+ * `stagedSchemas`). `{}` when nothing that is a module is staged, or when
60
+ * the overlay does not say. It names the STAGING, not whether this build
61
+ * was made of it: see {@link buildInputs} and {@link stagedAfterBuild}.
62
+ *
63
+ * Optional, as {@link buildInputs} is: a `val.server.ts` generated before
64
+ * these existed hands Val a proposal without them, and must still compile.
65
+ */
66
+ staged?: Record<string, string>;
67
+ /**
68
+ * Which staging the build serving the address was made of: its staged
69
+ * inputs (`VAL_BUILD_INPUTS`), or `null` when it was made of none -- the
70
+ * proposal's base serves it -- or the platform does not say.
71
+ */
72
+ buildInputs?: string | null;
53
73
  };
74
+ /** What a staged module's schema version starts with: `staged:<inputs>`. */
75
+ export { STAGED_SCHEMA_PREFIX };
76
+ /**
77
+ * The modules whose staged code the build serving the address was NOT made
78
+ * of, each with its schema version (`staged:<inputs>`): every module the
79
+ * overlay names as staged, except those whose version names the very inputs
80
+ * the build was made of. Those the build evaluated: they are served as any
81
+ * other module.
82
+ *
83
+ * A module staged after the build has a schema this server does not have.
84
+ * Its Source is read from its staged text ({@link ValProposal.files}), its
85
+ * version is the staging's, so no reader takes it for the build's, and a save
86
+ * applies to that text (`docs/plans/one-content-model.md`, "Phase 9 without
87
+ * phases 6 and 7"; valbuild/home `docs/proposals.md`, "Staged schemas").
88
+ *
89
+ * Whole-staging inputs, not one per module, and that is what makes this
90
+ * sound: a module's schema can move with a file it imports, so "its own file
91
+ * is unchanged" never says its code is in the build.
92
+ */
93
+ export declare function stagedAfterBuild(proposal: Pick<ValProposal, "staged" | "buildInputs">): Record<ModuleFilePath, string>;
54
94
  /**
55
95
  * The proposal a platform describes in its runtime env, or `undefined` when
56
96
  * this is not a proposal's address.
57
97
  *
58
98
  * `VAL_PROPOSAL` and `VAL_BRANCH` name it; `VAL_OVERLAY` is the snapshot as
59
- * JSON (`{ commit, modules, files }`). Throws on a snapshot that does not
60
- * parse rather than serving the base build as though it were the proposal: a
99
+ * JSON (`{ commit, modules, files, staged }`); `VAL_BUILD_INPUTS` says which
100
+ * staging the build was made of. Throws on a snapshot that does not parse
101
+ * rather than serving the base build as though it were the proposal: a
61
102
  * reviewer would be looking at the wrong content and nothing would say so.
62
103
  */
63
104
  export declare function proposalFromEnv(env: {
64
105
  VAL_PROPOSAL?: string | undefined;
65
106
  VAL_BRANCH?: string | undefined;
66
107
  VAL_OVERLAY?: string | undefined;
108
+ VAL_BUILD_INPUTS?: string | undefined;
67
109
  }): ValProposal | undefined;
68
110
  /**
69
111
  * A content version: the site's content, served by a build that bundles an
@@ -118,6 +160,15 @@ export declare function contentFromEnv(env: Record<string, string | undefined>):
118
160
  * build bundles it -- older than the site it was opened from.
119
161
  */
120
162
  export declare function layeredSnapshot(proposal: Pick<ValProposal, "modules" | "files"> | undefined, contentVersion: Pick<ValContentVersion, "modules" | "files"> | undefined): Pick<ValProposal, "modules" | "files"> | undefined;
163
+ /**
164
+ * The proposal as a reader whose code is the serving build reads it: without
165
+ * the Source of a module staged after that build ({@link stagedAfterBuild}),
166
+ * which was made for code the reader has not got. Left out, such a module
167
+ * reads as the site or the build has it -- content of the code that reads it
168
+ * -- until a build of the staging serves the address. The same rule as
169
+ * `layered`'s, for the one source that carries no version.
170
+ */
171
+ export declare function proposalAsBuilt<P extends Pick<ValProposal, "modules" | "staged" | "buildInputs">>(proposal: P): P;
121
172
  /**
122
173
  * The proposal's saved Source, as Source: every module whose value is JSON.
123
174
  * One place, so the server and the readers that render without it agree on
@@ -0,0 +1,35 @@
1
+ import { type ValModules } from "@valbuild/core";
2
+ import type { ValOpsFS } from "./ValOpsFS.js";
3
+ import type { ValOpsHttp } from "./ValOpsHttp.js";
4
+ import type { ValOpsMemory } from "./ValOpsMemory.js";
5
+ import type { ValServerConfig } from "./ValServer.js";
6
+ type AnyValOps = ValOpsFS | ValOpsHttp | ValOpsMemory;
7
+ /**
8
+ * One runtime per process (or isolate) for a project: see "One runtime per
9
+ * process, and the head" in `docs/plans/one-content-model.md`.
10
+ *
11
+ * The API route (`initValServer`), the draft readers (`initValContent`,
12
+ * `initValRsc`) and MCP (`initValMcp`) all read through it when they are
13
+ * given the same options, so a save moves every reader. MCP takes no
14
+ * options of its own (it builds them from the config), so it shares the
15
+ * runtime in fs and http mode -- where the config and the environment are
16
+ * the whole of them -- and not in memory mode, whose patch store the host
17
+ * hands to the others. It holds the data layer, whose head (`ops.head`) is the
18
+ * content at the newest chain, kept by version: one head for every editor,
19
+ * since draft content is not per user -- the session only decides who may
20
+ * see it ({@link ValRuntime.authorize}).
21
+ */
22
+ export type ValRuntime = {
23
+ readonly ops: AnyValOps;
24
+ /**
25
+ * Whether this session may read the draft: the rule the API's routes ask
26
+ * (`sessionAuth`), and in http mode a signed-in editor, as `/sources/~` and
27
+ * `/json` require. The readers that used to ask a private server of their
28
+ * own over those routes ask this instead, and read the head.
29
+ */
30
+ authorize(session: string | undefined): boolean;
31
+ };
32
+ /** See {@link registry}: the API, the readers and MCP, with room to spare. */
33
+ export declare const RUNTIMES_PER_MODULES = 8;
34
+ export declare function valRuntime(valModules: ValModules, options: ValServerConfig): ValRuntime;
35
+ export {};
@@ -0,0 +1,366 @@
1
+ 'use strict';
2
+
3
+ var core = require('@valbuild/core');
4
+ var internal = require('@valbuild/shared/internal');
5
+
6
+ /*
7
+ * The draft a server-side reader reads (`fetchVal` and friends, in
8
+ * `@valbuild/next/rsc` and `@valbuild/tanstack/server`): the HEAD of this
9
+ * process's runtime (`valRuntime`, `ValHead`), read directly with the
10
+ * request's session. One copy, for both frameworks.
11
+ *
12
+ * Before phase 6 of `docs/plans/one-content-model.md` each framework built a
13
+ * private Val server and asked it `PUT /sources/~` -- the whole tree,
14
+ * previewed and validated -- once per request, then `/patches` and `/json`
15
+ * for the entries a draft edits, and `/json` again per key read. Now a read
16
+ * asks the head "has the chain moved?" (`seq`) and is answered from modules
17
+ * made once per version: an unpatched module is the reader's own bundle, and
18
+ * nothing is read for it at all.
19
+ */
20
+
21
+ /** One module {@link readDraftChanges} read: what a reader's `reads` record. */
22
+
23
+ const SERVER_DRAFT = "server-draft";
24
+ const PASS = {
25
+ status: "pass"
26
+ };
27
+
28
+ /**
29
+ * The modules the editor's draft CHANGES, for this request: what
30
+ * `fetchValDraft` hands to `<ValProvider draft>`, in `@valbuild/tanstack/server`
31
+ * and `@valbuild/next/rsc` alike -- this is the whole of the read, and the
32
+ * frameworks add only where draft mode and the cookies come from (and, in
33
+ * TanStack, a proposal's snapshot).
34
+ *
35
+ * `null` -- and no read at all -- unless draft mode is on: a visitor pays one
36
+ * cookie lookup. Otherwise the head's modules a patch touches or a publish
37
+ * wrote and the host has not rebuilt since, with the `.jsonValues()` entries
38
+ * the draft changes in place of their markers, and the version of each (so
39
+ * the page compares versions with what the Studio relays, not content).
40
+ *
41
+ * Also `null` when the session is not one the server accepts, and when the
42
+ * draft could not be read at all (logged): published content, as before this
43
+ * existed -- a draft page that renders the site is a degraded preview, one
44
+ * that fails to render is an outage.
45
+ */
46
+ async function readDraftChanges(opts) {
47
+ try {
48
+ var _await$opts$getCookie;
49
+ if (!(await opts.isEnabled())) {
50
+ return null;
51
+ }
52
+ // Possibly absent: a local `fs` server answers without one. The runtime
53
+ // decides, as the API does.
54
+ const session = (_await$opts$getCookie = (await opts.getCookies()).get(internal.VAL_SESSION_COOKIE)) === null || _await$opts$getCookie === void 0 ? void 0 : _await$opts$getCookie.value;
55
+ const runtime = await opts.runtime;
56
+ if (!runtime.authorize(session)) {
57
+ return null;
58
+ }
59
+ // One chain for the whole answer: asked "has it moved?" once.
60
+ const synced = await runtime.ops.head.sync();
61
+ if ("error" in synced) {
62
+ core.Internal.log.error("could not read the draft", synced.error.message);
63
+ return null;
64
+ }
65
+ const chain = synced.ok;
66
+ const changed = await runtime.ops.head.changed(chain);
67
+ if ("error" in changed) {
68
+ core.Internal.log.error("could not read the draft", changed.error.message);
69
+ return null;
70
+ }
71
+ const sources = {};
72
+ const versions = {};
73
+ const reads = [];
74
+ for (const path of changed.ok) {
75
+ var _draft$ok;
76
+ const draft = await runtime.ops.head.draft(path, chain);
77
+ if ("error" in draft) {
78
+ core.Internal.log.error("could not read the draft", draft.error.message);
79
+ return null;
80
+ }
81
+ // Left out when its entries cannot all be read: the published render
82
+ // that existed before the draft did is worse than this, and never
83
+ // wrong for long.
84
+ if (((_draft$ok = draft.ok) === null || _draft$ok === void 0 ? void 0 : _draft$ok.kind) !== "draft" || draft.ok.entriesFailed) continue;
85
+ sources[path] = draft.ok.source;
86
+ versions[path] = draft.ok.version;
87
+ reads.push({
88
+ path,
89
+ from: SERVER_DRAFT,
90
+ version: draft.ok.version
91
+ });
92
+ }
93
+ return {
94
+ sources,
95
+ versions,
96
+ reads
97
+ };
98
+ } catch (err) {
99
+ core.Internal.log.error("could not read the draft", err);
100
+ return null;
101
+ }
102
+ }
103
+
104
+ /** A request's runtime, and the one chain it reads at. */
105
+
106
+ /** One thing this source has started to read, or has read. */
107
+
108
+ /**
109
+ * The draft, as a source: this process's head, for this request's session.
110
+ * Created per request. A module whose newest version is the bundle's own
111
+ * passes, so the reader's bundle answers it and nothing is read; any other is
112
+ * the head's (with the `.jsonValues()` entries the draft changes filled in).
113
+ * An entry is the head's, resolved once per version.
114
+ *
115
+ * Every error is a `pass`, logged: a draft that cannot be read is the
116
+ * published content, which a page can render.
117
+ *
118
+ * The request reads ONE chain: the head is asked "has the chain moved?" once,
119
+ * at the first read, and every module and entry after it is read at that
120
+ * chain. In http mode that question is a request to the content service, and
121
+ * a page reads tens of modules and entries; and a page is one answer, never
122
+ * half of one chain and half of the next.
123
+ *
124
+ * `modules: false` (the single-entry readers): every module passes.
125
+ */
126
+ function serverDraftSource(opts) {
127
+ const drafts = new Map();
128
+ const entries = new Map();
129
+ /**
130
+ * The runtime and the chain this request reads, once this session may read
131
+ * the draft (asked once per request); `null` when it may not, or the
132
+ * chain could not be read, which reads as published content.
133
+ */
134
+ let allowed = null;
135
+ const runtime = () => {
136
+ allowed ??= opts.runtime.then(async runtime => {
137
+ if (!runtime.authorize(opts.session)) return null;
138
+ const synced = await runtime.ops.head.sync();
139
+ if ("error" in synced) {
140
+ core.Internal.log.error("could not read the draft", synced.error);
141
+ return null;
142
+ }
143
+ return {
144
+ runtime,
145
+ chain: synced.ok
146
+ };
147
+ }, err => {
148
+ core.Internal.log.error("could not start Val's runtime", err);
149
+ return null;
150
+ });
151
+ return allowed;
152
+ };
153
+ return {
154
+ name: SERVER_DRAFT,
155
+ module(path) {
156
+ if (!opts.modules) return PASS;
157
+ let state = drafts.get(path);
158
+ if (state === undefined) {
159
+ const ready = runtime().then(pinned => pinned === null ? null : pinned.runtime.ops.head.draft(path, pinned.chain)).then(read => {
160
+ if (read !== null && "error" in read) {
161
+ core.Internal.log.error("could not read the draft", read.error);
162
+ }
163
+ drafts.set(path, {
164
+ done: true,
165
+ value: read === null || "error" in read ? null : read.ok
166
+ });
167
+ }, err => {
168
+ core.Internal.log.error("could not read the draft", err);
169
+ drafts.set(path, {
170
+ done: true,
171
+ value: null
172
+ });
173
+ });
174
+ state = {
175
+ done: false,
176
+ ready
177
+ };
178
+ drafts.set(path, state);
179
+ }
180
+ if (!state.done) return {
181
+ status: "pending",
182
+ ready: state.ready
183
+ };
184
+ const draft = state.value;
185
+ if (draft === null || draft.kind === "bundle") return PASS;
186
+ return {
187
+ status: "ready",
188
+ source: draft.source,
189
+ from: SERVER_DRAFT,
190
+ version: draft.version
191
+ };
192
+ },
193
+ entry(path, key) {
194
+ const id = `${path}\u0000${key}`;
195
+ let state = entries.get(id);
196
+ if (state === undefined) {
197
+ const ready = runtime().then(pinned => pinned === null ? PASS : readEntry(pinned, path, key)).then(read => {
198
+ entries.set(id, {
199
+ done: true,
200
+ value: read
201
+ });
202
+ }, err => {
203
+ core.Internal.log.error("could not load draft JSON entry: ", err);
204
+ entries.set(id, {
205
+ done: true,
206
+ value: PASS
207
+ });
208
+ });
209
+ state = {
210
+ done: false,
211
+ ready
212
+ };
213
+ entries.set(id, state);
214
+ }
215
+ return state.done ? state.value : {
216
+ status: "pending",
217
+ ready: state.ready
218
+ };
219
+ }
220
+ };
221
+ }
222
+
223
+ /**
224
+ * ONE `.jsonValues()` entry's DRAFT content, from the head. `gone` is
225
+ * authoritative -- the draft has no such entry, removed by a pending patch or
226
+ * never there -- and is not a reason to fall back to the published entry;
227
+ * `pass` means the bundle's entry is the draft's (the record is the bundle's
228
+ * own), or it could not be read.
229
+ */
230
+ async function readEntry({
231
+ runtime,
232
+ chain
233
+ }, path, key) {
234
+ const draft = await runtime.ops.head.draft(path, chain);
235
+ if ("error" in draft) {
236
+ core.Internal.log.error("could not load draft JSON entry: ", draft.error);
237
+ return PASS;
238
+ }
239
+ if (draft.ok === null) return {
240
+ status: "gone",
241
+ from: SERVER_DRAFT
242
+ };
243
+ if (draft.ok.kind === "bundle") return PASS;
244
+ const read = await runtime.ops.head.entries(path, [key], chain);
245
+ if (read.status === "not-found") return {
246
+ status: "gone",
247
+ from: SERVER_DRAFT
248
+ };
249
+ if (read.status !== "success") {
250
+ core.Internal.log.error("could not load draft JSON entry: ", read.message);
251
+ return PASS;
252
+ }
253
+ const entry = read.value.entries[0];
254
+ if (entry !== undefined) {
255
+ return {
256
+ status: "ready",
257
+ content: entry.content,
258
+ from: SERVER_DRAFT,
259
+ version: read.value.entryVersions[key] ?? null
260
+ };
261
+ }
262
+ const error = read.value.errors[0];
263
+ if (error !== undefined) {
264
+ core.Internal.log.error("could not load draft JSON entry: ", error.message);
265
+ return PASS;
266
+ }
267
+ return {
268
+ status: "gone",
269
+ from: SERVER_DRAFT
270
+ };
271
+ }
272
+
273
+ /**
274
+ * Whether this request reads the draft, and the source to read it from.
275
+ *
276
+ * `enabled` is draft mode; it decides edit tags whether or not the draft can
277
+ * be read. The draft is `null` when draft mode is off, or the request's
278
+ * cookies cannot be read (outside a request: published content).
279
+ *
280
+ * `where` names where these readers may be called, for the errors a misuse
281
+ * gets; without it (the single-entry readers) they stay quiet, as they were.
282
+ */
283
+ async function draftForRequest(opts) {
284
+ var _cookies$get;
285
+ const fail = (what, err) => {
286
+ if (opts.where !== undefined) {
287
+ core.Internal.log.error(`${what} ${opts.where}`, err);
288
+ }
289
+ };
290
+ let enabled = false;
291
+ try {
292
+ enabled = await opts.isEnabled();
293
+ } catch (err) {
294
+ fail("could not check if Val is enabled! This might be due to an error reading draft mode.", err);
295
+ }
296
+ if (!enabled) {
297
+ return {
298
+ enabled,
299
+ draft: null
300
+ };
301
+ }
302
+ let host = null;
303
+ if (opts.modules !== undefined) {
304
+ try {
305
+ const headers = await opts.modules.getHeaders();
306
+ if (typeof headers.get !== "function") {
307
+ throw new Error("Invalid headers");
308
+ }
309
+ host = getHost(headers);
310
+ } catch (err) {
311
+ fail("could not read headers!", err);
312
+ }
313
+ }
314
+ let cookies;
315
+ try {
316
+ cookies = await opts.getCookies();
317
+ } catch (err) {
318
+ fail("could not read cookies!", err);
319
+ return {
320
+ enabled,
321
+ draft: null
322
+ };
323
+ }
324
+ return {
325
+ enabled,
326
+ draft: serverDraftSource({
327
+ runtime: opts.runtime,
328
+ session: (_cookies$get = cookies.get(internal.VAL_SESSION_COOKIE)) === null || _cookies$get === void 0 ? void 0 : _cookies$get.value,
329
+ modules: opts.modules !== undefined && host !== null
330
+ })
331
+ };
332
+ }
333
+ function getHost(headers) {
334
+ var _headers$get;
335
+ const host = headers.get("host");
336
+ let proto = "https";
337
+ if (headers.get("x-forwarded-proto") === "http") {
338
+ proto = "http";
339
+ } else if ((_headers$get = headers.get("referer")) !== null && _headers$get !== void 0 && _headers$get.startsWith("http://")) {
340
+ proto = "http";
341
+ } else if (host !== null && host !== void 0 && host.startsWith("localhost")) {
342
+ proto = "http";
343
+ }
344
+ return host ? `${proto}://${host}` : null;
345
+ }
346
+ const schemaVersions = new WeakMap();
347
+
348
+ /**
349
+ * The version of the schema a reader's own code has for a module: what the
350
+ * readers hold a draft's version against (`layered`'s schema rule), so
351
+ * content is never read with a schema it was not made for. Hashed once per
352
+ * module object, which a build makes once: a load cost, not a read cost.
353
+ */
354
+ function readerSchemaVersion(module) {
355
+ const cached = schemaVersions.get(module);
356
+ if (cached !== undefined) return cached;
357
+ const schema = core.Internal.getSchema(module);
358
+ const version = schema === undefined ? null : internal.schemaVersionOf(schema["executeSerialize"]());
359
+ schemaVersions.set(module, version);
360
+ return version;
361
+ }
362
+
363
+ exports.draftForRequest = draftForRequest;
364
+ exports.readDraftChanges = readDraftChanges;
365
+ exports.readerSchemaVersion = readerSchemaVersion;
366
+ exports.serverDraftSource = serverDraftSource;