@gramlot/gramlot 0.3.33 → 0.3.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/dist/components/audio/__init__.py +1 -1
  2. package/dist/components/audio/assets/collection.js +2 -2
  3. package/dist/components/audio/assets/index.js +1 -1
  4. package/dist/components/charts/__init__.py +2 -2
  5. package/dist/components/charts/assets/collection.js +10 -44
  6. package/dist/components/charts/assets/index.js +1 -1
  7. package/dist/components/charts/assets/modules/chunk-USZCUBTC.js +1 -0
  8. package/dist/components/charts/assets/modules/echarts-gl.min-N6L67H2M.js +4282 -0
  9. package/dist/components/charts/assets/modules/echarts.esm.min-VHLRZDVQ.js +61 -0
  10. package/dist/components/charts/assets/modules/{plotly.min-4LB7HE7P.js → plotly.min-SSDU2DOH.js} +1 -1
  11. package/dist/components/charts/assets/modules/{uPlot.esm-5JJNHHRF.js → uPlot.esm-Q2UYUQHJ.js} +1 -1
  12. package/dist/components/charts/assets/modules/{uPlot.min-N3E3FA74.js → uPlot.min-XXHNQFXH.js} +1 -1
  13. package/dist/components/charts/assets/modules/{vega.module-2QCOVQ3A.js → vega.module-Y5CWNSZO.js} +1 -1
  14. package/dist/components/chat/__init__.py +1 -1
  15. package/dist/components/chat/assets/collection.js +3 -3
  16. package/dist/components/chat/assets/index.js +1 -1
  17. package/dist/components/drawing/__init__.py +1 -1
  18. package/dist/components/drawing/assets/collection.js +3 -24
  19. package/dist/components/drawing/assets/index.js +1 -1
  20. package/dist/components/editors/__init__.py +2 -2
  21. package/dist/components/editors/assets/collection.js +2 -47
  22. package/dist/components/editors/assets/index.js +1 -1
  23. package/dist/components/editors/assets/modules/{jodit-engine-MTSA4GZ3.js → jodit-engine-CXRSFV47.js} +6 -6
  24. package/dist/components/grid/__init__.py +2 -2
  25. package/dist/components/grid/assets/collection.js +6 -28
  26. package/dist/components/grid/assets/index.js +1 -1
  27. package/dist/components/grid/assets/modules/{browser-LVJHKBBV.js → browser-Y2BRNI3P.js} +1 -1
  28. package/dist/components/grid/assets/modules/chunk-BLMUM44K.js +1 -0
  29. package/dist/components/grouplets/__init__.py +1 -1
  30. package/dist/components/grouplets/assets/collection.js +3 -3
  31. package/dist/components/grouplets/assets/index.js +1 -1
  32. package/dist/components/inputs/__init__.py +1 -1
  33. package/dist/components/inputs/assets/collection.js +8 -65
  34. package/dist/components/inputs/assets/index.js +1 -1
  35. package/dist/components/layout/__init__.py +1 -1
  36. package/dist/components/layout/assets/collection.js +9 -30
  37. package/dist/components/layout/assets/index.js +1 -1
  38. package/dist/components/selection_trial/__init__.py +1 -1
  39. package/dist/components/selection_trial/assets/collection.js +3 -3
  40. package/dist/components/selection_trial/assets/index.js +1 -1
  41. package/dist/components/tree/__init__.py +1 -1
  42. package/dist/components/tree/assets/collection.js +6 -27
  43. package/dist/components/tree/assets/index.js +1 -1
  44. package/dist/components/typst/__init__.py +1 -1
  45. package/dist/components/typst/assets/collection.js +3 -3
  46. package/dist/components/typst/assets/index.js +1 -1
  47. package/dist/components/uploads/__init__.py +1 -1
  48. package/dist/components/uploads/assets/collection.js +3 -30
  49. package/dist/components/uploads/assets/index.js +1 -1
  50. package/dist/components/vizabi/__init__.py +1 -1
  51. package/dist/components/vizabi/assets/collection.js +3 -21
  52. package/dist/components/vizabi/assets/index.js +1 -1
  53. package/dist/gramlot.js +1577 -49
  54. package/dist/gramlot.min.js +49 -48
  55. package/dist/libraries.json +126 -0
  56. package/dist/runtime-notices.json +4 -0
  57. package/dist/standard-collections.js +1 -1
  58. package/package.json +2 -2
  59. package/src/components/chart-engines/echarts.js +10 -4
  60. package/src/components/chart-engines/plotly.js +3 -2
  61. package/src/components/chart-engines/uplot.js +5 -3
  62. package/src/components/chart-engines/vega.js +2 -1
  63. package/src/components/chart-gauge.js +7 -3
  64. package/src/components/chart-renderer.js +1 -1
  65. package/src/components/code-mirror.js +2 -1
  66. package/src/components/grid-tools.js +2 -1
  67. package/src/components/html-editor.js +2 -1
  68. package/src/components/markdown-editor.js +2 -1
  69. package/src/components/typst-preview.js +2 -1
  70. package/src/index.d.ts +16 -0
  71. package/src/index.js +5 -0
  72. package/src/libraries.js +83 -0
  73. package/src/server/gramlot-server.d.ts +8 -0
  74. package/src/server/gramlot-server.js +40 -4
  75. package/src/shared-modules.js +79 -0
  76. package/dist/components/charts/assets/modules/chunk-2CCTLZE7.js +0 -76
  77. package/dist/components/charts/assets/modules/chunk-RMRBEYTI.js +0 -1
  78. package/dist/components/charts/assets/modules/echarts-gl-CXVTZA6G.js +0 -4409
  79. package/dist/components/grid/assets/modules/chunk-RMRBEYTI.js +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gramlot/gramlot",
