@valbuild/server 0.150.16 → 0.150.18

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,33 @@
1
1
  # @valbuild/server
2
2
 
3
+ ## 0.150.18
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [[`43f72c8`](https://github.com/valbuild/val/commit/43f72c85c2114fe9a0ce536204858d2d3c05f962)]:
8
+ - @valbuild/shared@0.150.18
9
+ - @valbuild/ui@0.150.18
10
+
11
+ ## 0.150.17
12
+
13
+ ### Patch Changes
14
+
15
+ - [#992](https://github.com/valbuild/val/pull/992) [`ea3bf9b`](https://github.com/valbuild/val/commit/ea3bf9bbacd22bbb5485fd798d6b3a2d5916be81) Thanks [@freekh](https://github.com/freekh)! - Content analytics now counts on self-hosted sites (Custom hosting), not only on sites Val hosts.
16
+
17
+ A self-hosted app's own Val server now hands each analytics beacon on to Val's ingest, which counts it. To turn it on:
18
+
19
+ - Run the app with Val's content service: `VAL_API_KEY`, `VAL_SECRET` and `VAL_PROJECT` set. Most deployed apps already do.
20
+ - Set `VAL_ANALYTICS=true`. In TanStack Start, read it in your layout's loader (`{ enabled: process.env.VAL_ANALYTICS === "true" }`) and pass the result to `<ValProvider analytics>`. A self-hosted site has no platform to pass it for you.
21
+ - Switch analytics on for the project in Val's admin. While it is off there, the script on your pages is told so and stops sending.
22
+
23
+ The server forwards only same-origin beacons from a browser. It passes on the visitor's User-Agent and, where your host provides one (Vercel, Cloudflare or CloudFront), their country. It never passes on their IP address. If the api key is not accepted, the server logs one warning naming `VAL_API_KEY` and `VAL_PROJECT`. Local development (fs mode) works as before and counts nothing.
24
+
25
+ `VAL_ANALYTICS_INGEST_URL` overrides where beacons are sent. You will normally not need it.
26
+
27
+ - Updated dependencies [[`ea3bf9b`](https://github.com/valbuild/val/commit/ea3bf9bbacd22bbb5485fd798d6b3a2d5916be81)]:
28
+ - @valbuild/shared@0.150.17
29
+ - @valbuild/ui@0.150.16
30
+
3
31
  ## 0.150.16
4
32
 
5
33
  ### Patch Changes
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var core = require('@valbuild/core');
6
- var ValRouterCore = require('../../dist/ValRouterCore-4b42da9b.cjs.dev.js');
6
+ var ValRouterCore = require('../../dist/ValRouterCore-11a7abc7.cjs.dev.js');
7
7
  require('@valbuild/shared/internal');
8
8
  require('zod');
9
9
  require('zod-validation-error');
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var core = require('@valbuild/core');
6
- var ValRouterCore = require('../../dist/ValRouterCore-4ea2110e.cjs.prod.js');
6
+ var ValRouterCore = require('../../dist/ValRouterCore-35c1c490.cjs.prod.js');
7
7
  require('@valbuild/shared/internal');
8
8
  require('zod');
9
9
  require('zod-validation-error');
@@ -1,5 +1,5 @@
1
1
  import { DEFAULT_CONTENT_HOST } from '@valbuild/core';
2
- import { o as ValOpsMemory, L as bytesToBase64, E as ValServer, F as createValRequestHandler } from '../../dist/ValRouterCore-c250061f.esm.js';
2
+ import { o as ValOpsMemory, M as bytesToBase64, F as ValServer, G as createValRequestHandler } from '../../dist/ValRouterCore-94579e4e.esm.js';
3
3
  import '@valbuild/shared/internal';
4
4
  import 'zod';
5
5
  import 'zod-validation-error';
@@ -5509,7 +5509,7 @@ var packageJson = {
5509
5509
  ],
5510
5510
  exports: true
5511
5511
  },
5512
- version: "0.150.16",
5512
+ version: "0.150.18",
5513
5513
  scripts: {
5514
5514
  typecheck: "tsc --noEmit",
5515
5515
  test: "jest",
@@ -5785,6 +5785,164 @@ function failed(error) {
5785
5785
  };
5786
5786
  }
5787
5787
 
5788
+ /**
5789
+ * Content analytics on a SELF-HOSTED site: handing a visitor's beacon on to
5790
+ * Val's ingest, which counts it.
5791
+ *
5792
+ * On a site Val hosts, the platform's loader answers `POST /api/val/analytics`
5793
+ * before the app sees it. Anywhere else the beacon reaches this server, and
5794
+ * the only thing that can count it is the ingest -- which only takes it from a
5795
+ * server holding the project's api key, so the browser cannot send it there
5796
+ * itself.
5797
+ *
5798
+ * Kept out of `ValServer.ts` so it can be tested on its own, and free of Node
5799
+ * for the same reason the rest of the request handlers are: the demo runs
5800
+ * them in a browser tab (`noNodeFromBrowser.test.ts`).
5801
+ */
5802
+
5803
+ /** Where beacons go, unless `VAL_ANALYTICS_INGEST_URL` says otherwise. */
5804
+ const DEFAULT_ANALYTICS_INGEST_URL = "https://platform.valstart.dev/__ingest/analytics";
5805
+
5806
+ /**
5807
+ * The most the ingest takes: it answers 413 above this. The browser script
5808
+ * keeps its beacons well below it (`MAX_BEACON_BYTES` in
5809
+ * `@valbuild/react/analytics`), so one that is not was not built by it.
5810
+ */
5811
+ const MAX_FORWARDED_BEACON_BYTES = 16 * 1024;
5812
+
5813
+ /** A forward is a visitor's request waiting on another one, so it is short. */
5814
+ const ANALYTICS_FORWARD_TIMEOUT_MS = 3_000;
5815
+
5816
+ /**
5817
+ * The request headers the route reads, by lower-case name. Declared on the
5818
+ * route (`Api["/analytics"]`), so the router hands over these and no others:
5819
+ * the visitor's IP is never among them.
5820
+ */
5821
+
5822
+ /**
5823
+ * Where hosts in front of an app say which country a request came from, in
5824
+ * the order they are asked. Each is set by the host, never by the browser.
5825
+ */
5826
+ const COUNTRY_HEADERS = ["x-vercel-ip-country", "cf-ipcountry", "cloudfront-viewer-country"];
5827
+
5828
+ /**
5829
+ * The visitor's country, as ISO 3166-1 alpha-2, when a host in front of the
5830
+ * app said: the first of {@link COUNTRY_HEADERS} that holds two letters.
5831
+ *
5832
+ * Anything else is skipped rather than passed on: Cloudflare's `T1` (Tor)
5833
+ * is not a country, and `XX` is how it says it does not know.
5834
+ */
5835
+ function visitorCountry(headers) {
5836
+ for (const name of COUNTRY_HEADERS) {
5837
+ var _headers$name;
5838
+ const value = (_headers$name = headers[name]) === null || _headers$name === void 0 ? void 0 : _headers$name.trim();
5839
+ if (value && /^[A-Za-z]{2}$/.test(value)) {
5840
+ const country = value.toUpperCase();
5841
+ if (country !== "XX") {
5842
+ return country;
5843
+ }
5844
+ }
5845
+ }
5846
+ return undefined;
5847
+ }
5848
+
5849
+ /**
5850
+ * Why a beacon was not handed on, when the reason is the request's. Each of
5851
+ * these is answered as before -- `200 { counted: false }` -- because none of
5852
+ * them is something the script can do anything about.
5853
+ */
5854
+
5855
+ /**
5856
+ * Whether this request may be handed on, and if so what to send. The checks
5857
+ * are the ones only this server can make: a server-to-server forward loses
5858
+ * `Sec-Fetch-Site`, and the ingest would see this server's User-Agent rather
5859
+ * than the visitor's.
5860
+ */
5861
+ function prepareAnalyticsForward(headers, body) {
5862
+ // A beacon from another site's page is not one of this site's visitors.
5863
+ if (headers["sec-fetch-site"] !== "same-origin") {
5864
+ return {
5865
+ ok: false,
5866
+ reason: "not-same-origin"
5867
+ };
5868
+ }
5869
+ // The ingest tells a bot from a person by its User-Agent; without one there
5870
+ // is nothing to tell, and nothing a browser sends goes without.
5871
+ const userAgent = headers["user-agent"];
5872
+ if (!userAgent) {
5873
+ return {
5874
+ ok: false,
5875
+ reason: "no-user-agent"
5876
+ };
5877
+ }
5878
+ if (utf8ToBytes(body).length > MAX_FORWARDED_BEACON_BYTES) {
5879
+ return {
5880
+ ok: false,
5881
+ reason: "too-large"
5882
+ };
5883
+ }
5884
+ return {
5885
+ ok: true,
5886
+ userAgent,
5887
+ country: visitorCountry(headers)
5888
+ };
5889
+ }
5890
+
5891
+ /**
5892
+ * What the ingest said, or that it could not be asked: `null` for a forward
5893
+ * that threw or timed out. Never a throw -- a visitor's beacon failing to go
5894
+ * further is not the visitor's problem.
5895
+ */
5896
+ async function forwardAnalyticsBeacon(args) {
5897
+ const controller = new AbortController();
5898
+ const timer = setTimeout(() => controller.abort(), args.timeoutMs ?? ANALYTICS_FORWARD_TIMEOUT_MS);
5899
+ const headers = {
5900
+ authorization: `Bearer ${args.apiKey}`,
5901
+ "x-val-project": args.project,
5902
+ "x-val-visitor-user-agent": args.userAgent,
5903
+ "content-type": "text/plain;charset=UTF-8"
5904
+ };
5905
+ if (args.country !== undefined) {
5906
+ headers["x-val-visitor-country"] = args.country;
5907
+ }
5908
+ try {
5909
+ const res = await fetch(args.ingestUrl, {
5910
+ method: "POST",
5911
+ headers,
5912
+ body: args.body,
5913
+ signal: controller.signal
5914
+ });
5915
+ // Nothing in an answer is read but its status. Cancelled rather than left
5916
+ // for the garbage collector, which in Node holds the connection until then.
5917
+ try {
5918
+ var _res$body;
5919
+ await ((_res$body = res.body) === null || _res$body === void 0 ? void 0 : _res$body.cancel());
5920
+ } catch {
5921
+ // Already read or closed: nothing to free.
5922
+ }
5923
+ return res.status;
5924
+ } catch (err) {
5925
+ core.Internal.log.debug(`analytics: could not forward a beacon to ${args.ingestUrl}`, err);
5926
+ return null;
5927
+ } finally {
5928
+ clearTimeout(timer);
5929
+ }
5930
+ }
5931
+ let warnedUnauthorized = false;
5932
+
5933
+ /**
5934
+ * The ingest refused this server's api key: a misconfiguration the site's
5935
+ * developer can fix, and the same one on every beacon. So it is said once a
5936
+ * process, where a warning per visitor would bury everything else.
5937
+ */
5938
+ function warnAnalyticsUnauthorizedOnce(project) {
5939
+ if (warnedUnauthorized) {
5940
+ return;
5941
+ }
5942
+ warnedUnauthorized = true;
5943
+ core.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.");
5944
+ }
5945
+
5788
5946
  /** What {@link ValServerOptions.publishOverride} is given. */
5789
5947
 
5790
5948
  /** What a publish reports back, in either shape. */
@@ -6344,10 +6502,20 @@ const ValServer = (valModules, options, callbacks, platform) => {
6344
6502
  * Content analytics beacons, outside the hosted platform.
6345
6503
  *
6346
6504
  * On a site Val hosts, the platform's loader answers this route before a
6347
- * request reaches the app, and counts. Everywhere else nothing counts yet:
6348
- * this checks the beacon and answers, so a site with analytics on does not
6349
- * fill its visitors' consoles with 404s. In local dev it also logs a line
6350
- * per beacon, which is how the showcase shows analytics working.
6505
+ * request reaches the app, and counts.
6506
+ *
6507
+ * A SELF-HOSTED site in http mode has the project's api key, and hands
6508
+ * each beacon on to Val's ingest, which counts it (`analyticsForward.ts`).
6509
+ * For that the site needs `VAL_API_KEY` and `VAL_PROJECT` (which http
6510
+ * mode needs anyway), the script started -- `VAL_ANALYTICS`, read by the
6511
+ * layout and passed to `<ValProvider analytics>` -- and analytics switched
6512
+ * on for the project in Val's admin. While it is off there, the ingest
6513
+ * answers 410, which is passed on, and the script stops.
6514
+ *
6515
+ * Everywhere else -- fs mode, memory mode -- nothing counts: this checks
6516
+ * the beacon and answers, so a site with analytics on does not fill its
6517
+ * visitors' consoles with 404s. In local dev it also logs a line per
6518
+ * beacon, which is how the showcase shows analytics working.
6351
6519
  */
6352
6520
  "/analytics": {
6353
6521
  POST: async req => {
@@ -6376,10 +6544,52 @@ const ValServer = (valModules, options, callbacks, platform) => {
6376
6544
  const count = paths => Object.values(paths).reduce((n, list) => n + list.length, 0);
6377
6545
  core.Internal.log.debug(`analytics: ${beacon.route}${beacon.view ? " (page view)" : ""}: ${count(beacon.rendered)} rendered, ${count(beacon.viewed)} viewed`);
6378
6546
  }
6547
+ if (options.mode !== "http") {
6548
+ return {
6549
+ status: 200,
6550
+ json: {
6551
+ counted: false
6552
+ }
6553
+ };
6554
+ }
6555
+ const body = JSON.stringify(parsed.data);
6556
+ const plan = prepareAnalyticsForward(req.headers, body);
6557
+ if (!plan.ok) {
6558
+ core.Internal.log.debug(`analytics: not forwarded (${plan.reason})`);
6559
+ return {
6560
+ status: 200,
6561
+ json: {
6562
+ counted: false
6563
+ }
6564
+ };
6565
+ }
6566
+ const ingestStatus = await forwardAnalyticsBeacon({
6567
+ ingestUrl: options.valAnalyticsIngestUrl ?? DEFAULT_ANALYTICS_INGEST_URL,
6568
+ apiKey: options.apiKey,
6569
+ project: options.project,
6570
+ body,
6571
+ userAgent: plan.userAgent,
6572
+ country: plan.country
6573
+ });
6574
+ if (ingestStatus === 410) {
6575
+ // Off for this project: the script stops on a 410, so it is passed
6576
+ // on rather than answered as "not counted", which it would retry.
6577
+ return {
6578
+ status: 410,
6579
+ json: {
6580
+ message: "Content analytics is switched off for this project."
6581
+ }
6582
+ };
6583
+ }
6584
+ if (ingestStatus === 401) {
6585
+ warnAnalyticsUnauthorizedOnce(options.project);
6586
+ } else if (ingestStatus !== null && ingestStatus !== 204) {
6587
+ core.Internal.log.debug(`analytics: the ingest answered ${ingestStatus} to a beacon`);
6588
+ }
6379
6589
  return {
6380
6590
  status: 200,
6381
6591
  json: {
6382
- counted: false
6592
+ counted: ingestStatus === 204
6383
6593
  }
6384
6594
  };
6385
6595
  }
@@ -9485,7 +9695,7 @@ const ValServer = (valModules, options, callbacks, platform) => {
9485
9695
  // TypeScript compiler. See `patch/ts/publishKit.ts`.
9486
9696
  const {
9487
9697
  getJsonEntryAtCommit
9488
- } = await Promise.resolve().then(function () { return require('./getJsonEntryAtCommit-971b7bbe.cjs.dev.js'); });
9698
+ } = await Promise.resolve().then(function () { return require('./getJsonEntryAtCommit-1396c247.cjs.dev.js'); });
9489
9699
  const res = await getJsonEntryAtCommit(serverOps, req.query.commit_sha, req.query.path, req.query.key);
9490
9700
  if (fp.result.isErr(res)) {
9491
9701
  return historyErrorResponse(res.error);
@@ -11371,6 +11581,7 @@ function getCookies(req, cookiesDef) {
11371
11581
  return z.z.object(cookiesDef).safeParse(input);
11372
11582
  }
11373
11583
 
11584
+ exports.DEFAULT_ANALYTICS_INGEST_URL = DEFAULT_ANALYTICS_INGEST_URL;
11374
11585
  exports.InMemoryPatchStore = InMemoryPatchStore;
11375
11586
  exports.ValOps = ValOps;
11376
11587
  exports.ValOpsMemory = ValOpsMemory;
@@ -5509,7 +5509,7 @@ var packageJson = {
5509
5509
  ],
5510
5510
  exports: true
5511
5511
  },
5512
- version: "0.150.16",
5512
+ version: "0.150.18",
5513
5513
  scripts: {
5514
5514
  typecheck: "tsc --noEmit",
5515
5515
  test: "jest",
@@ -5785,6 +5785,164 @@ function failed(error) {
5785
5785
  };
5786
5786
  }
5787
5787
 
5788
+ /**
5789
+ * Content analytics on a SELF-HOSTED site: handing a visitor's beacon on to
5790
+ * Val's ingest, which counts it.
5791
+ *
5792
+ * On a site Val hosts, the platform's loader answers `POST /api/val/analytics`
5793
+ * before the app sees it. Anywhere else the beacon reaches this server, and
5794
+ * the only thing that can count it is the ingest -- which only takes it from a
5795
+ * server holding the project's api key, so the browser cannot send it there
5796
+ * itself.
5797
+ *
5798
+ * Kept out of `ValServer.ts` so it can be tested on its own, and free of Node
5799
+ * for the same reason the rest of the request handlers are: the demo runs
5800
+ * them in a browser tab (`noNodeFromBrowser.test.ts`).
5801
+ */
5802
+
5803
+ /** Where beacons go, unless `VAL_ANALYTICS_INGEST_URL` says otherwise. */
5804
+ const DEFAULT_ANALYTICS_INGEST_URL = "https://platform.valstart.dev/__ingest/analytics";
5805
+
5806
+ /**
5807
+ * The most the ingest takes: it answers 413 above this. The browser script
5808
+ * keeps its beacons well below it (`MAX_BEACON_BYTES` in
5809
+ * `@valbuild/react/analytics`), so one that is not was not built by it.
5810
+ */
5811
+ const MAX_FORWARDED_BEACON_BYTES = 16 * 1024;
5812
+
5813
+ /** A forward is a visitor's request waiting on another one, so it is short. */
5814
+ const ANALYTICS_FORWARD_TIMEOUT_MS = 3_000;
5815
+
5816
+ /**
5817
+ * The request headers the route reads, by lower-case name. Declared on the
5818
+ * route (`Api["/analytics"]`), so the router hands over these and no others:
5819
+ * the visitor's IP is never among them.
5820
+ */
5821
+
5822
+ /**
5823
+ * Where hosts in front of an app say which country a request came from, in
5824
+ * the order they are asked. Each is set by the host, never by the browser.
5825
+ */
5826
+ const COUNTRY_HEADERS = ["x-vercel-ip-country", "cf-ipcountry", "cloudfront-viewer-country"];
5827
+
5828
+ /**
5829
+ * The visitor's country, as ISO 3166-1 alpha-2, when a host in front of the
5830
+ * app said: the first of {@link COUNTRY_HEADERS} that holds two letters.
5831
+ *
5832
+ * Anything else is skipped rather than passed on: Cloudflare's `T1` (Tor)
5833
+ * is not a country, and `XX` is how it says it does not know.
5834
+ */
5835
+ function visitorCountry(headers) {
5836
+ for (const name of COUNTRY_HEADERS) {
5837
+ var _headers$name;
5838
+ const value = (_headers$name = headers[name]) === null || _headers$name === void 0 ? void 0 : _headers$name.trim();
5839
+ if (value && /^[A-Za-z]{2}$/.test(value)) {
5840
+ const country = value.toUpperCase();
5841
+ if (country !== "XX") {
5842
+ return country;
5843
+ }
5844
+ }
5845
+ }
5846
+ return undefined;
5847
+ }
5848
+
5849
+ /**
5850
+ * Why a beacon was not handed on, when the reason is the request's. Each of
5851
+ * these is answered as before -- `200 { counted: false }` -- because none of
5852
+ * them is something the script can do anything about.
5853
+ */
5854
+
5855
+ /**
5856
+ * Whether this request may be handed on, and if so what to send. The checks
5857
+ * are the ones only this server can make: a server-to-server forward loses
5858
+ * `Sec-Fetch-Site`, and the ingest would see this server's User-Agent rather
5859
+ * than the visitor's.
5860
+ */
5861
+ function prepareAnalyticsForward(headers, body) {
5862
+ // A beacon from another site's page is not one of this site's visitors.
5863
+ if (headers["sec-fetch-site"] !== "same-origin") {
5864
+ return {
5865
+ ok: false,
5866
+ reason: "not-same-origin"
5867
+ };
5868
+ }
5869
+ // The ingest tells a bot from a person by its User-Agent; without one there
5870
+ // is nothing to tell, and nothing a browser sends goes without.
5871
+ const userAgent = headers["user-agent"];
5872
+ if (!userAgent) {
5873
+ return {
5874
+ ok: false,
5875
+ reason: "no-user-agent"
5876
+ };
5877
+ }
5878
+ if (utf8ToBytes(body).length > MAX_FORWARDED_BEACON_BYTES) {
5879
+ return {
5880
+ ok: false,
5881
+ reason: "too-large"
5882
+ };
5883
+ }
5884
+ return {
5885
+ ok: true,
5886
+ userAgent,
5887
+ country: visitorCountry(headers)
5888
+ };
5889
+ }
5890
+
5891
+ /**
5892
+ * What the ingest said, or that it could not be asked: `null` for a forward
5893
+ * that threw or timed out. Never a throw -- a visitor's beacon failing to go
5894
+ * further is not the visitor's problem.
5895
+ */
5896
+ async function forwardAnalyticsBeacon(args) {
5897
+ const controller = new AbortController();
5898
+ const timer = setTimeout(() => controller.abort(), args.timeoutMs ?? ANALYTICS_FORWARD_TIMEOUT_MS);
5899
+ const headers = {
5900
+ authorization: `Bearer ${args.apiKey}`,
5901
+ "x-val-project": args.project,
5902
+ "x-val-visitor-user-agent": args.userAgent,
5903
+ "content-type": "text/plain;charset=UTF-8"
5904
+ };
5905
+ if (args.country !== undefined) {
5906
+ headers["x-val-visitor-country"] = args.country;
5907
+ }
5908
+ try {
5909
+ const res = await fetch(args.ingestUrl, {
5910
+ method: "POST",
5911
+ headers,
5912
+ body: args.body,
5913
+ signal: controller.signal
5914
+ });
5915
+ // Nothing in an answer is read but its status. Cancelled rather than left
5916
+ // for the garbage collector, which in Node holds the connection until then.
5917
+ try {
5918
+ var _res$body;
5919
+ await ((_res$body = res.body) === null || _res$body === void 0 ? void 0 : _res$body.cancel());
5920
+ } catch {
5921
+ // Already read or closed: nothing to free.
5922
+ }
5923
+ return res.status;
5924
+ } catch (err) {
5925
+ core.Internal.log.debug(`analytics: could not forward a beacon to ${args.ingestUrl}`, err);
5926
+ return null;
5927
+ } finally {
5928
+ clearTimeout(timer);
5929
+ }
5930
+ }
5931
+ let warnedUnauthorized = false;
5932
+
5933
+ /**
5934
+ * The ingest refused this server's api key: a misconfiguration the site's
5935
+ * developer can fix, and the same one on every beacon. So it is said once a
5936
+ * process, where a warning per visitor would bury everything else.
5937
+ */
5938
+ function warnAnalyticsUnauthorizedOnce(project) {
5939
+ if (warnedUnauthorized) {
5940
+ return;
5941
+ }
5942
+ warnedUnauthorized = true;
5943
+ core.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.");
5944
+ }
5945
+
5788
5946
  /** What {@link ValServerOptions.publishOverride} is given. */
5789
5947
 
5790
5948
  /** What a publish reports back, in either shape. */
@@ -6344,10 +6502,20 @@ const ValServer = (valModules, options, callbacks, platform) => {
6344
6502
  * Content analytics beacons, outside the hosted platform.
6345
6503
  *
6346
6504
  * On a site Val hosts, the platform's loader answers this route before a
6347
- * request reaches the app, and counts. Everywhere else nothing counts yet:
6348
- * this checks the beacon and answers, so a site with analytics on does not
6349
- * fill its visitors' consoles with 404s. In local dev it also logs a line
6350
- * per beacon, which is how the showcase shows analytics working.
6505
+ * request reaches the app, and counts.
6506
+ *
6507
+ * A SELF-HOSTED site in http mode has the project's api key, and hands
6508
+ * each beacon on to Val's ingest, which counts it (`analyticsForward.ts`).
6509
+ * For that the site needs `VAL_API_KEY` and `VAL_PROJECT` (which http
6510
+ * mode needs anyway), the script started -- `VAL_ANALYTICS`, read by the
6511
+ * layout and passed to `<ValProvider analytics>` -- and analytics switched
6512
+ * on for the project in Val's admin. While it is off there, the ingest
6513
+ * answers 410, which is passed on, and the script stops.
6514
+ *
6515
+ * Everywhere else -- fs mode, memory mode -- nothing counts: this checks
6516
+ * the beacon and answers, so a site with analytics on does not fill its
6517
+ * visitors' consoles with 404s. In local dev it also logs a line per
6518
+ * beacon, which is how the showcase shows analytics working.
6351
6519
  */
6352
6520
  "/analytics": {
6353
6521
  POST: async req => {
@@ -6376,10 +6544,52 @@ const ValServer = (valModules, options, callbacks, platform) => {
6376
6544
  const count = paths => Object.values(paths).reduce((n, list) => n + list.length, 0);
6377
6545
  core.Internal.log.debug(`analytics: ${beacon.route}${beacon.view ? " (page view)" : ""}: ${count(beacon.rendered)} rendered, ${count(beacon.viewed)} viewed`);
6378
6546
  }
6547
+ if (options.mode !== "http") {
6548
+ return {
6549
+ status: 200,
6550
+ json: {
6551
+ counted: false
6552
+ }
6553
+ };
6554
+ }
6555
+ const body = JSON.stringify(parsed.data);
6556
+ const plan = prepareAnalyticsForward(req.headers, body);
6557
+ if (!plan.ok) {
6558
+ core.Internal.log.debug(`analytics: not forwarded (${plan.reason})`);
6559
+ return {
6560
+ status: 200,
6561
+ json: {
6562
+ counted: false
6563
+ }
6564
+ };
6565
+ }
6566
+ const ingestStatus = await forwardAnalyticsBeacon({
6567
+ ingestUrl: options.valAnalyticsIngestUrl ?? DEFAULT_ANALYTICS_INGEST_URL,
6568
+ apiKey: options.apiKey,
6569
+ project: options.project,
6570
+ body,
6571
+ userAgent: plan.userAgent,
6572
+ country: plan.country
6573
+ });
6574
+ if (ingestStatus === 410) {
6575
+ // Off for this project: the script stops on a 410, so it is passed
6576
+ // on rather than answered as "not counted", which it would retry.
6577
+ return {
6578
+ status: 410,
6579
+ json: {
6580
+ message: "Content analytics is switched off for this project."
6581
+ }
6582
+ };
6583
+ }
6584
+ if (ingestStatus === 401) {
6585
+ warnAnalyticsUnauthorizedOnce(options.project);
6586
+ } else if (ingestStatus !== null && ingestStatus !== 204) {
6587
+ core.Internal.log.debug(`analytics: the ingest answered ${ingestStatus} to a beacon`);
6588
+ }
6379
6589
  return {
6380
6590
  status: 200,
6381
6591
  json: {
6382
- counted: false
6592
+ counted: ingestStatus === 204
6383
6593
  }
6384
6594
  };
6385
6595
  }
@@ -9485,7 +9695,7 @@ const ValServer = (valModules, options, callbacks, platform) => {
9485
9695
  // TypeScript compiler. See `patch/ts/publishKit.ts`.
9486
9696
  const {
9487
9697
  getJsonEntryAtCommit
9488
- } = await Promise.resolve().then(function () { return require('./getJsonEntryAtCommit-ece4f965.cjs.prod.js'); });
9698
+ } = await Promise.resolve().then(function () { return require('./getJsonEntryAtCommit-908d12f5.cjs.prod.js'); });
9489
9699
  const res = await getJsonEntryAtCommit(serverOps, req.query.commit_sha, req.query.path, req.query.key);
9490
9700
  if (fp.result.isErr(res)) {
9491
9701
  return historyErrorResponse(res.error);
@@ -11371,6 +11581,7 @@ function getCookies(req, cookiesDef) {
11371
11581
  return z.z.object(cookiesDef).safeParse(input);
11372
11582
  }
11373
11583
 
11584
+ exports.DEFAULT_ANALYTICS_INGEST_URL = DEFAULT_ANALYTICS_INGEST_URL;
11374
11585
  exports.InMemoryPatchStore = InMemoryPatchStore;
11375
11586
  exports.ValOps = ValOps;
11376
11587
  exports.ValOpsMemory = ValOpsMemory;
@@ -5503,7 +5503,7 @@ var packageJson = {
5503
5503
  ],
5504
5504
  exports: true
5505
5505
  },
5506
- version: "0.150.16",
5506
+ version: "0.150.18",
5507
5507
  scripts: {
5508
5508
  typecheck: "tsc --noEmit",
5509
5509
  test: "jest",
@@ -5779,6 +5779,164 @@ function failed(error) {
5779
5779
  };
5780
5780
  }
5781
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
+
5782
5940
  /** What {@link ValServerOptions.publishOverride} is given. */
5783
5941
 
5784
5942
  /** What a publish reports back, in either shape. */
@@ -6338,10 +6496,20 @@ const ValServer = (valModules, options, callbacks, platform) => {
6338
6496
  * Content analytics beacons, outside the hosted platform.
6339
6497
  *
6340
6498
  * On a site Val hosts, the platform's loader answers this route before a
6341
- * request reaches the app, and counts. Everywhere else nothing counts yet:
6342
- * this checks the beacon and answers, so a site with analytics on does not
6343
- * fill its visitors' consoles with 404s. In local dev it also logs a line
6344
- * 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.
6345
6513
  */
6346
6514
  "/analytics": {
6347
6515
  POST: async req => {
@@ -6370,10 +6538,52 @@ const ValServer = (valModules, options, callbacks, platform) => {
6370
6538
  const count = paths => Object.values(paths).reduce((n, list) => n + list.length, 0);
6371
6539
  Internal.log.debug(`analytics: ${beacon.route}${beacon.view ? " (page view)" : ""}: ${count(beacon.rendered)} rendered, ${count(beacon.viewed)} viewed`);
6372
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
+ }
6373
6583
  return {
6374
6584
  status: 200,
6375
6585
  json: {
6376
- counted: false
6586
+ counted: ingestStatus === 204
6377
6587
  }
6378
6588
  };
6379
6589
  }
@@ -9479,7 +9689,7 @@ const ValServer = (valModules, options, callbacks, platform) => {
9479
9689
  // TypeScript compiler. See `patch/ts/publishKit.ts`.
9480
9690
  const {
9481
9691
  getJsonEntryAtCommit
9482
- } = await import('./getJsonEntryAtCommit-5d340344.esm.js');
9692
+ } = await import('./getJsonEntryAtCommit-4f46d3ca.esm.js');
9483
9693
  const res = await getJsonEntryAtCommit(serverOps, req.query.commit_sha, req.query.path, req.query.key);
9484
9694
  if (result.isErr(res)) {
9485
9695
  return historyErrorResponse(res.error);
@@ -11365,4 +11575,4 @@ function getCookies(req, cookiesDef) {
11365
11575
  return z.object(cookiesDef).safeParse(input);
11366
11576
  }
11367
11577
 
11368
- export { needsHostCheck as A, rewriteRefHost as B, fallbackRemoteHost as C, checkRemoteFiles as D, ValServer as E, createValRequestHandler as F, getNewJsonEntryPaths as G, formatPatchSourceError as H, askOncePerHost as I, getSettings as J, InMemoryPatchStore as K, bytesToBase64 as L, bytesToUtf8 as M, posixPath as N, 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 };
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 };
@@ -197,6 +197,18 @@ type ValServerOverrides = Partial<{
197
197
  * @example "https://content.val.build"
198
198
  */
199
199
  valContentUrl: string;
200
+ /**
201
+ * Where content analytics beacons are forwarded to be counted, on a
202
+ * self-hosted site in proxy mode. A site Val hosts never uses it: the
203
+ * platform answers `/api/val/analytics` itself.
204
+ *
205
+ * Typically this should not be set.
206
+ *
207
+ * Can also be overridden using the VAL_ANALYTICS_INGEST_URL env var.
208
+ *
209
+ * @example "https://platform.valstart.dev/__ingest/analytics"
210
+ */
211
+ valAnalyticsIngestUrl: string;
200
212
  /**
201
213
  * The full project name of the Val project.
202
214
  *
@@ -12,6 +12,13 @@ export type ValServerOptions = {
12
12
  formatter?: (code: string, filePath: string) => string | Promise<string>;
13
13
  valBuildUrl?: string;
14
14
  valContentUrl: string;
15
+ /**
16
+ * Where a self-hosted site's content analytics beacons are forwarded, in
17
+ * `http` mode. `initHandlerOptions` resolves it (the `valAnalyticsIngestUrl`
18
+ * option, then `VAL_ANALYTICS_INGEST_URL`); absent is
19
+ * {@link DEFAULT_ANALYTICS_INGEST_URL}.
20
+ */
21
+ valAnalyticsIngestUrl?: string;
15
22
  valSecret?: string;
16
23
  apiKey?: string;
17
24
  project?: string;
@@ -69,14 +69,15 @@ export declare function createValOps(valModules: ValModules, options: ValServerC
69
69
  * only `valBuildUrl` hands back the app token that becomes the session cookie,
70
70
  * so a single shared sentence would overstate one and understate the other.
71
71
  */
72
- type CredentialBearingUrl = "valBuildUrl" | "valContentUrl";
72
+ type CredentialBearingUrl = "valBuildUrl" | "valContentUrl" | "valAnalyticsIngestUrl";
73
73
  /**
74
74
  * Returns a warning if `url` would send credentials somewhere they can be read
75
75
  * off the wire, or null if it is fine.
76
76
  *
77
- * Both URLs default to https, but each is overridable - `opts.valBuildUrl` /
78
- * `VAL_BUILD_URL`, `opts.valContentUrl` / `VAL_CONTENT_URL` - and neither
79
- * override has ever been scheme-checked. Point one at a plain http host and the
77
+ * Each URL defaults to https, but each is overridable - `opts.valBuildUrl` /
78
+ * `VAL_BUILD_URL`, `opts.valContentUrl` / `VAL_CONTENT_URL`,
79
+ * `opts.valAnalyticsIngestUrl` / `VAL_ANALYTICS_INGEST_URL` - and no override
80
+ * was scheme-checked before this. Point one at a plain http host and the
80
81
  * api key goes out in clear text, and whatever comes back is whatever the
81
82
  * network says: for `valBuildUrl` that includes the app token this server
82
83
  * re-signs into the session cookie.
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  var ts = require('typescript');
4
- var ValRouterCore = require('./ValRouterCore-4b42da9b.cjs.dev.js');
4
+ var ValRouterCore = require('./ValRouterCore-11a7abc7.cjs.dev.js');
5
5
  var fp = require('@valbuild/core/fp');
6
6
  var jsonValuesModule = require('./jsonValuesModule-8ae503a8.cjs.dev.js');
7
7
  require('@valbuild/core');
@@ -1,5 +1,5 @@
1
1
  import ts from 'typescript';
2
- import { M as bytesToUtf8, N as posixPath } from './ValRouterCore-c250061f.esm.js';
2
+ import { N as bytesToUtf8, O as posixPath } from './ValRouterCore-94579e4e.esm.js';
3
3
  import { result } from '@valbuild/core/fp';
4
4
  import { a as analyzeValModule, c as analyzeJsonValuesEntries } from './jsonValuesModule-427d68c8.esm.js';
5
5
  import '@valbuild/core';
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  var ts = require('typescript');
4
- var ValRouterCore = require('./ValRouterCore-4ea2110e.cjs.prod.js');
4
+ var ValRouterCore = require('./ValRouterCore-35c1c490.cjs.prod.js');
5
5
  var fp = require('@valbuild/core/fp');
6
6
  var jsonValuesModule = require('./jsonValuesModule-d1bb8d8f.cjs.prod.js');
7
7
  require('@valbuild/core');
@@ -12,7 +12,7 @@ var path = require('path');
12
12
  var fs = require('fs');
13
13
  var vm = require('node:vm');
14
14
  var node_module = require('node:module');
15
- var ValRouterCore = require('./ValRouterCore-4b42da9b.cjs.dev.js');
15
+ var ValRouterCore = require('./ValRouterCore-11a7abc7.cjs.dev.js');
16
16
  var server = require('@valbuild/ui/server');
17
17
  var z = require('zod');
18
18
  var zodValidationError = require('zod-validation-error');
@@ -8615,6 +8615,16 @@ async function initHandlerOptions(route, opts, config) {
8615
8615
  });
8616
8616
  if (isProxyMode) {
8617
8617
  var _config$files, _opts$versions, _opts$versions2;
8618
+ /*
8619
+ * Where a self-hosted site's analytics beacons are counted. Only http mode
8620
+ * forwards them -- it is the mode with the project's api key -- so only
8621
+ * it resolves this, and only here is it checked for a plain-http host:
8622
+ * the api key goes with every beacon.
8623
+ */
8624
+ const valAnalyticsIngestUrl = opts.valAnalyticsIngestUrl || process.env.VAL_ANALYTICS_INGEST_URL || ValRouterCore.DEFAULT_ANALYTICS_INGEST_URL;
8625
+ warnIfInsecureUrls({
8626
+ valAnalyticsIngestUrl
8627
+ });
8618
8628
  /*
8619
8629
  * Why this app is in http mode, in the message that says what is missing.
8620
8630
  *
@@ -8735,6 +8745,7 @@ async function initHandlerOptions(route, opts, config) {
8735
8745
  valDisableRedirectUrl,
8736
8746
  valContentUrl,
8737
8747
  valBuildUrl,
8748
+ valAnalyticsIngestUrl,
8738
8749
  config
8739
8750
  };
8740
8751
  } else {
@@ -8849,10 +8860,11 @@ function createValOps(valModules, options) {
8849
8860
  * so a single shared sentence would overstate one and understate the other.
8850
8861
  */
8851
8862
 
8852
- const CREDENTIAL_BEARING_URLS = ["valBuildUrl", "valContentUrl"];
8863
+ const CREDENTIAL_BEARING_URLS = ["valBuildUrl", "valContentUrl", "valAnalyticsIngestUrl"];
8853
8864
  const WHAT_IS_AT_RISK = {
8854
8865
  valBuildUrl: "Val's api key is sent to this host, and the token it returns is what this server signs into the session cookie, " + "so both can be read - and the token replaced - by anyone on the network path.",
8855
- valContentUrl: "Val's api key, or the caller's personal access token, is sent to this host, " + "so it can be read by anyone on the network path."
8866
+ valContentUrl: "Val's api key, or the caller's personal access token, is sent to this host, " + "so it can be read by anyone on the network path.",
8867
+ valAnalyticsIngestUrl: "Val's api key is sent to this host with every analytics beacon, " + "so it can be read by anyone on the network path."
8856
8868
  };
8857
8869
 
8858
8870
  // NOTE: `URL.hostname` keeps the brackets on an IPv6 literal, so this is
@@ -8880,9 +8892,10 @@ function forLog(parsed) {
8880
8892
  * Returns a warning if `url` would send credentials somewhere they can be read
8881
8893
  * off the wire, or null if it is fine.
8882
8894
  *
8883
- * Both URLs default to https, but each is overridable - `opts.valBuildUrl` /
8884
- * `VAL_BUILD_URL`, `opts.valContentUrl` / `VAL_CONTENT_URL` - and neither
8885
- * override has ever been scheme-checked. Point one at a plain http host and the
8895
+ * Each URL defaults to https, but each is overridable - `opts.valBuildUrl` /
8896
+ * `VAL_BUILD_URL`, `opts.valContentUrl` / `VAL_CONTENT_URL`,
8897
+ * `opts.valAnalyticsIngestUrl` / `VAL_ANALYTICS_INGEST_URL` - and no override
8898
+ * was scheme-checked before this. Point one at a plain http host and the
8886
8899
  * api key goes out in clear text, and whatever comes back is whatever the
8887
8900
  * network says: for `valBuildUrl` that includes the app token this server
8888
8901
  * re-signs into the session cookie.
@@ -8914,7 +8927,11 @@ function insecureUrlWarning(name, url) {
8914
8927
  }
8915
8928
  function warnIfInsecureUrls(urls) {
8916
8929
  for (const name of CREDENTIAL_BEARING_URLS) {
8917
- const warning = insecureUrlWarning(name, urls[name]);
8930
+ const url = urls[name];
8931
+ if (url === undefined) {
8932
+ continue;
8933
+ }
8934
+ const warning = insecureUrlWarning(name, url);
8918
8935
  if (warning) {
8919
8936
  core.Internal.log.warn(warning);
8920
8937
  }
@@ -12,7 +12,7 @@ var path = require('path');
12
12
  var fs = require('fs');
13
13
  var vm = require('node:vm');
14
14
  var node_module = require('node:module');
15
- var ValRouterCore = require('./ValRouterCore-4ea2110e.cjs.prod.js');
15
+ var ValRouterCore = require('./ValRouterCore-35c1c490.cjs.prod.js');
16
16
  var server = require('@valbuild/ui/server');
17
17
  var z = require('zod');
18
18
  var zodValidationError = require('zod-validation-error');
@@ -8615,6 +8615,16 @@ async function initHandlerOptions(route, opts, config) {
8615
8615
  });
8616
8616
  if (isProxyMode) {
8617
8617
  var _config$files, _opts$versions, _opts$versions2;
8618
+ /*
8619
+ * Where a self-hosted site's analytics beacons are counted. Only http mode
8620
+ * forwards them -- it is the mode with the project's api key -- so only
8621
+ * it resolves this, and only here is it checked for a plain-http host:
8622
+ * the api key goes with every beacon.
8623
+ */
8624
+ const valAnalyticsIngestUrl = opts.valAnalyticsIngestUrl || process.env.VAL_ANALYTICS_INGEST_URL || ValRouterCore.DEFAULT_ANALYTICS_INGEST_URL;
8625
+ warnIfInsecureUrls({
8626
+ valAnalyticsIngestUrl
8627
+ });
8618
8628
  /*
8619
8629
  * Why this app is in http mode, in the message that says what is missing.
8620
8630
  *
@@ -8735,6 +8745,7 @@ async function initHandlerOptions(route, opts, config) {
8735
8745
  valDisableRedirectUrl,
8736
8746
  valContentUrl,
8737
8747
  valBuildUrl,
8748
+ valAnalyticsIngestUrl,
8738
8749
  config
8739
8750
  };
8740
8751
  } else {
@@ -8849,10 +8860,11 @@ function createValOps(valModules, options) {
8849
8860
  * so a single shared sentence would overstate one and understate the other.
8850
8861
  */
8851
8862
 
8852
- const CREDENTIAL_BEARING_URLS = ["valBuildUrl", "valContentUrl"];
8863
+ const CREDENTIAL_BEARING_URLS = ["valBuildUrl", "valContentUrl", "valAnalyticsIngestUrl"];
8853
8864
  const WHAT_IS_AT_RISK = {
8854
8865
  valBuildUrl: "Val's api key is sent to this host, and the token it returns is what this server signs into the session cookie, " + "so both can be read - and the token replaced - by anyone on the network path.",
8855
- valContentUrl: "Val's api key, or the caller's personal access token, is sent to this host, " + "so it can be read by anyone on the network path."
8866
+ valContentUrl: "Val's api key, or the caller's personal access token, is sent to this host, " + "so it can be read by anyone on the network path.",
8867
+ valAnalyticsIngestUrl: "Val's api key is sent to this host with every analytics beacon, " + "so it can be read by anyone on the network path."
8856
8868
  };
8857
8869
 
8858
8870
  // NOTE: `URL.hostname` keeps the brackets on an IPv6 literal, so this is
@@ -8880,9 +8892,10 @@ function forLog(parsed) {
8880
8892
  * Returns a warning if `url` would send credentials somewhere they can be read
8881
8893
  * off the wire, or null if it is fine.
8882
8894
  *
8883
- * Both URLs default to https, but each is overridable - `opts.valBuildUrl` /
8884
- * `VAL_BUILD_URL`, `opts.valContentUrl` / `VAL_CONTENT_URL` - and neither
8885
- * override has ever been scheme-checked. Point one at a plain http host and the
8895
+ * Each URL defaults to https, but each is overridable - `opts.valBuildUrl` /
8896
+ * `VAL_BUILD_URL`, `opts.valContentUrl` / `VAL_CONTENT_URL`,
8897
+ * `opts.valAnalyticsIngestUrl` / `VAL_ANALYTICS_INGEST_URL` - and no override
8898
+ * was scheme-checked before this. Point one at a plain http host and the
8886
8899
  * api key goes out in clear text, and whatever comes back is whatever the
8887
8900
  * network says: for `valBuildUrl` that includes the app token this server
8888
8901
  * re-signs into the session cookie.
@@ -8914,7 +8927,11 @@ function insecureUrlWarning(name, url) {
8914
8927
  }
8915
8928
  function warnIfInsecureUrls(urls) {
8916
8929
  for (const name of CREDENTIAL_BEARING_URLS) {
8917
- const warning = insecureUrlWarning(name, urls[name]);
8930
+ const url = urls[name];
8931
+ if (url === undefined) {
8932
+ continue;
8933
+ }
8934
+ const warning = insecureUrlWarning(name, url);
8918
8935
  if (warning) {
8919
8936
  core.Internal.log.warn(warning);
8920
8937
  }
@@ -10,8 +10,8 @@ import path from 'path';
10
10
  import fs from 'fs';
11
11
  import vm from 'node:vm';
12
12
  import { Module } from 'node:module';
13
- import { r as resolveExistingJsonPath, f as findNestedJsonValuesRecords, v as validateJsonValuesEntries, i as isJsonValuesRootOp, a as rebaseContentOp, c as classifyJsonValuesOp, s as summaryOf, m as matchesFilter, b as byUpdatedAt, n as newSketchpad, d as isSketchpadId, e as applySketchpadChange, V as ValOps, g as bufferFromDataUrl, h as getFieldsForType, u as uploadRemoteFile, j as getFileExt, k as guessMimeTypeFromPath, l as createMetadataFromBuffer, o as ValOpsMemory, p as isHlsMasterPlaylist, q as sumHlsSegmentDurations, t as parseHlsMasterVariants, w as largestHlsVariant, x as fallbackRefOf, y as mapHlsUris, z as movedRemoteHost, A as needsHostCheck, B as rewriteRefHost, C as fallbackRemoteHost, D as checkRemoteFiles, E as ValServer, F as createValRequestHandler, G as getNewJsonEntryPaths, H as formatPatchSourceError } from './ValRouterCore-c250061f.esm.js';
14
- export { K as InMemoryPatchStore, o as ValOpsMemory, I as askOncePerHost, c as classifyJsonValuesOp, H as formatPatchSourceError, j as getFileExt, J as getSettings, a as rebaseContentOp, u as uploadRemoteFile } from './ValRouterCore-c250061f.esm.js';
13
+ import { r as resolveExistingJsonPath, f as findNestedJsonValuesRecords, v as validateJsonValuesEntries, i as isJsonValuesRootOp, a as rebaseContentOp, c as classifyJsonValuesOp, s as summaryOf, m as matchesFilter, b as byUpdatedAt, n as newSketchpad, d as isSketchpadId, e as applySketchpadChange, V as ValOps, g as bufferFromDataUrl, h as getFieldsForType, u as uploadRemoteFile, j as getFileExt, k as guessMimeTypeFromPath, l as createMetadataFromBuffer, D as DEFAULT_ANALYTICS_INGEST_URL, o as ValOpsMemory, p as isHlsMasterPlaylist, q as sumHlsSegmentDurations, t as parseHlsMasterVariants, w as largestHlsVariant, x as fallbackRefOf, y as mapHlsUris, z as movedRemoteHost, A as needsHostCheck, B as rewriteRefHost, C as fallbackRemoteHost, E as checkRemoteFiles, F as ValServer, G as createValRequestHandler, H as getNewJsonEntryPaths, I as formatPatchSourceError } from './ValRouterCore-94579e4e.esm.js';
14
+ export { L as InMemoryPatchStore, o as ValOpsMemory, J as askOncePerHost, c as classifyJsonValuesOp, I as formatPatchSourceError, j as getFileExt, K as getSettings, a as rebaseContentOp, u as uploadRemoteFile } from './ValRouterCore-94579e4e.esm.js';
15
15
  import { createUIRequestHandler } from '@valbuild/ui/server';
16
16
  import z$1, { z } from 'zod';
17
17
  import { fromError } from 'zod-validation-error';
@@ -8579,6 +8579,16 @@ async function initHandlerOptions(route, opts, config) {
8579
8579
  });
8580
8580
  if (isProxyMode) {
8581
8581
  var _config$files, _opts$versions, _opts$versions2;
8582
+ /*
8583
+ * Where a self-hosted site's analytics beacons are counted. Only http mode
8584
+ * forwards them -- it is the mode with the project's api key -- so only
8585
+ * it resolves this, and only here is it checked for a plain-http host:
8586
+ * the api key goes with every beacon.
8587
+ */
8588
+ const valAnalyticsIngestUrl = opts.valAnalyticsIngestUrl || process.env.VAL_ANALYTICS_INGEST_URL || DEFAULT_ANALYTICS_INGEST_URL;
8589
+ warnIfInsecureUrls({
8590
+ valAnalyticsIngestUrl
8591
+ });
8582
8592
  /*
8583
8593
  * Why this app is in http mode, in the message that says what is missing.
8584
8594
  *
@@ -8699,6 +8709,7 @@ async function initHandlerOptions(route, opts, config) {
8699
8709
  valDisableRedirectUrl,
8700
8710
  valContentUrl,
8701
8711
  valBuildUrl,
8712
+ valAnalyticsIngestUrl,
8702
8713
  config
8703
8714
  };
8704
8715
  } else {
@@ -8813,10 +8824,11 @@ function createValOps(valModules, options) {
8813
8824
  * so a single shared sentence would overstate one and understate the other.
8814
8825
  */
8815
8826
 
8816
- const CREDENTIAL_BEARING_URLS = ["valBuildUrl", "valContentUrl"];
8827
+ const CREDENTIAL_BEARING_URLS = ["valBuildUrl", "valContentUrl", "valAnalyticsIngestUrl"];
8817
8828
  const WHAT_IS_AT_RISK = {
8818
8829
  valBuildUrl: "Val's api key is sent to this host, and the token it returns is what this server signs into the session cookie, " + "so both can be read - and the token replaced - by anyone on the network path.",
8819
- valContentUrl: "Val's api key, or the caller's personal access token, is sent to this host, " + "so it can be read by anyone on the network path."
8830
+ valContentUrl: "Val's api key, or the caller's personal access token, is sent to this host, " + "so it can be read by anyone on the network path.",
8831
+ valAnalyticsIngestUrl: "Val's api key is sent to this host with every analytics beacon, " + "so it can be read by anyone on the network path."
8820
8832
  };
8821
8833
 
8822
8834
  // NOTE: `URL.hostname` keeps the brackets on an IPv6 literal, so this is
@@ -8844,9 +8856,10 @@ function forLog(parsed) {
8844
8856
  * Returns a warning if `url` would send credentials somewhere they can be read
8845
8857
  * off the wire, or null if it is fine.
8846
8858
  *
8847
- * Both URLs default to https, but each is overridable - `opts.valBuildUrl` /
8848
- * `VAL_BUILD_URL`, `opts.valContentUrl` / `VAL_CONTENT_URL` - and neither
8849
- * override has ever been scheme-checked. Point one at a plain http host and the
8859
+ * Each URL defaults to https, but each is overridable - `opts.valBuildUrl` /
8860
+ * `VAL_BUILD_URL`, `opts.valContentUrl` / `VAL_CONTENT_URL`,
8861
+ * `opts.valAnalyticsIngestUrl` / `VAL_ANALYTICS_INGEST_URL` - and no override
8862
+ * was scheme-checked before this. Point one at a plain http host and the
8850
8863
  * api key goes out in clear text, and whatever comes back is whatever the
8851
8864
  * network says: for `valBuildUrl` that includes the app token this server
8852
8865
  * re-signs into the session cookie.
@@ -8878,7 +8891,11 @@ function insecureUrlWarning(name, url) {
8878
8891
  }
8879
8892
  function warnIfInsecureUrls(urls) {
8880
8893
  for (const name of CREDENTIAL_BEARING_URLS) {
8881
- const warning = insecureUrlWarning(name, urls[name]);
8894
+ const url = urls[name];
8895
+ if (url === undefined) {
8896
+ continue;
8897
+ }
8898
+ const warning = insecureUrlWarning(name, url);
8882
8899
  if (warning) {
8883
8900
  Internal.log.warn(warning);
8884
8901
  }
package/package.json CHANGED
@@ -27,7 +27,7 @@
27
27
  ],
28
28
  "exports": true
29
29
  },
30
- "version": "0.150.16",
30
+ "version": "0.150.18",
31
31
  "devDependencies": {
32
32
  "@prettier/sync": "^0.6.1",
33
33
  "@types/jest": "^30.0.0",
@@ -42,8 +42,8 @@
42
42
  "zod": "^4.4.3",
43
43
  "zod-validation-error": "^5.0.0",
44
44
  "@valbuild/core": "0.150.3",
45
- "@valbuild/ui": "0.150.16",
46
- "@valbuild/shared": "0.150.16"
45
+ "@valbuild/ui": "0.150.18",
46
+ "@valbuild/shared": "0.150.18"
47
47
  },
48
48
  "engines": {
49
49
  "node": "^20.19.0 || >=22"