@valbuild/server 0.146.2 → 0.147.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 (37) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/browser/dist/valbuild-server-browser.cjs.d.ts +2 -0
  3. package/browser/dist/valbuild-server-browser.cjs.dev.js +146 -0
  4. package/browser/dist/valbuild-server-browser.cjs.js +7 -0
  5. package/browser/dist/valbuild-server-browser.cjs.prod.js +146 -0
  6. package/browser/dist/valbuild-server-browser.esm.js +142 -0
  7. package/browser/package.json +4 -0
  8. package/dist/ValRouterCore-3fd3d444.cjs.dev.js +9897 -0
  9. package/dist/ValRouterCore-7ffcc08c.cjs.prod.js +9897 -0
  10. package/dist/ValRouterCore-f5004f8f.esm.js +9866 -0
  11. package/dist/declarations/src/ValOps.d.ts +13 -1
  12. package/dist/declarations/src/ValOpsFS.d.ts +1 -0
  13. package/dist/declarations/src/ValOpsHttp.d.ts +11 -0
  14. package/dist/declarations/src/ValOpsMemory.d.ts +9 -0
  15. package/dist/declarations/src/ValRouter.d.ts +1 -1
  16. package/dist/declarations/src/ValServer.d.ts +9 -2
  17. package/dist/declarations/src/browser/inTabFetch.d.ts +27 -0
  18. package/dist/declarations/src/browser/index.d.ts +9 -0
  19. package/dist/declarations/src/fixHandlers.d.ts +1 -1
  20. package/dist/declarations/src/linkCheck/probeUrl.d.ts +40 -0
  21. package/dist/declarations/src/platform.d.ts +39 -0
  22. package/dist/getJsonEntryAtCommit-1e08d724.esm.js +136 -0
  23. package/dist/getJsonEntryAtCommit-df65d861.cjs.prod.js +143 -0
  24. package/dist/getJsonEntryAtCommit-e96beb9e.cjs.dev.js +143 -0
  25. package/dist/jsonValuesModule-427d68c8.esm.js +273 -0
  26. package/dist/jsonValuesModule-8ae503a8.cjs.dev.js +288 -0
  27. package/dist/jsonValuesModule-d1bb8d8f.cjs.prod.js +288 -0
  28. package/dist/ops-0d05feaf.esm.js +353 -0
  29. package/dist/ops-b15239ac.cjs.prod.js +361 -0
  30. package/dist/ops-f37d18c6.cjs.dev.js +361 -0
  31. package/dist/publishKit-580f558a.cjs.prod.js +41 -0
  32. package/dist/publishKit-5865095c.cjs.dev.js +41 -0
  33. package/dist/publishKit-bc8df53d.esm.js +31 -0
  34. package/dist/valbuild-server.cjs.dev.js +7795 -18093
  35. package/dist/valbuild-server.cjs.prod.js +7795 -18093
  36. package/dist/valbuild-server.esm.js +7988 -18285
  37. package/package.json +18 -5