3
- "version": "0.3.33",
3
+ "version": "0.3.34",
4
4
  "description": "Declarative HTML/SVG interfaces with live data binding, authored in JavaScript or Python.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -41,7 +41,7 @@
41
41
  "@myriaddreamin/typst.ts": "0.7.0",
42
42
  "codemirror-lang-typst": "0.6.0",
43
43
  "dompurify": "3.4.17",
44
- "echarts": "^6.1.0",
44
+ "echarts": "6.1.0",
45
45
  "echarts-gl": "2.1.0",
46
46
  "jodit": "4.18.10",
47
47
  "markdown-it": "14.3.3",
@@ -1,5 +1,5 @@
1
- import * as echarts from 'echarts/dist/echarts.js';
2
1
  import {randomId} from '../../random-id.js';
2
+ import {loadLibrary} from '../../libraries.js';
3
3
  import {chartType} from '../chart-types/index.js';
4
4
  import {cartesianOptions} from './echarts-options.js';
5
5
  import {chartBar3DOptions} from '../chart-bar3d-options.js';
@@ -17,11 +17,17 @@ import {chartBoxplotOptions} from '../chart-boxplot-options.js';
17
17
  import {chartTreemapOptions} from '../chart-treemap-options.js';
18
18
  import {chartSunburstOptions} from '../chart-sunburst-options.js';
19
19
 
