@valbuild/server 0.154.4 → 0.156.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/CHANGELOG.md +25 -0
  2. package/browser/dist/valbuild-server-browser.cjs.dev.js +2 -2
  3. package/browser/dist/valbuild-server-browser.cjs.prod.js +2 -2
  4. package/browser/dist/valbuild-server-browser.esm.js +2 -2
  5. package/dist/{ValOpsMemory-a1a58597.cjs.prod.js → ValOpsMemory-073f9526.cjs.prod.js} +1 -1
  6. package/dist/{ValOpsMemory-88633e0f.cjs.dev.js → ValOpsMemory-3ce3e9e8.cjs.dev.js} +1 -1
  7. package/dist/{ValOpsMemory-82af54c9.esm.js → ValOpsMemory-ecc15827.esm.js} +1 -1
  8. package/dist/{createPrettierFormatter-5d830bdf.cjs.dev.js → createPrettierFormatter-8e60f596.cjs.prod.js} +1 -1
  9. package/dist/{createPrettierFormatter-b31bfbe5.cjs.prod.js → createPrettierFormatter-a9109288.cjs.dev.js} +1 -1
  10. package/dist/{createPrettierFormatter-ce478de1.esm.js → createPrettierFormatter-fb68e363.esm.js} +1 -1
  11. package/dist/{createValRuntime-d34c69e8.esm.js → createValRuntime-02197b93.esm.js} +6 -4
  12. package/dist/{createValRuntime-07bf43dd.cjs.prod.js → createValRuntime-42622f8f.cjs.prod.js} +6 -4
  13. package/dist/{createValRuntime-858474b4.cjs.dev.js → createValRuntime-b55d14f0.cjs.dev.js} +6 -4
  14. package/dist/declarations/src/internal/index.d.ts +14 -0
  15. package/dist/declarations/src/proposalMerge/foldContent.d.ts +45 -0
  16. package/dist/declarations/src/proposalMerge/project.d.ts +124 -0
  17. package/dist/declarations/src/proposalMerge/threeWay.d.ts +51 -0
  18. package/dist/declarations/src/proposalMerge/validate.d.ts +16 -0
  19. package/dist/foldContent-2c218a30.cjs.dev.js +216 -0
  20. package/dist/foldContent-54f2c87c.cjs.prod.js +216 -0
  21. package/dist/foldContent-f065c19f.esm.js +214 -0
  22. package/dist/{inTabFetch-e9a48fac.cjs.prod.js → inTabFetch-46ad6b87.cjs.prod.js} +1 -1
  23. package/dist/{inTabFetch-54c1cb83.esm.js → inTabFetch-6dacc8a1.esm.js} +1 -1
  24. package/dist/{inTabFetch-fb9cf5e0.cjs.dev.js → inTabFetch-85b1aef4.cjs.dev.js} +1 -1
  25. package/dist/{proposalJsonEntries-2cd6f6fe.esm.js → jsonValuesModule-12fc4bb0.esm.js} +2 -128
  26. package/dist/{proposalJsonEntries-d21900d4.cjs.dev.js → jsonValuesModule-6cf73937.cjs.prod.js} +2 -130
  27. package/dist/{proposalJsonEntries-d4623810.cjs.prod.js → jsonValuesModule-ed68a9de.cjs.dev.js} +2 -130
  28. package/dist/merge-5a8fc685.cjs.prod.js +1596 -0
  29. package/dist/merge-a21a9c78.cjs.dev.js +1596 -0
  30. package/dist/merge-eca8ec38.esm.js +1566 -0
  31. package/dist/proposalJsonEntries-4fcfab08.cjs.prod.js +135 -0
  32. package/dist/proposalJsonEntries-878ad5b6.cjs.dev.js +135 -0
  33. package/dist/proposalJsonEntries-e1b07915.esm.js +128 -0
  34. package/dist/{publishKit-cf3858a0.cjs.prod.js → publishKit-70276aed.cjs.prod.js} +19 -22
  35. package/dist/{publishKit-4e7a1516.esm.js → publishKit-a732e3c3.esm.js} +11 -14
  36. package/dist/{publishKit-6b88a02e.cjs.dev.js → publishKit-f7a77be5.cjs.dev.js} +19 -22
  37. package/dist/{valRuntime-ca9958fc.esm.js → valRuntime-407399c1.esm.js} +11 -982
  38. package/dist/{valRuntime-5cadce34.cjs.dev.js → valRuntime-7a4bbb5d.cjs.dev.js} +21 -995
  39. package/dist/{valRuntime-ae69b225.cjs.prod.js → valRuntime-8585d3ce.cjs.prod.js} +21 -995
  40. package/dist/valbuild-server.cjs.dev.js +45 -462
  41. package/dist/valbuild-server.cjs.prod.js +45 -462
  42. package/dist/valbuild-server.esm.js +15 -431
  43. package/internal/browser/dist/valbuild-server-internal-browser.cjs.dev.js +2 -2
  44. package/internal/browser/dist/valbuild-server-internal-browser.cjs.prod.js +2 -2
  45. package/internal/browser/dist/valbuild-server-internal-browser.esm.js +2 -2
  46. package/internal/dist/valbuild-server-internal.cjs.dev.js +20 -2
  47. package/internal/dist/valbuild-server-internal.cjs.prod.js +20 -2
  48. package/internal/dist/valbuild-server-internal.esm.js +20 -3
  49. package/package.json +4 -4
