@hpcc-js/observablehq-compiler 1.1.1 → 1.1.3

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 (52) hide show
  1. package/LICENSE +43 -0
  2. package/README.md +105 -105
  3. package/bin/ojscc.mjs +74 -74
  4. package/dist/index.esm.js +586 -562
  5. package/dist/index.esm.js.map +1 -1
  6. package/dist/index.esm.min.js +2 -2
  7. package/dist/index.esm.min.js.map +1 -1
  8. package/dist/index.js +6716 -6688
  9. package/dist/index.js.map +1 -1
  10. package/dist/index.min.js +3 -3
  11. package/dist/index.min.js.map +1 -1
  12. package/package.json +5 -4
  13. package/src/__package__.ts +3 -3
  14. package/src/__tests__/File Attachments.ts +894 -894
  15. package/src/__tests__/Introduction to Imports.ts +748 -748
  16. package/src/__tests__/Observable TimeChart.ts +771 -771
  17. package/src/__tests__/index.ts +13 -13
  18. package/src/__tests__/node.ts +177 -177
  19. package/src/compiler.md +234 -234
  20. package/src/compiler.ts +279 -264
  21. package/src/cst.ts +172 -172
  22. package/src/index.css +459 -459
  23. package/src/index.ts +6 -7
  24. package/src/util.md +113 -113
  25. package/src/util.ts +163 -153
  26. package/src/writer.ts +80 -80
  27. package/types/__package__.d.ts +3 -3
  28. package/types/__tests__/File Attachments.d.ts +109 -109
  29. package/types/__tests__/Introduction to Imports.d.ts +119 -119
  30. package/types/__tests__/Observable TimeChart.d.ts +110 -110
  31. package/types/__tests__/index.d.ts +1 -1
  32. package/types/__tests__/node.d.ts +1 -1
  33. package/types/compiler.d.ts +90 -87
  34. package/types/compiler.d.ts.map +1 -1
  35. package/types/cst.d.ts +41 -41
  36. package/types/index.d.ts +4 -5
  37. package/types/index.d.ts.map +1 -1
  38. package/types/util.d.ts +28 -25
  39. package/types/util.d.ts.map +1 -1
  40. package/types/writer.d.ts +18 -18
  41. package/types-3.4/__package__.d.ts +4 -0
  42. package/types-3.4/__tests__/File Attachments.d.ts +110 -0
  43. package/types-3.4/__tests__/Introduction to Imports.d.ts +120 -0
  44. package/types-3.4/__tests__/Observable TimeChart.d.ts +111 -0
  45. package/types-3.4/__tests__/index.d.ts +2 -0
  46. package/types-3.4/__tests__/node.d.ts +2 -0
  47. package/types-3.4/compiler.d.ts +94 -0
  48. package/types-3.4/cst.d.ts +42 -0
  49. package/types-3.4/index.d.ts +5 -0
  50. package/types-3.4/util.d.ts +29 -0
  51. package/types-3.4/writer.d.ts +19 -0
  52. package/src/__tests__/tsconfig.json +0 -21
package/dist/index.esm.js CHANGED
@@ -6229,15 +6229,15 @@ function parseCell$1(input, {tag, raw, globals, ...options} = {}) {
6229
6229
  if (tag != null && input) {
6230
6230
  cell = TemplateCellParser.parse(input, options);
6231
6231
  const parsedTag = CellTagParser.parse(tag, options);
6232
- parseReferences(parsedTag, tag, globals);
6233
- parseFeatures(parsedTag, tag);
6232
+ parseReferences$1(parsedTag, tag, globals);
6233
+ parseFeatures$1(parsedTag, tag);
6234
6234
  cell.tag = parsedTag;
6235
6235
  cell.raw = !!raw;
6236
6236
  } else {
6237
6237
  cell = CellParser.parse(input, options);
6238
6238
  }
6239
- parseReferences(cell, input, globals);
6240
- parseFeatures(cell, input);
6239
+ parseReferences$1(cell, input, globals);
6240
+ parseFeatures$1(cell, input);
6241
6241
  return cell;
6242
6242
  }
6243
6243
 
