@yuneta/gobj-ui 7.27.34 → 7.28.1

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/LICENSE ADDED
@@ -0,0 +1,25 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020-2021 Niyamaka
4
+ Copyright (c) 2024-2026, ArtGins
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
23
+
24
+ Most icons of src/yui_icons.css are paths of Font Awesome Free, under the
25
+ CC BY 4.0 License: see THIRD-PARTY-NOTICES.
package/README.md CHANGED
@@ -4478,6 +4478,48 @@ export default { plugins: [ yunetaHtmlPlugin({ defaultTitle: "My App" }) ] };
4478
4478
  sorted names of the bundle's files, source maps excluded. `<version>` is the
4479
4479
  app's `package.json` version. `C_YUI_UPDATE_WATCH` reads it.
4480
4480
 
4481
+ ### `licenses.txt`: the notices of what the bundle carries
4482
+
4483
+ The bundle of an app carries code of others (gobj-js, this library, G6,
4484
+ Tabulator, i18next, Bulma ...), and every browser that loads it receives a
4485
+ copy. Their licenses ask for their notices to go with it, and Vite's
4486
+ minifier drops them all, `/*!` comments included. The vite plugin
4487
+ `yunetaLicensesPlugin` (`vite-plugin-yuneta-licenses.js`, 7.28.0) writes them
4488
+ beside the bundle at build time: `dist/licenses.txt`, served at
4489
+ `/licenses.txt`.
4490
+
4491
+ ```js
4492
+ // vite.config.js
4493
+ import { yunetaHtmlPlugin } from "@yuneta/gobj-ui/vite-plugin-yuneta-html.js";
4494
+ import { yunetaLicensesPlugin } from "@yuneta/gobj-ui/vite-plugin-yuneta-licenses.js";
4495
+ export default {
4496
+ plugins: [
4497
+ yunetaHtmlPlugin({ defaultTitle: "My App" }),
4498
+ yunetaLicensesPlugin()
4499
+ ]
4500
+ };
4501
+ ```
4502
+
4503
+ - **What is listed:** every package with a module that renders code in an
4504
+ emitted chunk, and every package whose stylesheet the bundle imports. A
4505
+ module tree-shaken to nothing is not in the bundle, so its package is not
4506
+ listed. The app's own sources are not listed. Code a package ships inside
4507
+ its own files (`@antv/layout` carries d3-force in `lib/node_modules/`) is
4508
+ listed as that package.
4509
+ - **What of each:** name, version, the license its `package.json` declares,
4510
+ its source url, and every `LICENSE` / `LICENCE` / `COPYING` / `NOTICE` /
4511
+ `THIRD-PARTY-NOTICES` file at its root. That last one is how the notice of
4512
+ `sprintf.js` (gobj-js) and the attribution of the Font Awesome icons of
4513
+ `yui_icons.css` (this library) reach the app. A package with no license
4514
+ file is listed with its declared license, and the build warns about it.
4515
+ - **Code of others that is no package** (vendored into the app's `src/`)
4516
+ goes in with `extra`:
4517
+ `yunetaLicensesPlugin({extra: [{name: "x.js (from ...)", license: "MIT", text: "..."}]})`.
4518
+ `fileName` changes the name of the file.
4519
+ - Link it from the app's "About" so a user can find it. The obligations of a
4520
+ closed app built with Yuneta are written in `OBLIGACIONES-LICENCIA.md` of
4521
+ each app.
4522
+
4481
4523
  ### Releasing
4482
4524
 
4483
4525
  `npm run build && npm test`, then `npm publish`. A published version reaches
@@ -0,0 +1,17 @@
1
+ THIRD-PARTY NOTICES
2
+ ===================
3
+
4
+ @yuneta/gobj-ui is under the MIT License of LICENSE. It carries the work of
5
+ others below, under its own license.
6
+
7
+ ------------------------------------------------------------------------------
8
+ Font Awesome Free (icons)
9
+ ------------------------------------------------------------------------------
10
+ Most icons of src/yui_icons.css are the SVG paths of Font Awesome Free (6.x
11
+ and 7.x, solid style), drawn as CSS masks; some are adjusted to their box.
12
+
13
+ Font Awesome Free by Fonticons, Inc. - https://fontawesome.com
14
+ Copyright (c) Fonticons, Inc.
15
+ The icons are licensed under the Creative Commons Attribution 4.0
16
+ International License (CC BY 4.0): https://creativecommons.org/licenses/by/4.0/
17
+ Font Awesome Free license: https://fontawesome.com/license/free
@@ -16000,6 +16000,10 @@ function register_c_yui_map() {
16000
16000
  * axes: yui_uplot_axes([{}]), // X and Y, with the ink of the theme
16001
16001
  * }, data, $el);
