@valbuild/server 0.155.0 → 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 +16 -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-f000531b.cjs.prod.js → ValOpsMemory-073f9526.cjs.prod.js} +1 -1
  6. package/dist/{ValOpsMemory-6e829758.cjs.dev.js → ValOpsMemory-3ce3e9e8.cjs.dev.js} +1 -1
  7. package/dist/{ValOpsMemory-1a0bc2dc.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-f55300a0.esm.js → createValRuntime-02197b93.esm.js} +6 -4
  12. package/dist/{createValRuntime-a519939b.cjs.prod.js → createValRuntime-42622f8f.cjs.prod.js} +6 -4
  13. package/dist/{createValRuntime-1c7d891e.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-3d8ceb84.cjs.prod.js → inTabFetch-46ad6b87.cjs.prod.js} +1 -1
  23. package/dist/{inTabFetch-dae5dd87.esm.js → inTabFetch-6dacc8a1.esm.js} +1 -1
  24. package/dist/{inTabFetch-75753a09.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-395b92e5.cjs.prod.js → publishKit-70276aed.cjs.prod.js} +19 -22
  35. package/dist/{publishKit-04b6d255.esm.js → publishKit-a732e3c3.esm.js} +11 -14
  36. package/dist/{publishKit-de4baed6.cjs.dev.js → publishKit-f7a77be5.cjs.dev.js} +19 -22
  37. package/dist/{valRuntime-7fd12e16.esm.js → valRuntime-407399c1.esm.js} +11 -982
  38. package/dist/{valRuntime-d3cc6e0d.cjs.dev.js → valRuntime-7a4bbb5d.cjs.dev.js} +21 -995
  39. package/dist/{valRuntime-e922e372.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
@@ -2,20 +2,19 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var proposalJsonEntries = require('./proposalJsonEntries-d21900d4.cjs.dev.js');
5
+ var jsonValuesModule = require('./jsonValuesModule-ed68a9de.cjs.dev.js');
6
6
  var patch = require('@valbuild/core/patch');
7
- var valRuntime = require('./valRuntime-d3cc6e0d.cjs.dev.js');
7
+ var merge = require('./merge-a21a9c78.cjs.dev.js');
8
8
  var fp = require('@valbuild/core/fp');
9
9
  var core = require('@valbuild/core');
10
10
  var ts = require('typescript');
11
11
  var path = require('path');
12
12
  var fs = require('fs');
13
- var vm = require('node:vm');
14
- var node_module = require('node:module');
15
13
  var jsonValuesPatch = require('./jsonValuesPatch-88bc661d.cjs.dev.js');
16
- var ValOpsMemory = require('./ValOpsMemory-6e829758.cjs.dev.js');
14
+ var ValOpsMemory = require('./ValOpsMemory-3ce3e9e8.cjs.dev.js');
17
15
  var internal = require('@valbuild/shared/internal');
18
16
  var server = require('@valbuild/ui/server');
17
+ var valRuntime = require('./valRuntime-7a4bbb5d.cjs.dev.js');
19
18
  var http = require('node:http');
20
19
  var https = require('node:https');
21
20
  var net = require('node:net');
@@ -23,14 +22,17 @@ var sizeOf = require('image-size');
23
22
  var http$1 = require('http');
24
23
  var https$1 = require('https');
25
24
  var ValRouterCore = require('./ValRouterCore-adb69698.cjs.dev.js');
26
- var createPrettierFormatter = require('./createPrettierFormatter-5d830bdf.cjs.dev.js');
25
+ var createPrettierFormatter = require('./createPrettierFormatter-a9109288.cjs.dev.js');
26
+ var proposalJsonEntries = require('./proposalJsonEntries-878ad5b6.cjs.dev.js');
27
27
  var sucrase = require('sucrase');
28
28
  var fs$1 = require('fs/promises');
29
+ var vm = require('node:vm');
29
30
  var z = require('zod');
30
31
  var os = require('os');
31
32
  var ValPatchStore = require('./ValPatchStore-b53db740.cjs.dev.js');
32
- require('zod-validation-error');
33
33
  require('crypto');
34
+ require('node:module');
35
+ require('zod-validation-error');
34
36
  require('buffer');
35
37
 
36
38
  function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
@@ -56,7 +58,6 @@ function _interopNamespace(e) {
56
58
  var ts__default = /*#__PURE__*/_interopDefault(ts);
57
59
  var path__default = /*#__PURE__*/_interopDefault(path);
58
60
  var fs__default = /*#__PURE__*/_interopDefault(fs);
59
- var vm__default = /*#__PURE__*/_interopDefault(vm);
60
61
  var http__default = /*#__PURE__*/_interopDefault(http);
61
62
  var https__default = /*#__PURE__*/_interopDefault(https);
62
63
  var net__default = /*#__PURE__*/_interopDefault(net);
@@ -64,6 +65,7 @@ var sizeOf__default = /*#__PURE__*/_interopDefault(sizeOf);
64
65
  var http__default$1 = /*#__PURE__*/_interopDefault(http$1);
65
66
  var https__default$1 = /*#__PURE__*/_interopDefault(https$1);
66
67
  var fs__default$1 = /*#__PURE__*/_interopDefault(fs$1);
68
+ var vm__default = /*#__PURE__*/_interopDefault(vm);
67
69
  var z__default = /*#__PURE__*/_interopDefault(z);
68
70
  var os__default = /*#__PURE__*/_interopDefault(os);
69
71
 
@@ -71,8 +73,8 @@ function getSyntheticContainingPath(rootDir) {
71
73
  return path__default["default"].join(rootDir, "<val>"); // TODO: this is the synthetic path used when evaluating / patching modules. I am not sure <val> is the best choice: val.ts / js better? But that is weird too. At least now it is clear(er) that it is indeed a synthetic file (i.e. not an actual file)
72
74
  }
73
75
 
74
- const ops = new valRuntime.TSOps(document => {
75
- return fp.pipe(proposalJsonEntries.analyzeValModule(document), fp.result.map(({
76
+ const ops = new merge.TSOps(document => {
77
+ return fp.pipe(jsonValuesModule.analyzeValModule(document), fp.result.map(({
76
78
  source
77
79
  }) => source));
78
80
  });
@@ -96,7 +98,7 @@ const patchValFile = async (id, rootDir, patch$1, sourceFileHandler) => {
96
98
  if (newSourceFile.error instanceof patch.PatchError) {
97
99
  throw newSourceFile.error;
98
100
  } else {
99
- throw new Error(`${filePath}\n${proposalJsonEntries.flatMapErrors(newSourceFile.error, error => proposalJsonEntries.formatSyntaxError(error, sourceFile)).join("\n")}`);
101
+ throw new Error(`${filePath}\n${jsonValuesModule.flatMapErrors(newSourceFile.error, error => jsonValuesModule.formatSyntaxError(error, sourceFile)).join("\n")}`);
100
102
  }
101
103
  }
102
104
  for (const [filePath, content] of Object.entries(derefRes.value.fileUpdates)) {
@@ -178,425 +180,6 @@ class ValSourceFileHandler {
178
180
  }
179
181
  }
180
182
 
181
- const getCompilerOptions = (rootDir, parseConfigHost) => {
182
- const tsConfigPath = path__default["default"].resolve(rootDir, "tsconfig.json");
183
- const jsConfigPath = path__default["default"].resolve(rootDir, "jsconfig.json");
184
- let configFilePath;
185
- if (parseConfigHost.fileExists(jsConfigPath)) {
186
- configFilePath = jsConfigPath;
187
- } else if (parseConfigHost.fileExists(tsConfigPath)) {
188
- configFilePath = tsConfigPath;
189
- } else {
190
- throw Error(`Could not read config from: "${tsConfigPath}" nor "${jsConfigPath}". Root dir: "${rootDir}"`);
191
- }
192
- const {
193
- config,
194
- error
195
- } = ts__default["default"].readConfigFile(configFilePath, parseConfigHost.readFile.bind(parseConfigHost));
196
- if (error) {
197
- if (typeof error.messageText === "string") {
198
- throw Error(`Could not parse config file: ${configFilePath}. Error: ${error.messageText}`);
199
- }
200
- throw Error(`Could not parse config file: ${configFilePath}. Error: ${error.messageText.messageText}`);
201
- }
202
- const optionsOverrides = undefined;
203
- const parsedConfigFile = ts__default["default"].parseJsonConfigFileContent(config, parseConfigHost, rootDir, optionsOverrides, configFilePath);
204
- if (parsedConfigFile.errors.length > 0) {
205
- throw Error(`Could not parse config file: ${configFilePath}. Errors: ${parsedConfigFile.errors.map(e => e.messageText).join("\n")}`);
206
- }
207
- return parsedConfigFile.options;
208
- };
209
-
210
- /**
211
- * Node's `require`, resolving as if from `filename`.
212
- *
213
- * Use this instead of importing `createRequire` from `node:module` directly.
214
- * webpack special-cases a `createRequire` binding imported from `module` /
215
- * `node:module`: it tries to resolve the call's argument at build time, and
216
- * when the argument is not a literal it gives up with
217
- *
218
- * module.createRequire failed parsing argument.
219
- *
220
- * Our argument is never a literal — it is a path inside the user's project,
221
- * known only at runtime — so there is nothing for that analysis to find, and
222
- * nothing the warning can tell anyone. It is emitted on every build of every
223
- * Next app that bundles `@valbuild/server` into its Val API route, which is
224
- * all of them. Reaching `createRequire` through the `Module` class is the same
225
- * function and is not what webpack tags, so the call is invisible to it.
226
- *
227
- * It has to stay a real `node:module` import: jest's module registry hands out
228
- * its own `node:module`, and a `require` obtained around it (via
229
- * `process.getBuiltinModule`, say) would resolve against the real filesystem
230
- * rather than the registry the tests run in.
231
- */
232
- function createNodeRequire(filename) {
233
- return node_module.Module.createRequire(filename);
234
- }
235
-
236
- /**
237
- * The filesystem seam `loadValModules` reads through.
238
- *
239
- * Defaults to `ts.sys`, i.e. the real filesystem. An editor integration (see
240
- * `@valbuild/language-server`) passes a host that overlays unsaved buffers, so
241
- * that evaluation sees what the user is looking at rather than what was last
242
- * saved.
243
- */
244
-
245
- /**
246
- * Loads the project's root `val.modules.ts` (or `.js`) using Node's `vm`
247
- * module and returns its default export (a `ValModules` registry).
248
- *
249
- * This is a recursive CommonJS loader: the root modules file and every
250
- * relative `*.val.ts` / `val.config.ts` it (dynamically) imports are
251
- * transpiled to CommonJS and evaluated in a `vm` sandbox. Bare specifiers
252
- * (e.g. `@valbuild/core`) are resolved with the real Node `require` so the
253
- * user modules share the exact same `@valbuild/core` instance that
254
- * `extractValModules` uses.
255
- *
256
- * Mirrors the pattern already used by the CLI's `evalValConfigFile`.
257
- *
258
- * SECURITY: The `vm` context is NOT a security sandbox. It deliberately exposes
259
- * `process` and a `require` that falls back to the real Node resolver (so user
260
- * modules share the same `@valbuild/core` instance). This loader must therefore
261
- * only ever be used to evaluate the project's own first-party, trusted files
262
- * (`val.modules` and the local `*.val.ts`/`val.config.ts` it imports) — i.e. the
263
- * same trust level as running the project's build. It must never be used to
264
- * evaluate untrusted or third-party modules.
265
- */
266
- function loadValModules(projectRoot, host = ts__default["default"].sys) {
267
- const valModulesPath = findValModulesPath(projectRoot, host);
268
- if (!valModulesPath) {
269
- throw Error(`Could not find 'val.modules.ts' nor 'val.modules.js' in project root: '${projectRoot}'`);
270
- }
271
- const compilerOptions = getCompilerOptions(projectRoot, host);
272
- const cache = {};
273
- const loaded = loadModule(valModulesPath, cache, compilerOptions, host);
274
- const valModules = loaded.exports.default;
275
- if (!valModules) {
276
- throw Error(`Val modules file at path: '${valModulesPath}' must have a default export. Got: ${valModules}`);
277
- }
278
- return valModules;
279
- }
280
- function findValModulesPath(projectRoot, host) {
281
- for (const fileName of ["val.modules.ts", "val.modules.js"]) {
282
- const candidate = path__default["default"].join(projectRoot, fileName);
283
- if (host.fileExists(candidate)) {
284
- return candidate;
285
- }
286
- }
287
- return null;
288
- }
289
- const RESOLVE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".cjs", ".mjs", ".json"];
290
-
291
- // Specifiers that user val files must not actually use. We stub them so that
292
- // importing is fine, but using a value throws a clear error. Real @valbuild
293
- // packages are resolved via the real require, so when they (legitimately)
294
- // import react/next internally those go through Node, not this stub.
295
- function isStubbedSpecifier(spec) {
296
- return spec === "react" || spec.startsWith("react/") || spec === "next" || spec.startsWith("next/") || spec === "@valbuild/ui" || spec === "@valbuild/react" || spec.startsWith("@valbuild/react/");
297
- }
298
- function makeStub(spec) {
299
- const throwing = prop => () => {
300
- throw Error(`Cannot use '${prop}' from '${spec}' in this type of file`);
301
- };
302
- const handler = {
303
- get(_target, prop) {
304
- if (prop === "__esModule") {
305
- return true;
306
- }
307
- if (typeof prop === "symbol") {
308
- return undefined;
309
- }
310
- // React.createContext is sometimes called at module top-level; return a
311
- // proxy-returning function so evaluation does not crash on import.
312
- if (prop === "createContext") {
313
- return () => new Proxy({}, handler);
314
- }
315
- if (prop === "default") {
316
- return stub;
317
- }
318
- return throwing(prop);
319
- }
320
- };
321
- const stub = new Proxy({}, handler);
322
- return stub;
323
- }
324
- function loadModule(absPath, cache, compilerOptions, host) {
325
- const cached = cache[absPath];
326
- if (cached) {
327
- return cached;
328
- }
329
- // JSON modules (e.g. the `*.val.json` files backing `.jsonValues()` entries)
330
- // are loaded by parsing, mirroring Node's `require("./x.json")` which returns
331
- // the parsed object as `module.exports`. The importing `.val.ts` wraps this
332
- // with `__importStar` so `import("./x.val.json")` yields `{ default, ... }`.
333
- // These are only loaded when an entry thunk is invoked, never during
334
- // `extractValModules`, so this stays lazy.
335
- //
336
- // Read through `host` like every other project file: an editor integration
337
- // passes a host that overlays unsaved buffers, and an entry the user is
338
- // editing has to resolve to what they are looking at.
339
- if (absPath.endsWith(".json")) {
340
- const json = host.readFile(absPath);
341
- if (json === undefined) {
342
- throw Error(`Could not read Val module file: '${absPath}'`);
343
- }
344
- const jsonModule = {
345
- exports: JSON.parse(json)
346
- };
347
- cache[absPath] = jsonModule;
348
- return jsonModule;
349
- }
350
- const code = host.readFile(absPath);
351
- if (code === undefined) {
352
- throw Error(`Could not read Val module file: '${absPath}'`);
353
- }
354
- const transpiled = ts__default["default"].transpileModule(code, {
355
- compilerOptions: {
356
- target: ts__default["default"].ScriptTarget.ES2020,
357
- module: ts__default["default"].ModuleKind.CommonJS,
358
- esModuleInterop: true,
359
- jsx: ts__default["default"].JsxEmit.ReactJSX
360
- },
361
- fileName: absPath
362
- });
363
- const moduleObj = {
364
- exports: {}
365
- };
366
- // Insert into the cache before evaluating so cyclic imports resolve.
367
- cache[absPath] = moduleObj;
368
- const dirName = path__default["default"].dirname(absPath);
369
- const realRequire = createNodeRequire(absPath);
370
- const customRequire = spec => {
371
- var _ts$resolveModuleName;
372
- if (isStubbedSpecifier(spec)) {
373
- return makeStub(spec);
374
- }
375
- if (spec.startsWith(".") || path__default["default"].isAbsolute(spec)) {
376
- const resolved = resolveRelative(dirName, spec, host);
377
- if (!resolved) {
378
- throw Error(`Could not resolve module '${spec}' from '${absPath}'`);
379
- }
380
- return loadModule(resolved, cache, compilerOptions, host).exports;
381
- }
382
- // Non-relative specifier: it might be a tsconfig path alias (e.g. "_/val.config")
383
- // pointing at a local source file, or an actual node_modules package.
384
- const tsResolved = (_ts$resolveModuleName = ts__default["default"].resolveModuleName(spec, absPath, compilerOptions, host).resolvedModule) === null || _ts$resolveModuleName === void 0 ? void 0 : _ts$resolveModuleName.resolvedFileName;
385
- if (tsResolved && !tsResolved.includes("/node_modules/") && !tsResolved.endsWith(".d.ts")) {
386
- return loadModule(tsResolved, cache, compilerOptions, host).exports;
387
- }
388
- // Real node_modules package – use the real require so user modules share
389
- // the same @valbuild/core instance as extractValModules.
390
- return realRequire(spec);
391
- };
392
-
393
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
394
- const sandbox = {
395
- exports: moduleObj.exports,
396
- module: moduleObj,
397
- require: customRequire,
398
- __filename: absPath,
399
- __dirname: dirName,
400
- console,
401
- process
402
- };
403
- sandbox.global = sandbox;
404
- sandbox.globalThis = sandbox;
405
- const context = vm__default["default"].createContext(sandbox);
406
- const script = new vm__default["default"].Script(transpiled.outputText, {
407
- filename: absPath
408
- });
409
- script.runInContext(context);
410
- return moduleObj;
411
- }
412
- function resolveRelative(dirName, spec, host) {
413
- var _host$directoryExists;
414
- const base = path__default["default"].resolve(dirName, spec);
415
- // Exact file (with extension)
416
- if (host.fileExists(base)) {
417
- return base;
418
- }
419
- // Probe extensions (handles `./x.val` -> `./x.val.ts`)
420
- for (const ext of RESOLVE_EXTENSIONS) {
421
- const candidate = base + ext;
422
- if (host.fileExists(candidate)) {
423
- return candidate;
424
- }
425
- }
426
- // Directory index
427
- if (((_host$directoryExists = host.directoryExists) === null || _host$directoryExists === void 0 ? void 0 : _host$directoryExists.call(host, base)) ?? fs__default["default"].existsSync(base)) {
428
- for (const ext of RESOLVE_EXTENSIONS) {
429
- const candidate = path__default["default"].join(base, "index" + ext);
430
- if (host.fileExists(candidate)) {
431
- return candidate;
432
- }
433
- }
434
- }
435
- return null;
436
- }
437
-
438
- /**
439
- * What a `*.val.ts` file that is NOT registered in `val.modules` turns out to
440
- * be.
441
- *
442
- * A file matching `*.val.ts` is not necessarily a Val module: the same
443
- * convention is used for shared schemas and other content-adjacent helpers, and
444
- * those are not meant to be registered. Only a file that actually default
445
- * exports a module is worth warning about; one that default exports something
446
- * else is a mistake, because nothing will ever load it.
447
- *
448
- * See {@link createValModuleFileInspector}.
449
- */
450
-
451
- /**
452
- * Inspects individual `*.val.{ts,js}` files, sharing one module cache and one
453
- * parsed tsconfig across every call.
454
- *
455
- * The default export is checked SYNTACTICALLY first and only evaluated if it is
456
- * there. That ordering is the point: a `.val.ts` with no default export is a
457
- * helper file, and evaluating it to learn that would be both wasted work and a
458
- * way to turn an unrelated top-level throw into a reported error.
459
- *
460
- * SECURITY: evaluation goes through the same `vm` loader as
461
- * {@link loadValModules} — see the warning there. Only ever point this at the
462
- * project's own first-party files.
463
- */
464
- function createValModuleFileInspector(projectRoot, host = ts__default["default"].sys) {
465
- const compilerOptions = getCompilerOptions(projectRoot, host);
466
- const cache = {};
467
- return absPath => {
468
- const code = host.readFile(absPath);
469
- if (code === undefined) {
470
- return {
471
- status: "invalid",
472
- message: `Could not read file: '${absPath}'`
473
- };
474
- }
475
- const sourceFile = ts__default["default"].createSourceFile(absPath, code, ts__default["default"].ScriptTarget.ES2020, true);
476
- if (!hasDefaultExport(sourceFile)) {
477
- return {
478
- status: "no-default-export"
479
- };
480
- }
481
- let exports;
482
- // `loadModule` inserts a module into the cache BEFORE evaluating it, so
483
- // that a cycle resolves. One that throws therefore leaves a half-built
484
- // entry behind - and unlike `loadValModules`, which builds a cache per
485
- // call and lets the throw escape, this cache outlives the failure. A later
486
- // inspection of the same file (or of the helper that actually threw) would
487
- // hit that entry, see empty exports, and report "default export is
488
- // undefined" instead of the real error - or, worse, quietly downgrade it to
489
- // a warning. So roll the cache back to what it was before this attempt.
490
- const before = new Set(Object.keys(cache));
491
- try {
492
- exports = loadModule(absPath, cache, compilerOptions, host).exports;
493
- } catch (e) {
494
- for (const key of Object.keys(cache)) {
495
- if (!before.has(key)) {
496
- delete cache[key];
497
- }
498
- }
499
- return {
500
- status: "invalid",
501
- message: `Could not be loaded. Error: ${errorMessage(e)}`
502
- };
503
- }
504
- if (core.Internal.isValModule(exports.default)) {
505
- return {
506
- status: "val-module"
507
- };
508
- }
509
- // NOTE: do NOT suggest wrapping this in `c.define`. A shared schema turned
510
- // into a module is an UNREGISTERED module, i.e. straight back to a warning.
511
- // The fix is to move it out of the default export slot, which is the one
512
- // thing about a `.val.ts` that Val reserves for itself.
513
- return {
514
- status: "invalid",
515
- 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`
516
- };
517
- };
518
- }
519
-
520
- /**
521
- * The statement that exports a RUNTIME value as `default`, without evaluating
522
- * it — or `undefined` when the file has no such export.
523
- *
524
- * This is the one rule that separates a Val module from a `*.val.ts` that
525
- * merely wears the naming convention: a shared schema or helper is exported by
526
- * name, a module is exported by default. Every caller that needs to tell those
527
- * apart goes through this — `val validate` to decide whether an unregistered
528
- * file is worth reporting, and the language server to decide the same thing and
529
- * to put its diagnostic on the export rather than on line 1.
530
- *
531
- * Two things deliberately do not count, because neither exists once the file is
532
- * transpiled — and treating either as a default export would send a pure helper
533
- * off to be evaluated and reported:
534
- *
535
- * - `export * from "./x"`, since a star re-export never carries the default;
536
- * - a type-only export, in any of its three spellings
537
- * (`export type { T as default }`, `export { type T as default }` and
538
- * `export default interface T {}` — the last one parses as a declaration
539
- * carrying a `default` modifier, exactly like `export default class`, and is
540
- * the one that looks like a runtime export and is not).
541
- */
542
- function findDefaultExport(sourceFile) {
543
- return sourceFile.statements.find(statement => {
544
- // `export default <expr>` — but not `export = x`, which shares this node.
545
- if (ts__default["default"].isExportAssignment(statement)) {
546
- return !statement.isExportEquals;
547
- }
548
- // `export { x as default }` / `export { default } from "./x"`
549
- if (ts__default["default"].isExportDeclaration(statement) && !statement.isTypeOnly && statement.exportClause && ts__default["default"].isNamedExports(statement.exportClause)) {
550
- return statement.exportClause.elements.some(element => !element.isTypeOnly && element.name.text === "default");
551
- }
552
- // `export default function f() {}` / `export default class C {}`, which are
553
- // declarations carrying a `default` modifier rather than export assignments.
554
- // `export default interface T {}` is spelled the same way and is a type, so
555
- // it is excluded here rather than by the `isTypeOnly` checks above.
556
- 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);
557
- });
558
- }
559
-
560
- /** Whether the file exports a runtime value as `default`. */
561
- function hasDefaultExport(sourceFile) {
562
- return findDefaultExport(sourceFile) !== undefined;
563
- }
564
-
565
- /** A short, human-readable "what you exported instead" for the error message. */
566
- function describeDefaultExport(value) {
567
- if (value === null) {
568
- return "null";
569
- }
570
- if (Array.isArray(value)) {
571
- return "an array";
572
- }
573
- if (typeof value === "object") {
574
- // Duck-typed rather than `instanceof Schema`, for the same cross-realm
575
- // reason `isValModule` avoids a constructor check.
576
- if ("executeSerialize" in value && typeof value["executeSerialize"] === "function") {
577
- return "a schema";
578
- }
579
- return "an object";
580
- }
581
- if (typeof value === "undefined") {
582
- return "undefined";
583
- }
584
- return `a ${typeof value}`;
585
- }
586
- function errorMessage(e) {
587
- // NOT `e instanceof Error`: an error thrown from inside the `vm` context is
588
- // built from that realm's Error constructor. Duck-type the message instead.
589
- if (typeof e === "object" && e !== null && "message" in e) {
590
- const {
591
- message
592
- } = e;
593
- if (typeof message === "string") {
594
- return message;
595
- }
596
- }
597
- return String(e);
598
- }
599
-
600
183
  /**
601
184
  * Which `*.val.json` holds a `.jsonValues()` entry's content, given the module's
602
185
  * `.val.ts`.
@@ -615,14 +198,14 @@ function errorMessage(e) {
615
198
  function findJsonEntryFilePath(moduleFilePath, valTsSourceFile, entryKey) {
616
199
  let analysis;
617
200
  try {
618
- analysis = proposalJsonEntries.analyzeValModule(valTsSourceFile);
201
+ analysis = jsonValuesModule.analyzeValModule(valTsSourceFile);
619
202
  } catch {
620
203
  return undefined;
621
204
  }
622
205
  if (fp.result.isErr(analysis)) {
623
206
  return undefined;
624
207
  }
625
- const entry = proposalJsonEntries.analyzeJsonValuesEntries(analysis.value.source).get(entryKey);
208
+ const entry = jsonValuesModule.analyzeJsonValuesEntries(analysis.value.source).get(entryKey);
626
209
  if (!entry) {
627
210
  return undefined;
628
211
  }
@@ -674,11 +257,11 @@ async function createService(projectRoot, host = {
674
257
  }
675
258
  }
676
259
  }) {
677
- const compilerOptions = getCompilerOptions(projectRoot, host);
260
+ const compilerOptions = merge.getCompilerOptions(projectRoot, host);
678
261
  const sourceFileHandler = new ValSourceFileHandler(projectRoot, compilerOptions, host);
679
262
  // Read val.modules (and everything it imports) through the same host, so an
680
263
  // embedder that overlays unsaved editor buffers evaluates what the user sees.
681
- const valModules = loadValModules(projectRoot, host);
264
+ const valModules = merge.loadValModules(projectRoot, host);
682
265
  const extracted = await core.extractValModules(valModules);
683
266
  return new Service(projectRoot, sourceFileHandler, extracted);
684
267
  }
@@ -6243,11 +5826,11 @@ function planJsonValuesEntryExtraction({
6243
5826
  // entry moves to the end of the record: entry ORDER in a jsonValues record is
6244
5827
  // not meaningful (the Studio and the runtime key entries by name), and
6245
5828
  // insert-in-place would mean reimplementing insertValJsonEntry.
6246
- const removed = valRuntime.removeValJsonEntry(sourceFile, [], entryKey);
5829
+ const removed = merge.removeValJsonEntry(sourceFile, [], entryKey);
6247
5830
  if (fp.result.isErr(removed)) {
6248
5831
  return fp.result.err(`${valTsPath}\n${formatOpsError(removed.error, sourceFile)}`);
6249
5832
  }
6250
- const inserted = valRuntime.insertValJsonEntry(removed.value, [], entryKey, importPath);
5833
+ const inserted = merge.insertValJsonEntry(removed.value, [], entryKey, importPath);
6251
5834
  if (fp.result.isErr(inserted)) {
6252
5835
  return fp.result.err(`${valTsPath}\n${formatOpsError(inserted.error, removed.value)}`);
6253
5836
  }
@@ -6314,7 +5897,7 @@ function formatOpsError(error, sourceFile) {
6314
5897
  if (error instanceof patch.PatchError) {
6315
5898
  return error.message;
6316
5899
  }
6317
- return proposalJsonEntries.flatMapErrors(error, e => proposalJsonEntries.formatSyntaxError(e, sourceFile)).join("\n");
5900
+ return jsonValuesModule.flatMapErrors(error, e => jsonValuesModule.formatSyntaxError(e, sourceFile)).join("\n");
6318
5901
  }
6319
5902
 
6320
5903
  /**
@@ -7039,7 +6622,7 @@ async function evalValConfigFile(projectRoot, configFileName) {
7039
6622
  },
7040
6623
  fileName: valConfigPath
7041
6624
  });
7042
- const projectRootRequire = createNodeRequire(valConfigPath);
6625
+ const projectRootRequire = merge.createNodeRequire(valConfigPath);
7043
6626
  const exportsObj = {};
7044
6627
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
7045
6628
  const sandbox = {
@@ -7468,7 +7051,7 @@ async function replaySnapshot(snapshotDir) {
7468
7051
  if (!fs__default["default"].existsSync(path__default["default"].join(root, "val.modules.ts"))) {
7469
7052
  throw new Error(`Not a Val debug snapshot: no val.modules.ts in ${root}. ` + `Unzip the snapshot first.`);
7470
7053
  }
7471
- const valModules = loadValModules(root);
7054
+ const valModules = merge.loadValModules(root);
7472
7055
  const serverOps = new valRuntime.ValOpsFS(process.env.VAL_CONTENT_URL || core.DEFAULT_CONTENT_HOST, root, valModules,
7473
7056
  // The snapshot's own val.config, as evaluated by loadValModules - no need to
7474
7057
  // re-read it, and this way the replay uses exactly the config the snapshot
@@ -7551,25 +7134,12 @@ function readCapturedReport(snapshotDir) {
7551
7134
  return JSON.parse(fs__default["default"].readFileSync(reportPath, "utf-8"));
7552
7135
  }
7553
7136
 
7554
- exports.analyzeValModule = proposalJsonEntries.analyzeValModule;
7555
- exports.formatSyntaxErrorTree = proposalJsonEntries.formatSyntaxErrorTree;
7556
- exports.proposalSnapshotForReaders = proposalJsonEntries.proposalSnapshotForReaders;
7557
- exports.APP_MODE_REQUIRES_REMOTE_FILES = valRuntime.APP_MODE_REQUIRES_REMOTE_FILES;
7558
- exports.ValOpsFS = valRuntime.ValOpsFS;
7559
- exports.ValOpsHttp = valRuntime.ValOpsHttp;
7560
- exports.createValOps = valRuntime.createValOps;
7561
- exports.decodeJwtWithoutVerifying = valRuntime.decodeJwtWithoutVerifying;
7562
- exports.describePatchStoreProblems = valRuntime.describePatchStoreProblems;
7563
- exports.encodeJwt = valRuntime.encodeJwt;
7564
- exports.getExpire = valRuntime.getExpire;
7565
- exports.getPersonalAccessTokenPath = valRuntime.getPersonalAccessTokenPath;
7566
- exports.initHandlerOptions = valRuntime.initHandlerOptions;
7567
- exports.loadTypeScriptKit = valRuntime.loadTypeScriptKit;
7568
- exports.parsePersonalAccessTokenFile = valRuntime.parsePersonalAccessTokenFile;
7569
- exports.readPatchStore = valRuntime.readPatchStore;
7570
- exports.resolveRemoteFileAuth = valRuntime.resolveRemoteFileAuth;
7571
- exports.valRuntime = valRuntime.valRuntime;
7572
- exports.verifyJwt = valRuntime.verifyJwt;
7137
+ exports.analyzeValModule = jsonValuesModule.analyzeValModule;
7138
+ exports.formatSyntaxErrorTree = jsonValuesModule.formatSyntaxErrorTree;
7139
+ exports.createValModuleFileInspector = merge.createValModuleFileInspector;
7140
+ exports.findDefaultExport = merge.findDefaultExport;
7141
+ exports.getCompilerOptions = merge.getCompilerOptions;
7142
+ exports.loadValModules = merge.loadValModules;
7573
7143
  Object.defineProperty(exports, 'hasRemoteFileSchema', {
7574
7144
  enumerable: true,
7575
7145
  get: function () { return core.hasRemoteFileSchema; }
@@ -7588,11 +7158,28 @@ Object.defineProperty(exports, 'rebaseContentOp', {
7588
7158
  enumerable: true,
7589
7159
  get: function () { return internal.rebaseContentOp; }
7590
7160
  });
7161
+ exports.APP_MODE_REQUIRES_REMOTE_FILES = valRuntime.APP_MODE_REQUIRES_REMOTE_FILES;
7162
+ exports.ValOpsFS = valRuntime.ValOpsFS;
7163
+ exports.ValOpsHttp = valRuntime.ValOpsHttp;
7164
+ exports.createValOps = valRuntime.createValOps;
7165
+ exports.decodeJwtWithoutVerifying = valRuntime.decodeJwtWithoutVerifying;
7166
+ exports.describePatchStoreProblems = valRuntime.describePatchStoreProblems;
7167
+ exports.encodeJwt = valRuntime.encodeJwt;
7168
+ exports.getExpire = valRuntime.getExpire;
7169
+ exports.getPersonalAccessTokenPath = valRuntime.getPersonalAccessTokenPath;
7170
+ exports.initHandlerOptions = valRuntime.initHandlerOptions;
7171
+ exports.loadTypeScriptKit = valRuntime.loadTypeScriptKit;
7172
+ exports.parsePersonalAccessTokenFile = valRuntime.parsePersonalAccessTokenFile;
7173
+ exports.readPatchStore = valRuntime.readPatchStore;
7174
+ exports.resolveRemoteFileAuth = valRuntime.resolveRemoteFileAuth;
7175
+ exports.valRuntime = valRuntime.valRuntime;
7176
+ exports.verifyJwt = valRuntime.verifyJwt;
7591
7177
  exports.contentFromEnv = createPrettierFormatter.contentFromEnv;
7592
7178
  exports.createPrettierFormatter = createPrettierFormatter.createPrettierFormatter;
7593
7179
  exports.layeredSnapshot = createPrettierFormatter.layeredSnapshot;
7594
7180
  exports.proposalFromEnv = createPrettierFormatter.proposalFromEnv;
7595
7181
  exports.proposalSnapshot = createPrettierFormatter.proposalSnapshot;
7182
+ exports.proposalSnapshotForReaders = proposalJsonEntries.proposalSnapshotForReaders;
7596
7183
  exports.InMemoryPatchStore = ValPatchStore.InMemoryPatchStore;
7597
7184
  exports.DEFAULT_LOGIN_EXPIRES_IN_SECONDS = DEFAULT_LOGIN_EXPIRES_IN_SECONDS;
7598
7185
  exports.DEFAULT_LOGIN_HOST = DEFAULT_LOGIN_HOST;
@@ -7612,7 +7199,6 @@ exports.createJsonEntryPathMap = createJsonEntryPathMap;
7612
7199
  exports.createModulePathMap = createModulePathMap;
7613
7200
  exports.createService = createService;
7614
7201
  exports.createValApiRouter = createValApiRouter;
7615
- exports.createValModuleFileInspector = createValModuleFileInspector;
7616
7202
  exports.createValServer = createValServer;
7617
7203
  exports.currentFixHandlers = currentFixHandlers;
7618
7204
  exports.defineExternal = defineExternal;
@@ -7627,12 +7213,10 @@ exports.extractVideoMetadataFromFile = extractVideoMetadataFromFile;
7627
7213
  exports.filesOfVideo = filesOfVideo;
7628
7214
  exports.filesOfVideosetEntry = filesOfVideosetEntry;
7629
7215
  exports.findAndEvalValConfigFile = findAndEvalValConfigFile;
7630
- exports.findDefaultExport = findDefaultExport;
7631
7216
  exports.findJsonEntryFilePath = findJsonEntryFilePath;
7632
7217
  exports.fixHandlers = fixHandlers;
7633
7218
  exports.getCachedRemoteFileDir = getCachedRemoteFileDir;
7634
7219
  exports.getCachedRemoteFilePath = getCachedRemoteFilePath;
7635
- exports.getCompilerOptions = getCompilerOptions;
7636
7220
  exports.getModulePathRange = getModulePathRange;
7637
7221
  exports.getValidationErrorFileRef = getValidationErrorFileRef;
7638
7222
  exports.handleCheckAllFiles = handleCheckAllFiles;
@@ -7649,7 +7233,6 @@ exports.handleVideosetCheckRemote = handleVideosetCheckRemote;
7649
7233
  exports.handleVideosetMetadata = handleVideosetMetadata;
7650
7234
  exports.handleVideosetUploadRemote = handleVideosetUploadRemote;
7651
7235
  exports.isExternalResult = isExternalResult;
7652
- exports.loadValModules = loadValModules;
7653
7236
  exports.ok = ok;
7654
7237
  exports.patchSourceFile = patchSourceFile;
7655
7238
  exports.persistPersonalAccessToken = persistPersonalAccessToken;