@@ -0,0 +1,143 @@
1
+ 'use strict';
2
+
3
+ var ts = require('typescript');
4
+ var ValRouterCore = require('./ValRouterCore-3fd3d444.cjs.dev.js');
5
+ var fp = require('@valbuild/core/fp');
6
+ var jsonValuesModule = require('./jsonValuesModule-8ae503a8.cjs.dev.js');
7
+ require('buffer');
8
+ require('@valbuild/core');
9
+ require('@valbuild/shared/internal');
10
+ require('zod');
11
+ require('zod-validation-error');
12
+ require('@valbuild/core/patch');
13
+ require('image-size');
14
+
15
+ function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
16
+
17
+ var ts__default = /*#__PURE__*/_interopDefault(ts);
18
+
19
+ /**
20
+ * One `.jsonValues()` entry's content, as it was at a commit.
21
+ *
22
+ * The history pane renders a commit through the real field components, and a
23
+ * `.jsonValues()` record's source is only `{_type:"json"}` markers - the
24
+ * content lives in a separate `*.val.json` per entry, fetched on demand. The
25
+ * live Studio fetches it from `GET /json`; the commit pane had nothing to
26
+ * fetch from, so every entry stayed a marker and rendered as though the field
27
+ * were empty. Which is worse than an error: an empty value is a claim, and it
28
+ * was a false one.
29
+ *
30
+ * ## Why this needs the module's own `.val.ts`
31
+ *
32
+ * There is no derivable relationship between a record key and its entry file.
33
+ * From the example app:
34
+ *
35
+ * "/support/getting-started": c.json(() => import("./content/getting-started.val.json"))
36
+ * "/support/faq": c.json(() => import("./content/faq.val.json"))
37
+ *
38
+ * The key is a route and the path is whatever the author wrote. The only place
39
+ * the two are related is the `import()` literal inside the `.val.ts`, which is
40
+ * why `findJsonEntryFilePathsInSource` reads them out of the AST too. The
41
+ * commit archive stores the module's SOURCE (the markers) and its schema, not
42
+ * its text - so the text is fetched from git at that commit and parsed here.
43
+ *
44
+ * Two round trips per entry, then: the module, and the entry. The module's
45
+ * parse is worth caching per (commit, module) by the caller; nothing here does,
46
+ * because a `ValOps` is not a cache and the endpoint above it is the layer that
47
+ * knows how long a commit stays interesting.
48
+ */
49
+ async function getJsonEntryAtCommit(ops, commitSha, moduleFilePath, key) {
50
+ const moduleGitPath = ops.gitPathOfModule(moduleFilePath);
51
+ if (fp.result.isErr(moduleGitPath)) {
52
+ return moduleGitPath;
53
+ }
54
+ const moduleRes = await ops.getFileAtCommit(commitSha, moduleGitPath.value, false);
55
+ if (fp.result.isErr(moduleRes)) {
56
+ return moduleRes;
57
+ }
58
+ const entryPath = findEntryImportPath(moduleFilePath, moduleGitPath.value, moduleRes.value.toString("utf-8"), key);
59
+ if (fp.result.isErr(entryPath)) {
60
+ return entryPath;
61
+ }
62
+ // The entry path resolved above is PROJECT-relative, like the module path it
63
+ // came from; the git path needs the root in front of it, and the ops are what
64
+ // know the root. Reusing gitPathOfModule rather than re-deriving the prefix:
65
+ // a `.val.json` is not a module, but "project-relative path -> repo path" is
66
+ // the same question and one implementation of it is the point.
67
+ const entryGitPath = ops.gitPathOfModule(entryPath.value);
68
+ if (fp.result.isErr(entryGitPath)) {
69
+ return entryGitPath;
70
+ }
71
+ const entryRes = await ops.getFileAtCommit(commitSha, entryGitPath.value, false);
72
+ if (fp.result.isErr(entryRes)) {
73
+ return entryRes;
74
+ }
75
+ try {
76
+ return fp.result.ok(JSON.parse(entryRes.value.toString("utf-8")));
77
+ } catch (err) {
78
+ return fp.result.err({
79
+ kind: "file-unavailable",
80
+ gitPath: entryGitPath.value,
81
+ message: `not valid JSON at this commit: ${err instanceof Error ? err.message : String(err)}`
82
+ });
83
+ }
84
+ }
85
+
86
+ /**
87
+ * The `import()` path a key's entry is behind, from the module's text.
88
+ *
89
+ * Exported for its own test: this is the part with a real chance of being
90
+ * wrong, and it is pure.
91
+ */
92
+ function findEntryImportPath(moduleFilePath,
93
+ /**
94
+ * The same module, repository-relative, for error reporting only.
95
+ *
96
+ * A `gitPath` in a HistoryError is a REPOSITORY path - that is what every
97
+ * other history helper reports, and what a reader can paste into a `git show`
98
+ * - so reporting the project-relative ModuleFilePath here named a file that
99
+ * does not exist at that path for any project not rooted at the repo root.
100
+ */
101
+ moduleGitPath, valTsSource, key) {
102
+ const sourceFile = ts__default["default"].createSourceFile(moduleFilePath, valTsSource, ts__default["default"].ScriptTarget.ES2015, true);
103
+ let analysis;
104
+ try {
105
+ analysis = jsonValuesModule.analyzeValModule(sourceFile);
106
+ } catch (err) {
107
+ // `file-unavailable` rather than a kind of its own: the module's TEXT is
108
+ // the file we could not use, and adding a wire kind for "unparseable"
109
+ // would be a new case every reader has to handle to say the same thing.
110
+ return fp.result.err({
111
+ kind: "file-unavailable",
112
+ gitPath: moduleGitPath,
113
+ message: `could not parse the module at this commit: ${err instanceof Error ? err.message : String(err)}`
114
+ });
115
+ }
116
+ if (fp.result.isErr(analysis)) {
117
+ return fp.result.err({
118
+ kind: "file-unavailable",
119
+ gitPath: moduleGitPath,
120
+ message: "could not read the module at this commit"
121
+ });
122
+ }
123
+ const entries = jsonValuesModule.analyzeJsonValuesEntries(analysis.value.source);
124
+ const entry = entries.get(key);
125
+ if (entry === undefined) {
126
+ /*
127
+ * Reported, not treated as empty. A key with no entry at this commit means
128
+ * the entry was added later - so "there is nothing to show for it here" is
129
+ * the true answer, and rendering an empty field instead would say the
130
+ * author had left it blank.
131
+ */
132
+ return fp.result.err({
133
+ kind: "file-unavailable",
134
+ gitPath: moduleGitPath,
135
+ message: `'${key}' had no entry at this commit`
136
+ });
137
+ }
138
+ const moduleDir = ValRouterCore.posixPath.dirname(moduleFilePath);
139
+ return fp.result.ok(ValRouterCore.posixPath.join(moduleDir, entry.importPath));
140
+ }
141
+
142
+ exports.findEntryImportPath = findEntryImportPath;
143
+ exports.getJsonEntryAtCommit = getJsonEntryAtCommit;
@@ -0,0 +1,273 @@
1
+ import ts from 'typescript';
2
+ import { pipe, result } from '@valbuild/core/fp';
3
+
4
+ class ValSyntaxError {
5
+ constructor(message, node) {
6
+ this.message = message;
7
+ this.node = node;
8
+ }
9
+ }
10
+ function forEachError(tree, callback) {
11
+ if (Array.isArray(tree)) {
12
+ for (const subtree of tree) {
13
+ forEachError(subtree, callback);
14
+ }
15
+ } else {
16
+ callback(tree);
17
+ }
18
+ }
19
+ function flatMapErrors(tree, cb) {
20
+ const result = [];
21
+ forEachError(tree, error => result.push(cb(error)));
22
+ return result;
23
+ }
24
+ function formatSyntaxError(error, sourceFile) {
25
+ const pos = sourceFile.getLineAndCharacterOfPosition(error.node.pos);
26
+ return `${pos.line}:${pos.character} ${error.message}`;
27
+ }
28
+ function formatSyntaxErrorTree(tree, sourceFile) {
29
+ return flatMapErrors(tree, error => formatSyntaxError(error, sourceFile));
30
+ }
31
+ function isLiteralPropertyName(name) {
32
+ return ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name);
33
+ }
34
+ function validateObjectProperties(nodes) {
35
+ const errors = [];
36
+ for (const node of nodes) {
37
+ if (!ts.isPropertyAssignment(node)) {
38
+ errors.push(new ValSyntaxError("Object literal element must be property assignment", node));
39
+ } else if (!isLiteralPropertyName(node.name)) {
40
+ errors.push(new ValSyntaxError("Object literal element key must be an identifier or a literal", node));
41
+ }
42
+ }
43
+ if (errors.length > 0) {
44
+ return result.err(errors);
45
+ }
46
+ return result.ok(nodes);
47
+ }
48
+
49
+ /**
50
+ * Validates that the expression is a JSON compatible type of expression without
51
+ * validating its children.
52
+ */
53
+ function shallowValidateExpression(value) {
54
+ return ts.isStringLiteralLike(value) || ts.isNumericLiteral(value) || value.kind === ts.SyntaxKind.TrueKeyword || value.kind === ts.SyntaxKind.FalseKeyword || value.kind === ts.SyntaxKind.NullKeyword || ts.isArrayLiteralExpression(value) || ts.isObjectLiteralExpression(value) ? undefined : new ValSyntaxError("Expression must be a literal", value);
55
+ }
56
+
57
+ /**
58
+ * Evaluates the expression as a JSON value
59
+ */
60
+ function evaluateExpression(value) {
61
+ // The text property of a LiteralExpression stores the interpreted value of the literal in text form. For a StringLiteral,
62
+ // or any literal of a template, this means quotes have been removed and escapes have been converted to actual characters.
63
+ // For a NumericLiteral, the stored value is the toString() representation of the number. For example 1, 1.00, and 1e0 are all stored as just "1".
64
+ // https://github.com/microsoft/TypeScript/blob/4b794fe1dd0d184d3f8f17e94d8187eace57c91e/src/compiler/types.ts#L2127-L2131
65
+
66
+ if (ts.isStringLiteralLike(value)) {
67
+ return result.ok(value.text);
68
+ } else if (ts.isNumericLiteral(value)) {
69
+ return result.ok(Number(value.text));
70
+ } else if (value.kind === ts.SyntaxKind.TrueKeyword) {
71
+ return result.ok(true);
72
+ } else if (value.kind === ts.SyntaxKind.FalseKeyword) {
73
+ return result.ok(false);
74
+ } else if (value.kind === ts.SyntaxKind.NullKeyword) {
75
+ return result.ok(null);
76
+ } else if (ts.isArrayLiteralExpression(value)) {
77
+ return result.all(value.elements.map(evaluateExpression));
78
+ } else if (ts.isObjectLiteralExpression(value)) {
79
+ return pipe(validateObjectProperties(value.properties), result.flatMap(assignments => pipe(assignments.map(assignment => pipe(evaluateExpression(assignment.initializer), result.map(value => [assignment.name.text, value]))), result.all)), result.map(Object.fromEntries));
80
+ } else {
81
+ return result.err(new ValSyntaxError("Expression must be a literal", value));
82
+ }
83
+ }
84
+ function findObjectPropertyAssignment(value, key) {
85
+ return pipe(validateObjectProperties(value.properties), result.flatMap(assignments => {
86
+ const matchingAssignments = assignments.filter(assignment => assignment.name.text === key);
87
+ if (matchingAssignments.length === 0) return result.ok(undefined);
88
+ if (matchingAssignments.length > 1) {
89
+ return result.err(new ValSyntaxError(`Object key "${key}" is ambiguous`, value));
90
+ }
91
+ const [assignment] = matchingAssignments;
92
+ return result.ok(assignment);
93
+ }));
94
+ }
95
+ function validateInitializers(nodes) {
96
+ for (const node of nodes) {
97
+ if (ts.isSpreadElement(node)) {
98
+ return new ValSyntaxError("Unexpected spread element", node);
99
+ }
100
+ }
101
+ return undefined;
102
+ }
103
+
104
+ function isPath(node, path) {
105
+ let currentNode = node;
106
+ for (let i = path.length - 1; i > 0; --i) {
107
+ const name = path[i];
108
+ if (!ts.isPropertyAccessExpression(currentNode)) {
109
+ return false;
110
+ }
111
+ if (!ts.isIdentifier(currentNode.name) || currentNode.name.text !== name) {
112
+ return false;
113
+ }
114
+ currentNode = currentNode.expression;
115
+ }
116
+ return ts.isIdentifier(currentNode) && currentNode.text === path[0];
117
+ }
118
+ function validateArguments(node, validators) {
119
+ return result.allV([node.arguments.length === validators.length ? result.voidOk : result.err(new ValSyntaxError(`Expected ${validators.length} arguments`, node)), ...node.arguments.slice(0, validators.length).map((argument, index) => validators[index](argument))]);
120
+ }
121
+ function analyzeDefaultExport(node) {
122
+ const cDefine = node.expression;
123
+ if (!ts.isCallExpression(cDefine)) {
124
+ return result.err(new ValSyntaxError("Expected default expression to be a call expression", cDefine));
125
+ }
126
+ if (!isPath(cDefine.expression, ["c", "define"])) {
127
+ return result.err(new ValSyntaxError("Expected default expression to be calling c.define", cDefine.expression));
128
+ }
129
+ return pipe(validateArguments(cDefine, [id => {
130
+ // TODO: validate ID value here?
131
+ if (!ts.isStringLiteralLike(id)) {
132
+ return result.err(new ValSyntaxError("Expected first argument to c.define to be a string literal", id));
133
+ }
134
+ return result.voidOk;
135
+ }, () => {
136
+ return result.voidOk;
137
+ }, () => {
138
+ return result.voidOk;
139
+ }]), result.map(() => {
140
+ const [, schema, source] = cDefine.arguments;
141
+ return {
142
+ schema,
143
+ source
144
+ };
145
+ }));
146
+ }
147
+ function analyzeValModule(sourceFile) {
148
+ const analysis = sourceFile.forEachChild(node => {
149
+ if (ts.isExportAssignment(node)) {
150
+ return analyzeDefaultExport(node);
151
+ }
152
+ });
153
+ if (!analysis) {
154
+ throw Error("Failed to find fixed content node in val module");
155
+ }
156
+ return analysis;
157
+ }
158
+
159
+ /**
160
+ * Given the `source` object-literal expression of a `.jsonValues()` record /
161
+ * router (the 3rd argument to `c.define`, via {@link analyzeValModule}),
162
+ * extracts each entry's `c.json(() => import("..."))` import path, keyed by
163
+ * entry key. Entries whose value is not a `c.json(...)` call are skipped.
164
+ */
165
+ function analyzeJsonValuesEntries(source) {
166
+ const entries = new Map();
167
+ if (!ts.isObjectLiteralExpression(source)) {
168
+ return entries;
169
+ }
170
+ for (const prop of source.properties) {
171
+ if (!ts.isPropertyAssignment(prop)) {
172
+ continue;
173
+ }
174
+ const key = getPropertyKey(prop.name);
175
+ if (key === null) {
176
+ continue;
177
+ }
178
+ const entry = analyzeCJsonCall(prop.initializer);
179
+ if (entry) {
180
+ entries.set(key, entry);
181
+ }
182
+ }
183
+ return entries;
184
+ }
185
+
186
+ /**
187
+ * Every key of a `.jsonValues()` record's source literal, thunked or not.
188
+ *
189
+ * {@link analyzeJsonValuesEntries} answers "which entries have a file behind
190
+ * them", which is the question for resolving a path. This is the other one:
191
+ * which keys the record HAS. They differ on a value that is not a
192
+ * `c.json(...)` call - written inline, or mid-edit - and telling an existing
193
+ * key from a new one is what decides whether a whole-record write adds a
194
+ * `c.json(...)` thunk or replaces one. Using the thunk set for that would
195
+ * insert a second property with a key the literal already has.
196
+ */
197
+ function jsonValuesRecordKeys(source) {
198
+ const keys = [];
199
+ if (!ts.isObjectLiteralExpression(source)) {
200
+ return keys;
201
+ }
202
+ for (const prop of source.properties) {
203
+ if (!ts.isPropertyAssignment(prop)) {
204
+ continue;
205
+ }
206
+ const key = getPropertyKey(prop.name);
207
+ if (key !== null) {
208
+ keys.push(key);
209
+ }
210
+ }
211
+ return keys;
212
+ }
213
+ function getPropertyKey(name) {
214
+ if (ts.isStringLiteralLike(name)) {
215
+ return name.text;
216
+ }
217
+ if (ts.isIdentifier(name)) {
218
+ return name.text;
219
+ }
220
+ return null;
221
+ }
222
+ function analyzeCJsonCall(node) {
223
+ // c.json(() => import("path"))
224
+ if (!ts.isCallExpression(node) || !isCJson(node.expression)) {
225
+ return null;
226
+ }
227
+ const [thunk] = node.arguments;
228
+ if (!thunk) {
229
+ return null;
230
+ }
231
+ const importPath = getImportPathFromThunk(thunk);
232
+ if (importPath === null) {
233
+ return null;
234
+ }
235
+ return {
236
+ importPath
237
+ };
238
+ }
239
+ function isCJson(expr) {
240
+ // c.json
241
+ return ts.isPropertyAccessExpression(expr) && ts.isIdentifier(expr.expression) && expr.expression.text === "c" && ts.isIdentifier(expr.name) && expr.name.text === "json";
242
+ }
243
+ function getImportPathFromThunk(thunk) {
244
+ // () => import("path") (concise body) OR () => { return import("path"); }
245
+ if (!ts.isArrowFunction(thunk)) {
246
+ return null;
247
+ }
248
+ let importCall;
249
+ if (ts.isCallExpression(thunk.body)) {
250
+ importCall = thunk.body;
251
+ } else if (ts.isBlock(thunk.body)) {
252
+ for (const stmt of thunk.body.statements) {
253
+ if (ts.isReturnStatement(stmt) && stmt.expression && ts.isCallExpression(stmt.expression)) {
254
+ importCall = stmt.expression;
255
+ break;
256
+ }
257
+ }
258
+ }
259
+ if (!importCall || !ts.isCallExpression(importCall)) {
260
+ return null;
261
+ }
262
+ const isImport = importCall.expression.kind === ts.SyntaxKind.ImportKeyword || ts.isIdentifier(importCall.expression) && importCall.expression.text === "import";
263
+ if (!isImport) {
264
+ return null;
265
+ }
266
+ const arg = importCall.arguments[0];
267
+ if (arg && ts.isStringLiteralLike(arg)) {
268
+ return arg.text;
269
+ }
270
+ return null;
271
+ }
272
+
273
+ export { analyzeValModule as a, formatSyntaxError as b, analyzeJsonValuesEntries as c, formatSyntaxErrorTree as d, findObjectPropertyAssignment as e, flatMapErrors as f, evaluateExpression as g, jsonValuesRecordKeys as j, shallowValidateExpression as s, validateInitializers as v };