@@ -6549,7 +6549,7 @@ class CellTagParser extends Parser {
6549
6549
  // Find references.
6550
6550
  // Check for illegal references to arguments.
6551
6551
  // Check for illegal assignments to global references.
6552
- function parseReferences(cell, input, globals = defaultGlobals) {
6552
+ function parseReferences$1(cell, input, globals = defaultGlobals) {
6553
6553
  if (!cell.body) {
6554
6554
  cell.references = [];
6555
6555
  } else if (cell.body.type === "ImportDeclaration") {
@@ -6576,7 +6576,7 @@ function parseReferences(cell, input, globals = defaultGlobals) {
6576
6576
  // Find features: file attachments, secrets, database clients.
6577
6577
  // Check for illegal references to arguments.
6578
6578
  // Check for illegal assignments to global references.
6579
- function parseFeatures(cell, input) {
6579
+ function parseFeatures$1(cell, input) {
6580
6580
  if (cell.body && cell.body.type !== "ImportDeclaration") {
6581
6581
  try {
6582
6582
  cell.fileAttachments = findFeatures(cell, "FileAttachment");
@@ -6599,570 +6599,594 @@ function parseFeatures(cell, input) {
6599
6599
  }
6600
6600
  return cell;
6601
6601
  }
6602
-
6603
- class ModuleParser extends CellParser {
6604
- parseTopLevel(node) {
6605
- if (!node.cells)
6606
- node.cells = [];
6607
- // @ts-ignore
6608
- while (this.type !== types$1.eof) {
6609
- // @ts-ignore
6610
- const cell = this.parseCell(this.startNode());
6611
- // @ts-ignore
6612
- cell.input = this.input;
6613
- node.cells.push(cell);
6614
- }
6615
- // @ts-ignore
6616
- this.next();
6617
- // @ts-ignore
6618
- return this.finishNode(node, "Program");
6619
- }
6620
- }
6621
- // @ts-ignore
6622
- function parseModule(input, { globals } = {}) {
6623
- // @ts-ignore
6624
- return ModuleParser.parse(input).cells.map(cell => input.substring(cell.start, cell.end));
6602
+ class ModuleParser extends CellParser {
6603
+ parseTopLevel(node) {
6604
+ if (!node.cells)
6605
+ node.cells = [];
6606
+ // @ts-ignore
6607
+ while (this.type !== types$1.eof) {
6608
+ // @ts-ignore
6609
+ const cell = this.parseCell(this.startNode());
6610
+ // @ts-ignore
6611
+ cell.input = this.input;
6612
+ node.cells.push(cell);
6613
+ }
6614
+ // @ts-ignore
6615
+ this.next();
6616
+ // @ts-ignore
6617
+ return this.finishNode(node, "Program");
6618
+ }
6619
+ }
6620
+ function splitModule(input) {
6621
+ // @ts-ignore
6622
+ return ModuleParser.parse(input, { ecmaVersion: "latest" }).cells.map(cell => input.substring(cell.start, cell.end));
6623
+ }
6624
+ function parseCell$2(input) {
6625
+ return parseCell$1(input);
6625
6626
  }
6626
6627
 
6627
- const FuncTypes = {
6628
- functionType: Object.getPrototypeOf(function () { }).constructor,
6629
- asyncFunctionType: Object.getPrototypeOf(async function () { }).constructor,
6630
- generatorFunctionType: Object.getPrototypeOf(function* () { }).constructor,
6631
- asyncGeneratorFunctionType: Object.getPrototypeOf(async function* () { }).constructor
6632
- };
6633
- function funcType(async = false, generator = false) {
6634
- if (!async && !generator)
6635
- return FuncTypes.functionType;
6636
- if (async && !generator)
6637
- return FuncTypes.asyncFunctionType;
6638
- if (!async && generator)
6639
- return FuncTypes.generatorFunctionType;
6640
- return FuncTypes.asyncGeneratorFunctionType;
6641
- }
6642
- function createFunction(refs, async = false, generator = false, blockStatement = false, body) {
6643
- if (body === undefined) {
6644
- return undefined;
6645
- }
6646
- refs.patches.sort((l, r) => r.start - l.start);
6647
- refs.patches.forEach(r => {
6648
- body = body.substring(0, r.start) + r.newText + body.substring(r.end);
6649
- });
6650
- return new (funcType(async, generator))(...refs.args, blockStatement ?
6651
- body.substring(1, body.length - 1).trim() :
6652
- `return (\n${body}\n);`);
6653
- }
6654
- // Hide "import" from bundlers as they have a habit of replacing "import" with "require"
6655
- async function obfuscatedImport(url) {
6656
- return new FuncTypes.asyncFunctionType("url", "return import(url)")(url);
6657
- }
6658
- function encodeBacktick(str) {
6659
- return str
6660
- .split("`").join("\\`");
6661
- }
6662
- function createParsedOJS(ojs, offset, inlineMD) {
6663
- return {
6664
- ojs,
6665
- offset,
6666
- inlineMD
6667
- };
6668
- }
6669
- function parseOmd(_) {
6670
- const retVal = [];
6671
- // Load Markdown ---
6672
- const re = /(```(?:\s|\S)[\s\S]*?```)/g;
6673
- let prevOffset = 0;
6674
- let match = re.exec(_);
6675
- while (match !== null) {
6676
- if (match.index > prevOffset) {
6677
- retVal.push(createParsedOJS(_.substring(prevOffset, match.index), prevOffset, true));
6678
- }
6679
- const outer = match[0];
6680
- if (outer.indexOf("``` ") === 0 || outer.indexOf("```\n") === 0 || outer.indexOf("```\r\n") === 0) {
6681
- const prefixLen = 3;
6682
- const inner = outer.substring(prefixLen, outer.length - prefixLen);
6683
- retVal.push(createParsedOJS(inner, match.index + prefixLen, false));
6684
- }
6685
- else {
6686
- retVal.push(createParsedOJS(outer, match.index, true));
6687
- }
6688
- prevOffset = match.index + match[0].length;
6689
- match = re.exec(_);
6690
- }
6691
- if (_.length > prevOffset) {
6692
- retVal.push(createParsedOJS(_.substring(prevOffset, _.length), prevOffset, true));
6693
- }
6694
- return retVal;
6695
- }
6696
- function ojs2notebook(ojs) {
6697
- const cells = parseModule(ojs);
6698
- return {
6699
- files: [],
6700
- nodes: cells.map((cell, idx) => {
6701
- return {
6702
- id: idx,
6703
- mode: "js",
6704
- value: cell
6705
- };
6706
- })
6707
- };
6708
- }
6709
- function omd2notebook(omd) {
6710
- const cells = parseOmd(omd);
6711
- return {
6712
- files: [],
6713
- nodes: cells.map((cell, idx) => {
6714
- return {
6715
- id: idx,
6716
- mode: cell.inlineMD ? "md" : "js",
6717
- value: cell.ojs
6718
- };
6719
- })
6720
- };
6721
- }
6722
- function fetchEx(url) {
6723
- return fetch(url)
6724
- .then(response => {
6725
- if (response.ok)
6726
- return response;
6727
- throw new Error("CORS?");
6728
- }).catch(e => {
6729
- const matches = url.match(/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n?]+)/img);
6730
- url = "https://observable-cors.glitch.me/" + url;
6731
- return fetch(url, {
6732
- headers: {
6733
- origin: matches[0],
6734
- referer: url
6735
- }
6736
- });
6737
- });
6738
- }
6739
- function download(impUrl) {
6740
- const isShared = impUrl.indexOf("https://observablehq.com/d") === 0;
6741
- return fetchEx(impUrl.replace(`https://observablehq.com/${isShared ? "d/" : ""}`, "https://api.observablehq.com/document/"))
6742
- .then(r => r.json());
6628
+ const FuncTypes = {
6629
+ functionType: Object.getPrototypeOf(function () { }).constructor,
6630
+ asyncFunctionType: Object.getPrototypeOf(async function () { }).constructor,
6631
+ generatorFunctionType: Object.getPrototypeOf(function* () { }).constructor,
6632
+ asyncGeneratorFunctionType: Object.getPrototypeOf(async function* () { }).constructor
6633
+ };
6634
+ function funcType(async = false, generator = false) {
6635
+ if (!async && !generator)
6636
+ return FuncTypes.functionType;
6637
+ if (async && !generator)
6638
+ return FuncTypes.asyncFunctionType;
6639
+ if (!async && generator)
6640
+ return FuncTypes.generatorFunctionType;
6641
+ return FuncTypes.asyncGeneratorFunctionType;
6642
+ }
6643
+ function createFunction(refs, async = false, generator = false, blockStatement = false, body) {
6644
+ if (body === undefined) {
6645
+ return undefined;
6646
+ }
6647
+ refs.patches.sort((l, r) => r.start - l.start);
6648
+ refs.patches.forEach(r => {
6649
+ body = body.substring(0, r.start) + r.newText + body.substring(r.end);
6650
+ });
6651
+ return new (funcType(async, generator))(...refs.args, blockStatement ?
6652
+ body.substring(1, body.length - 1).trim() :
6653
+ `return (\n${body}\n);`);
6654
+ }
6655
+ // Hide "import" from bundlers as they have a habit of replacing "import" with "require"
6656
+ async function obfuscatedImport(url) {
6657
+ return new FuncTypes.asyncFunctionType("url", "return import(url)")(url);
6658
+ }
6659
+ function encodeBacktick(str) {
6660
+ return str
6661
+ .split("`").join("\\`");
6662
+ }
6663
+ function createParsedOJS(ojs, offset, inlineMD) {
6664
+ let cell;
6665
+ let error;
6666
+ try {
6667
+ cell = parseCell$2(ojs);
6668
+ }
6669
+ catch (e) {
6670
+ error = e;
6671
+ }
6672
+ return {
6673
+ ojs,
6674
+ offset,
6675
+ inlineMD,
6676
+ cell,
6677
+ error
6678
+ };
6679
+ }
6680
+ function parseOmd(_) {
6681
+ const retVal = [];
6682
+ // Load Markdown ---
6683
+ const re = /(```(?:\s|\S)[\s\S]*?```)/g;
6684
+ let prevOffset = 0;
6685
+ let match = re.exec(_);
6686
+ while (match !== null) {
6687
+ if (match.index > prevOffset) {
6688
+ retVal.push(createParsedOJS(_.substring(prevOffset, match.index), prevOffset, true));
6689
+ }
6690
+ const outer = match[0];
6691
+ if (outer.indexOf("``` ") === 0 || outer.indexOf("```\n") === 0 || outer.indexOf("```\r\n") === 0) {
6692
+ const prefixLen = 3;
6693
+ const inner = outer.substring(prefixLen, outer.length - prefixLen);
6694
+ retVal.push(createParsedOJS(inner, match.index + prefixLen, false));
6695
+ }
6696
+ else {
6697
+ retVal.push(createParsedOJS(outer, match.index, true));
6698
+ }
6699
+ prevOffset = match.index + match[0].length;
6700
+ match = re.exec(_);
6701
+ }
6702
+ if (_.length > prevOffset) {
6703
+ retVal.push(createParsedOJS(_.substring(prevOffset, _.length), prevOffset, true));
6704
+ }
6705
+ return retVal;
6706
+ }
6707
+ function ojs2notebook(ojs) {
6708
+ const cells = splitModule(ojs);
6709
+ return {
6710
+ files: [],
6711
+ nodes: cells.map((cell, idx) => {
6712
+ return {
6713
+ id: idx,
6714
+ mode: "js",
6715
+ value: cell
6716
+ };
6717
+ })
6718
+ };
6719
+ }
6720
+ function omd2notebook(omd) {
6721
+ const cells = parseOmd(omd);
6722
+ return {
6723
+ files: [],
6724
+ nodes: cells.map((cell, idx) => {
6725
+ return {
6726
+ id: idx,
6727
+ mode: cell.inlineMD ? "md" : "js",
6728
+ value: cell.ojs
6729
+ };
6730
+ })
6731
+ };
6732
+ }
6733
+ function fetchEx(url, proxyPrefix = "https://observable-cors.glitch.me/", proxyPostfix = "") {
6734
+ return fetch(url)
6735
+ .then(response => {
6736
+ if (response.ok)
6737
+ return response;
6738
+ throw new Error("CORS?");
6739
+ }).catch(e => {
6740
+ const matches = url.match(/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n?]+)/img);
6741
+ url = `${proxyPrefix}${url}${proxyPostfix}`;
6742
+ return fetch(url, {
6743
+ headers: {
6744
+ origin: matches[0],
6745
+ referer: url
6746
+ }
6747
+ });
6748
+ });
6749
+ }
6750
+ function download(impUrl) {
6751
+ const isShared = impUrl.indexOf("https://observablehq.com/d") === 0;
6752
+ return fetchEx(impUrl.replace(`https://observablehq.com/${isShared ? "d/" : ""}`, "https://api.observablehq.com/document/"))
6753
+ .then(r => r.json());
6743
6754
  }
6744
6755
 
6745
- function calcRefs(cellAst, cellStr) {
6746
- if (cellAst.references === undefined)
6747
- return { inputs: [], args: [], patches: [] };
6748
- const dedup = {};
6749
- cellAst.references.forEach(r => dedup[cellStr.substring(r.start, r.end)] = true);
6750
- const retVal = {
6751
- inputs: Object.keys(dedup),
6752
- args: Object.keys(dedup).map(r => r.split(" ").join("_")),
6753
- patches: []
6754
- };
6755
- const pushPatch = (node, newText) => retVal.patches.push({ start: node.start - cellAst.body.start, end: node.end - cellAst.body.start, newText });
6756
- if (cellAst.body) {
6757
- ancestor(cellAst.body, {
6758
- Identifier(node) {
6759
- const value = cellStr.substring(node.start, node.end);
6760
- if (dedup[value]) ;
6761
- },
6762
- MutableExpression(node) {
6763
- const value = cellStr.substring(node.start, node.end);
6764
- const newText = value.split(" ").join("_") + ".value";
6765
- pushPatch(node, newText);
6766
- },
6767
- ViewExpression(node) {
6768
- const value = cellStr.substring(node.start, node.end);
6769
- const newText = value.split(" ").join("_");
6770
- pushPatch(node, newText);
6771
- },
6772
- ThisExpression(node, ancestors) {
6773
- const value = cellStr.substring(node.start, node.end);
6774
- if (value === "this" && !ancestors.find(n => n.type === "FunctionExpression")) {
6775
- pushPatch(node, "((this === globalThis || this === globalThis.window)? undefined : this?.valueOf())");
6776
- }
6777
- }
6778
- }, walk);
6779
- }
6780
- return retVal;
6781
- }
6782
- function parseImportExpression(cellAst) {
6783
- var _a, _b, _c, _d;
6784
- return {
6785
- type: "import",
6786
- src: cellAst.body.source.value,
6787
- specifiers: (_b = (_a = cellAst.body.specifiers) === null || _a === void 0 ? void 0 : _a.map(spec => {
6788
- var _a;
6789
- return {
6790
- view: spec.view,
6791
- name: spec.imported.name,
6792
- alias: (((_a = spec.local) === null || _a === void 0 ? void 0 : _a.name) && spec.imported.name !== spec.local.name) ? spec.local.name : spec.imported.name
6793
- };
6794
- })) !== null && _b !== void 0 ? _b : [],
6795
- injections: (_d = (_c = cellAst.body.injections) === null || _c === void 0 ? void 0 : _c.map(inj => {
6796
- var _a, _b;
6797
- return {
6798
- name: inj.imported.name,
6799
- alias: (_b = (_a = inj.local) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : inj.imported.name
6800
- };
6801
- })) !== null && _d !== void 0 ? _d : [],
6802
- };
6803
- }
6804
- function parseViewExpression(cellStr, cellAst, refs, bodyStr) {
6805
- var _a, _b;
6806
- const id = cellAst.id && cellStr.substring(cellAst.id.start, cellAst.id.end);
6807
- return {
6808
- type: "viewof",
6809
- variable: {
6810
- type: "variable",
6811
- id,
6812
- inputs: refs.inputs,
6813
- func: createFunction(refs, cellAst.async, cellAst.generator, cellAst.body.type === "BlockStatement", bodyStr)
6814
- },
6815
- variableValue: {
6816
- type: "variable",
6817
- id: (_b = (_a = cellAst === null || cellAst === void 0 ? void 0 : cellAst.id) === null || _a === void 0 ? void 0 : _a.id) === null || _b === void 0 ? void 0 : _b.name,
6818
- inputs: ["Generators", id],
6819
- func: (G, _) => G.input(_)
6820
- }
6821
- };
6822
- }
6823
- function parseMutableExpression(cellStr, cellAst, refs, bodyStr) {
6824
- var _a, _b;
6825
- const id = cellAst.id && cellStr.substring(cellAst.id.start, cellAst.id.end);
6826
- const initialValueId = (_b = (_a = cellAst === null || cellAst === void 0 ? void 0 : cellAst.id) === null || _a === void 0 ? void 0 : _a.id) === null || _b === void 0 ? void 0 : _b.name;
6827
- const initialId = `initial ${initialValueId}`;
6828
- return {
6829
- type: "mutable",
6830
- initial: {
6831
- type: "variable",
6832
- id: initialId,
6833
- inputs: refs.inputs,
6834
- func: createFunction(refs, cellAst.async, cellAst.generator, cellAst.body.type === "BlockStatement", bodyStr)
6835
- },
6836
- variable: {
6837
- type: "variable",
6838
- id,
6839
- inputs: ["Mutable", initialId],
6840
- func: (M, _) => new M(_)
6841
- },
6842
- variableValue: {
6843
- type: "variable",
6844
- id: initialValueId,
6845
- inputs: [id],
6846
- func: _ => _.generator
6847
- }
6848
- };
6849
- }
6850
- function parseVariableExpression(cellStr, cellAst, refs, bodyStr) {
6851
- var _a, _b;
6852
- return {
6853
- type: "variable",
6854
- id: cellAst.id && cellStr.substring((_a = cellAst.id) === null || _a === void 0 ? void 0 : _a.start, (_b = cellAst.id) === null || _b === void 0 ? void 0 : _b.end),
6855
- inputs: refs.inputs,
6856
- func: createFunction(refs, cellAst.async, cellAst.generator, cellAst.body.type === "BlockStatement", bodyStr)
6857
- };
6858
- }
6859
- function parseCell(cellStr) {
6860
- var _a, _b;
6861
- const cellAst = parseCell$1(cellStr);
6862
- if (((_a = (cellAst.body)) === null || _a === void 0 ? void 0 : _a.type) == "ImportDeclaration") {
6863
- return parseImportExpression(cellAst);
6864
- }
6865
- const refs = calcRefs(cellAst, cellStr);
6866
- const bodyStr = cellAst.body && cellStr.substring(cellAst.body.start, cellAst.body.end);
6867
- switch ((_b = cellAst.id) === null || _b === void 0 ? void 0 : _b.type) {
6868
- case "ViewExpression":
6869
- return parseViewExpression(cellStr, cellAst, refs, bodyStr);
6870
- case "MutableExpression":
6871
- return parseMutableExpression(cellStr, cellAst, refs, bodyStr);
6872
- default:
6873
- return parseVariableExpression(cellStr, cellAst, refs, bodyStr);
6874
- }
6756
+ function calcRefs(cellAst, cellStr) {
6757
+ if (cellAst.references === undefined)
6758
+ return { inputs: [], args: [], patches: [] };
6759
+ const dedup = {};
6760
+ cellAst.references.forEach(r => dedup[cellStr.substring(r.start, r.end)] = true);
6761
+ const retVal = {
6762
+ inputs: Object.keys(dedup),
6763
+ args: Object.keys(dedup).map(r => r.split(" ").join("_")),
6764
+ patches: []
6765
+ };
6766
+ const pushPatch = (node, newText) => retVal.patches.push({ start: node.start - cellAst.body.start, end: node.end - cellAst.body.start, newText });
6767
+ if (cellAst.body) {
6768
+ ancestor(cellAst.body, {
6769
+ Identifier(node) {
6770
+ const value = cellStr.substring(node.start, node.end);
6771
+ if (dedup[value]) ;
6772
+ },
6773
+ MutableExpression(node) {
6774
+ const value = cellStr.substring(node.start, node.end);
6775
+ const newText = value.split(" ").join("_") + ".value";
6776
+ pushPatch(node, newText);
6777
+ },
6778
+ ViewExpression(node) {
6779
+ const value = cellStr.substring(node.start, node.end);
6780
+ const newText = value.split(" ").join("_");
6781
+ pushPatch(node, newText);
6782
+ },
6783
+ ThisExpression(node, ancestors) {
6784
+ const value = cellStr.substring(node.start, node.end);
6785
+ if (value === "this" && !ancestors.find(n => n.type === "FunctionExpression")) {
6786
+ pushPatch(node, "((this === globalThis || this === globalThis.window)? undefined : this?.valueOf())");
6787
+ }
6788
+ }
6789
+ }, walk);
6790
+ }
6791
+ return retVal;
6792
+ }
6793
+ function parseImportExpression(cellAst) {
6794
+ var _a, _b, _c, _d;
6795
+ return {
6796
+ type: "import",
6797
+ src: cellAst.body.source.value,
6798
+ specifiers: (_b = (_a = cellAst.body.specifiers) === null || _a === void 0 ? void 0 : _a.map(spec => {
6799
+ var _a;
6800
+ return {
6801
+ view: spec.view,
6802
+ name: spec.imported.name,
6803
+ alias: (((_a = spec.local) === null || _a === void 0 ? void 0 : _a.name) && spec.imported.name !== spec.local.name) ? spec.local.name : spec.imported.name
6804
+ };
6805
+ })) !== null && _b !== void 0 ? _b : [],
6806
+ injections: (_d = (_c = cellAst.body.injections) === null || _c === void 0 ? void 0 : _c.map(inj => {
6807
+ var _a, _b;
6808
+ return {
6809
+ name: inj.imported.name,
6810
+ alias: (_b = (_a = inj.local) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : inj.imported.name
6811
+ };
6812
+ })) !== null && _d !== void 0 ? _d : [],
6813
+ };
6814
+ }
6815
+ function parseViewExpression(cellStr, cellAst, refs, bodyStr) {
6816
+ var _a, _b;
6817
+ const id = cellAst.id && cellStr.substring(cellAst.id.start, cellAst.id.end);
6818
+ return {
6819
+ type: "viewof",
6820
+ variable: {
6821
+ type: "variable",
6822
+ id,
6823
+ inputs: refs.inputs,
6824
+ func: createFunction(refs, cellAst.async, cellAst.generator, cellAst.body.type === "BlockStatement", bodyStr)
6825
+ },
6826
+ variableValue: {
6827
+ type: "variable",
6828
+ id: (_b = (_a = cellAst === null || cellAst === void 0 ? void 0 : cellAst.id) === null || _a === void 0 ? void 0 : _a.id) === null || _b === void 0 ? void 0 : _b.name,
6829
+ inputs: ["Generators", id],
6830
+ func: (G, _) => G.input(_)
6831
+ }
6832
+ };
6833
+ }
6834
+ function parseMutableExpression(cellStr, cellAst, refs, bodyStr) {
6835
+ var _a, _b;
6836
+ const id = cellAst.id && cellStr.substring(cellAst.id.start, cellAst.id.end);
6837
+ const initialValueId = (_b = (_a = cellAst === null || cellAst === void 0 ? void 0 : cellAst.id) === null || _a === void 0 ? void 0 : _a.id) === null || _b === void 0 ? void 0 : _b.name;
6838
+ const initialId = `initial ${initialValueId}`;
6839
+ return {
6840
+ type: "mutable",
6841
+ initial: {
6842
+ type: "variable",
6843
+ id: initialId,
6844
+ inputs: refs.inputs,
6845
+ func: createFunction(refs, cellAst.async, cellAst.generator, cellAst.body.type === "BlockStatement", bodyStr)
6846
+ },
6847
+ variable: {
6848
+ type: "variable",
6849
+ id,
6850
+ inputs: ["Mutable", initialId],
6851
+ func: (M, _) => new M(_)
6852
+ },
6853
+ variableValue: {
6854
+ type: "variable",
6855
+ id: initialValueId,
6856
+ inputs: [id],
6857
+ func: _ => _.generator
6858
+ }
6859
+ };
6860
+ }
6861
+ function parseVariableExpression(cellStr, cellAst, refs, bodyStr) {
6862
+ var _a, _b;
6863
+ return {
6864
+ type: "variable",
6865
+ id: cellAst.id && cellStr.substring((_a = cellAst.id) === null || _a === void 0 ? void 0 : _a.start, (_b = cellAst.id) === null || _b === void 0 ? void 0 : _b.end),
6866
+ inputs: refs.inputs,
6867
+ func: createFunction(refs, cellAst.async, cellAst.generator, cellAst.body.type === "BlockStatement", bodyStr)
6868
+ };
6869
+ }
6870
+ function parseCell(cellStr) {
6871
+ var _a, _b;
6872
+ const cellAst = parseCell$2(cellStr);
6873
+ if (((_a = (cellAst.body)) === null || _a === void 0 ? void 0 : _a.type) == "ImportDeclaration") {
6874
+ return parseImportExpression(cellAst);
6875
+ }
6876
+ const refs = calcRefs(cellAst, cellStr);
6877
+ const bodyStr = cellAst.body && cellStr.substring(cellAst.body.start, cellAst.body.end);
6878
+ switch ((_b = cellAst.id) === null || _b === void 0 ? void 0 : _b.type) {
6879
+ case "ViewExpression":
6880
+ return parseViewExpression(cellStr, cellAst, refs, bodyStr);
6881
+ case "MutableExpression":
6882
+ return parseMutableExpression(cellStr, cellAst, refs, bodyStr);
6883
+ default:
6884
+ return parseVariableExpression(cellStr, cellAst, refs, bodyStr);
6885
+ }
6875
6886
  }
6876
6887
 
6877
- class Writer {
6878
- constructor() {
6879
- this._files = [];
6880
- this._imports = [];
6881
- this._functions = [];
6882
- this._defines = [];
6883
- this._defineUid = 0;
6884
- this._functionUid = 0;
6885
- }
6886
- toString() {
6887
- return `\
6888
- ${this._imports.join("\n")}
6889
-
6890
- ${this._functions.join("\n").split("\n) {").join("){")}
6891
-
6892
- export default function define(runtime, observer) {
6893
- const main = runtime.module();
6894
-
6895
- function toString() { return this.url; }
6896
- const fileAttachments = new Map([
6897
- ${this._files.map(f => `["${f.name}", { url: new URL("${f.url}"), mimeType: ${JSON.stringify(f.mime_type)}, toString }]`).join(",\n ")}
6898
- ]);
6899
- main.builtin("FileAttachment", runtime.fileAttachments(name => fileAttachments.get(name)));
6900
-
6901
- ${this._defines.join("\n ")}
6902
-
6903
- return main;
6904
- }\n`;
6905
- }
6906
- files(files) {
6907
- this._files = [...this._files, ...files];
6908
- }
6909
- import(url) {
6910
- this._imports.push(`import define${++this._defineUid} from "${url}"; `);
6911
- }
6912
- importDefine(imp) {
6913
- const injections = imp.injections.map(inj => {
6914
- return inj.name === inj.alias ?
6915
- `"${inj.name}"` :
6916
- `{name: "${inj.name}", alias: "${inj.alias}"}`;
6917
- });
6918
- const derive = imp.injections.length ? `.derive([${injections.join(", ")}], main)` : "";
6919
- this._defines.push(`const child${this._defineUid} = runtime.module(define${this._defineUid})${derive};`);
6920
- imp.specifiers.forEach(s => {
6921
- this._defines.push(`main.import("${s.name}"${s.alias && s.alias !== s.name ? `, "${s.alias}"` : ""}, child${this._defineUid}); `);
6922
- });
6923
- }
6924
- function(variable) {
6925
- var _a, _b, _c;
6926
- let id = (_a = variable.id) !== null && _a !== void 0 ? _a : `${++this._functionUid}`;
6927
- const idParts = id.split(" ");
6928
- id = `_${idParts[idParts.length - 1]}`;
6929
- this._functions.push(`${(_c = (_b = variable.func) === null || _b === void 0 ? void 0 : _b.toString()) === null || _c === void 0 ? void 0 : _c.replace("anonymous", `${id}`)}`);
6930
- return id;
6931
- }
6932
- define(variable, observable = true, inlineFunc = false, funcId) {
6933
- var _a;
6934
- funcId = funcId !== null && funcId !== void 0 ? funcId : variable.id;
6935
- const observe = observable ? `.variable(observer(${variable.id ? JSON.stringify(variable.id) : ""}))` : "";
6936
- const id = variable.id ? `${JSON.stringify(variable.id)}, ` : "";
6937
- const inputs = variable.inputs.length ? `[${variable.inputs.map(i => JSON.stringify(i)).join(", ")}], ` : "";
6938
- const func = inlineFunc ?
6939
- (_a = variable.func) === null || _a === void 0 ? void 0 : _a.toString() :
6940
- funcId;
6941
- this._defines.push(`main${observe}.define(${id}${inputs}${func});`);
6942
- }
6943
- error(msg) {
6944
- }
6888
+ class Writer {
6889
+ constructor() {
6890
+ this._files = [];
6891
+ this._imports = [];
6892
+ this._functions = [];
6893
+ this._defines = [];
6894
+ this._defineUid = 0;
6895
+ this._functionUid = 0;
6896
+ }
6897
+ toString() {
6898
+ return `\
6899
+ ${this._imports.join("\n")}
6900
+
6901
+ ${this._functions.join("\n").split("\n) {").join("){")}
6902
+
6903
+ export default function define(runtime, observer) {
6904
+ const main = runtime.module();
6905
+
6906
+ function toString() { return this.url; }
6907
+ const fileAttachments = new Map([
6908
+ ${this._files.map(f => `["${f.name}", { url: new URL("${f.url}"), mimeType: ${JSON.stringify(f.mime_type)}, toString }]`).join(",\n ")}
6909
+ ]);
6910
+ main.builtin("FileAttachment", runtime.fileAttachments(name => fileAttachments.get(name)));
6911
+
6912
+ ${this._defines.join("\n ")}
6913
+
6914
+ return main;
6915
+ }\n`;
6916
+ }
6917
+ files(files) {
6918
+ this._files = [...this._files, ...files];
6919
+ }
6920
+ import(url) {
6921
+ this._imports.push(`import define${++this._defineUid} from "${url}"; `);
6922
+ }
6923
+ importDefine(imp) {
6924
+ const injections = imp.injections.map(inj => {
6925
+ return inj.name === inj.alias ?
6926
+ `"${inj.name}"` :
6927
+ `{name: "${inj.name}", alias: "${inj.alias}"}`;
6928
+ });
6929
+ const derive = imp.injections.length ? `.derive([${injections.join(", ")}], main)` : "";
6930
+ this._defines.push(`const child${this._defineUid} = runtime.module(define${this._defineUid})${derive};`);
6931
+ imp.specifiers.forEach(s => {
6932
+ this._defines.push(`main.import("${s.name}"${s.alias && s.alias !== s.name ? `, "${s.alias}"` : ""}, child${this._defineUid}); `);
6933
+ });
6934
+ }
6935
+ function(variable) {
6936
+ var _a, _b, _c;
6937
+ let id = (_a = variable.id) !== null && _a !== void 0 ? _a : `${++this._functionUid}`;
6938
+ const idParts = id.split(" ");
6939
+ id = `_${idParts[idParts.length - 1]}`;
6940
+ this._functions.push(`${(_c = (_b = variable.func) === null || _b === void 0 ? void 0 : _b.toString()) === null || _c === void 0 ? void 0 : _c.replace("anonymous", `${id}`)}`);
6941
+ return id;
6942
+ }
6943
+ define(variable, observable = true, inlineFunc = false, funcId) {
6944
+ var _a;
6945
+ funcId = funcId !== null && funcId !== void 0 ? funcId : variable.id;
6946
+ const observe = observable ? `.variable(observer(${variable.id ? JSON.stringify(variable.id) : ""}))` : "";
6947
+ const id = variable.id ? `${JSON.stringify(variable.id)}, ` : "";
6948
+ const inputs = variable.inputs.length ? `[${variable.inputs.map(i => JSON.stringify(i)).join(", ")}], ` : "";
6949
+ const func = inlineFunc ?
6950
+ (_a = variable.func) === null || _a === void 0 ? void 0 : _a.toString() :
6951
+ funcId;
6952
+ this._defines.push(`main${observe}.define(${id}${inputs}${func});`);
6953
+ }
6954
+ error(msg) {
6955
+ }
6945
6956
  }
6946
6957
 
6947
- async function importFile(relativePath, baseUrl) {
6948
- const path = join(baseUrl, relativePath);
6949
- const content = await fetchEx(path).then(r => r.text());
6950
- let notebook;
6951
- if (endsWith(relativePath, ".ojsnb")) {
6952
- notebook = JSON.parse(content);
6953
- }
6954
- else if (endsWith(relativePath, ".ojs")) {
6955
- notebook = ojs2notebook(content);
6956
- }
6957
- else if (endsWith(relativePath, ".omd")) {
6958
- notebook = omd2notebook(content);
6959
- }
6960
- const retVal = compile(notebook, baseUrl);
6961
- retVal.dispose = () => { };
6962
- retVal.write = (w) => {
6963
- w.import(path);
6964
- };
6965
- return retVal;
6966
- }
6967
- // @ts-ignore - use precompiled notebook from observable
6968
- async function importCompiledNotebook(partial) {
6969
- const url = `https://api.observablehq.com/${partial[0] === "@" ? partial : `d/${partial}`}.js?v=3`;
6970
- let impMod = {
6971
- default: function (runtime, inspector) {
6972
- return undefined;
6973
- }
6974
- };
6975
- try {
6976
- impMod = await obfuscatedImport(url);
6977
- }
6978
- catch (e) {
6979
- }
6980
- const retVal = impMod.default;
6981
- retVal.dispose = () => { };
6982
- retVal.write = (w) => {
6983
- w.import(url);
6984
- };
6985
- return retVal;
6986
- }
6987
- function createVariable(inspect, name, inputs, definition, inline = false) {
6988
- let i;
6989
- let v;
6990
- const retVal = (module, inspector) => {
6991
- i = inspect ? inspector(name) : undefined;
6992
- v = module.variable(i);
6993
- if (arguments.length > 1) {
6994
- try {
6995
- v.define(name, inputs, definition);
6996
- }
6997
- catch (e) {
6998
- console.error(e === null || e === void 0 ? void 0 : e.message);
6999
- }
7000
- }
7001
- return v;
7002
- };
7003
- retVal.dispose = () => {
7004
- var _a;
7005
- try {
7006
- (_a = i === null || i === void 0 ? void 0 : i._node) === null || _a === void 0 ? void 0 : _a.remove();
7007
- }
7008
- catch (e) {
7009
- }
7010
- i = undefined;
7011
- try {
7012
- v === null || v === void 0 ? void 0 : v.delete();
7013
- }
7014
- catch (e) {
7015
- }
7016
- v = undefined;
7017
- };
7018
- retVal.write = (w) => {
7019
- if (inline) {
7020
- w.define({ id: name, inputs, func: definition }, inspect, true);
7021
- }
7022
- else {
7023
- const id = w.function({ id: name, func: definition });
7024
- w.define({ id: name, inputs, func: definition }, inspect, false, id);
7025
- }
7026
- };
7027
- return retVal;
7028
- }
7029
- function createImportVariable(name, alias) {
7030
- let v;
7031
- const retVal = (main, otherModule) => {
7032
- v = main.variable();
7033
- v.import(name, alias, otherModule);
7034
- };
7035
- retVal.dispose = () => {
7036
- v === null || v === void 0 ? void 0 : v.delete();
7037
- };
7038
- return retVal;
7039
- }
7040
- async function createModule(parsed, text, baseUrl) {
7041
- const otherModule = [".", "/"].indexOf(parsed.src[0]) === 0 ?
7042
- await importFile(parsed.src, baseUrl) :
7043
- await importCompiledNotebook(parsed.src);
7044
- const importVariables = [];
7045
- const variables = [];
7046
- parsed.specifiers.forEach(spec => {
7047
- const viewof = spec.view ? "viewof " : "";
7048
- importVariables.push(createImportVariable(viewof + spec.name, viewof + spec.alias));
7049
- if (spec.view) {
7050
- importVariables.push(createImportVariable(spec.name, spec.alias));
7051
- }
7052
- });
7053
- variables.push(createVariable(true, undefined, ["md"], md => {
7054
- return md `\`\`\`JavaScript
7055
- ${text}
7056
- \`\`\``;
7057
- }));
7058
- const retVal = (runtime, main, inspector) => {
7059
- let mod = runtime.module(otherModule);
7060
- if (parsed.injections.length) {
7061
- mod = mod.derive(parsed.injections, main);
7062
- }
7063
- variables.forEach(v => v(main, inspector));
7064
- importVariables.forEach(v => v(main, mod));
7065
- return mod;
7066
- };
7067
- retVal.importVariables = importVariables;
7068
- retVal.variables = variables;
7069
- retVal.dispose = () => {
7070
- importVariables.forEach(v => v.dispose());
7071
- variables.forEach(v => v.dispose());
7072
- otherModule.dispose();
7073
- };
7074
- retVal.write = (w) => {
7075
- otherModule.write(w);
7076
- w.importDefine(parsed);
7077
- };
7078
- return retVal;
7079
- }
7080
- async function createCell(node, baseUrl) {
7081
- const modules = [];
7082
- const variables = [];
7083
- try {
7084
- const text = node.mode && node.mode !== "js" ? `${node.mode}\`${encodeBacktick(node.value)}\`` : node.value;
7085
- const parsed = parseCell(text);
7086
- switch (parsed.type) {
7087
- case "import":
7088
- modules.push(await createModule(parsed, text, baseUrl));
7089
- break;
7090
- case "viewof":
7091
- variables.push(createVariable(true, parsed.variable.id, parsed.variable.inputs, parsed.variable.func));
7092
- variables.push(createVariable(false, parsed.variableValue.id, parsed.variableValue.inputs, parsed.variableValue.func, true));
7093
- break;
7094
- case "mutable":
7095
- variables.push(createVariable(false, parsed.initial.id, parsed.initial.inputs, parsed.initial.func));
7096
- variables.push(createVariable(false, parsed.variable.id, parsed.variable.inputs, parsed.variable.func));
7097
- variables.push(createVariable(true, parsed.variableValue.id, parsed.variableValue.inputs, parsed.variableValue.func, true));
7098
- break;
7099
- case "variable":
7100
- variables.push(createVariable(true, parsed.id, parsed.inputs, parsed.func));
7101
- break;
7102
- }
7103
- }
7104
- catch (e) {
7105
- }
7106
- const retVal = (runtime, main, inspector) => {
7107
- modules.forEach(imp => imp(runtime, main, inspector));
7108
- variables.forEach(v => v(main, inspector));
7109
- };
7110
- retVal.modules = modules;
7111
- retVal.variables = variables;
7112
- retVal.dispose = () => {
7113
- variables.forEach(v => v.dispose());
7114
- modules.forEach(mod => mod.dispose());
7115
- };
7116
- retVal.write = (w) => {
7117
- modules.forEach(imp => imp.write(w));
7118
- variables.forEach(v => v.write(w));
7119
- };
7120
- return retVal;
7121
- }
7122
- function createFile(file) {
7123
- function toString() { return globalThis.url; }
7124
- return [file.name, { url: new URL(file.url), mimeType: file.mime_type, toString }];
7125
- }
7126
- async function compile(notebook, baseUrl = ".") {
7127
- const files = notebook.files.map(f => createFile(f));
7128
- const fileAttachments = new Map(files);
7129
- let cells = await Promise.all(notebook.nodes.map(n => createCell(n, baseUrl)));
7130
- const retVal = (runtime, inspector) => {
7131
- const main = runtime.module();
7132
- main.builtin("FileAttachment", runtime.fileAttachments(name => {
7133
- var _a;
7134
- return (_a = fileAttachments.get(name)) !== null && _a !== void 0 ? _a : { url: new URL(name), mimeType: null };
7135
- }));
7136
- cells.forEach(cell => {
7137
- cell(runtime, main, inspector);
7138
- });
7139
- return main;
7140
- };
7141
- retVal.fileAttachments = fileAttachments;
7142
- retVal.cells = cells;
7143
- retVal.appendCell = async (n, baseUrl = ".") => {
7144
- const cell = await createCell(n, baseUrl);
7145
- cells.push(cell);
7146
- return cell;
7147
- };
7148
- retVal.disposeCell = async (cell) => {
7149
- cells = cells.filter(c => c !== cell);
7150
- cell.dispose();
7151
- };
7152
- retVal.dispose = () => {
7153
- cells.forEach(cell => cell.dispose());
7154
- cells = [];
7155
- };
7156
- retVal.write = (w) => {
7157
- w.files(notebook.files);
7158
- cells.forEach(cell => cell.write(w));
7159
- };
7160
- retVal.toString = (w = new Writer()) => {
7161
- retVal.write(w);
7162
- return w.toString().trim();
7163
- };
7164
- return retVal;
6958
+ const isRelativePath = (path) => path[0] === ".";
6959
+ const fullUrl = (path, basePath) => isRelativePath(path) ? join(basePath, path) : path;
6960
+ async function importFile(relativePath, baseUrl) {
6961
+ const path = fullUrl(relativePath, baseUrl);
6962
+ const content = await fetchEx(path).then(r => r.text());
6963
+ let notebook;
6964
+ if (endsWith(relativePath, ".ojsnb")) {
6965
+ notebook = JSON.parse(content);
6966
+ }
6967
+ else if (endsWith(relativePath, ".ojs")) {
6968
+ notebook = ojs2notebook(content);
6969
+ }
6970
+ else if (endsWith(relativePath, ".omd")) {
6971
+ notebook = omd2notebook(content);
6972
+ }
6973
+ const retVal = compile(notebook, baseUrl);
6974
+ retVal.dispose = () => { };
6975
+ retVal.write = (w) => {
6976
+ w.import(path);
6977
+ };
6978
+ return retVal;
6979
+ }
6980
+ // @ts-ignore - use precompiled notebook from observable
6981
+ async function importCompiledNotebook(partial) {
6982
+ const url = `https://api.observablehq.com/${partial[0] === "@" ? partial : `d/${partial}`}.js?v=3`;
6983
+ let impMod = {
6984
+ default: function (runtime, inspector) {
6985
+ return undefined;
6986
+ }
6987
+ };
6988
+ try {
6989
+ impMod = await obfuscatedImport(url);
6990
+ }
6991
+ catch (e) {
6992
+ }
6993
+ const retVal = impMod.default;
6994
+ retVal.dispose = () => { };
6995
+ retVal.write = (w) => {
6996
+ w.import(url);
6997
+ };
6998
+ return retVal;
6999
+ }
7000
+ function createVariable(inspect, name, inputs, definition, inline = false) {
7001
+ let i;
7002
+ let v;
7003
+ const retVal = (module, inspector) => {
7004
+ i = inspect ? inspector(name) : undefined;
7005
+ v = module.variable(i);
7006
+ if (arguments.length > 1) {
7007
+ try {
7008
+ v.define(name, inputs, definition);
7009
+ }
7010
+ catch (e) {
7011
+ console.error(e === null || e === void 0 ? void 0 : e.message);
7012
+ }
7013
+ }
7014
+ return v;
7015
+ };
7016
+ retVal.dispose = () => {
7017
+ var _a;
7018
+ try {
7019
+ (_a = i === null || i === void 0 ? void 0 : i._node) === null || _a === void 0 ? void 0 : _a.remove();
7020
+ }
7021
+ catch (e) {
7022
+ }
7023
+ i = undefined;
7024
+ try {
7025
+ v === null || v === void 0 ? void 0 : v.delete();
7026
+ }
7027
+ catch (e) {
7028
+ }
7029
+ v = undefined;
7030
+ };
7031
+ retVal.write = (w) => {
7032
+ if (inline) {
7033
+ w.define({ id: name, inputs, func: definition }, inspect, true);
7034
+ }
7035
+ else {
7036
+ const id = w.function({ id: name, func: definition });
7037
+ w.define({ id: name, inputs, func: definition }, inspect, false, id);
7038
+ }
7039
+ };
7040
+ return retVal;
7041
+ }
7042
+ function createImportVariable(name, alias) {
7043
+ let v;
7044
+ const retVal = (main, otherModule) => {
7045
+ v = main.variable();
7046
+ v.import(name, alias, otherModule);
7047
+ };
7048
+ retVal.dispose = () => {
7049
+ v === null || v === void 0 ? void 0 : v.delete();
7050
+ };
7051
+ return retVal;
7052
+ }
7053
+ async function createModule(parsed, text, baseUrl) {
7054
+ const otherModule = isRelativePath(parsed.src) ?
7055
+ await importFile(parsed.src, baseUrl) :
7056
+ await importCompiledNotebook(parsed.src);
7057
+ const importVariables = [];
7058
+ const variables = [];
7059
+ parsed.specifiers.forEach(spec => {
7060
+ const viewof = spec.view ? "viewof " : "";
7061
+ importVariables.push(createImportVariable(viewof + spec.name, viewof + spec.alias));
7062
+ if (spec.view) {
7063
+ importVariables.push(createImportVariable(spec.name, spec.alias));
7064
+ }
7065
+ });
7066
+ variables.push(createVariable(true, undefined, ["md"], md => {
7067
+ return md `\`\`\`JavaScript
7068
+ ${text}
7069
+ \`\`\``;
7070
+ }));
7071
+ const retVal = (runtime, main, inspector) => {
7072
+ let mod = runtime.module(otherModule);
7073
+ if (parsed.injections.length) {
7074
+ mod = mod.derive(parsed.injections, main);
7075
+ }
7076
+ variables.forEach(v => v(main, inspector));
7077
+ importVariables.forEach(v => v(main, mod));
7078
+ return mod;
7079
+ };
7080
+ retVal.importVariables = importVariables;
7081
+ retVal.variables = variables;
7082
+ retVal.dispose = () => {
7083
+ importVariables.forEach(v => v.dispose());
7084
+ variables.forEach(v => v.dispose());
7085
+ otherModule.dispose();
7086
+ };
7087
+ retVal.write = (w) => {
7088
+ otherModule.write(w);
7089
+ w.importDefine(parsed);
7090
+ };
7091
+ return retVal;
7092
+ }
7093
+ async function createCell(node, baseUrl) {
7094
+ const modules = [];
7095
+ const variables = [];
7096
+ try {
7097
+ const text = node.mode && node.mode !== "js" ? `${node.mode}\`${encodeBacktick(node.value)}\`` : node.value;
7098
+ const parsedModule = splitModule(text);
7099
+ for (const text of parsedModule) {
7100
+ const parsed = parseCell(text);
7101
+ switch (parsed.type) {
7102
+ case "import":
7103
+ modules.push(await createModule(parsed, text, baseUrl));
7104
+ break;
7105
+ case "viewof":
7106
+ variables.push(createVariable(true, parsed.variable.id, parsed.variable.inputs, parsed.variable.func));
7107
+ variables.push(createVariable(false, parsed.variableValue.id, parsed.variableValue.inputs, parsed.variableValue.func, true));
7108
+ break;
7109
+ case "mutable":
7110
+ variables.push(createVariable(false, parsed.initial.id, parsed.initial.inputs, parsed.initial.func));
7111
+ variables.push(createVariable(false, parsed.variable.id, parsed.variable.inputs, parsed.variable.func));
7112
+ variables.push(createVariable(true, parsed.variableValue.id, parsed.variableValue.inputs, parsed.variableValue.func, true));
7113
+ break;
7114
+ case "variable":
7115
+ variables.push(createVariable(true, parsed.id, parsed.inputs, parsed.func));
7116
+ break;
7117
+ }
7118
+ }
7119
+ }
7120
+ catch (e) {
7121
+ variables.push(createVariable(true, undefined, [], e.message));
7122
+ }
7123
+ const retVal = (runtime, main, inspector) => {
7124
+ modules.forEach(imp => imp(runtime, main, inspector));
7125
+ variables.forEach(v => v(main, inspector));
7126
+ };
7127
+ retVal.id = "" + node.id;
7128
+ retVal.modules = modules;
7129
+ retVal.variables = variables;
7130
+ retVal.dispose = () => {
7131
+ variables.forEach(v => v.dispose());
7132
+ modules.forEach(mod => mod.dispose());
7133
+ };
7134
+ retVal.write = (w) => {
7135
+ modules.forEach(imp => imp.write(w));
7136
+ variables.forEach(v => v.write(w));
7137
+ };
7138
+ return retVal;
7139
+ }
7140
+ function createFile(file, baseUrl) {
7141
+ function toString() { return globalThis.url; }
7142
+ return [file.name, { url: new URL(fullUrl(file.url, baseUrl)), mimeType: file.mime_type, toString }];
7143
+ }
7144
+ async function compile(notebook, baseUrl = ".") {
7145
+ const files = notebook.files.map(f => createFile(f, baseUrl));
7146
+ const fileAttachments = new Map(files);
7147
+ const _cells = await Promise.all(notebook.nodes.map(n => createCell(n, baseUrl)));
7148
+ const cells = new Map(_cells.map(c => [c.id, c]));
7149
+ const retVal = (runtime, inspector) => {
7150
+ const main = runtime.module();
7151
+ main.builtin("FileAttachment", runtime.fileAttachments(name => {
7152
+ var _a;
7153
+ return (_a = fileAttachments.get(name)) !== null && _a !== void 0 ? _a : { url: new URL(fullUrl(name, baseUrl)), mimeType: null };
7154
+ }));
7155
+ main.builtin("fetchEx", fetchEx);
7156
+ cells.forEach(cell => {
7157
+ cell(runtime, main, inspector);
7158
+ });
7159
+ return main;
7160
+ };
7161
+ retVal.fileAttachments = fileAttachments;
7162
+ retVal.cells = cells;
7163
+ retVal.appendCell = async (n, baseUrl) => {
7164
+ const cell = await createCell(n, baseUrl);
7165
+ retVal.disposeCell(cell.id);
7166
+ cells.set(cell.id, cell);
7167
+ return cell;
7168
+ };
7169
+ retVal.disposeCell = async (id) => {
7170
+ const cell = cells.get(id);
7171
+ if (cell) {
7172
+ cells.delete(id);
7173
+ cell.dispose();
7174
+ }
7175
+ };
7176
+ retVal.dispose = () => {
7177
+ cells.forEach(cell => cell.dispose());
7178
+ cells.clear();
7179
+ };
7180
+ retVal.write = (w) => {
7181
+ w.files(notebook.files);
7182
+ cells.forEach(cell => cell.write(w));
7183
+ };
7184
+ retVal.toString = (w = new Writer()) => {
7185
+ retVal.write(w);
7186
+ return w.toString().trim();
7187
+ };
7188
+ return retVal;
7165
7189
  }
7166
7190
 
7167
- export { Writer, compile, download, ojs2notebook, omd2notebook };
7191
+ export { compile, download, ojs2notebook, omd2notebook, parseOmd };
7168
7192
  //# sourceMappingURL=index.esm.js.map