16002
16002
  *
16003
+ * A vertical axis is as wide as its longest label
16004
+ * (yui_uplot_axis_size, 7.28.1): uPlot's fixed 50px cut every
16005
+ * value past five digits.
16006
+ *
16003
16007
  * The palette is six colours that clear 3:1 on BOTH grounds
16004
16008
  * (worst 3.39 on white, 3.71 on near-black), ordered so the first
16005
16009
  * two are the pair that survives colour blindness -- blue and
@@ -16047,6 +16051,29 @@ var YUI_UPLOT_PALETTE = [
16047
16051
  }
16048
16052
  ];
16049
16053
  /************************************************************
16054
+ * The width of a vertical axis: its longest label, measured
16055
+ * in its own font, plus its ticks and its gap. uPlot gives a
16056
+ * Y axis a fixed 50px, which cuts any label wider than ~5
16057
+ * digits ("150,000" was drawn as ",0,000"). uPlot asks again
16058
+ * while the size settles (`cycle`): past the first answer the
16059
+ * last size stands, or the layout never converges.
16060
+ ************************************************************/
16061
+ function yui_uplot_axis_size(self, values, axis_idx, cycle) {
16062
+ let axis = self.axes[axis_idx];
16063
+ if (cycle > 1 && axis._size) return axis._size;
16064
+ let size = (axis.ticks && axis.ticks.size || 10) + (axis.gap || 5);
16065
+ let longest = (values || []).reduce((acc, v) => {
16066
+ let txt = v == null ? "" : String(v);
16067
+ return txt.length > acc.length ? txt : acc;
16068
+ }, "");
16069
+ if (longest && self.ctx) {
16070
+ self.ctx.font = Array.isArray(axis.font) ? axis.font[0] : axis.font || self.ctx.font;
16071
+ let dpr = typeof devicePixelRatio === "number" && devicePixelRatio > 0 ? devicePixelRatio : 1;
16072
+ size += self.ctx.measureText(longest).width / dpr;
16073
+ }
16074
+ return Math.max(50, Math.ceil(size));
16075
+ }
16076
+ /************************************************************
16050
16077
  * The axes the host asked for -- at least the X and the Y,
16051
16078
  * the two uPlot always draws -- with the ink it did not ask
16052
16079
  * about. A stroke, a grid or a ticks the host gave is kept.
@@ -16055,9 +16082,10 @@ var YUI_UPLOT_PALETTE = [
16055
16082
  function yui_uplot_axes(axes) {
16056
16083
  let list = Array.isArray(axes) ? axes.slice() : [axes || {}];
16057
16084
  while (list.length < 2) list.push({});
16058
- return list.map((ax) => {
16085
+ return list.map((ax, i) => {
16059
16086
  let a = Object.assign({}, ax || {});
16060
16087
  if (a.stroke === void 0) a.stroke = yui_uplot_axis_ink;
16088
+ if (i > 0 && (a.side === void 0 || a.side === 1 || a.side === 3) && a.size === void 0) a.size = yui_uplot_axis_size;
16061
16089
  a.grid = Object.assign({ stroke: yui_uplot_grid_ink }, a.grid || {});
16062
16090
  a.ticks = Object.assign({ stroke: yui_uplot_grid_ink }, a.ticks || {});
16063
16091
  return a;
@@ -15995,6 +15995,10 @@ function register_c_yui_map() {
15995
15995
  * axes: yui_uplot_axes([{}]), // X and Y, with the ink of the theme
15996
15996
  * }, data, $el);
15997
15997
  *
15998
+ * A vertical axis is as wide as its longest label
15999
+ * (yui_uplot_axis_size, 7.28.1): uPlot's fixed 50px cut every
16000
+ * value past five digits.
16001
+ *
15998
16002
  * The palette is six colours that clear 3:1 on BOTH grounds
15999
16003
  * (worst 3.39 on white, 3.71 on near-black), ordered so the first
16000
16004
  * two are the pair that survives colour blindness -- blue and
@@ -16042,6 +16046,29 @@ var YUI_UPLOT_PALETTE = [
16042
16046
  }
16043
16047
  ];
16044
16048
  /************************************************************
16049
+ * The width of a vertical axis: its longest label, measured
16050
+ * in its own font, plus its ticks and its gap. uPlot gives a
16051
+ * Y axis a fixed 50px, which cuts any label wider than ~5
16052
+ * digits ("150,000" was drawn as ",0,000"). uPlot asks again
16053
+ * while the size settles (`cycle`): past the first answer the
16054
+ * last size stands, or the layout never converges.
16055
+ ************************************************************/
16056
+ function yui_uplot_axis_size(self, values, axis_idx, cycle) {
16057
+ let axis = self.axes[axis_idx];
16058
+ if (cycle > 1 && axis._size) return axis._size;
16059
+ let size = (axis.ticks && axis.ticks.size || 10) + (axis.gap || 5);
16060
+ let longest = (values || []).reduce((acc, v) => {
16061
+ let txt = v == null ? "" : String(v);
16062
+ return txt.length > acc.length ? txt : acc;
16063
+ }, "");
16064
+ if (longest && self.ctx) {
16065
+ self.ctx.font = Array.isArray(axis.font) ? axis.font[0] : axis.font || self.ctx.font;
16066
+ let dpr = typeof devicePixelRatio === "number" && devicePixelRatio > 0 ? devicePixelRatio : 1;
16067
+ size += self.ctx.measureText(longest).width / dpr;
16068
+ }
16069
+ return Math.max(50, Math.ceil(size));
16070
+ }
16071
+ /************************************************************
16045
16072
  * The axes the host asked for -- at least the X and the Y,
16046
16073
  * the two uPlot always draws -- with the ink it did not ask
16047
16074
  * about. A stroke, a grid or a ticks the host gave is kept.
@@ -16050,9 +16077,10 @@ var YUI_UPLOT_PALETTE = [
16050
16077
  function yui_uplot_axes(axes) {
16051
16078
  let list = Array.isArray(axes) ? axes.slice() : [axes || {}];
16052
16079
  while (list.length < 2) list.push({});
16053
- return list.map((ax) => {
16080
+ return list.map((ax, i) => {
16054
16081
  let a = Object.assign({}, ax || {});
16055
16082
  if (a.stroke === void 0) a.stroke = yui_uplot_axis_ink;
16083
+ if (i > 0 && (a.side === void 0 || a.side === 1 || a.side === 3) && a.size === void 0) a.size = yui_uplot_axis_size;
16056
16084
  a.grid = Object.assign({ stroke: yui_uplot_grid_ink }, a.grid || {});
16057
16085
  a.ticks = Object.assign({ stroke: yui_uplot_grid_ink }, a.ticks || {});
16058
16086
  return a;
package/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "@yuneta/gobj-ui",
3
- "version": "7.27.34",
3
+ "version": "7.28.1",
4
+ "license": "MIT",
4
5
  "type": "module",
5
6
  "main": "dist/gobj-ui.cjs.js",
6
7
  "module": "dist/gobj-ui.es.js",
@@ -11,14 +12,17 @@
11
12
  },
12
13
  "./index.js": "./index.js",
13
14
  "./vite-plugin-yuneta-html.js": "./vite-plugin-yuneta-html.js",
15
+ "./vite-plugin-yuneta-licenses.js": "./vite-plugin-yuneta-licenses.js",
14
16
  "./src/*": "./src/*"
15
17
  },
16
18
  "files": [
19
+ "THIRD-PARTY-NOTICES",
17
20
  "dist/gobj-ui.es.js",
18
21
  "dist/gobj-ui.cjs.js",
19
22
  "index.js",
20
23
  "src/",
21
24
  "vite-plugin-yuneta-html.js",
25
+ "vite-plugin-yuneta-licenses.js",
22
26
  "scripts/check-markup-strings.mjs",
23
27
  "scripts/validate-locales.mjs"
24
28
  ],
@@ -43,7 +47,7 @@
43
47
  "devDependencies": {
44
48
  "@rollup/plugin-terser": "^1.0.2",
45
49
  "@vitest/coverage-v8": "^5.0.5",
46
- "@yuneta/gobj-js": "^7.27.0",
50
+ "@yuneta/gobj-js": "^7.28.0",
47
51
  "jsdom": "^30.1.3",
48
52
  "vite": "^8.3.5",
49
53
  "vitest": "^5.0.5"
@@ -42,7 +42,7 @@ const {
42
42
  } = await import("@yuneta/gobj-js");
43
43
  const {register_c_yui_uplot} = await import("./c_yui_uplot.js");
44
44
  const {
45
- yui_uplot_axes, yui_uplot_axis_ink, yui_uplot_grid_ink,
45
+ yui_uplot_axes, yui_uplot_axis_ink, yui_uplot_grid_ink, yui_uplot_axis_size,
46
46
  } = await import("./yui_uplot_ink.js");
47
47
 
48
48
  const logged = [];
@@ -67,6 +67,35 @@ afterEach(() => {
67
67
  document.documentElement.removeAttribute("data-theme");
68
68
  });
69
69
 
70
+ describe("the width of a vertical axis", () => {
71
+ const fake = (px_per_char) => ({
72
+ ctx: {font: "", measureText: (t) => ({width: t.length * px_per_char})},
73
+ axes: [{}, {ticks: {size: 10}, gap: 5, font: ["12px sans-serif"]}]
74
+ });
75
+
76
+ test("the Y axes are sized by their labels, the X is not; a host's size stands", () => {
77
+ const axes = yui_uplot_axes([{}, {}, {side: 1}, {side: 2}, {size: 80}]);
78
+ expect(axes[0].size).toBeUndefined();
79
+ expect(axes[1].size).toBe(yui_uplot_axis_size);
80
+ expect(axes[2].size).toBe(yui_uplot_axis_size);
81
+ expect(axes[3].size).toBeUndefined();
82
+ expect(axes[4].size).toBe(80);
83
+ });
84
+
85
+ test("fits the longest label, never under uPlot's 50px", () => {
86
+ const self = fake(7);
87
+ expect(yui_uplot_axis_size(self, ["0", "50,000", "150,000"], 1, 0)).toBe(Math.ceil(15 + 7 * 7));
88
+ expect(yui_uplot_axis_size(fake(7), ["0", "5"], 1, 0)).toBe(50);
89
+ expect(yui_uplot_axis_size(fake(7), null, 1, 0)).toBe(50);
90
+ });
91
+
92
+ test("past the first cycle the size settled stands", () => {
93
+ const self = fake(7);
94
+ self.axes[1]._size = 66;
95
+ expect(yui_uplot_axis_size(self, ["1,000,000,000"], 1, 2)).toBe(66);
96
+ });
97
+ });
98
+
70
99
  describe("yui_uplot_axes()", () => {
71
100
  test("gives the X and the Y axes, the two uPlot draws", () => {
72
101
  expect(yui_uplot_axes([{}]).length).toBe(2);
package/src/yui_icons.css CHANGED
@@ -3,6 +3,11 @@
3
3
  * Custom icon set — replaces FontAwesome for this app.
4
4
  * Usage: <i class="yi-bars"> (same pattern as FA, without style prefix class)
5
5
  * Color: inherits currentColor from parent via CSS mask.
6
+ *
7
+ * Most icons are the SVG paths of Font Awesome Free (6.x and 7.x, solid),
8
+ * some adjusted to their box: Font Awesome Free by Fonticons, Inc.,
9
+ * https://fontawesome.com, icons under the CC BY 4.0 License
10
+ * (https://creativecommons.org/licenses/by/4.0/). See THIRD-PARTY-NOTICES.
6
11
  */
