@valbuild/server 0.150.14 → 0.150.17

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.
@@ -1,5 +1,5 @@
1
1
  import { Internal, VAL_EXTENSION, extractValModules, computeValModuleShas, ImageSchema, DEFAULT_CONTENT_HOST, hasRemoteFileSchema } from '@valbuild/core';
2
- import { isSchemaSourceFixError, resolveSchemaSourceFixForError, SerializedSchema, AnalyticsBeacon, VAL_ENABLE_COOKIE_NAME, VAL_STATE_COOKIE, VAL_SESSION_COOKIE, newestCommitSha, parseJob, VAL_STUDIO_HEADER, AIToolCallSummaries, getErrorMessageFromUnknownJson, QUICK_PREVIEW_SERVICE_WORKER_PATH, QUICK_PREVIEW_SERVICE_WORKER_SOURCE, Api } from '@valbuild/shared/internal';
2
+ import { isSchemaSourceFixError, resolveSchemaSourceFixForError, SerializedSchema, sketchTitle, parseSketch, SKETCHPAD_MAX_TEXT_LENGTH, checkSketch, AnalyticsBeacon, VAL_ENABLE_COOKIE_NAME, VAL_STATE_COOKIE, VAL_SESSION_COOKIE, newestCommitSha, parseJob, VAL_STUDIO_HEADER, AIToolCallSummaries, getErrorMessageFromUnknownJson, QUICK_PREVIEW_SERVICE_WORKER_PATH, QUICK_PREVIEW_SERVICE_WORKER_SOURCE, Api } from '@valbuild/shared/internal';
3
3
  import { z } from 'zod';
4
4
  import { fromError } from 'zod-validation-error';
5
5
  import { result, array } from '@valbuild/core/fp';