@@ -0,0 +1,1596 @@
1
+ 'use strict';
2
+
3
+ var ts = require('typescript');
4
+ var patch = require('@valbuild/core/patch');
5
+ var fp = require('@valbuild/core/fp');
6
+ var internal = require('@valbuild/shared/internal');
7
+ var path = require('path');
8
+ var jsonValuesModule = require('./jsonValuesModule-ed68a9de.cjs.dev.js');
9
+ var core = require('@valbuild/core');
10
+ require('crypto');
11
+ var fs = require('fs');
12
+ var vm = require('node:vm');
13
+ var node_module = require('node:module');
14
+
15
+ function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
16
+
17
+ var ts__default = /*#__PURE__*/_interopDefault(ts);
18
+ var path__default = /*#__PURE__*/_interopDefault(path);
19
+ var fs__default = /*#__PURE__*/_interopDefault(fs);
20
+ var vm__default = /*#__PURE__*/_interopDefault(vm);
21
+
22
+ function isValidIdentifier(text) {
23
+ if (text.length === 0) {
24
+ return false;
25
+ }
26
+ if (!ts__default["default"].isIdentifierStart(text.charCodeAt(0), ts__default["default"].ScriptTarget.ES2020)) {
27
+ return false;
28
+ }
29
+ for (let i = 1; i < text.length; ++i) {
30
+ if (!ts__default["default"].isIdentifierPart(text.charCodeAt(i), ts__default["default"].ScriptTarget.ES2020)) {
31
+ return false;
32
+ }
33
+ }
34
+ return true;
35
+ }
36
+ function createPropertyAssignment(key, value) {
37
+ return ts__default["default"].factory.createPropertyAssignment(isValidIdentifier(key) ? ts__default["default"].factory.createIdentifier(key) : ts__default["default"].factory.createStringLiteral(key), toExpression(value));
38
+ }
39
+
40
+ /**
41
+ * Builds the expression `c.json(() => import("<importPath>"))` used to reference
42
+ * a lazily-loaded `*.val.json` entry of a `.jsonValues()` record.
43
+ */
44
+ function createValJsonReference(importPath) {
45
+ // () => import("<importPath>")
46
+ // NOTE: an `import` identifier prints as the dynamic-import keyword call,
47
+ // which avoids casting the ImportKeyword token (not typed as an Expression).
48
+ const importCall = ts__default["default"].factory.createCallExpression(ts__default["default"].factory.createIdentifier("import"), undefined, [ts__default["default"].factory.createStringLiteral(importPath)]);
49
+ const thunk = ts__default["default"].factory.createArrowFunction(undefined, undefined, [], undefined, ts__default["default"].factory.createToken(ts__default["default"].SyntaxKind.EqualsGreaterThanToken), importCall);
50
+ // c.json(<thunk>)
51
+ return ts__default["default"].factory.createCallExpression(ts__default["default"].factory.createPropertyAccessExpression(ts__default["default"].factory.createIdentifier("c"), ts__default["default"].factory.createIdentifier("json")), undefined, [thunk]);
52
+ }
53
+
54
+ /**
55
+ * Inserts a new `.jsonValues()` entry `"<key>": c.json(() => import("<importPath>"))`
56
+ * into the record's object literal in a `.val.ts` module. `recordPath` is the
57
+ * path from the module source to the record (empty for a root record/router).
58
+ * Fails if the entry key already exists.
59
+ */
60
+ function insertValJsonEntry(document, recordPath, key, importPath) {
61
+ return fp.pipe(jsonValuesModule.analyzeValModule(document), fp.result.flatMap(({
62
+ source
63
+ }) => getAtPath(source, recordPath)), fp.result.flatMap(recordNode => {
64
+ if (!ts__default["default"].isObjectLiteralExpression(recordNode)) {
65
+ return fp.result.err(new patch.PatchError("Cannot add jsonValues entry: record source is not an object literal"));
66
+ }
67
+ return fp.pipe(jsonValuesModule.findObjectPropertyAssignment(recordNode, key), fp.result.flatMap(assignment => {
68
+ if (assignment) {
69
+ return fp.result.err(new patch.PatchError(`Cannot add jsonValues entry '${key}': it already exists`));
70
+ }
71
+ const property = ts__default["default"].factory.createPropertyAssignment(isValidIdentifier(key) ? ts__default["default"].factory.createIdentifier(key) : ts__default["default"].factory.createStringLiteral(key), createValJsonReference(importPath));
72
+ return fp.result.ok(insertAt(document, recordNode.properties, recordNode.properties.length, property));
73
+ }));
74
+ }));
75
+ }
76
+
77
+ /**
78
+ * Removes the `.jsonValues()` entry `"<key>"` from the record's object literal
79
+ * in a `.val.ts` module. `recordPath` is the path from the module source to the
80
+ * record (empty for a root record/router). Fails if the entry key is missing.
81
+ */
82
+ function removeValJsonEntry(document, recordPath, key) {
83
+ return fp.pipe(jsonValuesModule.analyzeValModule(document), fp.result.flatMap(({
84
+ source
85
+ }) => getAtPath(source, recordPath)), fp.result.flatMap(recordNode => {
86
+ if (!ts__default["default"].isObjectLiteralExpression(recordNode)) {
87
+ return fp.result.err(new patch.PatchError("Cannot remove jsonValues entry: record source is not an object literal"));
88
+ }
89
+ return fp.pipe(jsonValuesModule.findObjectPropertyAssignmentToRemove(recordNode, key), fp.result.flatMap(assignment => {
90
+ if (!assignment) {
91
+ return fp.result.err(new patch.PatchError(`Cannot remove jsonValues entry '${key}': it does not exist`));
92
+ }
93
+ const [doc] = removeAt(document, recordNode.properties, recordNode.properties.indexOf(assignment));
94
+ return fp.result.ok(doc);
95
+ }));
96
+ }));
97
+ }
98
+ function toExpression(value) {
99
+ if (typeof value === "string") {
100
+ // TODO: Use configuration/heuristics to determine use of single quote or double quote
101
+ return ts__default["default"].factory.createStringLiteral(value);
102
+ } else if (typeof value === "number") {
103
+ // TODO: do we want to do something like this for very large numbers?
104
+ // if (value > Number.MAX_SAFE_INTEGER) {
105
+ // return ts.factory.createBigIntLiteral(`${value}n`);
106
+ // }
107
+ // if (value < Number.MIN_SAFE_INTEGER) {
108
+ // return ts.factory.createPrefixUnaryExpression(
109
+ // ts.SyntaxKind.MinusToken,
110
+ // ts.factory.createBigIntLiteral(`${value}n`),
111
+ // );
112
+ // }
113
+ if (value < 0) {
114
+ return ts__default["default"].factory.createPrefixUnaryExpression(ts__default["default"].SyntaxKind.MinusToken, ts__default["default"].factory.createNumericLiteral(Math.abs(value)));
115
+ }
116
+ return ts__default["default"].factory.createNumericLiteral(value);
117
+ } else if (typeof value === "boolean") {
118
+ return value ? ts__default["default"].factory.createTrue() : ts__default["default"].factory.createFalse();
119
+ } else if (value === null) {
120
+ return ts__default["default"].factory.createNull();
121
+ } else if (Array.isArray(value)) {
122
+ return ts__default["default"].factory.createArrayLiteralExpression(value.map(toExpression));
123
+ } else if (typeof value === "object") {
124
+ return ts__default["default"].factory.createObjectLiteralExpression(Object.entries(value)
125
+ // `patch_id` is injected server-side onto a media source whose bytes are
126
+ // not committed yet. It describes the draft, not the content, and a
127
+ // whole-object write built from the client's optimistic view would
128
+ // otherwise print it into the user's file.
129
+ .filter(([key]) => key !== "patch_id").map(([key, value]) => createPropertyAssignment(key, value)));
130
+ } else {
131
+ return ts__default["default"].factory.createStringLiteral(value);
132
+ }
133
+ }
134
+
135
+ // TODO: Choose newline based on project settings/heuristics/system default?
136
+ const newLine = ts__default["default"].NewLineKind.LineFeed;
137
+ // TODO: Handle indentation of printed code
138
+ const printer = ts__default["default"].createPrinter({
139
+ newLine: newLine
140
+ // neverAsciiEscape: true,
141
+ });
142
+ function replaceNodeValue(document, node, value) {
143
+ const replacementText = printer.printNode(ts__default["default"].EmitHint.Unspecified, toExpression(value), document);
144
+ const span = ts__default["default"].createTextSpanFromBounds(node.getStart(document, false), node.end);
145
+ const newText = `${document.text.substring(0, span.start)}${replacementText}${document.text.substring(ts__default["default"].textSpanEnd(span))}`;
146
+ return [document.update(newText, ts__default["default"].createTextChangeRange(span, replacementText.length)), node];
147
+ }
148
+ function isIndentation(s) {
149
+ for (let i = 0; i < s.length; ++i) {
150
+ const c = s.charAt(i);
151
+ if (c !== " " && c !== "\t") {
152
+ return false;
153
+ }
154
+ }
155
+ return true;
156
+ }
157
+ function newLineStr(kind) {
158
+ if (kind === ts__default["default"].NewLineKind.CarriageReturnLineFeed) {
159
+ return "\r\n";
160
+ } else {
161
+ return "\n";
162
+ }
163
+ }
164
+ function getSeparator(document, neighbor) {
165
+ const startPos = neighbor.getStart(document, true);
166
+ const basis = document.getLineAndCharacterOfPosition(startPos);
167
+ const lineStartPos = document.getPositionOfLineAndCharacter(basis.line, 0);
168
+ const maybeIndentation = document.getText().substring(lineStartPos, startPos);
169
+ if (isIndentation(maybeIndentation)) {
170
+ return `,${newLineStr(newLine)}${maybeIndentation}`;
171
+ } else {
172
+ return `, `;
173
+ }
174
+ }
175
+ function insertAt(document, nodes, index, node) {
176
+ let span;
177
+ let replacementText;
178
+ if (nodes.length === 0) {
179
+ // Replace entire range of nodes
180
+ replacementText = printer.printNode(ts__default["default"].EmitHint.Unspecified, node, document);
181
+ span = ts__default["default"].createTextSpanFromBounds(nodes.pos, nodes.end);
182
+ } else if (index === nodes.length) {
183
+ // Insert after last node
184
+ const neighbor = nodes[nodes.length - 1];
185
+ replacementText = `${getSeparator(document, neighbor)}${printer.printNode(ts__default["default"].EmitHint.Unspecified, node, document)}`;
186
+ span = ts__default["default"].createTextSpan(neighbor.end, 0);
187
+ } else {
188
+ // Insert before node
189
+ const neighbor = nodes[index];
190
+ replacementText = `${printer.printNode(ts__default["default"].EmitHint.Unspecified, node, document)}${getSeparator(document, neighbor)}`;
191
+ span = ts__default["default"].createTextSpan(neighbor.getStart(document, true), 0);
192
+ }
193
+ const newText = `${document.text.substring(0, span.start)}${replacementText}${document.text.substring(ts__default["default"].textSpanEnd(span))}`;
194
+ return document.update(newText, ts__default["default"].createTextChangeRange(span, replacementText.length));
195
+ }
196
+ function removeAt(document, nodes, index) {
197
+ const node = nodes[index];
198
+ let span;
199
+ if (nodes.length === 1) {
200
+ span = ts__default["default"].createTextSpanFromBounds(nodes.pos, nodes.end);
201
+ } else if (index === nodes.length - 1) {
202
+ // Remove until previous node
203
+ const neighbor = nodes[index - 1];
204
+ span = ts__default["default"].createTextSpanFromBounds(neighbor.end, node.end);
205
+ } else {
206
+ // Remove before next node
207
+ const neighbor = nodes[index + 1];
208
+ span = ts__default["default"].createTextSpanFromBounds(node.getStart(document, true), neighbor.getStart(document, true));
209
+ }
210
+ const newText = `${document.text.substring(0, span.start)}${document.text.substring(ts__default["default"].textSpanEnd(span))}`;
211
+ return [document.update(newText, ts__default["default"].createTextChangeRange(span, 0)), node];
212
+ }
213
+ function parseAndValidateArrayInsertIndex(key, nodes) {
214
+ if (key === "-") {
215
+ // For insertion, all nodes up until the insertion index must be valid
216
+ // initializers
217
+ const err = jsonValuesModule.validateInitializers(nodes);
218
+ if (err) {
219
+ return fp.result.err(err);
220
+ }
221
+ return fp.result.ok(nodes.length);
222
+ }
223
+ return fp.pipe(patch.parseAndValidateArrayIndex(key), fp.result.flatMap(index => {
224
+ // For insertion, all nodes up until the insertion index must be valid
225
+ // initializers
226
+ const err = jsonValuesModule.validateInitializers(nodes.slice(0, index));
227
+ if (err) {
228
+ return fp.result.err(err);
229
+ }
230
+ if (index > nodes.length) {
231
+ return fp.result.err(new patch.PatchError("Array index out of bounds"));
232
+ } else {
233
+ return fp.result.ok(index);
234
+ }
235
+ }));
236
+ }
237
+ function parseAndValidateArrayInboundsIndex(key, nodes) {
238
+ return fp.pipe(patch.parseAndValidateArrayIndex(key), fp.result.flatMap(index => {
239
+ // For in-bounds operations, all nodes up until and including the index
240
+ // must be valid initializers
241
+ const err = jsonValuesModule.validateInitializers(nodes.slice(0, index + 1));
242
+ if (err) {
243
+ return fp.result.err(err);
244
+ }
245
+ if (index >= nodes.length) {
246
+ return fp.result.err(new patch.PatchError("Array index out of bounds"));
247
+ } else {
248
+ return fp.result.ok(index);
249
+ }
250
+ }));
251
+ }
252
+ function replaceInNode(document, node, key, value) {
253
+ if (ts__default["default"].isArrayLiteralExpression(node)) {
254
+ return fp.pipe(parseAndValidateArrayInboundsIndex(key, node.elements), fp.result.map(index => replaceNodeValue(document, node.elements[index], value)));
255
+ } else if (ts__default["default"].isObjectLiteralExpression(node)) {
256
+ return fp.pipe(jsonValuesModule.findObjectPropertyAssignment(node, key), fp.result.flatMap(assignment => {
257
+ if (!assignment) {
258
+ return fp.result.err(new patch.PatchError("Cannot replace object element which does not exist"));
259
+ }
260
+ return fp.result.ok(assignment);
261
+ }), fp.result.map(assignment => replaceNodeValue(document, assignment.initializer, value)));
262
+ } else {
263
+ return fp.result.err(jsonValuesModule.shallowValidateExpression(node) ?? new patch.PatchError("Cannot replace in non-object/array"));
264
+ }
265
+ }
266
+ function replaceAtPath(document, rootNode, path, value) {
267
+ if (patch.isNotRoot(path)) {
268
+ return fp.pipe(getPointerFromPath(rootNode, path), fp.result.flatMap(([node, key]) => replaceInNode(document, node, key, value)));
269
+ } else {
270
+ return fp.result.ok(replaceNodeValue(document, rootNode, value));
271
+ }
272
+ }
273
+ function getFromNode(node, key) {
274
+ if (ts__default["default"].isArrayLiteralExpression(node)) {
275
+ return fp.pipe(parseAndValidateArrayInboundsIndex(key, node.elements), fp.result.map(index => node.elements[index]));
276
+ } else if (ts__default["default"].isObjectLiteralExpression(node)) {
277
+ return fp.pipe(jsonValuesModule.findObjectPropertyAssignment(node, key), fp.result.map(assignment => assignment === null || assignment === void 0 ? void 0 : assignment.initializer));
278
+ } else {
279
+ return fp.result.err(jsonValuesModule.shallowValidateExpression(node) ?? new patch.PatchError("Cannot access non-object/array"));
280
+ }
281
+ }
282
+ function getPointerFromPath(node, path) {
283
+ let targetNode = node;
284
+ let key = path[0];
285
+ for (let i = 0; i < path.length - 1; ++i, key = path[i]) {
286
+ const childNode = getFromNode(targetNode, key);
287
+ if (fp.result.isErr(childNode)) {
288
+ return childNode;
289
+ }
290
+ if (childNode.value === undefined) {
291
+ return fp.result.err(new patch.PatchError(`Path refers to non-existing object/array: ${path.join("/")}`));
292
+ }
293
+ targetNode = childNode.value;
294
+ }
295
+ return fp.result.ok([targetNode, key]);
296
+ }
297
+ function getAtPath(rootNode, path) {
298
+ return fp.pipe(path, fp.result.flatMapReduce((node, key) => fp.pipe(getFromNode(node, key), fp.result.filterOrElse(childNode => childNode !== undefined, () => new patch.PatchError("Path refers to non-existing object/array"))), rootNode));
299
+ }
300
+ function removeFromNode(document, node, key) {
301
+ if (ts__default["default"].isArrayLiteralExpression(node)) {
302
+ return fp.pipe(parseAndValidateArrayInboundsIndex(key, node.elements), fp.result.map(index => removeAt(document, node.elements, index)));
303
+ } else if (ts__default["default"].isObjectLiteralExpression(node)) {
304
+ return fp.pipe(jsonValuesModule.findObjectPropertyAssignmentToRemove(node, key), fp.result.flatMap(assignment => {
305
+ if (!assignment) {
306
+ return fp.result.err(new patch.PatchError("Cannot remove object element which does not exist"));
307
+ }
308
+ return fp.result.ok(assignment);
309
+ }), fp.result.map(assignment => [removeAt(document, node.properties, node.properties.indexOf(assignment))[0], assignment.initializer]));
310
+ } else {
311
+ return fp.result.err(jsonValuesModule.shallowValidateExpression(node) ?? new patch.PatchError("Cannot remove from non-object/array"));
312
+ }
313
+ }
314
+ function removeAtPath(document, rootNode, path) {
315
+ return fp.pipe(getPointerFromPath(rootNode, path), fp.result.flatMap(([node, key]) => removeFromNode(document, node, key)));
316
+ }
317
+ function addToNode(document, node, key, value) {
318
+ if (ts__default["default"].isArrayLiteralExpression(node)) {
319
+ return fp.pipe(parseAndValidateArrayInsertIndex(key, node.elements), fp.result.map(index => [insertAt(document, node.elements, index, toExpression(value))]));
320
+ } else if (ts__default["default"].isObjectLiteralExpression(node)) {
321
+ return fp.pipe(jsonValuesModule.findObjectPropertyAssignment(node, key), fp.result.map(assignment => {
322
+ if (!assignment) {
323
+ return [insertAt(document, node.properties, node.properties.length, createPropertyAssignment(key, value))];
324
+ } else {
325
+ return replaceNodeValue(document, assignment.initializer, value);
326
+ }
327
+ }));
328
+ } else {
329
+ return fp.result.err(jsonValuesModule.shallowValidateExpression(node) ?? new patch.PatchError("Cannot add to non-object/array"));
330
+ }
331
+ }
332
+ function addAtPath(document, rootNode, path, value) {
333
+ if (patch.isNotRoot(path)) {
334
+ return fp.pipe(getPointerFromPath(rootNode, path), fp.result.flatMap(([node, key]) => addToNode(document, node, key, value)));
335
+ } else {
336
+ return fp.result.ok(replaceNodeValue(document, rootNode, value));
337
+ }
338
+ }
339
+ function pickDocument([document]) {
340
+ return document;
341
+ }
342
+ class TSOps {
343
+ constructor(findRoot) {
344
+ this.findRoot = findRoot;
345
+ }
346
+ get(document, path) {
347
+ return fp.pipe(document, this.findRoot, fp.result.flatMap(rootNode => getAtPath(rootNode, path)), fp.result.flatMap(jsonValuesModule.evaluateExpression));
348
+ }
349
+ add(document, path, value) {
350
+ return fp.pipe(document, this.findRoot, fp.result.flatMap(rootNode => addAtPath(document, rootNode, path, value)), fp.result.map(pickDocument));
351
+ }
352
+ remove(document, path) {
353
+ return fp.pipe(document, this.findRoot, fp.result.flatMap(rootNode => removeAtPath(document, rootNode, path)), fp.result.map(pickDocument));
354
+ }
355
+ replace(document, path, value) {
356
+ return fp.pipe(document, this.findRoot, fp.result.flatMap(rootNode => replaceAtPath(document, rootNode, path, value)), fp.result.map(pickDocument));
357
+ }
358
+ move(document, from, path) {
359
+ return fp.pipe(document, this.findRoot, fp.result.flatMap(rootNode => removeAtPath(document, rootNode, from)), fp.result.flatMap(([document, removedNode]) => fp.pipe(jsonValuesModule.evaluateExpression(removedNode), fp.result.map(removedValue => [document, removedValue]))), fp.result.flatMap(([document, removedValue]) => fp.pipe(document, this.findRoot, fp.result.flatMap(root => addAtPath(document, root, path, removedValue)))), fp.result.map(pickDocument));
360
+ }
361
+ copy(document, from, path) {
362
+ return fp.pipe(document, this.findRoot, fp.result.flatMap(rootNode => fp.pipe(getAtPath(rootNode, from), fp.result.flatMap(jsonValuesModule.evaluateExpression), fp.result.flatMap(value => addAtPath(document, rootNode, path, value)))), fp.result.map(pickDocument));
363
+ }
364
+ test(document, path, value) {
365
+ return fp.pipe(document, this.findRoot, fp.result.flatMap(rootNode => getAtPath(rootNode, path)), fp.result.flatMap(jsonValuesModule.evaluateExpression), fp.result.map(documentValue => patch.deepEqual(value, documentValue)));
366
+ }
367
+ }
368
+
369
+ const getCompilerOptions = (rootDir, parseConfigHost) => {
370
+ const tsConfigPath = path__default["default"].resolve(rootDir, "tsconfig.json");
371
+ const jsConfigPath = path__default["default"].resolve(rootDir, "jsconfig.json");
372
+ let configFilePath;
373
+ if (parseConfigHost.fileExists(jsConfigPath)) {
374
+ configFilePath = jsConfigPath;
375
+ } else if (parseConfigHost.fileExists(tsConfigPath)) {
376
+ configFilePath = tsConfigPath;
377
+ } else {
378
+ throw Error(`Could not read config from: "${tsConfigPath}" nor "${jsConfigPath}". Root dir: "${rootDir}"`);
379
+ }
380
+ const {
381
+ config,
382
+ error
383
+ } = ts__default["default"].readConfigFile(configFilePath, parseConfigHost.readFile.bind(parseConfigHost));
384
+ if (error) {
385
+ if (typeof error.messageText === "string") {
386
+ throw Error(`Could not parse config file: ${configFilePath}. Error: ${error.messageText}`);
387
+ }
388
+ throw Error(`Could not parse config file: ${configFilePath}. Error: ${error.messageText.messageText}`);
389
+ }
390
+ const optionsOverrides = undefined;
391
+ const parsedConfigFile = ts__default["default"].parseJsonConfigFileContent(config, parseConfigHost, rootDir, optionsOverrides, configFilePath);
392
+ if (parsedConfigFile.errors.length > 0) {
393
+ throw Error(`Could not parse config file: ${configFilePath}. Errors: ${parsedConfigFile.errors.map(e => e.messageText).join("\n")}`);
394
+ }
395
+ return parsedConfigFile.options;
396
+ };
397
+
398
+ /**
399
+ * Node's `require`, resolving as if from `filename`.
400
+ *
401
+ * Use this instead of importing `createRequire` from `node:module` directly.
402
+ * webpack special-cases a `createRequire` binding imported from `module` /
403
+ * `node:module`: it tries to resolve the call's argument at build time, and
404
+ * when the argument is not a literal it gives up with
405
+ *
406
+ * module.createRequire failed parsing argument.
407
+ *
408
+ * Our argument is never a literal — it is a path inside the user's project,
409
+ * known only at runtime — so there is nothing for that analysis to find, and
410
+ * nothing the warning can tell anyone. It is emitted on every build of every
411
+ * Next app that bundles `@valbuild/server` into its Val API route, which is
412
+ * all of them. Reaching `createRequire` through the `Module` class is the same
413
+ * function and is not what webpack tags, so the call is invisible to it.
414
+ *
415
+ * It has to stay a real `node:module` import: jest's module registry hands out
416
+ * its own `node:module`, and a `require` obtained around it (via
417
+ * `process.getBuiltinModule`, say) would resolve against the real filesystem
418
+ * rather than the registry the tests run in.
419
+ */
420
+ function createNodeRequire(filename) {
421
+ return node_module.Module.createRequire(filename);
422
+ }
423
+
424
+ /**
425
+ * The filesystem seam `loadValModules` reads through.
426
+ *
427
+ * Defaults to `ts.sys`, i.e. the real filesystem. An editor integration (see
428
+ * `@valbuild/language-server`) passes a host that overlays unsaved buffers, so
429
+ * that evaluation sees what the user is looking at rather than what was last
430
+ * saved.
431
+ */
432
+
433
+ /**
434
+ * Loads the project's root `val.modules.ts` (or `.js`) using Node's `vm`
435
+ * module and returns its default export (a `ValModules` registry).
436
+ *
437
+ * This is a recursive CommonJS loader: the root modules file and every
438
+ * relative `*.val.ts` / `val.config.ts` it (dynamically) imports are
439
+ * transpiled to CommonJS and evaluated in a `vm` sandbox. Bare specifiers
440
+ * (e.g. `@valbuild/core`) are resolved with the real Node `require` so the
441
+ * user modules share the exact same `@valbuild/core` instance that
442
+ * `extractValModules` uses.
443
+ *
444
+ * Mirrors the pattern already used by the CLI's `evalValConfigFile`.
445
+ *
446
+ * SECURITY: The `vm` context is NOT a security sandbox. It deliberately exposes
447
+ * `process` and a `require` that falls back to the real Node resolver (so user
448
+ * modules share the same `@valbuild/core` instance). This loader must therefore
449
+ * only ever be used to evaluate the project's own first-party, trusted files
450
+ * (`val.modules` and the local `*.val.ts`/`val.config.ts` it imports) — i.e. the
451
+ * same trust level as running the project's build. It must never be used to
452
+ * evaluate untrusted or third-party modules.
453
+ */
454
+ function loadValModules(projectRoot, host = ts__default["default"].sys) {
455
+ const valModulesPath = findValModulesPath(projectRoot, host);
456
+ if (!valModulesPath) {
457
+ throw Error(`Could not find 'val.modules.ts' nor 'val.modules.js' in project root: '${projectRoot}'`);
458
+ }
459
+ const compilerOptions = getCompilerOptions(projectRoot, host);
460
+ const cache = {};
461
+ const loaded = loadModule(valModulesPath, cache, compilerOptions, host);
462
+ const valModules = loaded.exports.default;
463
+ if (!valModules) {
464
+ throw Error(`Val modules file at path: '${valModulesPath}' must have a default export. Got: ${valModules}`);
465
+ }
466
+ return valModules;
467
+ }
468
+ function findValModulesPath(projectRoot, host) {
469
+ for (const fileName of ["val.modules.ts", "val.modules.js"]) {
470
+ const candidate = path__default["default"].join(projectRoot, fileName);
471
+ if (host.fileExists(candidate)) {
472
+ return candidate;
473
+ }
474
+ }
475
+ return null;
476
+ }
477
+ const RESOLVE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".cjs", ".mjs", ".json"];
478
+
479
+ // Specifiers that user val files must not actually use. We stub them so that
480
+ // importing is fine, but using a value throws a clear error. Real @valbuild
481
+ // packages are resolved via the real require, so when they (legitimately)
482
+ // import react/next internally those go through Node, not this stub.
483
+ function isStubbedSpecifier(spec) {
484
+ return spec === "react" || spec.startsWith("react/") || spec === "next" || spec.startsWith("next/") || spec === "@valbuild/ui" || spec === "@valbuild/react" || spec.startsWith("@valbuild/react/");
485
+ }
486
+ function makeStub(spec) {
487
+ const throwing = prop => () => {
488
+ throw Error(`Cannot use '${prop}' from '${spec}' in this type of file`);
489
+ };
490
+ const handler = {
491
+ get(_target, prop) {
492
+ if (prop === "__esModule") {
493
+ return true;
494
+ }
495
+ if (typeof prop === "symbol") {
496
+ return undefined;
497
+ }
498
+ // React.createContext is sometimes called at module top-level; return a
499
+ // proxy-returning function so evaluation does not crash on import.
500
+ if (prop === "createContext") {
501
+ return () => new Proxy({}, handler);
502
+ }
503
+ if (prop === "default") {
504
+ return stub;
505
+ }
506
+ return throwing(prop);
507
+ }
508
+ };
509
+ const stub = new Proxy({}, handler);
510
+ return stub;
511
+ }
512
+ function loadModule(absPath, cache, compilerOptions, host) {
513
+ const cached = cache[absPath];
514
+ if (cached) {
515
+ return cached;
516
+ }
517
+ // JSON modules (e.g. the `*.val.json` files backing `.jsonValues()` entries)
518
+ // are loaded by parsing, mirroring Node's `require("./x.json")` which returns
519
+ // the parsed object as `module.exports`. The importing `.val.ts` wraps this
520
+ // with `__importStar` so `import("./x.val.json")` yields `{ default, ... }`.
521
+ // These are only loaded when an entry thunk is invoked, never during
522
+ // `extractValModules`, so this stays lazy.
523
+ //
524
+ // Read through `host` like every other project file: an editor integration
525
+ // passes a host that overlays unsaved buffers, and an entry the user is
526
+ // editing has to resolve to what they are looking at.
527
+ if (absPath.endsWith(".json")) {
528
+ const json = host.readFile(absPath);
529
+ if (json === undefined) {
530
+ throw Error(`Could not read Val module file: '${absPath}'`);
531
+ }
532
+ const jsonModule = {
533
+ exports: JSON.parse(json)
534
+ };
535
+ cache[absPath] = jsonModule;
536
+ return jsonModule;
537
+ }
538
+ const code = host.readFile(absPath);
539
+ if (code === undefined) {
540
+ throw Error(`Could not read Val module file: '${absPath}'`);
541
+ }
542
+ const transpiled = ts__default["default"].transpileModule(code, {
543
+ compilerOptions: {
544
+ target: ts__default["default"].ScriptTarget.ES2020,
545
+ module: ts__default["default"].ModuleKind.CommonJS,
546
+ esModuleInterop: true,
547
+ jsx: ts__default["default"].JsxEmit.ReactJSX
548
+ },
549
+ fileName: absPath
550
+ });
551
+ const moduleObj = {
552
+ exports: {}
553
+ };
554
+ // Insert into the cache before evaluating so cyclic imports resolve.
555
+ cache[absPath] = moduleObj;
556
+ const dirName = path__default["default"].dirname(absPath);
557
+ const realRequire = createNodeRequire(absPath);
558
+ const customRequire = spec => {
559
+ var _ts$resolveModuleName;
560
+ if (isStubbedSpecifier(spec)) {
561
+ return makeStub(spec);
562
+ }
563
+ if (spec.startsWith(".") || path__default["default"].isAbsolute(spec)) {
564
+ const resolved = resolveRelative(dirName, spec, host);
565
+ if (!resolved) {
566
+ throw Error(`Could not resolve module '${spec}' from '${absPath}'`);
567
+ }
568
+ return loadModule(resolved, cache, compilerOptions, host).exports;
569
+ }
570
+ // Non-relative specifier: it might be a tsconfig path alias (e.g. "_/val.config")
571
+ // pointing at a local source file, or an actual node_modules package.
572
+ const tsResolved = (_ts$resolveModuleName = ts__default["default"].resolveModuleName(spec, absPath, compilerOptions, host).resolvedModule) === null || _ts$resolveModuleName === void 0 ? void 0 : _ts$resolveModuleName.resolvedFileName;
573
+ if (tsResolved && !tsResolved.includes("/node_modules/") && !tsResolved.endsWith(".d.ts")) {
574
+ return loadModule(tsResolved, cache, compilerOptions, host).exports;
575
+ }
576
+ // Real node_modules package – use the real require so user modules share
577
+ // the same @valbuild/core instance as extractValModules.
578
+ return realRequire(spec);
579
+ };
580
+
581
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
582
+ const sandbox = {
583
+ exports: moduleObj.exports,
584
+ module: moduleObj,
585
+ require: customRequire,
586
+ __filename: absPath,
587
+ __dirname: dirName,
588
+ console,
589
+ process
590
+ };
591
+ sandbox.global = sandbox;
592
+ sandbox.globalThis = sandbox;
593
+ const context = vm__default["default"].createContext(sandbox);
594
+ const script = new vm__default["default"].Script(transpiled.outputText, {
595
+ filename: absPath
596
+ });
597
+ script.runInContext(context);
598
+ return moduleObj;
599
+ }
600
+ function resolveRelative(dirName, spec, host) {
601
+ var _host$directoryExists;
602
+ const base = path__default["default"].resolve(dirName, spec);
603
+ // Exact file (with extension)
604
+ if (host.fileExists(base)) {
605
+ return base;
606
+ }
607
+ // Probe extensions (handles `./x.val` -> `./x.val.ts`)
608
+ for (const ext of RESOLVE_EXTENSIONS) {
609
+ const candidate = base + ext;
610
+ if (host.fileExists(candidate)) {
611
+ return candidate;
612
+ }
613
+ }
614
+ // Directory index
615
+ if (((_host$directoryExists = host.directoryExists) === null || _host$directoryExists === void 0 ? void 0 : _host$directoryExists.call(host, base)) ?? fs__default["default"].existsSync(base)) {
616
+ for (const ext of RESOLVE_EXTENSIONS) {
617
+ const candidate = path__default["default"].join(base, "index" + ext);
618
+ if (host.fileExists(candidate)) {
619
+ return candidate;
620
+ }
621
+ }
622
+ }
623
+ return null;
624
+ }
625
+
626
+ /**
627
+ * What a `*.val.ts` file that is NOT registered in `val.modules` turns out to
628
+ * be.
629
+ *
630
+ * A file matching `*.val.ts` is not necessarily a Val module: the same
631
+ * convention is used for shared schemas and other content-adjacent helpers, and
632
+ * those are not meant to be registered. Only a file that actually default
633
+ * exports a module is worth warning about; one that default exports something
634
+ * else is a mistake, because nothing will ever load it.
635
+ *
636
+ * See {@link createValModuleFileInspector}.
637
+ */
638
+
639
+ /**
640
+ * Inspects individual `*.val.{ts,js}` files, sharing one module cache and one
641
+ * parsed tsconfig across every call.
642
+ *
643
+ * The default export is checked SYNTACTICALLY first and only evaluated if it is
644
+ * there. That ordering is the point: a `.val.ts` with no default export is a
645
+ * helper file, and evaluating it to learn that would be both wasted work and a
646
+ * way to turn an unrelated top-level throw into a reported error.
647
+ *
648
+ * SECURITY: evaluation goes through the same `vm` loader as
649
+ * {@link loadValModules} — see the warning there. Only ever point this at the
650
+ * project's own first-party files.
651
+ */
652
+ function createValModuleFileInspector(projectRoot, host = ts__default["default"].sys) {
653
+ const compilerOptions = getCompilerOptions(projectRoot, host);
654
+ const cache = {};
655
+ return absPath => {
656
+ const code = host.readFile(absPath);
657
+ if (code === undefined) {
658
+ return {
659
+ status: "invalid",
660
+ message: `Could not read file: '${absPath}'`
661
+ };
662
+ }
663
+ const sourceFile = ts__default["default"].createSourceFile(absPath, code, ts__default["default"].ScriptTarget.ES2020, true);
664
+ if (!hasDefaultExport(sourceFile)) {
665
+ return {
666
+ status: "no-default-export"
667
+ };
668
+ }
669
+ let exports;
670
+ // `loadModule` inserts a module into the cache BEFORE evaluating it, so
671
+ // that a cycle resolves. One that throws therefore leaves a half-built
672
+ // entry behind - and unlike `loadValModules`, which builds a cache per
673
+ // call and lets the throw escape, this cache outlives the failure. A later
674
+ // inspection of the same file (or of the helper that actually threw) would
675
+ // hit that entry, see empty exports, and report "default export is
676
+ // undefined" instead of the real error - or, worse, quietly downgrade it to
677
+ // a warning. So roll the cache back to what it was before this attempt.
678
+ const before = new Set(Object.keys(cache));
679
+ try {
680
+ exports = loadModule(absPath, cache, compilerOptions, host).exports;
681
+ } catch (e) {
682
+ for (const key of Object.keys(cache)) {
683
+ if (!before.has(key)) {
684
+ delete cache[key];
685
+ }
686
+ }
687
+ return {
688
+ status: "invalid",
689
+ message: `Could not be loaded. Error: ${errorMessage(e)}`
690
+ };
691
+ }
692
+ if (core.Internal.isValModule(exports.default)) {
693
+ return {
694
+ status: "val-module"
695
+ };
696
+ }
697
+ // NOTE: do NOT suggest wrapping this in `c.define`. A shared schema turned
698
+ // into a module is an UNREGISTERED module, i.e. straight back to a warning.
699
+ // The fix is to move it out of the default export slot, which is the one
700
+ // thing about a `.val.ts` that Val reserves for itself.
701
+ return {
702
+ status: "invalid",
703
+ message: `Default export is ${describeDefaultExport(exports.default)}, not a Val module. Only 'c.define(...)' may be the default export of a '*.val.ts' file: use a named export for a shared schema or helper`
704
+ };
705
+ };
706
+ }
707
+
708
+ /**
709
+ * The statement that exports a RUNTIME value as `default`, without evaluating
710
+ * it — or `undefined` when the file has no such export.
711
+ *
712
+ * This is the one rule that separates a Val module from a `*.val.ts` that
713
+ * merely wears the naming convention: a shared schema or helper is exported by
714
+ * name, a module is exported by default. Every caller that needs to tell those
715
+ * apart goes through this — `val validate` to decide whether an unregistered
716
+ * file is worth reporting, and the language server to decide the same thing and
717
+ * to put its diagnostic on the export rather than on line 1.
718
+ *
719
+ * Two things deliberately do not count, because neither exists once the file is
720
+ * transpiled — and treating either as a default export would send a pure helper
721
+ * off to be evaluated and reported:
722
+ *
723
+ * - `export * from "./x"`, since a star re-export never carries the default;
724
+ * - a type-only export, in any of its three spellings
725
+ * (`export type { T as default }`, `export { type T as default }` and
726
+ * `export default interface T {}` — the last one parses as a declaration
727
+ * carrying a `default` modifier, exactly like `export default class`, and is
728
+ * the one that looks like a runtime export and is not).
729
+ */
730
+ function findDefaultExport(sourceFile) {
731
+ return sourceFile.statements.find(statement => {
732
+ // `export default <expr>` — but not `export = x`, which shares this node.
733
+ if (ts__default["default"].isExportAssignment(statement)) {
734
+ return !statement.isExportEquals;
735
+ }
736
+ // `export { x as default }` / `export { default } from "./x"`
737
+ if (ts__default["default"].isExportDeclaration(statement) && !statement.isTypeOnly && statement.exportClause && ts__default["default"].isNamedExports(statement.exportClause)) {
738
+ return statement.exportClause.elements.some(element => !element.isTypeOnly && element.name.text === "default");
739
+ }
740
+ // `export default function f() {}` / `export default class C {}`, which are
741
+ // declarations carrying a `default` modifier rather than export assignments.
742
+ // `export default interface T {}` is spelled the same way and is a type, so
743
+ // it is excluded here rather than by the `isTypeOnly` checks above.
744
+ 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);
745
+ });
746
+ }
747
+
748
+ /** Whether the file exports a runtime value as `default`. */
749
+ function hasDefaultExport(sourceFile) {
750
+ return findDefaultExport(sourceFile) !== undefined;
751
+ }
752
+
753
+ /** A short, human-readable "what you exported instead" for the error message. */
754
+ function describeDefaultExport(value) {
755
+ if (value === null) {
756
+ return "null";
757
+ }
758
+ if (Array.isArray(value)) {
759
+ return "an array";
760
+ }
761
+ if (typeof value === "object") {
762
+ // Duck-typed rather than `instanceof Schema`, for the same cross-realm
763
+ // reason `isValModule` avoids a constructor check.
764
+ if ("executeSerialize" in value && typeof value["executeSerialize"] === "function") {
765
+ return "a schema";
766
+ }
767
+ return "an object";
768
+ }
769
+ if (typeof value === "undefined") {
770
+ return "undefined";
771
+ }
772
+ return `a ${typeof value}`;
773
+ }
774
+ function errorMessage(e) {
775
+ // NOT `e instanceof Error`: an error thrown from inside the `vm` context is
776
+ // built from that realm's Error constructor. Duck-type the message instead.
777
+ if (typeof e === "object" && e !== null && "message" in e) {
778
+ const {
779
+ message
780
+ } = e;
781
+ if (typeof message === "string") {
782
+ return message;
783
+ }
784
+ }
785
+ return String(e);
786
+ }
787
+
788
+ /** What a schema reports about this content: see `schemaErrorsOf`. */
789
+ const validateWith = (schema, moduleFilePath, source) => internal.schemaErrorsOf(schema, moduleFilePath, source);
790
+
791
+ /**
792
+ * A module's errors for this content: its own `validate` where the schema was
793
+ * evaluated, custom rules and all; otherwise what its serialized schema says,
794
+ * which is every rule but a custom `.validate(...)` (a closure does not
795
+ * serialize).
796
+ */
797
+ function validateModule(moduleFilePath, module, source) {
798
+ if (module.validate) return module.validate(source);
799
+ return validateWith(core.deserializeSchema(module.schema), moduleFilePath, source);
800
+ }
801
+
802
+ /** The errors of a module's own Source: as evaluated where they were, else found here. */
803
+ function errorsOfSource(moduleFilePath, module) {
804
+ return module.errors ?? validateModule(moduleFilePath, module, module.source);
805
+ }
806
+
807
+ /**
808
+ * A project as git holds it: every file's text, by path from the project
809
+ * root. A commit in the world is one of these -- `.val.ts` files, the
810
+ * components that render them, `val.modules.ts` -- and nothing else, the same
811
+ * way a commit on content's line is.
812
+ */
813
+
814
+ /**
815
+ * Where the files are said to be. Nothing is written there: the loader reads
816
+ * through {@link host}, which answers from the files for anything under it and
817
+ * from the disk for everything else, so `@valbuild/core` resolves to the one
818
+ * the tests run on.
819
+ */
820
+ function projectRoot() {
821
+ /*
822
+ * Asked when a project is loaded, never at import: `__dirname` exists only
823
+ * in CommonJS, and this module is imported by Val's server wherever it runs
824
+ * -- in the TanStack example's Vite SSR, which is ESM, a top-level read of
825
+ * it stopped the server from starting. There the app's own directory is
826
+ * where `@valbuild/core` resolves from, which is what a merge in a running
827
+ * app should load.
828
+ */
829
+ const base = typeof __dirname === "string" ? __dirname : process.cwd();
830
+ return path__default["default"].join(base, "__project__");
831
+ }
832
+ function host(files) {
833
+ const ROOT = projectRoot();
834
+ const byAbs = new Map();
835
+ for (const [file, text] of Object.entries(files)) {
836
+ if (text !== null) byAbs.set(path__default["default"].join(ROOT, file), text);
837
+ }
838
+ const dirs = new Set();
839
+ for (const file of byAbs.keys()) {
840
+ for (let dir = path__default["default"].dirname(file); dir.startsWith(ROOT);) {
841
+ dirs.add(dir);
842
+ dir = path__default["default"].dirname(dir);
843
+ }
844
+ }
845
+ const inProject = p => p === ROOT || p.startsWith(ROOT + path__default["default"].sep);
846
+ return {
847
+ ...ts__default["default"].sys,
848
+ fileExists: p => inProject(p) ? byAbs.has(p) : ts__default["default"].sys.fileExists(p),
849
+ readFile: p => inProject(p) ? byAbs.get(p) : ts__default["default"].sys.readFile(p),
850
+ directoryExists: p => {
851
+ var _ts$sys$directoryExis, _ts$sys;
852
+ return inProject(p) ? dirs.has(p) : ((_ts$sys$directoryExis = (_ts$sys = ts__default["default"].sys).directoryExists) === null || _ts$sys$directoryExis === void 0 ? void 0 : _ts$sys$directoryExis.call(_ts$sys, p)) ?? false;
853
+ },
854
+ /*
855
+ * A real project's `tsconfig.json` names its inputs by glob (`include`),
856
+ * and parsing it asks for them: with no listing, every project but one
857
+ * whose config names its files outright failed to load ("No inputs were
858
+ * found"). The project's own files under `dir`, by extension, less what
859
+ * the config excludes by name (`node_modules`, `dist`, ...). Which files
860
+ * are inputs does not decide anything here: only the compiler options
861
+ * are read from the config.
862
+ */
863
+ readDirectory: (dir, extensions, excludes, includes, depth) => {
864
+ if (!inProject(dir)) {
865
+ return ts__default["default"].sys.readDirectory(dir, extensions, excludes, includes, depth);
866
+ }
867
+ const excluded = new Set((excludes ?? []).map(pattern => pattern.replace(/^\.?\/|\/\*\*.*$/g, "")));
868
+ return [...byAbs.keys()].filter(file => {
869
+ if (file !== dir && !file.startsWith(dir + path__default["default"].sep)) return false;
870
+ if (extensions !== undefined && !extensions.some(extension => file.endsWith(extension))) {
871
+ return false;
872
+ }
873
+ return !path__default["default"].relative(dir, file).split(path__default["default"].sep).some(part => excluded.has(part));
874
+ });
875
+ }
876
+ };
877
+ }
878
+
879
+ /**
880
+ * A module, as the merge needs it: data, so whoever evaluated the project's
881
+ * schemas can hand it over -- Val's loader here and in `val validate`, the
882
+ * builder tab with rolldown -- and the merge itself never runs project code.
883
+ */
884
+
885
+ /** A project at one commit: its files, and its modules as data. */
886
+
887
+ /** A loaded project, as the merge takes it. */
888
+ function projectOf(files, loaded) {
889
+ const modules = {};
890
+ for (const [path, {
891
+ module,
892
+ source,
893
+ entries
894
+ }] of Object.entries(loaded.modules)) {
895
+ const moduleFilePath = path;
896
+ const schema = core.Internal.getSchema(module);
897
+ if (!schema) continue;
898
+ modules[moduleFilePath] = {
899
+ source,
900
+ schema: schema["executeSerialize"](),
901
+ entries,
902
+ validate: content => validateWith(schema, moduleFilePath, content)
903
+ };
904
+ }
905
+ return {
906
+ files,
907
+ modules
908
+ };
909
+ }
910
+
911
+ /** A module as the project defines it, read by Val's own loader. */
912
+
913
+ /**
914
+ * Loads the project at a commit the way `val validate` does: `val.modules.ts`
915
+ * and every `.val.ts` it imports, transpiled and evaluated
916
+ * (`loadValModules`). So a schema a proposal changed is the schema it changed
917
+ * to, read from the text it wrote.
918
+ */
919
+ async function loadProject(files) {
920
+ const valModules = loadValModules(projectRoot(), host(files));
921
+ const modules = {};
922
+ for (const {
923
+ def
924
+ } of valModules.modules) {
925
+ const module = (await def()).default;
926
+ const id = core.Internal.getValPath(module);
927
+ if (id === undefined) continue;
928
+ const moduleFilePath = id;
929
+ const text = files[moduleFilePath.slice(1)] ?? null;
930
+ modules[moduleFilePath] = {
931
+ module,
932
+ // The one conversion, as `ValOps.getSources` makes it: a module's
933
+ // Source is JSON once its entries are read (media are plain objects).
934
+ source: patch.deepClone(await core.Internal.resolveJsonValues(core.Internal.getSource(module))),
935
+ entries: text === null ? null : entryFilesOf(moduleFilePath, text)
936
+ };
937
+ }
938
+ const sourceFiles = {};
939
+ for (const [file, text] of Object.entries(files)) {
940
+ if (text !== null && (file.endsWith(".val.ts") || file.endsWith(".val.json"))) {
941
+ sourceFiles[file] = text;
942
+ }
943
+ }
944
+ return {
945
+ valModules,
946
+ modules,
947
+ sourceFiles
948
+ };
949
+ }
950
+
951
+ /**
952
+ * A `.jsonValues()` record's entry files, by key, read out of its `.val.ts`
953
+ * (the loaded marker does not carry the path). `null` when it has none.
954
+ */
955
+ function entryFilesOf(moduleFilePath, text) {
956
+ const analysis = valModuleOf(moduleFilePath, text);
957
+ if (analysis === null) return null;
958
+ const entries = jsonValuesModule.analyzeJsonValuesEntries(analysis.source);
959
+ if (entries.size === 0) return null;
960
+ const dir = path__default["default"].posix.dirname(moduleFilePath.slice(1));
961
+ return Object.fromEntries([...entries].map(([key, {
962
+ importPath
963
+ }]) => [key, path__default["default"].posix.join(dir, importPath)]));
964
+ }
965
+
966
+ // --- code and content ------------------------------------------------------------
967
+
968
+ /**
969
+ * A file's code: for a `.val.ts`, everything but `c.define`'s content
970
+ * argument, which Val reads at request time (step 2) and so is no part of a
971
+ * build; a `.val.json` entry is no code at all. Every other file is code
972
+ * whole.
973
+ */
974
+ function codeOf(file, text) {
975
+ // A `.jsonValues()` entry is content, read at request time like the rest.
976
+ if (file.endsWith(".val.json")) return "";
977
+ if (!file.endsWith(".val.ts")) return text;
978
+ const analysis = valModuleOf(file, text);
979
+ if (analysis === null) return text;
980
+ const {
981
+ source
982
+ } = analysis;
983
+ return text.slice(0, source.getStart()) + "/* content */" + text.slice(source.end);
984
+ }
985
+
986
+ /**
987
+ * A `.val.ts`'s `c.define(...)`, or `null` when it has none: a file of schemas
988
+ * that pages share (`export const heroSchema = s.object(...)`) is named like a
989
+ * module and is code. `analyzeValModule` throws for one; this does not.
990
+ */
991
+ function valModuleOf(file, text) {
992
+ const sourceFile = ts__default["default"].createSourceFile(file, text, ts__default["default"].ScriptTarget.ES2015, true);
993
+ if (!sourceFile.statements.some(node => ts__default["default"].isExportAssignment(node))) {
994
+ return null;
995
+ }
996
+ const analysis = jsonValuesModule.analyzeValModule(sourceFile);
997
+ return fp.result.isErr(analysis) ? null : analysis.value;
998
+ }
999
+
1000
+ /**
1001
+ * The three-way merge of a module's content: where both sides started
1002
+ * (`base`), and each side's version. Pure JSON -- the schema decides nothing
1003
+ * here, and is checked afterwards (the schema check in `merge.ts`).
1004
+ *
1005
+ * The rules (valbuild/home `docs/hosted-publishing.md` step 8.2):
1006
+ *
1007
+ * - Changed on one side: that side's.
1008
+ * - Changed on both: a conflict -- even to the same value, which is an easy
1009
+ * conflict to resolve but still one somebody decides.
1010
+ * - An object (a page, a record) merges key by key, so two keys changed on
1011
+ * two sides combine.
1012
+ * - A list merges item by item only when neither side changed its shape: no
1013
+ * item added, removed or moved. Otherwise positions mean different items on
1014
+ * the two sides, and the whole list is the conflict.
1015
+ */
1016
+
1017
+ function isObject(value) {
1018
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1019
+ }
1020
+ function same(a, b) {
1021
+ if (a === undefined || b === undefined) return a === b;
1022
+ return patch.deepEqual(a, b);
1023
+ }
1024
+
1025
+ /**
1026
+ * Did this side add, remove or move an item? Lengths differ, or an item now
1027
+ * sits where it was not, while it is still what used to be somewhere else.
1028
+ */
1029
+ function reshaped(base, side) {
1030
+ if (base.length !== side.length) return true;
1031
+ return side.some((item, at) => !same(item, base[at]) && base.some((was, from) => from !== at && same(item, was)));
1032
+ }
1033
+
1034
+ /**
1035
+ * Where a value is one value, though it is an object: a media value (its path
1036
+ * and what describes that file) or rich text. The schema says; see `merge.ts`.
1037
+ */
1038
+
1039
+ function mergeValues(base, site, proposal, atomic = () => false, path = []) {
1040
+ if (same(site, base)) return {
1041
+ value: proposal,
1042
+ conflicts: []
1043
+ };
1044
+ if (same(proposal, base)) return {
1045
+ value: site,
1046
+ conflicts: []
1047
+ };
1048
+ if (atomic(path)) {
1049
+ return {
1050
+ value: site,
1051
+ conflicts: [{
1052
+ path,
1053
+ base,
1054
+ site,
1055
+ proposal
1056
+ }]
1057
+ };
1058
+ }
1059
+ if (isObject(base) && isObject(site) && isObject(proposal)) {
1060
+ const keys = [...new Set([...Object.keys(site), ...Object.keys(proposal), ...Object.keys(base)])];
1061
+ const value = {};
1062
+ const conflicts = [];
1063
+ for (const key of keys) {
1064
+ const merged = mergeValues(base[key], site[key], proposal[key], atomic, [...path, key]);
1065
+ if (merged.value !== undefined) value[key] = merged.value;
1066
+ conflicts.push(...merged.conflicts);
1067
+ }
1068
+ return {
1069
+ value,
1070
+ conflicts
1071
+ };
1072
+ }
1073
+ if (Array.isArray(base) && Array.isArray(site) && Array.isArray(proposal) && !reshaped(base, site) && !reshaped(base, proposal)) {
1074
+ const value = [];
1075
+ const conflicts = [];
1076
+ base.forEach((item, at) => {
1077
+ const merged = mergeValues(item, site[at], proposal[at], atomic, [...path, String(at)]);
1078
+ // Neither side removed an item, so every position holds one.
1079
+ value.push(merged.value ?? null);
1080
+ conflicts.push(...merged.conflicts);
1081
+ });
1082
+ return {
1083
+ value,
1084
+ conflicts
1085
+ };
1086
+ }
1087
+ return {
1088
+ value: site,
1089
+ conflicts: [{
1090
+ path,
1091
+ base,
1092
+ site,
1093
+ proposal
1094
+ }]
1095
+ };
1096
+ }
1097
+
1098
+ /** `doc` with `value` at `path`; `undefined` removes it. `doc` is not changed. */
1099
+ function setAt(doc, path, value) {
1100
+ if (path.length === 0) return value;
1101
+ const [head, ...rest] = path;
1102
+ if (Array.isArray(doc)) {
1103
+ const copy = [...doc];
1104
+ const at = Number(head);
1105
+ const next = setAt(copy[at], rest, value);
1106
+ if (next === undefined) copy.splice(at, 1);else copy[at] = next;
1107
+ return copy;
1108
+ }
1109
+ const copy = isObject(doc) ? {
1110
+ ...doc
1111
+ } : {};
1112
+ const next = setAt(copy[head], rest, value);
1113
+ if (next === undefined) delete copy[head];else copy[head] = next;
1114
+ return copy;
1115
+ }
1116
+ function valueAt(doc, path) {
1117
+ let current = doc;
1118
+ for (const key of path) {
1119
+ if (Array.isArray(current)) current = current[Number(key)];else if (isObject(current)) current = current[key];else return undefined;
1120
+ }
1121
+ return current;
1122
+ }
1123
+
1124
+ /**
1125
+ * The Val patch that turns `from` into `to`, as small as it can be: what
1126
+ * writes a merge into a `.val.ts` without rewriting what did not change.
1127
+ */
1128
+ function diffOps(from, to, path = []) {
1129
+ if (same(from, to)) return [];
1130
+ if (isObject(from) && isObject(to)) {
1131
+ const ops = [];
1132
+ for (const key of Object.keys(from)) {
1133
+ if (!(key in to)) ops.push({
1134
+ op: "remove",
1135
+ path: below(path, key)
1136
+ });
1137
+ }
1138
+ for (const [key, value] of Object.entries(to)) {
1139
+ ops.push(...(key in from ? diffOps(from[key], value, [...path, key]) : [add([...path, key], value)]));
1140
+ }
1141
+ return ops;
1142
+ }
1143
+ if (Array.isArray(from) && Array.isArray(to) && from.length === to.length) {
1144
+ return from.flatMap((item, at) => diffOps(item, to[at], [...path, String(at)]));
1145
+ }
1146
+ return [{
1147
+ op: "replace",
1148
+ path,
1149
+ value: to ?? null
1150
+ }];
1151
+ }
1152
+ function add(path, value) {
1153
+ return {
1154
+ op: "add",
1155
+ path,
1156
+ value
1157
+ };
1158
+ }
1159
+ function below(path, key) {
1160
+ return path.length === 0 ? [key] : [path[0], ...path.slice(1), key];
1161
+ }
1162
+
1163
+ /**
1164
+ * Publishing a proposal as a pull request is merged: valbuild/home
1165
+ * `docs/hosted-publishing.md`, step 8.2.
1166
+ *
1167
+ * Val's half: the two answers that need a schema. Content gets them as files
1168
+ * and change ids and carries them out, never looking at a field, a list or a
1169
+ * patch set.
1170
+ *
1171
+ * - {@link mergeFromSite} -- Update from the site: the merge commit `M`.
1172
+ * - {@link changesToMove} -- which of the site's pending changes leave the
1173
+ * site when a proposal is merged.
1174
+ *
1175
+ * `mergeScenarios.test.ts` is their specification.
1176
+ */
1177
+
1178
+ /** A field both sides changed since the proposal started. */
1179
+
1180
+ /**
1181
+ * Code both sides changed: a component, `val.modules.ts`, or the schema of a
1182
+ * `.val.ts` (its code -- everything but `c.define`'s content argument, whose
1183
+ * fields merge on their own).
1184
+ */
1185
+
1186
+ /**
1187
+ * The schema check: content that merged cleanly and is not valid under the
1188
+ * schema the merge ends with -- an entry the site added, say, under a field
1189
+ * whose type the proposal changed.
1190
+ */
1191
+
1192
+ /** How a conflict is resolved: keep one side, or write it -- as AI or a developer does. */
1193
+
1194
+ /**
1195
+ * Update from the site: a three-way merge of where the proposal started
1196
+ * (`base`), the site's head and the proposal's last save, written whole.
1197
+ * Every conflict needs a resolution, or nothing is merged.
1198
+ *
1199
+ * File by file. A file that is not a `.val.ts` is code, and merges as a
1200
+ * file: changed on one side, that side's; on both, a conflict. A `.val.ts`
1201
+ * is code (everything but `c.define`'s content argument) and content, and the
1202
+ * two merge apart: the code as a file, the content field by field
1203
+ * (`mergeValues`). So a schema the proposal changed and a field the site
1204
+ * published in the same file do not conflict. A code conflict in a `.val.ts`
1205
+ * is resolved by keeping a side's code -- the content still merges -- or by
1206
+ * writing the whole file.
1207
+ *
1208
+ * Not here: the schema check ({@link schemaCheck}). It needs the merged
1209
+ * files' schemas, so whoever can evaluate them -- Val's loader, the builder
1210
+ * tab -- runs it on `files` before the merge is committed.
1211
+ */
1212
+ function mergeFromSite(input) {
1213
+ const {
1214
+ base,
1215
+ site,
1216
+ proposal,
1217
+ resolutions
1218
+ } = input;
1219
+ const files = {};
1220
+ const modules = {};
1221
+ const conflicts = [];
1222
+ const paths = [...new Set([...Object.keys(base.files), ...Object.keys(site.files), ...Object.keys(proposal.files)])].sort();
1223
+ // A `.jsonValues()` entry is written with its module, never on its own.
1224
+ const entryFiles = new Set([base, site, proposal].flatMap(side => Object.values(side.modules).flatMap(module => Object.values(module.entries ?? {}))));
1225
+ for (const file of paths) {
1226
+ var _moduleOf3, _moduleOf4, _moduleOf5, _moduleOf6;
1227
+ if (entryFiles.has(file)) continue;
1228
+ const b = base.files[file] ?? null;
1229
+ const s = site.files[file] ?? null;
1230
+ const p = proposal.files[file] ?? null;
1231
+ const resolution = fileResolution(resolutions, file);
1232
+ const codeConflict = () => ({
1233
+ kind: "code",
1234
+ file,
1235
+ base: b,
1236
+ site: s,
1237
+ proposal: p
1238
+ });
1239
+
1240
+ // A file named like a module that no side defines as one -- schemas the
1241
+ // pages share -- is code.
1242
+ const moduleFilePath = `/${file}`;
1243
+ const isModule = [base, site, proposal].some(side => side.modules[moduleFilePath] !== undefined);
1244
+ if (!file.endsWith(".val.ts") || !isModule) {
1245
+ if (s === b) files[file] = p;else if (p === b) files[file] = s;else if (resolution) files[file] = resolvedText(resolution, s, p);else {
1246
+ conflicts.push(codeConflict());
1247
+ files[file] = s;
1248
+ }
1249
+ continue;
1250
+ }
1251
+
1252
+ // A .val.ts: whose code, then the content under it.
1253
+ const code = text => text === null ? null : codeOf(file, text);
1254
+ let side;
1255
+ if (code(s) === code(b)) side = "proposal";else if (code(p) === code(b)) side = "site";else if (resolution && "text" in resolution) {
1256
+ files[file] = resolution.text;
1257
+ continue;
1258
+ } else if (resolution) side = resolution.keep;else {
1259
+ conflicts.push(codeConflict());
1260
+ files[file] = s;
1261
+ continue;
1262
+ }
1263
+ const moduleOf = project => project.modules[moduleFilePath];
1264
+ const sourceOf = project => {
1265
+ var _moduleOf;
1266
+ return (_moduleOf = moduleOf(project)) === null || _moduleOf === void 0 ? void 0 : _moduleOf.source;
1267
+ };
1268
+ const chosen = side === "site" ? site : proposal;
1269
+ const text = side === "site" ? s : p;
1270
+ if (text === null) {
1271
+ // That side deleted the file. Content the other side changed would go
1272
+ // with it: that is for a person to decide -- unless they have.
1273
+ const other = side === "site" ? p : s;
1274
+ if (!resolution && other !== b) {
1275
+ conflicts.push(codeConflict());
1276
+ }
1277
+ files[file] = null;
1278
+ for (const project of [base, site, proposal]) {
1279
+ for (const entry of Object.values(((_moduleOf2 = moduleOf(project)) === null || _moduleOf2 === void 0 ? void 0 : _moduleOf2.entries) ?? {})) {
1280
+ var _moduleOf2;
1281
+ files[entry] = null;
1282
+ }
1283
+ }
1284
+ continue;
1285
+ }
1286
+ // What the chosen text holds, which the merge is written over.
1287
+ const from = ((_moduleOf3 = moduleOf(chosen)) === null || _moduleOf3 === void 0 ? void 0 : _moduleOf3.written) ?? ((_moduleOf4 = moduleOf(chosen)) === null || _moduleOf4 === void 0 ? void 0 : _moduleOf4.source);
1288
+ const merged = mergeValues(sourceOf(base), sourceOf(site), sourceOf(proposal), atomicFor((_moduleOf5 = moduleOf(chosen)) === null || _moduleOf5 === void 0 ? void 0 : _moduleOf5.schema));
1289
+ const resolved = resolveContent(moduleFilePath, merged, resolutions);
1290
+ conflicts.push(...resolved.unresolved);
1291
+ const content = resolved.content;
1292
+ modules[moduleFilePath] = content;
1293
+ const entries = (_moduleOf6 = moduleOf(chosen)) === null || _moduleOf6 === void 0 ? void 0 : _moduleOf6.entries;
1294
+ if (entries) {
1295
+ var _moduleOf7, _moduleOf8;
1296
+ Object.assign(files, writeEntries(file, text, chosen.files, entries, from, content, [(_moduleOf7 = moduleOf(site)) === null || _moduleOf7 === void 0 ? void 0 : _moduleOf7.entries, (_moduleOf8 = moduleOf(proposal)) === null || _moduleOf8 === void 0 ? void 0 : _moduleOf8.entries]));
1297
+ } else {
1298
+ files[file] = writeContent(file, text, from, content);
1299
+ }
1300
+ }
1301
+ if (conflicts.length > 0) return {
1302
+ status: "conflicts",
1303
+ conflicts
1304
+ };
1305
+ return {
1306
+ status: "merged",
1307
+ files,
1308
+ modules,
1309
+ code: Object.keys(files).filter(file => {
1310
+ const text = files[file];
1311
+ const before = site.files[file] ?? null;
1312
+ if (text === null || before === null) return text !== before;
1313
+ return codeOf(file, text) !== codeOf(file, before);
1314
+ })
1315
+ };
1316
+ }
1317
+
1318
+ /** A change pending on the site, in chain order. */
1319
+
1320
+ /**
1321
+ * The site's pending changes that conflict with going from `site` to
1322
+ * `merged`, as whole patch sets: each inner list moves together, into a
1323
+ * proposal of its own. Everything else stays pending.
1324
+ *
1325
+ * Patch sets are the Studio's own (`PatchSets`), from the schema the changes
1326
+ * were written against; sets that share a change are one, because a change
1327
+ * cannot be split. A set moves when, taken as the site's side of a three-way
1328
+ * merge with the merged commit as the other, it conflicts (`mergeValues`, so
1329
+ * the same value on both sides moves too); or when it no longer applies to
1330
+ * the merged commit, or leaves it invalid under the merged schema.
1331
+ */
1332
+ function changesToMove(input) {
1333
+ const {
1334
+ site,
1335
+ merged,
1336
+ pending
1337
+ } = input;
1338
+ const sets = new internal.PatchSets();
1339
+ for (const change of pending) {
1340
+ var _site$modules$change$;
1341
+ sets.insert(change.moduleFilePath, (_site$modules$change$ = site.modules[change.moduleFilePath]) === null || _site$modules$change$ === void 0 ? void 0 : _site$modules$change$.schema, change.patch, change.patchId, "", null);
1342
+ }
1343
+ const groups = internal.joinSharedChanges(sets.serialize().map(set => set.patches.map(p => p.patchId)));
1344
+ const moves = [];
1345
+ for (const group of groups) {
1346
+ const changes = pending.filter(change => group.has(change.patchId));
1347
+ if (conflictsWithMerge(changes, site, merged)) {
1348
+ moves.push(changes.map(change => change.patchId));
1349
+ }
1350
+ }
1351
+ // In chain order, so the moved proposals are opened in the order the
1352
+ // changes were written.
1353
+ const order = ids => pending.findIndex(change => change.patchId === ids[0]);
1354
+ return moves.sort((a, b) => order(a) - order(b));
1355
+ }
1356
+
1357
+ // --- the pieces --------------------------------------------------------------
1358
+
1359
+ /**
1360
+ * A module's merged content with the resolutions written in: each field
1361
+ * conflict that has one, and any value written for the schema check (or
1362
+ * anywhere else) as given. What is left is what still needs a person.
1363
+ */
1364
+ function resolveContent(moduleFilePath, merged, resolutions) {
1365
+ let content = merged.value;
1366
+ const unresolved = [];
1367
+ for (const conflict of merged.conflicts) {
1368
+ const resolved = fieldResolution(resolutions, moduleFilePath, conflict);
1369
+ if (resolved === null) {
1370
+ unresolved.push({
1371
+ kind: "field",
1372
+ moduleFilePath,
1373
+ ...conflict
1374
+ });
1375
+ } else {
1376
+ content = setAt(content, conflict.path, resolved.value);
1377
+ }
1378
+ }
1379
+ for (const resolution of resolutions) {
1380
+ if ("moduleFilePath" in resolution && resolution.moduleFilePath === moduleFilePath && "value" in resolution && !merged.conflicts.some(c => samePath(c.path, resolution.path))) {
1381
+ content = setAt(content, resolution.path, resolution.value);
1382
+ }
1383
+ }
1384
+ return {
1385
+ content,
1386
+ unresolved
1387
+ };
1388
+ }
1389
+ function conflictsWithMerge(changes, site, merged) {
1390
+ const modules = [...new Set(changes.map(change => change.moduleFilePath))];
1391
+ for (const moduleFilePath of modules) {
1392
+ var _site$modules$moduleF;
1393
+ const ops = changes.filter(change => change.moduleFilePath === moduleFilePath).flatMap(change => change.patch).filter(op => op.op !== "file");
1394
+ const before = (_site$modules$moduleF = site.modules[moduleFilePath]) === null || _site$modules$moduleF === void 0 ? void 0 : _site$modules$moduleF.source;
1395
+ const after = merged.modules[moduleFilePath];
1396
+ if (before === undefined || after === undefined) return true;
1397
+ const written = apply(before, ops);
1398
+ if (written === undefined) return true;
1399
+ const mergedSource = after.source;
1400
+ const atomic = atomicFor(after.schema);
1401
+ if (mergeValues(before, written, mergedSource, atomic).conflicts.length) {
1402
+ return true;
1403
+ }
1404
+ // Over the merged commit: it applies, and is as valid as it was.
1405
+ const over = apply(mergedSource, ops);
1406
+ if (over === undefined) return true;
1407
+ const known = new Set(errorPaths(moduleFilePath, after, mergedSource));
1408
+ if (errorPaths(moduleFilePath, after, over).some(path => !known.has(path))) {
1409
+ return true;
1410
+ }
1411
+ }
1412
+ return false;
1413
+ }
1414
+ function apply(source, ops) {
1415
+ if (source === undefined) return undefined;
1416
+ const applied = patch.applyPatch(patch.deepClone(source), new patch.JSONOps(), ops);
1417
+ return fp.result.isOk(applied) ? applied.value : undefined;
1418
+ }
1419
+ function errorPaths(moduleFilePath, module, source) {
1420
+ return validateModule(moduleFilePath, module, source).map(error => error.path.join("/"));
1421
+ }
1422
+
1423
+ /**
1424
+ * The schema check of a merge: content in `merged` -- the project
1425
+ * {@link mergeFromSite} wrote, with its schemas evaluated -- that is invalid
1426
+ * under the schema it ends with, leaving out what was already invalid on a
1427
+ * side. A conflict, each; a resolution with a value for one is written into
1428
+ * the content by the merge, and so is checked here.
1429
+ */
1430
+ function schemaCheck(merged, sides) {
1431
+ const conflicts = [];
1432
+ for (const [path, module] of Object.entries(merged.modules)) {
1433
+ const moduleFilePath = path;
1434
+ const known = new Set(sides.flatMap(side => {
1435
+ const there = side.modules[moduleFilePath];
1436
+ return there ? errorsOfSource(moduleFilePath, there).map(e => e.path.join("/")) : [];
1437
+ }));
1438
+ for (const error of errorsOfSource(moduleFilePath, module)) {
1439
+ if (known.has(error.path.join("/"))) continue;
1440
+ conflicts.push({
1441
+ kind: "invalid",
1442
+ moduleFilePath,
1443
+ path: error.path,
1444
+ value: valueAt(module.source, error.path),
1445
+ message: error.message
1446
+ });
1447
+ }
1448
+ }
1449
+ return conflicts;
1450
+ }
1451
+
1452
+ /**
1453
+ * The values that merge whole, though they are objects: media (an image's
1454
+ * alt text describes that image, not another) and rich text.
1455
+ */
1456
+ const ATOMIC = new Set(["image", "file", "video", "font", "richtext"]);
1457
+
1458
+ /** See {@link ATOMIC}: where this schema holds a value that merges whole. */
1459
+ function atomicFor(schema) {
1460
+ if (!schema) return () => false;
1461
+ return path => {
1462
+ const types = internal.schemaTypesOfPath(schema, path);
1463
+ return [...types].some(type => ATOMIC.has(type));
1464
+ };
1465
+ }
1466
+ const tsOps = new TSOps(document => fp.pipe(jsonValuesModule.analyzeValModule(document), fp.result.map(({
1467
+ source
1468
+ }) => source)));
1469
+
1470
+ /**
1471
+ * `content` written into the `.val.ts` `text`, whose content is `from`: as
1472
+ * the smallest patch, through the same AST operations a save uses, so what
1473
+ * did not change is left exactly as it was.
1474
+ */
1475
+ function writeContent(file, text, from, content) {
1476
+ const ops = diffOps(from, content);
1477
+ if (ops.length === 0) return text;
1478
+ const sourceFile = ts__default["default"].createSourceFile(file, text, ts__default["default"].ScriptTarget.ES2015, true);
1479
+ return printed(unwrap(file, patch.applyPatch(sourceFile, tsOps, ops)));
1480
+ }
1481
+
1482
+ /**
1483
+ * A `.jsonValues()` module, written as its files: the `.val.ts` names the
1484
+ * entries -- one added gets a `c.json(...)` line, as a save writes it, one
1485
+ * removed loses its line -- and each entry is its own `.val.json`. An entry
1486
+ * whose content did not change keeps its file's text exactly.
1487
+ */
1488
+ function writeEntries(file, text, chosenFiles, entries, from, content, others) {
1489
+ const written = {};
1490
+ const before = isRecord(from) ? from : {};
1491
+ const after = isRecord(content) ? content : {};
1492
+ const moduleDir = path__default["default"].posix.dirname(file);
1493
+ let sourceFile = ts__default["default"].createSourceFile(file, text, ts__default["default"].ScriptTarget.ES2015, true);
1494
+ for (const key of Object.keys(before)) {
1495
+ if (key in after) continue;
1496
+ sourceFile = unwrap(file, removeValJsonEntry(sourceFile, [], key));
1497
+ written[entries[key]] = null;
1498
+ }
1499
+ for (const [key, value] of Object.entries(after)) {
1500
+ const entryFile = entries[key] ?? others.map(other => other === null || other === void 0 ? void 0 : other[key]).find(f => f !== undefined) ?? path__default["default"].posix.join(moduleDir, path__default["default"].posix.basename(file, ".val.ts"), `${key}.val.json`);
1501
+ if (!(key in before)) {
1502
+ const importPath = `./${path__default["default"].posix.relative(moduleDir, entryFile)}`;
1503
+ sourceFile = unwrap(file, insertValJsonEntry(sourceFile, [], key, importPath));
1504
+ }
1505
+ const kept = chosenFiles[entryFile];
1506
+ written[entryFile] = key in before && diffOps(before[key], value).length === 0 && kept ? kept : JSON.stringify(value, null, 2);
1507
+ }
1508
+ written[file] = printed(sourceFile);
1509
+ return written;
1510
+ }
1511
+
1512
+ /**
1513
+ * What the AST operations said, in words: a `PatchError` or `Error` has a
1514
+ * message, a syntax error tree has one per node. `String()` of either is
1515
+ * `[object Object]`.
1516
+ */
1517
+ function writeErrorText(error) {
1518
+ if (error instanceof Error) return error.message;
1519
+ if (isSyntaxErrorTree(error)) {
1520
+ return jsonValuesModule.flatMapErrors(error, e => e.message).join("; ");
1521
+ }
1522
+ if (typeof error === "object" && error !== null && "message" in error) {
1523
+ return String(error.message);
1524
+ }
1525
+ return String(error);
1526
+ }
1527
+ function isSyntaxErrorTree(error) {
1528
+ if (error instanceof jsonValuesModule.ValSyntaxError) return true;
1529
+ return Array.isArray(error) && error.length > 0 && error.every(isSyntaxErrorTree);
1530
+ }
1531
+ function isRecord(value) {
1532
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1533
+ }
1534
+ function unwrap(file, written) {
1535
+ if (fp.result.isErr(written)) {
1536
+ throw new Error(`could not write the merge into ${file}: ${writeErrorText(written.error)}`);
1537
+ }
1538
+ return written.value;
1539
+ }
1540
+
1541
+ /** As `prepare` prints: TypeScript escapes non-ASCII as \\u sequences. */
1542
+ function printed(sourceFile) {
1543
+ return unescape(sourceFile.getText(sourceFile).replace(/\\u/g, "%u"));
1544
+ }
1545
+ function fileResolution(resolutions, file) {
1546
+ for (const resolution of resolutions) {
1547
+ if ("file" in resolution && resolution.file === file) return resolution;
1548
+ }
1549
+ return null;
1550
+ }
1551
+ function resolvedText(resolution, site, proposal) {
1552
+ if ("text" in resolution) return resolution.text;
1553
+ return resolution.keep === "site" ? site : proposal;
1554
+ }
1555
+
1556
+ /** A field conflict's resolution, as the value it leaves; `null` when it has none. */
1557
+ function fieldResolution(resolutions, moduleFilePath, conflict) {
1558
+ for (const resolution of resolutions) {
1559
+ if (!("moduleFilePath" in resolution) || resolution.moduleFilePath !== moduleFilePath || !samePath(resolution.path, conflict.path)) {
1560
+ continue;
1561
+ }
1562
+ if ("value" in resolution) return {
1563
+ value: resolution.value
1564
+ };
1565
+ return {
1566
+ value: resolution.keep === "site" ? conflict.site : conflict.proposal
1567
+ };
1568
+ }
1569
+ return null;
1570
+ }
1571
+ function samePath(a, b) {
1572
+ return a.length === b.length && a.every((key, at) => key === b[at]);
1573
+ }
1574
+
1575
+ exports.TSOps = TSOps;
1576
+ exports.atomicFor = atomicFor;
1577
+ exports.changesToMove = changesToMove;
1578
+ exports.createNodeRequire = createNodeRequire;
1579
+ exports.createValModuleFileInspector = createValModuleFileInspector;
1580
+ exports.diffOps = diffOps;
1581
+ exports.entryFilesOf = entryFilesOf;
1582
+ exports.findDefaultExport = findDefaultExport;
1583
+ exports.getCompilerOptions = getCompilerOptions;
1584
+ exports.insertValJsonEntry = insertValJsonEntry;
1585
+ exports.loadProject = loadProject;
1586
+ exports.loadValModules = loadValModules;
1587
+ exports.mergeFromSite = mergeFromSite;
1588
+ exports.mergeValues = mergeValues;
1589
+ exports.projectOf = projectOf;
1590
+ exports.removeValJsonEntry = removeValJsonEntry;
1591
+ exports.resolveContent = resolveContent;
1592
+ exports.schemaCheck = schemaCheck;
1593
+ exports.validateWith = validateWith;
1594
+ exports.valueAt = valueAt;
1595
+ exports.writeContent = writeContent;
1596
+ exports.writeEntries = writeEntries;