7
12
 
8
13
  [class^="yi-"]::before,
@@ -28,6 +28,10 @@
28
28
  * axes: yui_uplot_axes([{}]), // X and Y, with the ink of the theme
29
29
  * }, data, $el);
30
30
  *
31
+ * A vertical axis is as wide as its longest label
32
+ * (yui_uplot_axis_size, 7.28.1): uPlot's fixed 50px cut every
33
+ * value past five digits.
34
+ *
31
35
  * The palette is six colours that clear 3:1 on BOTH grounds
32
36
  * (worst 3.39 on white, 3.71 on near-black), ordered so the first
33
37
  * two are the pair that survives colour blindness -- blue and
@@ -63,6 +67,33 @@ const YUI_UPLOT_PALETTE = [
63
67
  {stroke: "#d1344b", fill: "rgba(209,52,75,0.10)"}, /* 4.88 / 3.71 */
64
68
  ];
65
69
 
70
+ /************************************************************
71
+ * The width of a vertical axis: its longest label, measured
72
+ * in its own font, plus its ticks and its gap. uPlot gives a
73
+ * Y axis a fixed 50px, which cuts any label wider than ~5
74
+ * digits ("150,000" was drawn as ",0,000"). uPlot asks again
75
+ * while the size settles (`cycle`): past the first answer the
76
+ * last size stands, or the layout never converges.
77
+ ************************************************************/
78
+ function yui_uplot_axis_size(self, values, axis_idx, cycle)
79
+ {
80
+ let axis = self.axes[axis_idx];
81
+ if(cycle > 1 && axis._size) {
82
+ return axis._size;
83
+ }
84
+ let size = ((axis.ticks && axis.ticks.size) || 10) + (axis.gap || 5);
85
+ let longest = (values || []).reduce((acc, v) => {
86
+ let txt = v == null ? "" : String(v);
87
+ return txt.length > acc.length ? txt : acc;
88
+ }, "");
89
+ if(longest && self.ctx) {
90
+ self.ctx.font = Array.isArray(axis.font) ? axis.font[0] : (axis.font || self.ctx.font);
91
+ let dpr = (typeof devicePixelRatio === "number" && devicePixelRatio > 0) ? devicePixelRatio : 1;
92
+ size += self.ctx.measureText(longest).width / dpr;
93
+ }
94
+ return Math.max(50, Math.ceil(size));
95
+ }
96
+
66
97
  /************************************************************
67
98
  * The axes the host asked for -- at least the X and the Y,
68
99
  * the two uPlot always draws -- with the ink it did not ask
@@ -75,11 +106,17 @@ function yui_uplot_axes(axes)
75
106
  while(list.length < 2) {
76
107
  list.push({});
77
108
  }
78
- return list.map((ax) => {
109
+ return list.map((ax, i) => {
79
110
  let a = Object.assign({}, ax || {});
80
111
  if(a.stroke === undefined) {
81
112
  a.stroke = yui_uplot_axis_ink;
82
113
  }
114
+ /* A vertical axis (uPlot's sides 1 and 3; the Y default is 3)
115
+ * as wide as its labels, unless the host sized it */
116
+ let vertical = i > 0 && (a.side === undefined || a.side === 1 || a.side === 3);
117
+ if(vertical && a.size === undefined) {
118
+ a.size = yui_uplot_axis_size;
119
+ }
83
120
  a.grid = Object.assign({stroke: yui_uplot_grid_ink}, a.grid || {});