20
- let glLoading;
20
+ let echarts;
21
21
  export class EChartsAdapter {
22
22
  static label='ECharts';
23
- static async load(type) {
24
- if(chartType(type).threeD)await (glLoading ??= import('echarts-gl/dist/echarts-gl.js'));
23
+ /** ECharts, and ECharts GL for a 3D type, on first use. The UMD build of ECharts GL registers itself
24
+ * into the ECharts it reads from the window property `echarts`. */
25
+ static async load(type,document) {
26
+ echarts=await loadLibrary('echarts',document,()=>import('echarts/dist/echarts.esm.min.mjs'));
27
+ if(chartType(type).threeD) {
28
+ document.defaultView.echarts=echarts;
29
+ await loadLibrary('echartsGl',document,()=>import('echarts-gl/dist/echarts-gl.min.js'));
30
+ }
25
31
  }
26
32
  #chart; #type; #element; #options; #renderer;
27
33
  #mapName=`chart_${randomId()}`; #mapData;
@@ -2,12 +2,13 @@ import {chartPalette} from '../chart-domains.js';
2
2
  import {chartData} from '../chart-data.js';
3
3
  import {plotlySpatial} from './plotly-spatial.js';
4
4
  import {plotlyMap} from './plotly-map.js';
5
+ import {loadLibrary} from '../../libraries.js';
5
6
 
6
7
  let loading,Plotly;
7
8
  export class PlotlyAdapter {
8
9
  static label='Plotly';
9
- static async load() {
10
- Plotly=await (loading ??= import('plotly.js-dist-min').then(module=>module.default));
10
+ static async load(type,document) {
11
+ Plotly=await (loading ??= loadLibrary('plotly',document,()=>import('plotly.js-dist-min')).then(module=>module.default));
11
12
  }
12
13
  #element; #options; #type; #listening=false; #style; #disposed=false; #pending=Promise.resolve(); #drawn=false;
13
14
  constructor(element,options={}) { this.#element=element;this.#options=options; }
@@ -1,11 +1,13 @@
1
1
  import {chartData} from '../chart-data.js';
2
+ import {loadLibrary} from '../../libraries.js';
2
3
 
3
4
  let loading,UPlot,styleText;
4
5
  export class UPlotAdapter {
5
6
  static label='uPlot';
6
- static async load() {
7
- await (loading ??= Promise.all([import('uplot'),import('uplot/dist/uPlot.min.css')])
8
- .then(([engine,style])=>{UPlot=engine.default;styleText=style.default;}));
7
+ static async load(type,document) {
8
+ await (loading ??= Promise.all([loadLibrary('uplot',document,()=>import('uplot/dist/uPlot.esm.js')),
9
+ loadLibrary('uplotStyle',document,()=>import('uplot/dist/uPlot.min.css'))])
10
+ .then(([engine,style])=>{UPlot=engine.default;styleText=style;}));
9
11
  }
10
12
  #element; #plot; #style; #signature; #disposed=false;
11
13
  constructor(element) { this.#element=element; }
@@ -1,10 +1,11 @@
1
1
  import {chartPalette} from '../chart-domains.js';
2
2
  import {chartData} from '../chart-data.js';
3
+ import {loadLibrary} from '../../libraries.js';
3
4
 
4
5
  let loading,Vega;
5
6
  export class VegaAdapter {
6
7
  static label='Vega';
7
- static async load() { Vega=await (loading ??= import('vega')); }
8
+ static async load(type,document) { Vega=await (loading ??= loadLibrary('vega',document,()=>import('vega'))); }
8
9
  #element; #view; #signature; #disposed=false; #pending=Promise.resolve(); #width; #height;
9
10
  constructor(element) { this.#element=element; }
10
11
  validate(context) { return this[`render_${context.type.id}`](context); }
@@ -1,4 +1,4 @@
1
- import * as echarts from 'echarts/dist/echarts.js';
1
+ import {loadLibrary} from '../libraries.js';
2
2
  import {defineComponent} from './registry.js';
3
3
  import {Container} from './container.js';
4
4
  import {gaugeOption, gaugeValue, parseThresholds} from './chart-gauge-options.js';
@@ -52,13 +52,17 @@ export const Gauge = defineComponent({
52
52
  }
53
53
  connectedCallback() {
54
54
  this.#active = true;
55
- this.#chart = echarts.init(this.#surface, null, {renderer: 'svg'});
56
55
  // The node text is where the renderer writes the resolved node value.
57
56
  this.#text.observe(this, {childList: true, subtree: true, characterData: true});
58
57
  this.#theme.observe(this.ownerDocument.documentElement, {attributes: true, attributeFilter: ['data-theme', 'class']});
59
58
  this.#dark.addEventListener('change', this.#onTheme);
60
59
  this.#resize.observe(this.#surface);
61
- this.#render();
60
+ // ECharts loads on first use; the chart starts when it arrives, if the gauge is still connected.
61
+ this.ready = loadLibrary('echarts', this.ownerDocument, () => import('echarts/dist/echarts.esm.min.mjs')).then(echarts => {
62
+ if (!this.#active || this.#chart) return;
63
+ this.#chart = echarts.init(this.#surface, null, {renderer: 'svg'});
64
+ this.#render();
65
+ });
62
66
  }
63
67
  #onTheme = () => this.#render();
64
68
  #palette() {
@@ -25,7 +25,7 @@ export function chartContext(view,structure,seriesOptions) {
25
25
  export class ChartRenderer {
26
26
  #element; #view; #options; #adapter; #engine; #host; #revision=0;
27
27
  constructor(element,view,options={}) { this.#element=element;this.#view=view;this.#options=options; }
28
- async prepare(engine,type) { await requireChartCapability(engine,type).load(type); }
28
+ async prepare(engine,type) { await requireChartCapability(engine,type).load(type,this.#element.ownerDocument); }
29
29
  invalidate() { this.#revision++; }
30
30
  update(structure,seriesOptions) {
31
31
  const engine=structure.getItem('engine') ?? 'echarts';
@@ -1,4 +1,5 @@
1
1
  import {controlElement} from './bases.js';
2
+ import {loadLibrary} from '../libraries.js';
2
3
  import {defineComponent} from './registry.js';
3
4
  import {Labelbox} from './labelbox.js';
4
5
  import {FieldState} from './field-state.js';
@@ -32,7 +33,7 @@ function EditorControl(HTMLElement) {
32
33
  connectedCallback() {
33
34
  const generation = ++this.#generation;
34
35
  this.control.textContent = 'Loading editor…';
35
- this.ready = (engineModule ??= import('./code-mirror-engine.js')).then(module => {
36
+ this.ready = (engineModule ??= loadLibrary('codemirror',this.ownerDocument,()=>import('./code-mirror-engine.js'))).then(module => {
36
37
  if (generation !== this.#generation || !this.isConnected) return;
37
38
  this.control.textContent = '';
38
39
  this.editor = module.createEditor(this);
@@ -1,4 +1,5 @@
1
1
  import {Bag} from '@gramlot/gramlot';
2
+ import {loadLibrary} from '../libraries.js';
2
3
  import {isDecimal} from '@genrojs/tytx';
3
4
  import {GridRows} from './grid-rows.js';
4
5
 
@@ -126,7 +127,7 @@ export class GridTools {
126
127
  /** XLSX Blob of the visible rows: captions, then typed cells (numbers, dates, booleans, text). */
127
128
  async xlsx() {
128
129
  const {columns, rows} = this.#records();
129
- const writeExcelFile = (await (excelEngine ??= import('write-excel-file/browser'))).default;
130
+ const writeExcelFile = (await (excelEngine ??= loadLibrary('writeExcelFile', this.#host.document, () => import('write-excel-file/browser')))).default;
130
131
  const cell = (value, column) => {
131
132
  if (value === null) return null;
132
133
  if (isDecimal(value)) return Number(value.toString());
@@ -1,4 +1,5 @@
1
1
  import {controlElement} from './bases.js';
2
+ import {loadLibrary} from '../libraries.js';
2
3
  import {defineComponent} from './registry.js';
3
4
  import {Labelbox} from './labelbox.js';
4
5
  import {FieldState} from './field-state.js';
@@ -26,7 +27,7 @@ function HtmlControl(HTMLElement) {
26
27
  const generation=++this.#generation;
27
28
  this.engine?.destroy();this.engine=null;
28
29
  this.control.textContent='Loading HTML editor…';
29
- this.ready=(engineModule ??= import('./jodit-engine.js')).then(module=>{
30
+ this.ready=(engineModule ??= loadLibrary('jodit',this.ownerDocument,()=>import('./jodit-engine.js'))).then(module=>{
30
31
  if (generation!==this.#generation || !this.isConnected) return;
31
32
  this.control.textContent='';
32
33
  this.engine=module.createHtmlEditor(this);
@@ -1,4 +1,5 @@
1
1
  import {controlElement} from './bases.js';
2
+ import {loadLibrary} from '../libraries.js';
2
3
  import {defineComponent} from './registry.js';
3
4
  import {Labelbox} from './labelbox.js';
4
5
  import {FieldState} from './field-state.js';
@@ -26,7 +27,7 @@ function MarkdownControl(MarkdownElement) {
26
27
  const generation=++this.#generation;
27
28
  this.engine?.destroy();this.engine=null;
28
29
  this.control.textContent='Loading Markdown editor…';
29
- this.ready=(engineModule ??= import('./prose-mirror-engine.js')).then(module=>{
30
+ this.ready=(engineModule ??= loadLibrary('prosemirror',this.ownerDocument,()=>import('./prose-mirror-engine.js'))).then(module=>{
30
31
  if (generation!==this.#generation || !this.isConnected) return;
31
32
  this.control.textContent='';
32
33
  this.engine=module.createMarkdownEditor(this);
@@ -1,4 +1,5 @@
1
1
  import {defineComponent} from './registry.js';
2
+ import {loadLibrary} from '../libraries.js';
2
3
  import {projectParameters} from './parameters.js';
3
4
 
4
5
  function PreviewElement(HTMLElement){
@@ -61,7 +62,7 @@ function PreviewElement(HTMLElement){
61
62
  const revision=this.#revision;
62
63
  this.#busy=true;
63
64
  try{
64
- this.#loading??=import('./typst-client.js');
65
+ this.#loading??=loadLibrary('typst',this.ownerDocument,()=>import('./typst-client.js'));
65
66
  const module=await this.#loading;
66
67
  if(!this.isConnected || revision!==this.#revision)return;
67
68
  this.#compiler??=module.acquireCompiler();
package/src/index.d.ts CHANGED
@@ -68,3 +68,19 @@ export {VisualEditorLogic, visualEditorScope} from './visual-editor.js';
68
68
  export {VisualEditor} from './server/visual-editor.js';
69
69
  export {SourceImport} from './server/source-import.js';
70
70
  export {SourcePicker} from './source-picker.js';
71
+
72
+ /** The libraries and runtime modules shared with prepared collections, keyed by import specifier. */
73
+ export declare const sharedModules: Readonly<Record<string, Readonly<Record<string, unknown>>>>;
74
+ /** One third-party library of the manifest (GC-325 §160). */
75
+ export interface LibraryEntry {
76
+ readonly packages: Readonly<Record<string, string>>;
77
+ readonly local: string;
78
+ readonly url: string | null;
79
+ readonly integrity: string | null;
80
+ readonly format: 'module' | 'style' | 'script';
81
+ readonly global?: string;
82
+ }
83
+ /** The third-party libraries of the standard components, keyed by name. */
84
+ export declare const libraries: Readonly<Record<string, LibraryEntry>>;
85
+ /** The library `name` for a component of `document`: from jsDelivr when the document says `cdn`, else the local copy. */
86
+ export declare function loadLibrary(name: string, document: Document, localImport: () => Promise<unknown>): Promise<unknown>;
package/src/index.js CHANGED
@@ -61,3 +61,8 @@ export {VisualEditorLogic, visualEditorScope} from './visual-editor.js';
61
61
  export {VisualEditor} from './server/visual-editor.js';
62
62
  export {SourceImport} from './server/source-import.js';
63
63
  export {SourcePicker} from './source-picker.js';
64
+
65
+ // Prepared collections read the shared libraries and runtime modules from this table (GC-325 §155).
66
+ export {sharedModules} from './shared-modules.js';
67
+ // Third-party libraries of components: the manifest and the loader on first use (GC-325 §160).
68
+ export {libraries, loadLibrary} from './libraries.js';
@@ -0,0 +1,83 @@
1
+ /**
2
+ * The third-party libraries of the standard components, and the function that loads one on first use.
3
+ *
4
+ * `libraries` is the manifest: one entry per library, keyed by its name. An entry holds
5
+ *
6
+ * - `packages`: the npm packages it contains, each with its exact installed version;
7
+ * - `local`: the import specifier of the local copy, a file of the package (`echarts/dist/echarts.esm.min.mjs`)
8
+ * or a Gramlot engine module that bundles the packages (`./components/code-mirror-engine.js`, relative to
9
+ * `js/src`); the collection generator emits it as a deferred module of the collection;
10
+ * - `url`: the same file on jsDelivr at the exact version, or `null` when the library has no ESM build that a
11
+ * browser can import alone (UMD builds, builds split across packages, the Typst WebAssembly);
12
+ * - `integrity`: the SRI hash (sha384) of that file, `null` without `url`;
13
+ * - `format`: `module` (the import gives the library), `style` (CSS text) or `script` (a UMD build evaluated as
14
+ * a browser script: it reads its dependencies from globals of the window and writes the library to the
15
+ * window property `global`).
16
+ *
17
+ * The page document says where the libraries come from: the bootstrap HTML of a server carries
18
+ * `data-gramlot-library-source="cdn"` or `"local"` on its root element. A document without the marker (the
19
+ * serverless and file exports) uses the local copies.
20
+ *
21
+ * @module
22
+ */
23
+
24
+ const jsdelivr = (name, version, file) => `https://cdn.jsdelivr.net/npm/${name}@${version}/${file}`;
25
+
26
+ export const libraries = Object.freeze({
27
+ echarts: Object.freeze({packages: {echarts: '6.1.0'}, local: 'echarts/dist/echarts.esm.min.mjs',
28
+ url: jsdelivr('echarts', '6.1.0', 'dist/echarts.esm.min.mjs'),
29
+ integrity: 'sha384-2svH5QplTeBKhRXWxXOJE2P6pRpgnqVq8l8U1dYXUBXvc2zJ/FMMardtnPnnCXnt', format: 'module'}),
30
+ echartsGl: Object.freeze({packages: {'echarts-gl': '2.1.0'}, local: 'echarts-gl/dist/echarts-gl.min.js',
31
+ url: null, integrity: null, format: 'script', global: 'echarts-gl'}),
32
+ uplot: Object.freeze({packages: {uplot: '1.6.32'}, local: 'uplot/dist/uPlot.esm.js',
33
+ url: jsdelivr('uplot', '1.6.32', 'dist/uPlot.esm.js'),
34
+ integrity: 'sha384-iUdBlEO5qc07+gOz+3rq/Besyud+KVIxM+xJEuUBObxLG3C/Dlkz8OYuPUcPrCGP', format: 'module'}),
35
+ uplotStyle: Object.freeze({packages: {uplot: '1.6.32'}, local: 'uplot/dist/uPlot.min.css',
36
+ url: jsdelivr('uplot', '1.6.32', 'dist/uPlot.min.css'),
37
+ integrity: 'sha384-IfV0B7MIOYuO95kO9G5ySKPz/85zqFNOAs8iy4tkK5zd9izhJAB8b7lHrwYqqmYE', format: 'style'}),
38
+ plotly: Object.freeze({packages: {'plotly.js-dist-min': '4.2.0'}, local: 'plotly.js-dist-min',
39
+ url: null, integrity: null, format: 'module'}),
40
+ vega: Object.freeze({packages: {vega: '6.4.0'}, local: 'vega', url: null, integrity: null, format: 'module'}),
41
+ writeExcelFile: Object.freeze({packages: {'write-excel-file': '4.1.1'}, local: 'write-excel-file/browser',
42
+ url: null, integrity: null, format: 'module'}),
43
+ jodit: Object.freeze({packages: {jodit: '4.18.10'}, local: './components/jodit-engine.js',
44
+ url: null, integrity: null, format: 'module'}),
45
+ codemirror: Object.freeze({packages: {
46
+ '@codemirror/autocomplete': '6.20.4', '@codemirror/commands': '6.11.1', '@codemirror/lang-css': '6.3.1',
47
+ '@codemirror/lang-html': '6.4.12', '@codemirror/lang-javascript': '6.2.5', '@codemirror/lang-json': '6.0.2',
48
+ '@codemirror/lang-markdown': '6.5.2', '@codemirror/lang-python': '6.2.1', '@codemirror/lang-sql': '6.10.0',
49
+ '@codemirror/lang-xml': '6.1.0', '@codemirror/language': '6.13.1', '@codemirror/lint': '6.9.7',
50
+ '@codemirror/search': '6.7.2', '@codemirror/state': '6.7.6', '@codemirror/view': '6.43.15',
51
+ '@lezer/highlight': '1.2.5', 'codemirror-lang-typst': '0.6.0'},
52
+ local: './components/code-mirror-engine.js', url: null, integrity: null, format: 'module'}),
53
+ prosemirror: Object.freeze({packages: {
54
+ 'prosemirror-commands': '1.6.2', 'prosemirror-history': '1.4.1', 'prosemirror-keymap': '1.2.2',
55
+ 'prosemirror-markdown': '1.13.1', 'prosemirror-model': '1.25.12', 'prosemirror-state': '1.4.3',
56
+ 'prosemirror-view': '1.42.6'},
57
+ local: './components/prose-mirror-engine.js', url: null, integrity: null, format: 'module'}),
58
+ typst: Object.freeze({packages: {'@myriaddreamin/typst.ts': '0.7.0', '@myriaddreamin/typst-ts-web-compiler': '0.7.0',
59
+ '@myriaddreamin/typst-ts-renderer': '0.7.0'},
60
+ local: './components/typst-client.js', url: null, integrity: null, format: 'module'}),
61
+ });
62
+
63
+ /**
64
+ * The library `name` of the manifest, for a component of `document`. `localImport` is the dynamic import of the
65
+ * local copy written in the component (`() => import('echarts/dist/echarts.esm.min.mjs')`), so that the
66
+ * collection generator emits the copy as a deferred module. With `data-gramlot-library-source="cdn"` on the
67
+ * document and a `url` in the entry the library comes from jsDelivr: the import map of the bootstrap carries
68
+ * its integrity, a style is fetched with it. Resolves with the module namespace (`module`), the CSS text
69
+ * (`style`) or the window property `global` (`script`).
70
+ */
71
+ export async function loadLibrary(name, document, localImport) {
72
+ if (!Object.hasOwn(libraries, name)) throw new Error(`Unknown third-party library: ${name}`);
73
+ const library = libraries[name];
74
+ const cdn = library.url !== null && document.documentElement.getAttribute('data-gramlot-library-source') === 'cdn';
75
+ if (library.format === 'style') {
76
+ if (!cdn) return (await localImport()).default;
77
+ const response = await document.defaultView.fetch(library.url, {integrity: library.integrity});
78
+ if (!response.ok) throw new Error(`${name}: ${library.url} answered ${response.status}`);
79
+ return response.text();
80
+ }
81
+ const module = cdn ? await import(library.url) : await localImport();
82
+ return library.format === 'script' ? document.defaultView[library.global] : module;
83
+ }
@@ -78,6 +78,8 @@ export interface GramlotServerOptions {
78
78
  uploadsEnabled?: boolean;
79
79
  /** The base theme of every page, a folder of the core themes, or false for none; default `gramlot-base`. */
80
80
  cssTheme?: string | false;
81
+ /** Where the pages take the third-party libraries of the components: jsDelivr or the local copies; default `cdn`. */
82
+ librarySource?: 'cdn' | 'local';
81
83
  }
82
84
 
83
85
  /** The result of `registerPage`. */
@@ -153,6 +155,12 @@ export class GramlotServer {
153
155
  evaluateAuth(rule: string | null, options?: {owner?: unknown; identity?: unknown}): AuthOutcome;
154
156
  /** Drop the expired pages. */
155
157
  prune(): void;
158
+ /** Where the pages take the third-party libraries of the components. */
159
+ librarySource: 'cdn' | 'local';
160
+ /** The origins the pages load third-party libraries from: the CDN origin with `cdn`, else none. */
161
+ get libraryOrigins(): string[];
162
+ /** The page policy: `{nonce}` replaced and the library origins added to the directives of scripts and connections. */
163
+ contentSecurityPolicy(policy: string, nonce: string): string;
156
164
  /** The CSS URL of the theme of a page class, in an array, or an empty array. */
157
165
  themeCss(PageClass: typeof Page): string[];
158
166
  /** The file of a `/themes/<path>` URL path whose real path is a file of the core themes, or null. Node.js and Bun only. */
@@ -14,6 +14,7 @@ import {gramlotDev} from './assets.js';
14
14
  import {ENDPOINT_METHOD, Page, SOURCE_METHOD, UPLOAD_METHOD, resolveDeclared} from './page.js';
15
15
  import {UploadRegistry, UploadTarget} from './upload.js';
16
16
  import {InvalidResourceName, SEGMENT, loadOrder} from './resources.js';
17
+ import {libraries} from '../libraries.js';
17
18
 
18
19
  export class PageExpired extends Error { name = 'PageExpired'; }
19
20
  export class PageNotFound extends Error { name = 'PageNotFound'; }
@@ -105,13 +106,21 @@ const prefixed = (prefix, url) => url.startsWith('/') && !url.startsWith('//') ?
105
106
  *
106
107
  * A page expires `pageTtl` seconds after its last use: opening it and every call that names it for its
107
108
  * owner move the expiry to now plus `pageTtl` (GC-230 §010).
109
+ *
110
+ * `librarySource` says where the pages take the third-party libraries of the components: `'cdn'` (jsDelivr,
111
+ * at the exact version of the manifest) or `'local'` (the copies served with the collections). With `'cdn'`
112
+ * the import map of the bootstrap carries the integrity of each CDN module and contentSecurityPolicy adds the
113
+ * CDN origin to the policy (GC-325 §160).
108
114
  */
109
115
  export class GramlotServer {
110
116
  get markdownUrl() { return this.runtimeUrl.replace(/[^/]+$/, 'gramlot-markdown.js'); }
111
117
 
112
118
  constructor({runtimeUrl = '/assets/gramlot.js', rpcUrl = '/gramlot/rpc', closeUrl = '/gramlot/close',
113
119
  rootId = 'gramlot-root', pageTtl = 1800, maxPages = 1000, collections = [], uploadsEnabled = false,
114
- cssTheme = 'gramlot-base'} = {}) {
120
+ cssTheme = 'gramlot-base', librarySource = 'cdn'} = {}) {
121
+ if (!['cdn', 'local'].includes(librarySource)) {
122
+ throw new TypeError(`The library source must be 'cdn' or 'local', not ${JSON.stringify(librarySource)}`);
123
+ }
115
124
  if (cssTheme !== false && !isThemeName(cssTheme)) {
116
125
  throw new TypeError(`The base theme must be a theme name or false, not ${JSON.stringify(cssTheme)}`);
117
126
  }
@@ -120,7 +129,8 @@ export class GramlotServer {
120
129
  !Number.isSafeInteger(maxPages) || maxPages < 1) {
121
130
  throw new TypeError('Page TTL must be finite and positive; capacity must be a positive safe integer');
122
131
  }
123
- Object.assign(this, {runtimeUrl, rpcUrl, closeUrl, rootId, pageTtl, maxPages, cssTheme});
132
+ Object.assign(this, {runtimeUrl, rpcUrl, closeUrl, rootId, pageTtl, maxPages, cssTheme, librarySource});
133
+ this.libraries = libraries;
124
134
  this.pages = new Map();
125
135
  this.uploads = uploadsEnabled ? new UploadRegistry() : null;
126
136
  this.collections = this.collectionGraph([...standardCollections, ...collections]);
@@ -128,6 +138,30 @@ export class GramlotServer {
128
138
  this.environmentPages = new WeakMap();
129
139
  }
130
140
 
141
+ /** The origins the pages load third-party libraries from: the CDN origin with `'cdn'`, else none. */
142
+ get libraryOrigins() {
143
+ if (this.librarySource === 'local') return [];
144
+ return [...new Set(Object.values(this.libraries).filter(entry => entry.url !== null)
145
+ .map(entry => entry.url.split('/').slice(0, 3).join('/')))];
146
+ }
147
+
148
+ /** The `Content-Security-Policy` header of one page: `policy` with `{nonce}` replaced by the nonce of its
149
+ * bootstrap and the library origins added to the directive that governs scripts (`script-src`, else
150
+ * `default-src`) and to the one that governs connections (`connect-src`, else `default-src`); a policy
151
+ * without such a directive leaves that kind unrestricted (GC-101 §140). */
152
+ contentSecurityPolicy(policy, nonce) {
153
+ const directives = policy.replaceAll('{nonce}', nonce).split(';').filter(part => part.trim())
154
+ .map(part => part.trim().split(/\s+/));
155
+ const names = directives.map(directive => directive[0]);
156
+ for (const kind of ['script-src', 'connect-src']) {
157
+ const name = names.includes(kind) ? kind : names.includes('default-src') ? 'default-src' : null;
158
+ if (name === null) continue;
159
+ const directive = directives[names.indexOf(name)];
160
+ directive.push(...this.libraryOrigins.filter(origin => !directive.includes(origin)));
161
+ }
162
+ return directives.map(directive => directive.join(' ')).join('; ');
163
+ }
164
+
131
165
  /** The Page class of path, or PageNotFound. */
132
166
  async resolvePage(path) { throw new PageNotFound(`Page not found: ${path}`); }
133
167
 
@@ -325,7 +359,7 @@ export class GramlotServer {
325
359
  ...(resources.serverAdapter ? {serverAdapter: prefixed(prefix, resources.serverAdapter)} : {})},
326
360
  });
327
361
  const document = new GramlotBuilder();
328
- const root = document.root.html();
362
+ const root = document.root.html({'data-gramlot-library-source': this.librarySource});
329
363
  const head = root.head();
330
364
  head.meta({charset: 'utf-8'});
331
365
  head.meta({name: 'viewport', content: 'width=device-width,initial-scale=1'});
@@ -338,7 +372,9 @@ export class GramlotServer {
338
372
  '@gramlot/gramlot': prefixed(prefix, this.runtimeUrl),
339
373
  '@gramlot/gramlot/components':prefixed(prefix,this.runtimeUrl),
340
374
  '@gramlot/gramlot/markdown':prefixed(prefix,this.markdownUrl),
341
- ...Object.fromEntries((resources.collections ?? []).map(({name,url})=>[`@gramlot/collections/${encodeURIComponent(name)}`,prefixed(prefix,url)]))}}),
375
+ ...Object.fromEntries((resources.collections ?? []).map(({name,url})=>[`@gramlot/collections/${encodeURIComponent(name)}`,prefixed(prefix,url)]))},
376
+ ...(this.librarySource === 'cdn' ? {integrity: Object.fromEntries(Object.values(this.libraries)
377
+ .filter(entry => entry.url !== null && entry.format !== 'style').map(entry => [entry.url, entry.integrity]))} : {})}),
342
378
  {type: 'importmap', nonce});
343
379
  const body = root.body();
344
380
  body.div({id: this.rootId});
@@ -0,0 +1,79 @@
1
+ /**
2
+ * The modules that the runtime shares with prepared collections.
3
+ *
4
+ * The collection generator keeps every module of this table out of a collection bundle: an import of
5
+ * one of them becomes a read of this table from `@gramlot/gramlot`. A page therefore holds one copy
6
+ * of each module, and its classes keep their identity across the runtime and the collections
7
+ * (`instanceof Bag` holds for a Bag created by a collection).
8
+ *
9
+ * A key is the import specifier: the package name for a library, the path relative to this
10
+ * directory for a runtime module. The generator refuses a collection that would bundle a module of
11
+ * the runtime missing from this table.
12
+ *
13
+ * @module
14
+ */
15
+ import * as genrojsBag from '@genrojs/bag';
16
+ import * as genrojsBuilders from '@genrojs/builders';
17
+ import * as genrojsToolbox from '@genrojs/toolbox';
18
+ import * as genrojsTytx from '@genrojs/tytx';
19
+ import * as xmldom from '@xmldom/xmldom';
20
+ import * as decimal from 'decimal.js';
21
+ import * as big from 'big.js';
22
+ import * as msgpack from '@msgpack/msgpack';
23
+ import * as dompurify from 'dompurify';
24
+ import * as randomId from './random-id.js';
25
+ import * as format from './format.js';
26
+ import * as librariesModule from './libraries.js';
27
+ import * as mediaFrame from './media-frame.js';
28
+ import * as validationRun from './validation-run.js';
29
+ import * as rendererAttributes from './renderer/attributes.js';
30
+ import * as viewLabelbox from './view/labelbox.js';
31
+ import * as columnFilter from './stores/column-filter.js';
32
+ import * as collectionFilter from './stores/collection-filter.js';
33
+ import * as idSet from './stores/id-set.js';
34
+ import * as bagCollectionStore from './stores/bag-collection-store.js';
35
+ import * as bagCollectionView from './stores/bag-collection-view.js';
36
+ import * as bases from './components/bases.js';
37
+ import * as choices from './components/choices.js';
38
+ import * as choiceFieldStyles from './components/choice-field-styles.js';
39
+ import * as fieldState from './components/field-state.js';
40
+ import * as gridFormulas from './components/grid-formulas.js';
41
+ import * as gridStructure from './components/grid-structure.js';
42
+ import * as labelbox from './components/labelbox.js';
43
+ import * as parameters from './components/parameters.js';
44
+ import * as popup from './components/popup.js';
45
+ import * as validation from './components/validation.js';
46
+
47
+ export const sharedModules = Object.freeze({
48
+ '@genrojs/bag': genrojsBag,
49
+ '@genrojs/builders': genrojsBuilders,
50
+ '@genrojs/toolbox': genrojsToolbox,
51
+ '@genrojs/tytx': genrojsTytx,
52
+ '@xmldom/xmldom': xmldom,
53
+ 'decimal.js': decimal,
54
+ 'big.js': big,
55
+ '@msgpack/msgpack': msgpack,
56
+ 'dompurify': dompurify,
57
+ './random-id.js': randomId,
58
+ './format.js': format,
59
+ './libraries.js': librariesModule,
60
+ './media-frame.js': mediaFrame,
61
+ './validation-run.js': validationRun,
62
+ './renderer/attributes.js': rendererAttributes,
63
+ './view/labelbox.js': viewLabelbox,
64
+ './stores/column-filter.js': columnFilter,
65
+ './stores/collection-filter.js': collectionFilter,
66
+ './stores/id-set.js': idSet,
67
+ './stores/bag-collection-store.js': bagCollectionStore,
68
+ './stores/bag-collection-view.js': bagCollectionView,
69
+ './components/bases.js': bases,
70
+ './components/choices.js': choices,
71
+ './components/choice-field-styles.js': choiceFieldStyles,
72
+ './components/field-state.js': fieldState,
73
+ './components/grid-formulas.js': gridFormulas,
74
+ './components/grid-structure.js': gridStructure,
75
+ './components/labelbox.js': labelbox,
76
+ './components/parameters.js': parameters,
77
+ './components/popup.js': popup,
78
+ './components/validation.js': validation,
79
+ });