@@ -4558,6 +4558,11 @@ class ValOps {
4558
4558
  * narrow on it with type-only imports.
4559
4559
  */
4560
4560
 
4561
+ /**
4562
+ * The project's sketchpads, kept wherever this mode keeps things: see
4563
+ * `sketchpads/SketchpadStore.ts`. Not patches, and never published.
4564
+ */
4565
+
4561
4566
  /**
4562
4567
  * Save a patch's binary file from a `data:...;base64,...` URL.
4563
4568
  *
@@ -5498,7 +5503,7 @@ var packageJson = {
5498
5503
  ],
5499
5504
  exports: true
5500
5505
  },
5501
- version: "0.150.14",
5506
+ version: "0.150.17",
5502
5507
  scripts: {
5503
5508
  typecheck: "tsc --noEmit",
5504
5509
  test: "jest",
@@ -5541,6 +5546,397 @@ var packageJson = {
5541
5546
  */
5542
5547
  const VERSION = packageJson.version;
5543
5548
 
5549
+ /**
5550
+ * `/sketchpads` and `/sketchpad`. Here rather than inline in `ValServer` so
5551
+ * the rules every mode shares are in one place: a text is a sketch in the
5552
+ * one spelling or it is refused, line by line; an archived sketchpad is
5553
+ * reopened before it is changed; a change names the version it was made on.
5554
+ */
5555
+ function createSketchpadRoutes(options) {
5556
+ const {
5557
+ store,
5558
+ getAuth,
5559
+ profileOf
5560
+ } = options;
5561
+ return {
5562
+ "/sketchpads": {
5563
+ GET: async req => {
5564
+ const auth = getAuth(req.cookies);
5565
+ if (auth.error) {
5566
+ return {
5567
+ status: 401,
5568
+ json: {
5569
+ message: auth.error
5570
+ }
5571
+ };
5572
+ }
5573
+ const archived = req.query.archived ?? "exclude";
5574
+ if (!isArchivedFilter(archived)) {
5575
+ return {
5576
+ status: 400,
5577
+ json: {
5578
+ message: `"archived" is exclude, include or only, not "${archived}".`
5579
+ }
5580
+ };
5581
+ }
5582
+ try {
5583
+ const sketchpads = await store().list({
5584
+ archived,
5585
+ ...(req.query.page !== undefined ? {
5586
+ page: req.query.page
5587
+ } : {})
5588
+ });
5589
+ return {
5590
+ status: 200,
5591
+ json: {
5592
+ sketchpads
5593
+ }
5594
+ };
5595
+ } catch (error) {
5596
+ return failed(error);
5597
+ }
5598
+ },
5599
+ POST: async req => {
5600
+ const auth = getAuth(req.cookies);
5601
+ if (auth.error) {
5602
+ return {
5603
+ status: 401,
5604
+ json: {
5605
+ message: auth.error
5606
+ }
5607
+ };
5608
+ }
5609
+ const refused = refuseText(req.body.text);
5610
+ if (refused) {
5611
+ return refused;
5612
+ }
5613
+ try {
5614
+ const sketchpad = await store().create({
5615
+ text: req.body.text,
5616
+ title: titleOf(req.body.text),
5617
+ page: req.body.page,
5618
+ by: profileOf(auth)
5619
+ });
5620
+ return {
5621
+ status: 201,
5622
+ json: {
5623
+ sketchpad
5624
+ }
5625
+ };
5626
+ } catch (error) {
5627
+ return failed(error);
5628
+ }
5629
+ }
5630
+ },
5631
+ "/sketchpad": {
5632
+ GET: async req => {
5633
+ const auth = getAuth(req.cookies);
5634
+ if (auth.error) {
5635
+ return {
5636
+ status: 401,
5637
+ json: {
5638
+ message: auth.error
5639
+ }
5640
+ };
5641
+ }
5642
+ try {
5643
+ const sketchpad = await store().get(req.query.id);
5644
+ if (sketchpad === null) {
5645
+ return notFound(req.query.id);
5646
+ }
5647
+ return {
5648
+ status: 200,
5649
+ json: {
5650
+ sketchpad
5651
+ }
5652
+ };
5653
+ } catch (error) {
5654
+ return failed(error);
5655
+ }
5656
+ },
5657
+ PATCH: async req => {
5658
+ const auth = getAuth(req.cookies);
5659
+ if (auth.error) {
5660
+ return {
5661
+ status: 401,
5662
+ json: {
5663
+ message: auth.error
5664
+ }
5665
+ };
5666
+ }
5667
+ const {
5668
+ id,
5669
+ baseVersion,
5670
+ text,
5671
+ page,
5672
+ archived
5673
+ } = req.body;
5674
+ if (text !== undefined) {
5675
+ const refused = refuseText(text);
5676
+ if (refused) {
5677
+ return refused;
5678
+ }
5679
+ }
5680
+ try {
5681
+ const current = await store().get(id);
5682
+ if (current === null) {
5683
+ return notFound(id);
5684
+ }
5685
+ // Reopening is the one change an archived sketchpad takes, and it
5686
+ // can come with others: "reopen and put this in it".
5687
+ if (current.archived && archived !== false && (text !== undefined || page !== undefined)) {
5688
+ return {
5689
+ status: 400,
5690
+ json: {
5691
+ message: "This sketchpad is archived, so it is not changed. Reopen it first (archived: false), or ask the person to."
5692
+ }
5693
+ };
5694
+ }
5695
+ const result = await store().update(id, {
5696
+ baseVersion,
5697
+ ...(text !== undefined ? {
5698
+ text,
5699
+ title: titleOf(text)
5700
+ } : {}),
5701
+ ...(page !== undefined ? {
5702
+ page
5703
+ } : {}),
5704
+ ...(archived !== undefined ? {
5705
+ archived
5706
+ } : {}),
5707
+ by: profileOf(auth)
5708
+ });
5709
+ if (result.status === "not-found") {
5710
+ return notFound(id);
5711
+ }
5712
+ if (result.status === "conflict") {
5713
+ return {
5714
+ status: 409,
5715
+ json: {
5716
+ message: `The sketchpad changed since version ${baseVersion}: it is at version ${result.sketchpad.version} now. Here it is; make the change again on top of it.`,
5717
+ sketchpad: result.sketchpad
5718
+ }
5719
+ };
5720
+ }
5721
+ return {
5722
+ status: 200,
5723
+ json: {
5724
+ sketchpad: result.sketchpad
5725
+ }
5726
+ };
5727
+ } catch (error) {
5728
+ return failed(error);
5729
+ }
5730
+ }
5731
+ }
5732
+ };
5733
+ }
5734
+ function isArchivedFilter(value) {
5735
+ return value === "exclude" || value === "include" || value === "only";
5736
+ }
5737
+ function titleOf(text) {
5738
+ return sketchTitle(parseSketch(text).blocks);
5739
+ }
5740
+ /** A 400 for a text the server will not keep, saying which lines and why. */
5741
+ function refuseText(text) {
5742
+ // Bytes, not characters, as the content service counts them: a page in
5743
+ // Norwegian is longer in UTF-8 than it looks.
5744
+ const bytes = new TextEncoder().encode(text).length;
5745
+ if (bytes > SKETCHPAD_MAX_TEXT_LENGTH) {
5746
+ return {
5747
+ status: 400,
5748
+ json: {
5749
+ message: `A sketchpad holds at most ${SKETCHPAD_MAX_TEXT_LENGTH / 1024} KiB of text; this is ${Math.ceil(bytes / 1024)} KiB.`
5750
+ }
5751
+ };
5752
+ }
5753
+ const errors = checkSketch(text);
5754
+ if (errors.length === 0) {
5755
+ return null;
5756
+ }
5757
+ return {
5758
+ status: 400,
5759
+ json: {
5760
+ message: `That is not a sketch the Sketchpad can show: ${errors.map(error => `line ${error.line}: ${error.message}`).join(" ")}`,
5761
+ errors
5762
+ }
5763
+ };
5764
+ }
5765
+ function notFound(id) {
5766
+ return {
5767
+ status: 404,
5768
+ json: {
5769
+ message: `There is no sketchpad "${id}" in this project.`
5770
+ }
5771
+ };
5772
+ }
5773
+ function failed(error) {
5774
+ return {
5775
+ status: 500,
5776
+ json: {
5777
+ message: error instanceof Error ? error.message : "The sketchpads could not be reached."
5778
+ }
5779
+ };
5780
+ }
5781
+
5782
+ /**
5783
+ * Content analytics on a SELF-HOSTED site: handing a visitor's beacon on to
5784
+ * Val's ingest, which counts it.
5785
+ *
5786
+ * On a site Val hosts, the platform's loader answers `POST /api/val/analytics`
5787
+ * before the app sees it. Anywhere else the beacon reaches this server, and
5788
+ * the only thing that can count it is the ingest -- which only takes it from a
5789
+ * server holding the project's api key, so the browser cannot send it there
5790
+ * itself.
5791
+ *
5792
+ * Kept out of `ValServer.ts` so it can be tested on its own, and free of Node
5793
+ * for the same reason the rest of the request handlers are: the demo runs
5794
+ * them in a browser tab (`noNodeFromBrowser.test.ts`).
5795
+ */
5796
+
5797
+ /** Where beacons go, unless `VAL_ANALYTICS_INGEST_URL` says otherwise. */
5798
+ const DEFAULT_ANALYTICS_INGEST_URL = "https://platform.valstart.dev/__ingest/analytics";
5799
+
5800
+ /**
5801
+ * The most the ingest takes: it answers 413 above this. The browser script
5802
+ * keeps its beacons well below it (`MAX_BEACON_BYTES` in
5803
+ * `@valbuild/react/analytics`), so one that is not was not built by it.
5804
+ */
5805
+ const MAX_FORWARDED_BEACON_BYTES = 16 * 1024;
5806
+
5807
+ /** A forward is a visitor's request waiting on another one, so it is short. */
5808
+ const ANALYTICS_FORWARD_TIMEOUT_MS = 3_000;
5809
+
5810
+ /**
5811
+ * The request headers the route reads, by lower-case name. Declared on the
5812
+ * route (`Api["/analytics"]`), so the router hands over these and no others:
5813
+ * the visitor's IP is never among them.
5814
+ */
5815
+
5816
+ /**
5817
+ * Where hosts in front of an app say which country a request came from, in
5818
+ * the order they are asked. Each is set by the host, never by the browser.
5819
+ */
5820
+ const COUNTRY_HEADERS = ["x-vercel-ip-country", "cf-ipcountry", "cloudfront-viewer-country"];
5821
+
5822
+ /**
5823
+ * The visitor's country, as ISO 3166-1 alpha-2, when a host in front of the
5824
+ * app said: the first of {@link COUNTRY_HEADERS} that holds two letters.
5825
+ *
5826
+ * Anything else is skipped rather than passed on: Cloudflare's `T1` (Tor)
5827
+ * is not a country, and `XX` is how it says it does not know.
5828
+ */
5829
+ function visitorCountry(headers) {
5830
+ for (const name of COUNTRY_HEADERS) {
5831
+ var _headers$name;
5832
+ const value = (_headers$name = headers[name]) === null || _headers$name === void 0 ? void 0 : _headers$name.trim();
5833
+ if (value && /^[A-Za-z]{2}$/.test(value)) {
5834
+ const country = value.toUpperCase();
5835
+ if (country !== "XX") {
5836
+ return country;
5837
+ }
5838
+ }
5839
+ }
5840
+ return undefined;
5841
+ }
5842
+
5843
+ /**
5844
+ * Why a beacon was not handed on, when the reason is the request's. Each of
5845
+ * these is answered as before -- `200 { counted: false }` -- because none of
5846
+ * them is something the script can do anything about.
5847
+ */
5848
+
5849
+ /**
5850
+ * Whether this request may be handed on, and if so what to send. The checks
5851
+ * are the ones only this server can make: a server-to-server forward loses
5852
+ * `Sec-Fetch-Site`, and the ingest would see this server's User-Agent rather
5853
+ * than the visitor's.
5854
+ */
5855
+ function prepareAnalyticsForward(headers, body) {
5856
+ // A beacon from another site's page is not one of this site's visitors.
5857
+ if (headers["sec-fetch-site"] !== "same-origin") {
5858
+ return {
5859
+ ok: false,
5860
+ reason: "not-same-origin"
5861
+ };
5862
+ }
5863
+ // The ingest tells a bot from a person by its User-Agent; without one there
5864
+ // is nothing to tell, and nothing a browser sends goes without.
5865
+ const userAgent = headers["user-agent"];
5866
+ if (!userAgent) {
5867
+ return {
5868
+ ok: false,
5869
+ reason: "no-user-agent"
5870
+ };
5871
+ }
5872
+ if (utf8ToBytes(body).length > MAX_FORWARDED_BEACON_BYTES) {
5873
+ return {
5874
+ ok: false,
5875
+ reason: "too-large"
5876
+ };
5877
+ }
5878
+ return {
5879
+ ok: true,
5880
+ userAgent,
5881
+ country: visitorCountry(headers)
5882
+ };
5883
+ }
5884
+
5885
+ /**
5886
+ * What the ingest said, or that it could not be asked: `null` for a forward
5887
+ * that threw or timed out. Never a throw -- a visitor's beacon failing to go
5888
+ * further is not the visitor's problem.
5889
+ */
5890
+ async function forwardAnalyticsBeacon(args) {
5891
+ const controller = new AbortController();
5892
+ const timer = setTimeout(() => controller.abort(), args.timeoutMs ?? ANALYTICS_FORWARD_TIMEOUT_MS);
5893
+ const headers = {
5894
+ authorization: `Bearer ${args.apiKey}`,
5895
+ "x-val-project": args.project,
5896
+ "x-val-visitor-user-agent": args.userAgent,
5897
+ "content-type": "text/plain;charset=UTF-8"
5898
+ };
5899
+ if (args.country !== undefined) {
5900
+ headers["x-val-visitor-country"] = args.country;
5901
+ }
5902
+ try {
5903
+ const res = await fetch(args.ingestUrl, {
5904
+ method: "POST",
5905
+ headers,
5906
+ body: args.body,
5907
+ signal: controller.signal
5908
+ });
5909
+ // Nothing in an answer is read but its status. Cancelled rather than left
5910
+ // for the garbage collector, which in Node holds the connection until then.
5911
+ try {
5912
+ var _res$body;
5913
+ await ((_res$body = res.body) === null || _res$body === void 0 ? void 0 : _res$body.cancel());
5914
+ } catch {
5915
+ // Already read or closed: nothing to free.
5916
+ }
5917
+ return res.status;
5918
+ } catch (err) {
5919
+ Internal.log.debug(`analytics: could not forward a beacon to ${args.ingestUrl}`, err);
5920
+ return null;
5921
+ } finally {
5922
+ clearTimeout(timer);
5923
+ }
5924
+ }
5925
+ let warnedUnauthorized = false;
5926
+
5927
+ /**
5928
+ * The ingest refused this server's api key: a misconfiguration the site's
5929
+ * developer can fix, and the same one on every beacon. So it is said once a
5930
+ * process, where a warning per visitor would bury everything else.
5931
+ */
5932
+ function warnAnalyticsUnauthorizedOnce(project) {
5933
+ if (warnedUnauthorized) {
5934
+ return;
5935
+ }
5936
+ warnedUnauthorized = true;
5937
+ Internal.log.warn(`Content analytics is not being counted: Val's analytics ingest did not accept this site's api key for the project "${project}" (401). ` + "Check that VAL_API_KEY is an api key of that project, and that VAL_PROJECT names it as org/project.");
5938
+ }
5939
+
5544
5940
  /** What {@link ValServerOptions.publishOverride} is given. */
5545
5941
 
5546
5942
  /** What a publish reports back, in either shape. */
@@ -6043,6 +6439,11 @@ const ValServer = (valModules, options, callbacks, platform) => {
6043
6439
  };
6044
6440
  };