84
121
  a.ticks = Object.assign({stroke: yui_uplot_grid_ink}, a.ticks || {});
85
122
  return a;
@@ -88,6 +125,7 @@ function yui_uplot_axes(axes)
88
125
 
89
126
  export {
90
127
  yui_uplot_axes,
128
+ yui_uplot_axis_size,
91
129
  yui_uplot_axis_ink,
92
130
  yui_uplot_grid_ink,
93
131
  YUI_UPLOT_PALETTE,
@@ -0,0 +1,264 @@
1
+ /***********************************************************************
2
+ * vite-plugin-yuneta-licenses.js
3
+ *
4
+ * Vite plugin for Yuneta GUI projects: at build time it writes
5
+ * `licenses.txt` beside the bundle, with the license of every
6
+ * package whose code is IN the bundle.
7
+ *
8
+ * An app is closed or open, but the code of others inside its
9
+ * bundle is distributed to every browser that loads it, and its
10
+ * licenses (MIT, BSD, ISC, Apache-2.0, CC BY ...) ask for their
11
+ * notices to go with it. A minifier drops most of them (the
12
+ * attribution of the Font Awesome icons of yui_icons.css never
13
+ * reached a bundle; Vite 8 drops even the /*! comments), so the
14
+ * notices are gathered here instead,
15
+ * from the packages themselves.
16
+ *
17
+ * Which packages: the modules of the emitted chunks that render
18
+ * some code (a module tree-shaken to nothing is not in the
19
+ * bundle, and neither is its license), plus the stylesheets
20
+ * they import. Each module is mapped to the package that holds
21
+ * it under node_modules/; the app's own sources are not listed.
22
+ *
23
+ * What of each package: its name, version, declared license
24
+ * and source url, and the text of every LICENSE / LICENCE / COPYING /
25
+ * NOTICE / THIRD-PARTY-NOTICES file at its root -- which is how
26
+ * the notices that a package carries for code of others inside
27
+ * it (sprintf.js in gobj-js, Font Awesome in gobj-ui) come along.
28
+ * A package with no license file is listed with what its
29
+ * package.json declares, and warned about.
30
+ *
31
+ * Usage in vite.config.js:
32
+ * import {yunetaLicensesPlugin} from "@yuneta/gobj-ui/vite-plugin-yuneta-licenses.js";
33
+ * plugins: [yunetaHtmlPlugin({...}), yunetaLicensesPlugin()]
34
+ *
35
+ * Options:
36
+ * fileName: the name of the file in the bundle ("licenses.txt")
37
+ * extra: [{name, license, text}] for code of others that is
38
+ * not a package (vendored into the app's sources)
39
+ *
40
+ * Copyright (c) 2026, ArtGins.
41
+ * All Rights Reserved.
42
+ ***********************************************************************/
43
+ import fs from "fs";
44
+ import path from "path";
45
+
46
+ const LICENSE_FILE_RE = /^(licen[cs]e|copying|notice|third[-_]party[-_]notices?)([._-].*)?$/i;
47
+ const STYLESHEET_RE = /\.(css|scss|sass|less|styl)$/i;
48
+ const RULE = "-".repeat(78);
49
+
50
+ /*
51
+ * The root of the package that holds `id`, or null when it is not under
52
+ * node_modules/ (the app's own code). The LAST node_modules/ of the path
53
+ * is the one that holds it, and a scoped package takes two segments.
54
+ */
55
+ export function package_root_of(id)
56
+ {
57
+ let file = String(id).replace(/^\0/, "").split("?")[0];
58
+ let marker = `${path.sep}node_modules${path.sep}`;
59
+ let at = file.lastIndexOf(marker);
60
+ if(at < 0) {
61
+ return null;
62
+ }
63
+ let rest = file.slice(at + marker.length).split(path.sep);
64
+ let segments = rest[0].startsWith("@")? 2 : 1;
65
+ if(rest.length <= segments) {
66
+ return null;
67
+ }
68
+ return file.slice(0, at + marker.length) + rest.slice(0, segments).join(path.sep);
69
+ }
70
+
71
+ /*
72
+ * The license a package.json declares, as text: "MIT", the SPDX
73
+ * expression, or the old {type} / [{type}] forms joined with OR
74
+ */
75
+ export function declared_license(pkg)
76
+ {
77
+ let lic = pkg.license || pkg.licenses;
78
+ if(!lic) {
79
+ return "(none declared)";
80
+ }
81
+ if(typeof lic === "string") {
82
+ return lic;
83
+ }
84
+ if(Array.isArray(lic)) {
85
+ return lic.map(l => (typeof l === "string")? l : (l.type || "?")).join(" OR ");
86
+ }
87
+ return lic.type || "?";
88
+ }
89
+
90
+ /*
91
+ * Where the source of a package is: its repository, else its homepage,
92
+ * as an https url when it is one in disguise ("git+https://...git",
93
+ * "github:owner/repo"). Empty when the package says neither.
94
+ */
95
+ export function source_url(pkg)
96
+ {
97
+ let repo = pkg.repository;
98
+ let url = (typeof repo === "string")? repo : (repo && repo.url) || pkg.homepage || "";
99
+ url = String(url).trim()
100
+ .replace(/^git\+/, "")
101
+ .replace(/^git:\/\//, "https://")
102
+ .replace(/^git@github\.com:/, "https://github.com/")
103
+ .replace(/\.git$/, "");
104
+ let short = url.match(/^(github|gitlab|bitbucket):(.+)$/);
105
+ if(short) {
106
+ url = `https://${short[1]}.${short[1] === "bitbucket"? "org" : "com"}/${short[2]}`;
107
+ } else if(/^[\w.-]+\/[\w.-]+$/.test(url)) {
108
+ url = `https://github.com/${url}`;
109
+ }
110
+ return url;
111
+ }
112
+
113
+ /*
114
+ * The ids of the modules that put something in the bundle
115
+ */
116
+ export function bundled_module_ids(bundle)
117
+ {
118
+ let ids = new Set();
119
+ for(const out of Object.values(bundle)) {
120
+ if(out.type !== "chunk") {
121
+ continue;
122
+ }
123
+ let modules = out.modules || {};
124
+ let module_ids = out.moduleIds || Object.keys(modules);
125
+ for(const id of module_ids) {
126
+ let clean = String(id).split("?")[0];
127
+ let rendered = modules[id]? modules[id].renderedLength : 1;
128
+ if(rendered > 0 || STYLESHEET_RE.test(clean)) {
129
+ ids.add(id);
130
+ }
131
+ }
132
+ }
133
+ return ids;
134
+ }
135
+
136
+ /*
137
+ * The text of licenses.txt for the packages of `ids`. `warn` is told of
138
+ * a package with no license file.
139
+ */
140
+ export function build_licenses_text(ids, app, extra = [], warn = console.warn)
141
+ {
142
+ let roots = new Set();
143
+ for(const id of ids) {
144
+ let root = package_root_of(id);
145
+ if(root) {
146
+ roots.add(root);
147
+ }
148
+ }
149
+
150
+ let packages = new Map();
151
+ for(const start of roots) {
152
+ /*
153
+ * A directory under node_modules/ with no package.json is code a
154
+ * package ships inside its own files (@antv/layout carries d3-force
155
+ * and others in lib/node_modules/): it is listed as that package.
156
+ */
157
+ let root = start;
158
+ while(root && !fs.existsSync(path.join(root, "package.json"))) {
159
+ let marker = `${path.sep}node_modules${path.sep}`;
160
+ root = package_root_of(root.slice(0, root.lastIndexOf(marker)));
161
+ }
162
+ if(!root) {
163
+ warn(`yuneta-licenses: no package.json for ${start}, not listed`);
164
+ continue;
165
+ }
166
+ let pkg_path = path.join(root, "package.json");
167
+ let pkg = JSON.parse(fs.readFileSync(pkg_path, "utf-8"));
168
+ let key = `${pkg.name}@${pkg.version}`;
169
+ if(packages.has(key)) {
170
+ continue;
171
+ }
172
+ let files = fs.readdirSync(root)
173
+ .filter(name => LICENSE_FILE_RE.test(name) && fs.statSync(path.join(root, name)).isFile())
174
+ .sort((a, b) => {
175
+ let rank = (n) => /^licen[cs]e|^copying/i.test(n)? 0 : 1;
176
+ return (rank(a) - rank(b)) || a.localeCompare(b);
177
+ });
178
+ if(files.length === 0) {
179
+ warn(`yuneta-licenses: ${key} carries no license file; listed with its declared license only`);
180
+ }
181
+ packages.set(key, {
182
+ name: pkg.name,
183
+ version: pkg.version,
184
+ license: declared_license(pkg),
185
+ source: source_url(pkg),
186
+ texts: files.map(name => fs.readFileSync(path.join(root, name), "utf-8").trimEnd())
187
+ });
188
+ }
189
+
190
+ let sorted = [...packages.values()].sort((a, b) => a.name.localeCompare(b.name));
191
+
192
+ let out = [];
193
+ out.push("Licenses of the software in this application");
194
+ out.push("=".repeat(44));
195
+ out.push("");
196
+ out.push(`${app.name || "This application"}${app.version? " " + app.version : ""} includes the software ` +
197
+ "below, each part under its own license.");
198
+ out.push("This file is written at build time from the code that is in the bundle.");
199
+ out.push("");
200
+
201
+ for(const p of sorted) {
202
+ out.push(RULE);
203
+ out.push(`${p.name} ${p.version}`);
204
+ out.push(`License: ${p.license}`);
205
+ if(p.source) {
206
+ out.push(`Source: ${p.source}`);
207
+ }
208
+ out.push(RULE);
209
+ if(p.texts.length === 0) {
210
+ out.push("(The package carries no license file.)");
211
+ }
212
+ for(const text of p.texts) {
213
+ out.push(text);
214
+ out.push("");
215
+ }
216
+ out.push("");
217
+ }
218
+ for(const e of extra) {
219
+ out.push(RULE);
220
+ out.push(e.name);
221
+ out.push(`License: ${e.license || "?"}`);
222
+ out.push(RULE);
223
+ out.push(String(e.text || "").trimEnd());
224
+ out.push("");
225
+ out.push("");
226
+ }
227
+ return out.join("\n");
228
+ }
229
+
230
+ /**
231
+ * @param {object} [options]
232
+ * @param {string} [options.fileName] - The file in the bundle (default licenses.txt)
233
+ * @param {Array} [options.extra] - [{name, license, text}] not from a package
234
+ */
235
+ export function yunetaLicensesPlugin(options = {})
236
+ {
237
+ const fileName = options.fileName || "licenses.txt";
238
+ const extra = options.extra || [];
239
+
240
+ return {
241
+ name: "yuneta-licenses",
242
+ apply: "build",
243
+ generateBundle: {
244
+ order: "post",
245
+ handler(output_options, bundle) {
246
+ let app = {};
247
+ let pkg_path = path.resolve(process.cwd(), "package.json");
248
+ if(fs.existsSync(pkg_path)) {
249
+ app = JSON.parse(fs.readFileSync(pkg_path, "utf-8"));
250
+ }
251
+ let ids = bundled_module_ids(bundle);
252
+ if(ids.size === 0) {
253
+ console.error("❌ yuneta-licenses: no module in the bundle, no licenses file written");
254
+ return;
255
+ }
256
+ this.emitFile({
257
+ type: "asset",
258
+ fileName: fileName,
259
+ source: build_licenses_text(ids, app, extra)
260
+ });
261
+ }
262
+ }
263
+ };
264
+ }