6045
6441
  return {
6442
+ ...createSketchpadRoutes({
6443
+ store: () => serverOps.sketchpads,
6444
+ getAuth,
6445
+ profileOf
6446
+ }),
6046
6447
  "/draft/enable": {
6047
6448
  GET: async req => {
6048
6449
  const cookies = req.cookies;
@@ -6095,10 +6496,20 @@ const ValServer = (valModules, options, callbacks, platform) => {
6095
6496
  * Content analytics beacons, outside the hosted platform.
6096
6497
  *
6097
6498
  * On a site Val hosts, the platform's loader answers this route before a
6098
- * request reaches the app, and counts. Everywhere else nothing counts yet:
6099
- * this checks the beacon and answers, so a site with analytics on does not
6100
- * fill its visitors' consoles with 404s. In local dev it also logs a line
6101
- * per beacon, which is how the showcase shows analytics working.
6499
+ * request reaches the app, and counts.
6500
+ *
6501
+ * A SELF-HOSTED site in http mode has the project's api key, and hands
6502
+ * each beacon on to Val's ingest, which counts it (`analyticsForward.ts`).
6503
+ * For that the site needs `VAL_API_KEY` and `VAL_PROJECT` (which http
6504
+ * mode needs anyway), the script started -- `VAL_ANALYTICS`, read by the
6505
+ * layout and passed to `<ValProvider analytics>` -- and analytics switched
6506
+ * on for the project in Val's admin. While it is off there, the ingest
6507
+ * answers 410, which is passed on, and the script stops.
6508
+ *
6509
+ * Everywhere else -- fs mode, memory mode -- nothing counts: this checks
6510
+ * the beacon and answers, so a site with analytics on does not fill its
6511
+ * visitors' consoles with 404s. In local dev it also logs a line per
6512
+ * beacon, which is how the showcase shows analytics working.
6102
6513
  */
6103
6514
  "/analytics": {
6104
6515
  POST: async req => {
@@ -6127,10 +6538,52 @@ const ValServer = (valModules, options, callbacks, platform) => {
6127
6538
  const count = paths => Object.values(paths).reduce((n, list) => n + list.length, 0);
6128
6539
  Internal.log.debug(`analytics: ${beacon.route}${beacon.view ? " (page view)" : ""}: ${count(beacon.rendered)} rendered, ${count(beacon.viewed)} viewed`);
6129
6540
  }
6541
+ if (options.mode !== "http") {
6542
+ return {
6543
+ status: 200,
6544
+ json: {
6545
+ counted: false
6546
+ }
6547
+ };
6548
+ }
6549
+ const body = JSON.stringify(parsed.data);
6550
+ const plan = prepareAnalyticsForward(req.headers, body);
6551
+ if (!plan.ok) {
6552
+ Internal.log.debug(`analytics: not forwarded (${plan.reason})`);
6553
+ return {
6554
+ status: 200,
6555
+ json: {
6556
+ counted: false
6557
+ }
6558
+ };
6559
+ }
6560
+ const ingestStatus = await forwardAnalyticsBeacon({
6561
+ ingestUrl: options.valAnalyticsIngestUrl ?? DEFAULT_ANALYTICS_INGEST_URL,
6562
+ apiKey: options.apiKey,
6563
+ project: options.project,
6564
+ body,
6565
+ userAgent: plan.userAgent,
6566
+ country: plan.country
6567
+ });
6568
+ if (ingestStatus === 410) {
6569
+ // Off for this project: the script stops on a 410, so it is passed
6570
+ // on rather than answered as "not counted", which it would retry.
6571
+ return {
6572
+ status: 410,
6573
+ json: {
6574
+ message: "Content analytics is switched off for this project."
6575
+ }
6576
+ };
6577
+ }
6578
+ if (ingestStatus === 401) {
6579
+ warnAnalyticsUnauthorizedOnce(options.project);
6580
+ } else if (ingestStatus !== null && ingestStatus !== 204) {
6581
+ Internal.log.debug(`analytics: the ingest answered ${ingestStatus} to a beacon`);
6582
+ }
6130
6583
  return {
6131
6584
  status: 200,
6132
6585
  json: {
6133
- counted: false
6586
+ counted: ingestStatus === 204
6134
6587
  }
6135
6588
  };
6136
6589
  }
@@ -9236,7 +9689,7 @@ const ValServer = (valModules, options, callbacks, platform) => {
9236
9689
  // TypeScript compiler. See `patch/ts/publishKit.ts`.
9237
9690
  const {
9238
9691
  getJsonEntryAtCommit
9239
- } = await import('./getJsonEntryAtCommit-28be5ffd.esm.js');
9692
+ } = await import('./getJsonEntryAtCommit-a5932dc3.esm.js');
9240
9693
  const res = await getJsonEntryAtCommit(serverOps, req.query.commit_sha, req.query.path, req.query.key);
9241
9694
  if (result.isErr(res)) {
9242
9695
  return historyErrorResponse(res.error);
@@ -9966,6 +10419,138 @@ async function uploadRemoteFile(contentHost, project, bucket, fileHash, fileExt,
9966
10419
  };
9967
10420
  }
9968
10421
 
10422
+ /**
10423
+ * Where a project's sketchpads are kept, in each of the server's modes:
10424
+ * `.val/sketchpads` in `fs` mode, the content service in `http` mode, the
10425
+ * tab's memory in the demo. See `Sketchpad` in `ApiRoutes.ts` for what one
10426
+ * is.
10427
+ *
10428
+ * The store keeps what it is given. Whether a text is a sketch at all is
10429
+ * decided before it gets here (`checkSketch`, in `ValServer`), once for every
10430
+ * mode, so no store has its own idea of the format.
10431
+ */
10432
+
10433
+ /**
10434
+ * Whether `id` is in the shape a sketchpad's id has. Every store checks it
10435
+ * before the id goes anywhere it could mean something else: a file name in
10436
+ * fs mode, a URL path in http mode, where `..` is not an id but a way out.
10437
+ */
10438
+ function isSketchpadId(id) {
10439
+ return /^[0-9a-f-]{36}$/.test(id);
10440
+ }
10441
+
10442
+ /**
10443
+ * A random id in the shape of a UUID. `getRandomValues` rather than
10444
+ * `randomUUID`, which a browser only has in a secure context -- and the demo
10445
+ * runs this server in the visitor's tab.
10446
+ */
10447
+ function newSketchpadId() {
10448
+ const bytes = new Uint8Array(16);
10449
+ globalThis.crypto.getRandomValues(bytes);
10450
+ bytes[6] = bytes[6] & 0x0f | 0x40;
10451
+ bytes[8] = bytes[8] & 0x3f | 0x80;
10452
+ const hex = Array.from(bytes, b => b.toString(16).padStart(2, "0"));
10453
+ return [hex.slice(0, 4).join(""), hex.slice(4, 6).join(""), hex.slice(6, 8).join(""), hex.slice(8, 10).join(""), hex.slice(10, 16).join("")].join("-");
10454
+ }
10455
+ function summaryOf(sketchpad) {
10456
+ const {
10457
+ text,
10458
+ ...summary
10459
+ } = sketchpad;
10460
+ return summary;
10461
+ }
10462
+ function matchesFilter(sketchpad, filter) {
10463
+ if (filter.page !== undefined && sketchpad.page !== filter.page) {
10464
+ return false;
10465
+ }
10466
+ return filter.archived === "include" ? true : filter.archived === "only" ? sketchpad.archived : !sketchpad.archived;
10467
+ }
10468
+
10469
+ /** Newest change first, as every list of them is read. */
10470
+ function byUpdatedAt(a, b) {
10471
+ return b.updatedAt.localeCompare(a.updatedAt);
10472
+ }
10473
+ function newSketchpad(input, now) {
10474
+ const at = now.toISOString();
10475
+ return {
10476
+ id: newSketchpadId(),
10477
+ page: input.page,
10478
+ title: input.title,
10479
+ text: input.text,
10480
+ version: 1,
10481
+ archived: false,
10482
+ createdAt: at,
10483
+ updatedAt: at,
10484
+ createdBy: input.by,
10485
+ updatedBy: input.by
10486
+ };
10487
+ }
10488
+
10489
+ /** `current` with `change` applied, or why not. Pure: storing is the caller's. */
10490
+ function applySketchpadChange(current, change, now) {
10491
+ if (current === null) {
10492
+ return {
10493
+ status: "not-found"
10494
+ };
10495
+ }
10496
+ if (current.version !== change.baseVersion) {
10497
+ return {
10498
+ status: "conflict",
10499
+ sketchpad: current
10500
+ };
10501
+ }
10502
+ return {
10503
+ status: "updated",
10504
+ sketchpad: {
10505
+ ...current,
10506
+ ...(change.text !== undefined ? {
10507
+ text: change.text
10508
+ } : {}),
10509
+ ...(change.title !== undefined ? {
10510
+ title: change.title
10511
+ } : {}),
10512
+ ...(change.page !== undefined ? {
10513
+ page: change.page
10514
+ } : {}),
10515
+ ...(change.archived !== undefined ? {
10516
+ archived: change.archived
10517
+ } : {}),
10518
+ version: current.version + 1,
10519
+ updatedAt: now.toISOString(),
10520
+ updatedBy: change.by
10521
+ }
10522
+ };
10523
+ }
10524
+
10525
+ /**
10526
+ * Sketchpads kept in memory, for as long as the server runs: the demo's
10527
+ * store, where a reload starts over anyway, and the tests'.
10528
+ */
10529
+ function createMemorySketchpadStore(now = () => new Date()) {
10530
+ const sketchpads = new Map();
10531
+ return {
10532
+ async list(filter) {
10533
+ return Array.from(sketchpads.values()).map(summaryOf).filter(sketchpad => matchesFilter(sketchpad, filter)).sort(byUpdatedAt);
10534
+ },
10535
+ async get(id) {
10536
+ return sketchpads.get(id) ?? null;
10537
+ },
10538
+ async create(input) {
10539
+ const sketchpad = newSketchpad(input, now());
10540
+ sketchpads.set(sketchpad.id, sketchpad);
10541
+ return sketchpad;
10542
+ },
10543
+ async update(id, change) {
10544
+ // Synchronous from the read to the write, so nothing interleaves.
10545
+ const result = applySketchpadChange(sketchpads.get(id) ?? null, change, now());
10546
+ if (result.status === "updated") {
10547
+ sketchpads.set(id, result.sketchpad);
10548
+ }
10549
+ return result;
10550
+ }
10551
+ };
10552
+ }
10553
+
9969
10554
  /**
9970
10555
  * One stored patch. Everything the ordered chain needs and nothing else.
9971
10556
  */
@@ -10098,6 +10683,8 @@ class ValOpsMemory extends ValOps {
10098
10683
  */
10099
10684
  patchesAreLocal = true;
10100
10685
  kind = "memory";
10686
+ /** For as long as the tab is open, like everything else in the demo. */
10687
+ sketchpads = createMemorySketchpadStore();
10101
10688
  /**
10102
10689
  * Required, unless the host explicitly takes the boundary itself.
10103
10690
  *
@@ -10988,4 +11575,4 @@ function getCookies(req, cookiesDef) {
10988
11575
  return z.object(cookiesDef).safeParse(input);
10989
11576
  }
10990
11577
 
10991
- export { getNewJsonEntryPaths as A, formatPatchSourceError as B, askOncePerHost as C, getSettings as D, bytesToBase64 as E, bytesToUtf8 as F, posixPath as G, InMemoryPatchStore as I, ValOps as V, rebaseContentOp as a, bufferFromDataUrl as b, classifyJsonValuesOp as c, getFileExt as d, guessMimeTypeFromPath as e, findNestedJsonValuesRecords as f, getFieldsForType as g, createMetadataFromBuffer as h, isJsonValuesRootOp as i, ValOpsMemory as j, isHlsMasterPlaylist as k, largestHlsVariant as l, fallbackRefOf as m, mapHlsUris as n, movedRemoteHost as o, parseHlsMasterVariants as p, needsHostCheck as q, resolveExistingJsonPath as r, sumHlsSegmentDurations as s, rewriteRefHost as t, uploadRemoteFile as u, validateJsonValuesEntries as v, fallbackRemoteHost as w, checkRemoteFiles as x, ValServer as y, createValRequestHandler as z };
11578
+ export { needsHostCheck as A, rewriteRefHost as B, fallbackRemoteHost as C, DEFAULT_ANALYTICS_INGEST_URL as D, checkRemoteFiles as E, ValServer as F, createValRequestHandler as G, getNewJsonEntryPaths as H, formatPatchSourceError as I, askOncePerHost as J, getSettings as K, InMemoryPatchStore as L, bytesToBase64 as M, bytesToUtf8 as N, posixPath as O, ValOps as V, rebaseContentOp as a, byUpdatedAt as b, classifyJsonValuesOp as c, isSketchpadId as d, applySketchpadChange as e, findNestedJsonValuesRecords as f, bufferFromDataUrl as g, getFieldsForType as h, isJsonValuesRootOp as i, getFileExt as j, guessMimeTypeFromPath as k, createMetadataFromBuffer as l, matchesFilter as m, newSketchpad as n, ValOpsMemory as o, isHlsMasterPlaylist as p, sumHlsSegmentDurations as q, resolveExistingJsonPath as r, summaryOf as s, parseHlsMasterVariants as t, uploadRemoteFile as u, validateJsonValuesEntries as v, largestHlsVariant as w, fallbackRefOf as x, mapHlsUris as y, movedRemoteHost as z };
@@ -9,6 +9,7 @@ import type { ValSyntaxError, ValSyntaxErrorTree } from "./patch/ts/syntax.js";
9
9
  import { ParentPatchId } from "@valbuild/core";
10
10
  import type { ReifiedPreview } from "@valbuild/core";
11
11
  import { ValCommit, ValDeployment } from "@valbuild/shared/internal";
12
+ import type { SketchpadStore } from "./sketchpads/SketchpadStore.js";
12
13
  export type BaseSha = string & {
13
14
  readonly _tag: unique symbol;
14
15
  };
@@ -640,6 +641,11 @@ export declare abstract class ValOps {
640
641
  * narrow on it with type-only imports.
641
642
  */
642
643
  abstract readonly kind: "fs" | "http" | "memory";
644
+ /**
645
+ * The project's sketchpads, kept wherever this mode keeps things: see
646
+ * `sketchpads/SketchpadStore.ts`. Not patches, and never published.
647
+ */
648
+ abstract readonly sketchpads: SketchpadStore;
643
649
  abstract onInit(baseSha: BaseSha, schemaSha: SchemaSha): Promise<void>;
644
650
  abstract fetchPatches<ExcludePatchOps extends boolean>(filters: {
645
651
  patchIds?: PatchId[];